From 352645b41711436306bc30e41e139b2d3809005a Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Sun, 25 Oct 2026 00:07:31 +0500 Subject: [PATCH 01/16] Predict block placement on the client, so fast bridging stops losing clicks MultiPlayerGameMode.useItemOn places the block on the client's level at once, kept under the use's sequence until BlockChangedAck. Without it the next fast click aimed past the block still on its way from the server, the server refused it, and the arm swung for nothing. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/remote.rs | 56 +++++++++++++++++++----- 1 file changed, 46 insertions(+), 10 deletions(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index da0def0fb..e54b33b02 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3862,11 +3862,17 @@ impl Game<'_> { self.predict_item_on_block(stack, &hit); } if held_block { - if reacts - || held - .as_ref() - .is_some_and(|stack| self.remote_can_place(&hit, stack)) - { + let placed = if reacts { + None + } else { + held.as_ref() + .and_then(|stack| self.remote_can_place(&hit, stack)) + }; + if let Some(placed) = &placed { + self.predict_place(placed, seq); + self.with_hand(hand, Game::consume_held); + } + if reacts || placed.is_some() { self.with_hand(hand, Game::swing_arm); } // BlockItem.place returns FAIL when placement is rejected: @@ -3997,12 +4003,41 @@ impl Game<'_> { }) } - /// Run BlockItem.place on a disposable level before predicting its swing. - /// The real level supplies collision shapes and building-blocking entities; - /// block writes, random draws, scheduled ticks and events stay in the preview. - fn remote_can_place(&mut self, hit: &super::Hit, stack: &ItemStack) -> bool { + /// MultiPlayerGameMode.useItemOn inside startPrediction, for a block item: + /// the blocks `BlockItem.place` set are placed on this client's level at + /// once, each kept as predicted under the use's sequence until the server + /// acknowledges it (a placement the server refused goes back). Without + /// this, the next click of a fast bridge aims past the block still on its + /// way from the server, and the server refuses it. + fn predict_place( + &mut self, + changes: &[(horizon_core::position::BlockPos, BlockStateId)], + seq: i32, + ) { + for &(p, state) in changes { + let pos = [p.x, p.y, p.z]; + let before = self.world.block(p.x, p.y, p.z); + // BlockStatePredictionHandler.retainKnownServerState. + if let Some(r) = self.remote.as_mut() { + r.predictions + .entry(pos) + .and_modify(|e| e.0 = seq) + .or_insert((seq, before.0 as i32)); + } + self.set_block(pos, state.0 as i32); + } + } + + /// Run BlockItem.place on a disposable level: the blocks it set, if it + /// placed. The real level supplies collision shapes and building-blocking + /// entities; random draws, scheduled ticks and events stay in the preview. + fn remote_can_place( + &mut self, + hit: &super::Hit, + stack: &ItemStack, + ) -> Option> { if !self.may_build() { - return false; + return None; } let ctx = horizon_world::level::PlaceContext { clicked_pos: horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]), @@ -4025,6 +4060,7 @@ impl Game<'_> { ), horizon_world::level::PlaceOutcome::Placed { .. } ) + .then(|| level.changed.into_iter().collect()) }) } From d742d725f4ac51a55d8748ef646522c7b574de1b Mon Sep 17 00:00:00 2001 From: socksprox Date: Sat, 24 Oct 2026 21:29:08 +0200 Subject: [PATCH 02/16] =?UTF-8?q?Client:=20the=20boss-overlay=20=E2=80=94?= =?UTF-8?q?=20BossEvent=20bars,=20wither=20darkening=20and=20world=20fog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The clientbound boss_event packet (add/update/remove/style/progress), a BossOverlay that renders each bar, darkens the world under a wither, and suppresses the create-the-world fog — vanilla's BossHealthOverlay and GameRenderer behaviour on a real server. Co-Authored-By: Devin --- crates/horizon-client/src/boss_overlay.rs | 201 +++++++ crates/horizon-client/src/bossbar.rs | 108 ++-- crates/horizon-client/src/fog.rs | 29 + crates/horizon-client/src/game.rs | 15 +- crates/horizon-client/src/game/bossbars.rs | 553 ++++++++++++++++-- crates/horizon-client/src/game/dragon.rs | 46 +- crates/horizon-client/src/game/raids.rs | 74 ++- crates/horizon-client/src/game/remote.rs | 4 + crates/horizon-client/src/game/render_tick.rs | 5 +- crates/horizon-client/src/game/wither.rs | 41 -- crates/horizon-client/src/gfx.rs | 6 + crates/horizon-client/src/lib.rs | 1 + crates/horizon-protocol/src/packets/play.rs | 156 +++++ 13 files changed, 1055 insertions(+), 184 deletions(-) create mode 100644 crates/horizon-client/src/boss_overlay.rs diff --git a/crates/horizon-client/src/boss_overlay.rs b/crates/horizon-client/src/boss_overlay.rs new file mode 100644 index 000000000..e51a59668 --- /dev/null +++ b/crates/horizon-client/src/boss_overlay.rs @@ -0,0 +1,201 @@ +//! `BossHealthOverlay` and `LerpingBossEvent`: the boss bars a client is +//! showing, in the order their add packets arrived. +use crate::{hud_overlays::BossBar, text::Text}; + +/// `LerpingBossEvent.LERP_MILLISECONDS`. +const LERP_MS: u128 = 100; + +/// `Util.getMillis`. +pub fn now_millis() -> u128 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis()) + .unwrap_or(0) +} + +/// One `LerpingBossEvent`. +#[derive(Clone, Debug)] +struct Event { + id: u128, + name: Text, + /// The progress the lerp started from (`progress`). + progress: f32, + /// `targetPercent`. + target: f32, + /// `setTime`. + set_at: u128, + color: u8, + overlay: u8, + darken: bool, + music: bool, + fog: bool, +} +impl Event { + /// `LerpingBossEvent.getProgress`. + fn displayed(&self, now: u128) -> f32 { + let t = ((now.saturating_sub(self.set_at)) as f32 / LERP_MS as f32).clamp(0.0, 1.0); + self.progress + (self.target - self.progress) * t + } + /// `LerpingBossEvent.setProgress`: the bar starts the next lerp from + /// whatever it is showing now. + fn set_progress(&mut self, progress: f32, now: u128) { + self.progress = self.displayed(now); + self.target = progress; + self.set_at = now; + } +} + +/// `BossHealthOverlay`: the events, plus `GameRenderer`'s world darkening. +#[derive(Clone, Debug, Default)] +pub struct BossOverlay { + events: Vec, + /// `bossOverlayWorldDarkening` and the previous tick's value. + darken: f32, + darken_o: f32, +} +impl BossOverlay { + pub fn reset(&mut self) { + *self = Self::default(); + } + /// `Handler.add`. An id already shown keeps its place. + pub fn add( + &mut self, + id: u128, + name: Text, + progress: f32, + color: u8, + overlay: u8, + darken: bool, + music: bool, + fog: bool, + now: u128, + ) { + let event = Event { + id, + name, + progress, + target: progress, + set_at: now, + color: color.min(6), + overlay: overlay.min(4), + darken, + music, + fog, + }; + if let Some(slot) = self.events.iter_mut().find(|e| e.id == id) { + *slot = event; + } else { + self.events.push(event); + } + } + pub fn remove(&mut self, id: u128) { + self.events.retain(|e| e.id != id); + } + pub fn set_progress(&mut self, id: u128, progress: f32, now: u128) { + if let Some(e) = self.events.iter_mut().find(|e| e.id == id) { + e.set_progress(progress, now); + } + } + pub fn set_name(&mut self, id: u128, name: Text) { + if let Some(e) = self.events.iter_mut().find(|e| e.id == id) { + e.name = name; + } + } + pub fn set_style(&mut self, id: u128, color: u8, overlay: u8) { + if let Some(e) = self.events.iter_mut().find(|e| e.id == id) { + e.color = color.min(6); + e.overlay = overlay.min(4); + } + } + pub fn set_properties(&mut self, id: u128, darken: bool, music: bool, fog: bool) { + if let Some(e) = self.events.iter_mut().find(|e| e.id == id) { + e.darken = darken; + e.music = music; + e.fog = fog; + } + } + /// `GameRenderer.tick` while the level runs. + pub fn tick_darken(&mut self, running: bool) { + if !running { + return; + } + self.darken_o = self.darken; + if self.should_darken() { + self.darken = (self.darken + 0.05).min(1.0); + } else if self.darken > 0.0 { + self.darken = (self.darken - 0.0125).max(0.0); + } + } + /// `GameRenderer.bossOverlayWorldDarkening`. + pub fn darken_amount(&self, partial: f32) -> f32 { + let t = partial.clamp(0.0, 1.0); + self.darken_o + (self.darken - self.darken_o) * t + } + pub fn should_darken(&self) -> bool { + self.events.iter().any(|e| e.darken) + } + pub fn should_play_music(&self) -> bool { + self.events.iter().any(|e| e.music) + } + pub fn should_create_world_fog(&self) -> bool { + self.events.iter().any(|e| e.fog) + } + /// The bars `extractRenderState` walks, with the lerped progress. + pub fn bars(&self, now: u128) -> Vec { + self.events + .iter() + .map(|e| BossBar { + name: e.name.clone(), + progress: e.displayed(now), + color: e.color as usize, + overlay: e.overlay as usize, + }) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn progress_lerps_over_a_tenth_of_a_second() { + let mut overlay = BossOverlay::default(); + overlay.add(1, Text::literal("W"), 0.0, 5, 0, true, false, false, 0); + overlay.set_progress(1, 1.0, 0); + assert!((overlay.bars(50)[0].progress - 0.5).abs() < 1.0e-5); + assert!((overlay.bars(100)[0].progress - 1.0).abs() < 1.0e-5); + // A new target starts from the value on screen. + overlay.set_progress(1, 0.0, 50); + assert!((overlay.bars(150)[0].progress - 0.0).abs() < 1.0e-5); + } + + #[test] + fn darken_ramps_and_fades() { + let mut overlay = BossOverlay::default(); + overlay.add(1, Text::literal("W"), 1.0, 5, 0, true, false, false, 0); + overlay.tick_darken(true); + assert!((overlay.darken_amount(1.0) - 0.05).abs() < 1.0e-5); + overlay.remove(1); + overlay.tick_darken(true); + assert!((overlay.darken - 0.0375).abs() < 1.0e-5); + assert!(!overlay.should_play_music()); + } + + #[test] + fn bars_keep_arrival_order() { + let mut overlay = BossOverlay::default(); + overlay.add(2, Text::literal("b"), 1.0, 0, 0, false, true, true, 0); + overlay.add(1, Text::literal("a"), 1.0, 0, 0, false, false, false, 0); + overlay.add(2, Text::literal("c"), 0.5, 1, 2, false, true, true, 0); + let names: Vec<_> = overlay + .bars(0) + .into_iter() + .map(|b| b.name.plain()) + .collect(); + assert_eq!(names, ["c", "a"]); + assert!(overlay.should_create_world_fog()); + overlay.remove(2); + assert!(!overlay.should_create_world_fog()); + } +} diff --git a/crates/horizon-client/src/bossbar.rs b/crates/horizon-client/src/bossbar.rs index eab31a5e5..2ecdb25e9 100644 --- a/crates/horizon-client/src/bossbar.rs +++ b/crates/horizon-client/src/bossbar.rs @@ -14,40 +14,64 @@ pub const STYLES: [&str; 5] = [ "notched_12", "notched_20", ]; -/// `BossBarColor.getFormatting`. +/// `BossBarColor.getFormatting`. Purple is dark blue in 26.3. pub fn color_rgb(color: &str) -> u32 { let name = match color { "pink" => "red", "red" => "dark_red", - "purple" => "dark_purple", + "purple" => "dark_blue", other => other, }; text::named_color(name).unwrap_or(text::WHITE) } +/// A version-4 shaped id from a resource id. Saved boss events do not keep +/// their UUID (`CustomBossEvents` mints a new one on load). +pub fn stable_uuid(id: &str) -> u128 { + let mut h = 0xcbf29ce484222325u64; + for b in id.as_bytes() { + h ^= u64::from(*b); + h = h.wrapping_mul(0x100000001b3); + } + let most = (h as i64) & -61441 | 16384; + let least = (h.rotate_left(17) as i64) & 4_611_686_018_427_387_903 | i64::MIN; + ((most as u64 as u128) << 64) | (least as u64 as u128) +} + #[derive(Clone, Debug, PartialEq)] pub struct BossBar { pub id: String, + /// The `ServerBossEvent` UUID. Not saved. + pub uuid: u128, pub name: Comp, pub color: String, pub style: String, pub value: i32, pub max: i32, + /// `ServerBossEvent.visible`. A new bar is visible; nobody sees it until + /// a player is added. pub visible: bool, - /// Whether the (single) local player is in the bar's player set. - pub player: bool, + pub darken: bool, + pub music: bool, + pub fog: bool, + /// `CustomBossEvent.players`, the UUIDs told about the bar. + pub players: Vec<[i32; 4]>, } impl BossBar { pub fn new(id: &str, name: Comp) -> Self { Self { id: id.to_owned(), + uuid: stable_uuid(id), name, color: "white".into(), style: "progress".into(), value: 0, max: 100, visible: true, - player: false, + darken: false, + music: false, + fog: false, + players: Vec::new(), } } /// `CustomBossEvent.getDisplayName`. @@ -91,31 +115,34 @@ impl BossBars { pub fn ids(&self) -> Vec { self.bars.iter().map(|b| b.id.clone()).collect() } - /// The saved compound; the player's UUID stands for "the local player". - pub fn pack(&self, player: Option<[i32; 4]>) -> Tag { + /// The saved compound (`CustomBossEvent.Packed`). + pub fn pack(&self) -> Tag { let mut c = Compound::new(); for b in &self.bars { - let mut e = vec![ - ("Name", json_to_tag(&b.name)), - ("Visible", Tag::Byte(i8::from(b.visible))), - ("Value", Tag::Int(b.value)), - ("Max", Tag::Int(b.max)), - ("Color", Tag::String(b.color.as_str().into())), - ("Overlay", Tag::String(b.style.as_str().into())), - ("DarkenScreen", Tag::Byte(0)), - ("PlayBossMusic", Tag::Byte(0)), - ("CreateWorldFog", Tag::Byte(0)), - ]; - let players = match (b.player, player) { - (true, Some(u)) => vec![Tag::IntArray(u.to_vec())], - _ => Vec::new(), - }; - e.push(("Players", Tag::List(players))); - c.insert(b.id.as_str().into(), Tag::compound(e)); + let players = b + .players + .iter() + .map(|u| Tag::IntArray(u.to_vec())) + .collect(); + c.insert( + b.id.as_str().into(), + Tag::compound([ + ("Name", json_to_tag(&b.name)), + ("Visible", Tag::Byte(i8::from(b.visible))), + ("Value", Tag::Int(b.value)), + ("Max", Tag::Int(b.max)), + ("Color", Tag::String(b.color.as_str().into())), + ("Overlay", Tag::String(b.style.as_str().into())), + ("DarkenScreen", Tag::Byte(i8::from(b.darken))), + ("PlayBossMusic", Tag::Byte(i8::from(b.music))), + ("CreateWorldFog", Tag::Byte(i8::from(b.fog))), + ("Players", Tag::List(players)), + ]), + ); } Tag::Compound(c) } - pub fn unpack(data: &Tag, player: Option<[i32; 4]>) -> Self { + pub fn unpack(data: &Tag) -> Self { let mut bars = Vec::new(); if let Tag::Compound(c) = data { for (id, e) in c { @@ -130,21 +157,30 @@ impl BossBars { Some(Tag::Byte(v)) => i32::from(*v), _ => d, }; - let in_players = match (get("Players"), player) { - (Some(Tag::List(l)), Some(u)) => l + let players = match get("Players") { + Some(Tag::List(l)) => l .iter() - .any(|t| matches!(t, Tag::IntArray(a) if a.as_slice() == u)), - _ => false, + .filter_map(|t| match t { + Tag::IntArray(a) if a.len() == 4 => Some([a[0], a[1], a[2], a[3]]), + _ => None, + }) + .collect(), + _ => Vec::new(), }; + let id = id.to_string_lossy(); bars.push(BossBar { - id: id.to_string_lossy(), + uuid: stable_uuid(&id), + id, name: get("Name").map_or_else(|| literal(""), tag_to_json), color: text("Color", "white"), style: text("Overlay", "progress"), value: num("Value", 0), max: num("Max", 100), visible: num("Visible", 0) != 0, - player: in_players, + darken: num("DarkenScreen", 0) != 0, + music: num("PlayBossMusic", 0) != 0, + fog: num("CreateWorldFog", 0) != 0, + players, }); } } @@ -167,17 +203,15 @@ mod tests { bar.value = 25; bar.max = 50; bar.visible = true; - bar.player = true; - let uuid = Some([1, 2, 3, 4]); - let back = BossBars::unpack(&b.pack(uuid), uuid); + bar.darken = true; + bar.players = vec![[1, 2, 3, 4]]; + let back = BossBars::unpack(&b.pack()); assert_eq!(back, b); - // Another player's UUID does not include the local player. - assert!(!BossBars::unpack(&b.pack(uuid), Some([9, 9, 9, 9])).bars[0].player); let bar = b.get("test:x").unwrap(); assert_eq!(bar.progress(), 0.5); assert_eq!(bar.display_name().plain(), "chat.square_brackets"); assert_eq!(color_rgb("pink"), text::RED); - assert_eq!(color_rgb("purple"), 0xAA00AA); + assert_eq!(color_rgb("purple"), text::named_color("dark_blue").unwrap()); b.remove("test:x"); assert!(b.bars.is_empty()); } diff --git a/crates/horizon-client/src/fog.rs b/crates/horizon-client/src/fog.rs index 942bae556..11ffda151 100644 --- a/crates/horizon-client/src/fog.rs +++ b/crates/horizon-client/src/fog.rs @@ -198,6 +198,8 @@ pub struct FogInputs<'a> { pub blindness: Option<(i32, bool)>, /// The darkness effect's blend factor, while the effect is on. pub darkness: Option, + /// `GameRenderer.bossOverlayWorldDarkening`: a wither's bar dims the fog. + pub darken_world: f32, /// `BossHealthOverlay.shouldCreateWorldFog`: a boss bar with /// `createWorldFog` is shown (the Ender Dragon's). pub boss_world_fog: bool, @@ -263,6 +265,13 @@ pub fn setup_fog(tables: &FogTables, state: &FogState, input: &FogInputs) -> Fog let brightness = (1.0 - darkness) * (1.0 - darkness); color = color.map(|c| c * brightness); } + // FogRenderer.computeFogColor: a boss bar's world darkening. + if input.darken_world > 0.0 { + let t = input.darken_world; + color[0] += (color[0] * 0.7 - color[0]) * t; + color[1] += (color[1] * 0.6 - color[1]) * t; + color[2] += (color[2] * 0.6 - color[2]) * t; + } let brighten = if eye_in_water { water_vision } else { 0.0 }; if color.iter().all(|&c| c != 0.0) { let scale = 1.0 / color[0].max(color[1]).max(color[2]); @@ -394,6 +403,7 @@ mod tests { skybox: true, blindness: None, darkness: None, + darken_world: 0.0, boss_world_fog: false, } } @@ -422,6 +432,25 @@ mod tests { assert_eq!(water.environmental_start, -8.0); } #[test] + fn boss_darkening_dims_fog_color() { + // FogRenderer.computeFogColor: lerp toward 70/60/60% of each channel. + let sky = Sky { + fog_color: [1.0, 1.0, 1.0], + sky_color: [1.0, 1.0, 1.0], + ..Sky::default() + }; + let tables = FogTables { + water_fog_end: vec![1.0], + }; + let mut input = inputs(&sky); + input.skybox = false; + input.darken_world = 1.0; + let fog = setup_fog(&tables, &FogState::default(), &input); + assert!((fog.color[0] - 0.7).abs() < 1.0e-5); + assert!((fog.color[1] - 0.6).abs() < 1.0e-5); + assert!((fog.color[2] - 0.6).abs() < 1.0e-5); + } + #[test] fn void_darkness_starts_32_above_the_floor() { let sky = Sky { fog_end: 1024.0, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 533973805..f0765e0f6 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1562,6 +1562,8 @@ struct Game<'a> { score: scoreboard::ScoreState, fns: functions::FnState, bosses: bossbars::BossState, + /// `Hud.bossOverlay`: the bars this window is showing. + boss_overlay: horizon_client::boss_overlay::BossOverlay, exec: commands::execute::ExecState, rand_sequences: horizon_client::random_sequences::RandomSequences, border: horizon_client::worldborder::WorldBorder, @@ -4060,6 +4062,8 @@ impl Game<'_> { self.track_experience_display(); // `/tick freeze` stops the world but not the player. let running = self.clock.world_runs(); + // GameRenderer.tick: a wither's bar darkens the world, then fades. + self.boss_overlay.tick_darken(running); if running { self.world.game_time += 1; if self.ui.rules.bool("advance_weather") { @@ -4435,6 +4439,8 @@ impl Game<'_> { }); horizon_client::spans::time("tick_particles", || self.tick_particles()); } + // ServerBossEvent broadcasts, after this level's entities have ticked. + self.publish_boss_bars(); // Minecraft.handleKeybinds: held use repeats only while no item is in // use (a raised shield or a drawn bow places and uses nothing). if self.right @@ -7952,6 +7958,8 @@ impl Game<'_> { self.session_lock = None; horizon_client::crash::clear_detail("World"); self.debug_charts.reset(); + self.boss_overlay.reset(); + self.bosses = Default::default(); self.streaming.paused = true; self.world = World::new(self.res.facts().air, 0); self.player = None; @@ -10095,7 +10103,7 @@ impl Game<'_> { if !self.settings.horizon.fog && !underwater && self.darkness_fog().is_none() - && !self.dragon_bar_shown() + && !self.boss_overlay.should_create_world_fog() && self.potions.effects.get("blindness").is_none() && fog.environmental_end >= (self.streaming.radius * 16) as f32 { @@ -10166,6 +10174,9 @@ impl Game<'_> { darkness: self.darkness_lighting(alpha as f32), night_vision: self.night_vision_intensity(), block_flicker: self.fog.block_light_flicker, + boss_darken: self + .boss_overlay + .darken_amount(self.clock.fraction() as f32), menu_blur: self.menu_blur(), }; let result = match self.renderer.as_mut() { @@ -11953,6 +11964,7 @@ impl<'a> Game<'a> { score: Default::default(), fns: Default::default(), bosses: Default::default(), + boss_overlay: Default::default(), exec: Default::default(), rand_sequences: Default::default(), border: Default::default(), @@ -12680,6 +12692,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> { darkness: (0.0, 0.0), night_vision: 0.0, block_flicker: 0.0, + boss_darken: 0.0, menu_blur: None, } } diff --git a/crates/horizon-client/src/game/bossbars.rs b/crates/horizon-client/src/game/bossbars.rs index ec7b72632..85638da4a 100644 --- a/crates/horizon-client/src/game/bossbars.rs +++ b/crates/horizon-client/src/game/bossbars.rs @@ -1,22 +1,29 @@ //! `/bossbar` (BossBarCommands) and drawing the custom boss bars. use super::{ - Game, - commands::{R, err}, + Dim, Game, + commands::{R, Target, err}, }; use horizon_client::{ + boss_overlay, bossbar::{self, BossBars}, command::{Arg, Context}, - hud_overlays, save, - scoreboard::{self as sb, Comp, comp_text}, + mobs::Species, + save, + scoreboard::{self as sb, Comp, comp_text, json_to_tag, tag_to_json}, scoreboard_cmd::format_list, text::Text, }; +use horizon_core::random::RandomSource; +use horizon_protocol::packets::play::{self, BossAction, Clientbound as C}; use horizon_world::nbt::Tag; +use std::collections::{HashMap, HashSet}; #[derive(Default)] pub(super) struct BossState { pub bars: BossBars, loaded: bool, + /// What each viewer was last sent, so a change becomes one packet. + sent: HashMap>, } fn num(n: impl std::fmt::Display) -> Text { @@ -36,7 +43,7 @@ impl Game<'_> { if let Some(root) = save::read_dat(&self.bossbar_path()) && let Some(data) = root.get("data") { - self.bosses.bars = BossBars::unpack(data, self.level.player_uuid); + self.bosses.bars = BossBars::unpack(data); } self.ui.registries.bossbars = self.bosses.bars.ids(); } @@ -50,7 +57,7 @@ impl Game<'_> { let _ = save::write_dat( &self.bossbar_path(), Tag::compound([ - ("data", self.bosses.bars.pack(self.level.player_uuid)), + ("data", self.bosses.bars.pack()), ("DataVersion", Tag::Int(horizon_world::DATA_VERSION)), ]), ); @@ -68,6 +75,7 @@ impl Game<'_> { b.value = b.value.min(b.max); } } + self.publish_boss_bars(); } fn bar_id(ctx: &Context) -> String { match ctx.get("id") { @@ -86,6 +94,7 @@ impl Game<'_> { self.load_bossbars(); let result = self.bossbar_command(id, ctx); self.ui.registries.bossbars = self.bosses.bars.ids(); + self.publish_boss_bars(); result } fn bossbar_command(&mut self, id: &str, ctx: &Context) -> R { @@ -97,6 +106,10 @@ impl Game<'_> { } let name = self.component_json(ctx, "name")?; self.bosses.bars.add(&bar, name); + if let Some(b) = self.bosses.bars.get_mut(&bar) { + // CustomBossEvents.create: Mth.createInsecureUUID(level.random). + b.uuid = insecure_uuid(&mut self.world.random); + } let shown = self .bosses .bars @@ -173,19 +186,20 @@ impl Game<'_> { i32::from(b.visible) } _ => { - if b.player { - let name = self.target_name(super::commands::Target::Player); - self.feedback(Text::translate( - "commands.bossbar.get.players.some", - &[s, num(1), format_list(vec![name])], - )); - } else { + let names = self.bossbar_player_names(&b.players); + let n = names.len(); + if n == 0 { self.feedback(Text::translate( "commands.bossbar.get.players.none", &[s], )); + } else { + self.feedback(Text::translate( + "commands.bossbar.get.players.some", + &[s, num(n), format_list(names)], + )); } - i32::from(b.player) + n as i32 } }) } @@ -295,31 +309,46 @@ impl Game<'_> { Ok(0) } _ => { - // players [] - let include = if ctx.get("targets").is_some() { - !self.entities(ctx, "targets", true)?.is_empty() + // players []: replace the set. No argument clears it. + let targets = if ctx.get("targets").is_some() { + self.entities(ctx, "targets", true)? } else { - false + Vec::new() }; + let mut uuids = Vec::new(); + let mut names = Vec::new(); + for t in &targets { + let Some(uuid) = self.player_target_uuid(*t) else { + continue; + }; + if !uuids.contains(&uuid) { + uuids.push(uuid); + names.push(self.target_name(*t)); + } + } let b = self.bosses.bars.get_mut(bar).expect("checked"); - if b.player == include { + let mut had = b.players.clone(); + had.sort(); + let mut next = uuids.clone(); + next.sort(); + if had == next { return Err(err("commands.bossbar.set.players.unchanged", &[])); } - b.player = include; + b.players = uuids; + let n = b.players.len(); let s = shown(self); - if include { - let name = self.target_name(super::commands::Target::Player); - self.feedback(Text::translate( - "commands.bossbar.set.players.success.some", - &[s, num(1), format_list(vec![name])], - )); - } else { + if n == 0 { self.feedback(Text::translate( "commands.bossbar.set.players.success.none", &[s], )); + } else { + self.feedback(Text::translate( + "commands.bossbar.set.players.success.some", + &[s, num(targets.len()), format_list(names)], + )); } - Ok(i32::from(include)) + Ok(n as i32) } } } @@ -333,29 +362,455 @@ impl Game<'_> { Ok(self.resolve_component(value)) } - // ---- drawing ------------------------------------------------------------------ + /// Names of the online players in a boss bar's set, in join order. + fn bossbar_player_names(&self, players: &[[i32; 4]]) -> Vec { + self.known_boss_players() + .into_iter() + .filter(|(uuid, _)| players.contains(uuid)) + .map(|(_, name)| name) + .collect() + } + /// The players who can be told about a bar: the one in place, then guests. + fn known_boss_players(&self) -> Vec<([i32; 4], Text)> { + let mut out = Vec::new(); + if self.player.is_some() { + out.push((self.acting_uuid(), self.target_name(Target::Player))); + } + if let Some(host) = &self.lan { + for g in host.hub.guests.iter().filter(|g| g.placed) { + let ints = horizon_client::lan::playerdata::uuid_ints(g.uuid); + if out.iter().any(|(uuid, _)| *uuid == ints) { + continue; + } + out.push((ints, Text::literal(g.name.clone()))); + } + } + out + } + fn player_target_uuid(&self, target: Target) -> Option<[i32; 4]> { + match target { + Target::Player => Some(self.acting_uuid()), + Target::Guest(conn) => self.lan.as_ref().and_then(|h| { + h.hub + .guests + .iter() + .find(|g| g.conn == conn) + .map(|g| horizon_client::lan::playerdata::uuid_ints(g.uuid)) + }), + _ => None, + } + } - /// The visible custom bars (`/bossbar`), after the built-in ones. - pub(super) fn custom_bossbars(&self, bars: &mut Vec) { - for b in self - .bosses - .bars - .bars - .iter() - .filter(|b| b.visible && b.player) - { - bars.push(hud_overlays::BossBar { - name: comp_text(&b.name), - progress: b.progress(), - color: bossbar::COLORS - .iter() - .position(|c| *c == b.color) - .unwrap_or(0), - overlay: bossbar::STYLES - .iter() - .position(|s| *s == b.style) - .unwrap_or(0), + // ---- ServerBossEvent delivery ------------------------------------------------ + + /// Tell every viewer the boss events they should be seeing. The window + /// that simulates the world applies them to its own overlay; everyone + /// else gets `ClientboundBossEventPacket`s. + pub(super) fn publish_boss_bars(&mut self) { + if self.remote.is_some() { + return; + } + self.load_bossbars(); + let now = boss_overlay::now_millis(); + let viewers = self.boss_viewers(); + let live: HashSet = viewers.iter().map(|v| v.uuid).collect(); + self.bosses.sent.retain(|id, _| live.contains(id)); + let mut packets = Vec::new(); + for viewer in &viewers { + let desired = self.boss_events_for(viewer); + let changes = self.diff_boss_events(viewer, &desired); + if viewer.local { + apply_local(&mut self.boss_overlay, &changes, now); + } else if let Some(conn) = viewer.conn { + for change in changes { + packets.push((conn, boss_packet(change))); + } + } + } + if packets.is_empty() { + return; + } + let Some(host) = self.lan.as_ref() else { + return; + }; + for (conn, packet) in &packets { + host.hub.send_to(*conn, packet); + } + } + fn boss_viewers(&self) -> Vec { + let mut out = Vec::new(); + // While `as_guest` has swapped a guest in, the host's own position + // is not in place. Their overlay updates once the tick puts it back. + let local = + self.serving.is_none() && self.options.dedicated.is_none() && self.lan_acting.is_none(); + if local && let Some(p) = &self.player { + let ints = self.level.player_uuid.unwrap_or_else(|| self.acting_uuid()); + out.push(Viewer { + uuid: ints_to_uuid(ints), + ints, + at: [p.position.x, p.position.y, p.position.z], + alive: !p.health.dead_or_dying(), + here: true, + local: true, + conn: None, + view_chunks: self.settings.render_distance, }); } + if let Some(host) = &self.lan { + for g in host.hub.guests.iter().filter(|g| g.placed) { + if out.iter().any(|v| v.uuid == g.uuid) { + continue; + } + out.push(Viewer { + uuid: g.uuid, + ints: horizon_client::lan::playerdata::uuid_ints(g.uuid), + at: g.position, + alive: !g.dead, + here: g.dimension == self.dim.id(), + local: false, + conn: Some(g.conn), + view_chunks: g.view_distance, + }); + } + } + out + } + /// Dragon, withers, the raid and custom bars, in that order. + fn boss_events_for(&self, viewer: &Viewer) -> Vec { + let mut out = Vec::new(); + if viewer.here + && let Some(progress) = self.dragon_boss_progress(viewer.at, viewer.alive) + { + out.push(Offer { + id: bossbar::stable_uuid("minecraft:ender_dragon"), + name: translate_tag("entity.minecraft.ender_dragon"), + progress, + color: 0, + overlay: 0, + darken: false, + music: true, + fog: true, + scope: Scope::Level(self.dim), + }); + } + if viewer.here { + let range = f64::from(10.min(viewer.view_chunks.max(0)) * 16); + for m in self + .mobs + .iter() + .filter(|m| m.species() == Species::Wither && m.alive() && !m.removed) + { + let (dx, dz) = (m.position.x - viewer.at[0], m.position.z - viewer.at[2]); + if dx * dx + dz * dz > range * range { + continue; + } + let progress = if m.extra.counter > 0 { + 1.0 - m.extra.counter as f32 / horizon_client::mobs::wither::INVULNERABLE as f32 + } else { + (m.health / m.attrs.max_health).clamp(0.0, 1.0) + }; + let name = if let Some(text) = &m.custom_name_text { + json_to_tag(&text.component()) + } else if let Some(name) = &m.custom_name { + Tag::String(name.as_str().into()) + } else { + translate_tag("entity.minecraft.wither") + }; + out.push(Offer { + id: super::lan::entity_uuid(m.id), + name, + progress, + color: 5, + overlay: 0, + darken: true, + music: false, + fog: false, + scope: Scope::Level(self.dim), + }); + } + } + if viewer.here + && let Some((id, name, progress)) = self.raid_boss_at(viewer.at, viewer.alive) + { + out.push(Offer { + id: bossbar::stable_uuid(&format!("raid:{id}")), + name, + progress, + color: 2, + overlay: 2, + darken: false, + music: false, + fog: false, + scope: Scope::Level(self.dim), + }); + } + for b in &self.bosses.bars.bars { + if !b.visible || !b.players.contains(&viewer.ints) { + continue; + } + out.push(Offer { + id: b.uuid, + name: json_to_tag(&b.name), + progress: b.progress(), + color: color_index(&b.color) as u8, + overlay: style_index(&b.style) as u8, + darken: b.darken, + music: b.music, + fog: b.fog, + scope: Scope::Global, + }); + } + out + } + fn diff_boss_events(&mut self, viewer: &Viewer, desired: &[Offer]) -> Vec { + let full = viewer.local; + let dim = self.dim; + let sent = self.bosses.sent.entry(viewer.uuid).or_default(); + let mut changes = Vec::new(); + let gone: Vec = sent + .iter() + .filter(|(id, prev)| { + let owned = full || prev.scope == Scope::Global || prev.scope == Scope::Level(dim); + owned && !desired.iter().any(|e| e.id == **id) + }) + .map(|(id, _)| *id) + .collect(); + for id in gone { + sent.remove(&id); + changes.push(Change::Remove(id)); + } + for event in desired { + let snap = event.snap(); + match sent.get(&event.id).map(|s| s.snap.clone()) { + None => { + sent.insert( + event.id, + Sent { + snap, + scope: event.scope, + }, + ); + changes.push(Change::Add(event.clone())); + } + Some(prev) => { + if prev.progress != snap.progress { + changes.push(Change::Progress(event.id, snap.progress)); + } + if prev.name != snap.name { + changes.push(Change::Name(event.id, snap.name.clone())); + } + if prev.color != snap.color || prev.overlay != snap.overlay { + changes.push(Change::Style(event.id, snap.color, snap.overlay)); + } + if prev.darken != snap.darken + || prev.music != snap.music + || prev.fog != snap.fog + { + changes.push(Change::Properties( + event.id, + snap.darken, + snap.music, + snap.fog, + )); + } + sent.insert( + event.id, + Sent { + snap, + scope: event.scope, + }, + ); + } + } + } + changes + } + /// `ClientPacketListener.handleBossUpdate`. + pub(super) fn apply_boss_event(&mut self, packet: play::BossEvent) { + let now = boss_overlay::now_millis(); + let ord = |v: i32| v.clamp(0, 255) as u8; + match packet.action { + BossAction::Add { + name, + progress, + color, + overlay, + darken, + music, + fog, + } => self.boss_overlay.add( + packet.id, + component_text(&name), + progress, + ord(color), + ord(overlay), + darken, + music, + fog, + now, + ), + BossAction::Remove => self.boss_overlay.remove(packet.id), + BossAction::UpdateProgress { progress } => { + self.boss_overlay.set_progress(packet.id, progress, now) + } + BossAction::UpdateName { name } => { + self.boss_overlay.set_name(packet.id, component_text(&name)) + } + BossAction::UpdateStyle { color, overlay } => { + self.boss_overlay + .set_style(packet.id, ord(color), ord(overlay)) + } + BossAction::UpdateProperties { darken, music, fog } => self + .boss_overlay + .set_properties(packet.id, darken, music, fog), + } } } + +/// `Mth.createInsecureUUID`. +fn insecure_uuid(random: &mut impl RandomSource) -> u128 { + let most = random.next_long() & -61441 | 16384; + let least = random.next_long() & 4_611_686_018_427_387_903 | i64::MIN; + ((most as u64 as u128) << 64) | (least as u64 as u128) +} +fn ints_to_uuid(ints: [i32; 4]) -> u128 { + ints.iter() + .fold(0u128, |acc, &i| (acc << 32) | u128::from(i as u32)) +} +fn translate_tag(key: &str) -> Tag { + Tag::compound([("translate", Tag::String(key.into()))]) +} +fn color_index(color: &str) -> usize { + bossbar::COLORS + .iter() + .position(|c| *c == color) + .unwrap_or(6) +} +fn style_index(style: &str) -> usize { + bossbar::STYLES + .iter() + .position(|s| *s == style) + .unwrap_or(0) +} +fn component_text(tag: &Tag) -> Text { + comp_text(&tag_to_json(tag)) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Scope { + Global, + Level(Dim), +} +#[derive(Clone)] +struct Snap { + name: Tag, + progress: f32, + color: u8, + overlay: u8, + darken: bool, + music: bool, + fog: bool, +} +struct Sent { + snap: Snap, + scope: Scope, +} +struct Viewer { + uuid: u128, + ints: [i32; 4], + at: [f64; 3], + alive: bool, + here: bool, + local: bool, + conn: Option, + view_chunks: i32, +} +#[derive(Clone)] +struct Offer { + id: u128, + name: Tag, + progress: f32, + color: u8, + overlay: u8, + darken: bool, + music: bool, + fog: bool, + scope: Scope, +} +impl Offer { + fn snap(&self) -> Snap { + Snap { + name: self.name.clone(), + progress: self.progress, + color: self.color, + overlay: self.overlay, + darken: self.darken, + music: self.music, + fog: self.fog, + } + } +} +enum Change { + Add(Offer), + Remove(u128), + Progress(u128, f32), + Name(u128, Tag), + Style(u128, u8, u8), + Properties(u128, bool, bool, bool), +} +fn apply_local(overlay: &mut boss_overlay::BossOverlay, changes: &[Change], now: u128) { + for change in changes { + match change { + Change::Add(e) => overlay.add( + e.id, + component_text(&e.name), + e.progress, + e.color, + e.overlay, + e.darken, + e.music, + e.fog, + now, + ), + Change::Remove(id) => overlay.remove(*id), + Change::Progress(id, progress) => overlay.set_progress(*id, *progress, now), + Change::Name(id, name) => overlay.set_name(*id, component_text(name)), + Change::Style(id, color, overlay_style) => { + overlay.set_style(*id, *color, *overlay_style) + } + Change::Properties(id, darken, music, fog) => { + overlay.set_properties(*id, *darken, *music, *fog) + } + } + } +} +fn boss_packet(change: Change) -> C { + let (id, action) = match change { + Change::Add(e) => ( + e.id, + BossAction::Add { + name: e.name, + progress: e.progress, + color: i32::from(e.color), + overlay: i32::from(e.overlay), + darken: e.darken, + music: e.music, + fog: e.fog, + }, + ), + Change::Remove(id) => (id, BossAction::Remove), + Change::Progress(id, progress) => (id, BossAction::UpdateProgress { progress }), + Change::Name(id, name) => (id, BossAction::UpdateName { name }), + Change::Style(id, color, overlay) => ( + id, + BossAction::UpdateStyle { + color: i32::from(color), + overlay: i32::from(overlay), + }, + ), + Change::Properties(id, darken, music, fog) => { + (id, BossAction::UpdateProperties { darken, music, fog }) + } + }; + C::BossEvent(play::BossEvent { id, action }) +} diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index c6f5d419b..54b260c67 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -12,7 +12,6 @@ use horizon_client::{ hud_layout, hud_overlays, mesher::Vertex, particles::{ParticleOptions, ParticleType}, - text::Text, }; use horizon_core::{ geometry::{Aabb, Vec3}, @@ -2157,23 +2156,12 @@ impl Game<'_> { }); } } - /// `BossHealthOverlay`: the dragon's pink bar, then the withers', the - /// raids' and the custom bars, in that order. + /// `BossHealthOverlay.extractRenderState`: whatever `publish_boss_bars` + /// (or a server's packets) put on this client's overlay. pub(super) fn draw_boss_bars(&self, batch: &mut HudBatch) { - let mut bars = Vec::new(); - if let Some(d) = self.dragon.as_ref().filter(|_| self.dragon_bar_shown()) { - bars.push(hud_overlays::BossBar { - name: Text::literal( - self.translate("entity.minecraft.ender_dragon", "Ender Dragon"), - ), - progress: (d.health / MAX_HEALTH).clamp(0.0, 1.0), - color: 0, - overlay: 0, - }); - } - self.wither_bars(&mut bars); - self.raid_bars(&mut bars); - self.custom_bossbars(&mut bars); + let bars = self + .boss_overlay + .bars(horizon_client::boss_overlay::now_millis()); let draws = hud_overlays::boss_overlay( batch.width as i32, batch.height as i32, @@ -2182,14 +2170,26 @@ impl Game<'_> { ); hud_layout::paint(batch, &self.gui.atlas, &draws); } - /// The dragon fight's boss bar shows (`EnderDragonFight.dragonEvent`, - /// with `setCreateWorldFog`). - pub(super) fn dragon_bar_shown(&self) -> bool { - self.dim == Dim::End && self.dragon.is_some() + /// The dragon fight's bar for a player at `at` + /// (`EnderDragonFight.dragonEvent`, visible while the fight is not won + /// and the player is alive within 192 blocks of (0, 128, 0)). + pub(super) fn dragon_boss_progress(&self, at: [f64; 3], alive: bool) -> Option { + if self.dim != Dim::End || !alive || !self.fight.loaded || self.fight.killed { + return None; + } + let near = at[0].powi(2) + (at[1] - 128.0).powi(2) + at[2].powi(2) <= 192.0 * 192.0; + if !near { + return None; + } + Some( + self.dragon + .as_ref() + .map_or(1.0, |d| (d.health / MAX_HEALTH).clamp(0.0, 1.0)), + ) } - /// `music.dragon` while the boss bar plays music. + /// `BossHealthOverlay.shouldPlayMusic`. pub(super) fn boss_music(&self) -> bool { - self.dim == Dim::End && self.dragon.is_some() || self.wither_near() + self.boss_overlay.should_play_music() } } pub(super) struct DragonFireball { diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index bff4a9918..bedca5708 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -6,7 +6,6 @@ use super::{Dim, Game}; use horizon_client::mobs::villager as mobs_villager; use horizon_client::{ effects::{EffectInstance, OmenTick}, - hud_overlays, mobs::{ Mob, Species, raider, spawn_rules::{self, SpawnLevel}, @@ -15,9 +14,9 @@ use horizon_client::{ }, patrol::{GameplayAttributes, Member, PatrolLevel, PatrolSpawner}, raid::{self, Action, BarName, RaidLevel, RaidPlayer, RaiderInfo, RaiderType, Raids, Spawn}, - text::Text, }; use horizon_core::{geometry::Vec3, random::RandomSource}; +use horizon_world::nbt::Tag; use std::collections::{HashMap, HashSet}; /// Patrol and raid state owned by the game. @@ -1063,37 +1062,18 @@ impl Game<'_> { } } - /// The raid boss bars: red and notched in tens, with the raid's title. - pub(super) fn raid_bars(&self, bars: &mut Vec) { - for raid in self.raiding.raids.map.values() { - if !raid.bar.visible || !raid.bar.player || raid.is_stopped() { - continue; - } - let title = self.translate("event.minecraft.raid", "Raid"); - let name = match raid.bar.name { - BarName::Raid => title, - BarName::Remaining(n) => format!( - "{title} - {}", - self.translate( - "event.minecraft.raid.raiders_remaining", - "Raiders Remaining: %s" - ) - .replace("%s", &n.to_string()) - ), - BarName::Victory => { - self.translate("event.minecraft.raid.victory.full", "Raid - Victory") - } - BarName::Defeat => { - self.translate("event.minecraft.raid.defeat.full", "Raid - Defeat") - } - }; - bars.push(hud_overlays::BossBar { - name: Text::literal(name), - progress: raid.bar.progress, - color: 2, - overlay: 2, - }); + /// The raid bar a living player at `at` is in (`Raid.getPlayers`): red, + /// notched in tens. The name is the translate component the client draws. + pub(super) fn raid_boss_at(&self, at: [f64; 3], alive: bool) -> Option<(i32, Tag, f32)> { + if !alive || self.dim != Dim::Overworld { + return None; } + let block = block_of(Vec3::new(at[0], at[1], at[2])); + let (id, raid) = self.raiding.raids.nearby(block)?; + if !raid.bar.visible || raid.is_stopped() { + return None; + } + Some((id, raid_name_tag(raid.bar.name), raid.bar.progress)) } /// A firework a villager launches to celebrate (`CelebrateVillagersSurvivedRaid`). pub(super) fn villager_firework(&mut self, at: [f64; 3], color: usize, flight: u8) { @@ -1239,6 +1219,36 @@ impl Game<'_> { } } +/// `Raid.raidEvent`'s name: the raid title, the remaining-raiders line, or +/// the victory and defeat lines. +fn raid_name_tag(name: BarName) -> Tag { + let key = |k: &str| Tag::compound([("translate", Tag::String(k.into()))]); + match name { + BarName::Raid => key("event.minecraft.raid"), + BarName::Victory => key("event.minecraft.raid.victory.full"), + BarName::Defeat => key("event.minecraft.raid.defeat.full"), + BarName::Remaining(n) => Tag::compound([ + ("translate", Tag::String("event.minecraft.raid".into())), + ( + "extra", + Tag::List(vec![ + Tag::String(" - ".into()), + Tag::compound([ + ( + "translate", + Tag::String("event.minecraft.raid.raiders_remaining".into()), + ), + ( + "with", + Tag::List(vec![Tag::String(n.to_string().as_str().into())]), + ), + ]), + ]), + ), + ]), + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index da0def0fb..9c0504a2c 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -369,6 +369,7 @@ impl Game<'_> { } self.apply_settings(); self.clear_waypoints(); + self.boss_overlay.reset(); self.remote = Some(Remote { session, brand: "unknown".into(), @@ -450,6 +451,7 @@ impl Game<'_> { self.extras_left(); } self.clear_waypoints(); + self.boss_overlay.reset(); if let Some(mut r) = self.remote.take() { r.session.disconnect(); } @@ -2640,6 +2642,7 @@ impl Game<'_> { } // ClientPacketListener.setActionBarText, setTitleText, // setSubtitleText, setTitlesAnimation and handleTitlesClear. + C::BossEvent(p) => self.apply_boss_event(p), C::SetActionBarText(p) => self.titles.set_overlay(remote_text(&p.text), false), C::SetTitleText(p) => self.titles.set_title(remote_text(&p.text)), C::SetSubtitleText(p) => self.titles.set_subtitle(remote_text(&p.text)), @@ -3053,6 +3056,7 @@ impl Game<'_> { // Minecraft.tick: TickRateManager.tick; ClientLevel.tickTime advances // the time only while the level runs normally. let running = self.clock.world_runs(); + self.boss_overlay.tick_darken(running); if running { self.world.game_time += 1; self.remote_clock_tick(); diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index 331db8833..e013c8d29 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -100,7 +100,10 @@ impl Game<'_> { skybox: self.dim == Dim::Overworld, blindness: None, darkness: self.darkness_fog(), - boss_world_fog: self.dragon_bar_shown(), + darken_world: self + .boss_overlay + .darken_amount(self.clock.fraction() as f32), + boss_world_fog: self.boss_overlay.should_create_world_fog(), }, ) } diff --git a/crates/horizon-client/src/game/wither.rs b/crates/horizon-client/src/game/wither.rs index 7b86dc527..91fe91b00 100644 --- a/crates/horizon-client/src/game/wither.rs +++ b/crates/horizon-client/src/game/wither.rs @@ -2,10 +2,8 @@ //! its boss bar, and its skulls hitting and exploding. use super::Game; use horizon_client::{ - hud_overlays, mobs::{Damage, DamageKind, Species, Who}, projectiles::{Projectile, ProjectileKind}, - text::Text, }; impl Game<'_> { @@ -78,45 +76,6 @@ impl Game<'_> { } Ok(()) } - /// The wither boss bars (purple), within range. - pub(super) fn wither_bars(&self, bars: &mut Vec) { - let Some(p) = self.player.as_ref() else { - return; - }; - for m in self - .mobs - .iter() - .filter(|m| m.species() == Species::Wither && m.alive()) - { - if m.position.distance_squared(p.position) > 64.0 * 64.0 { - continue; - } - let progress = if m.extra.counter > 0 { - 1.0 - m.extra.counter as f32 / horizon_client::mobs::wither::INVULNERABLE as f32 - } else { - (m.health / m.attrs.max_health).clamp(0.0, 1.0) - }; - let name = m - .custom_name - .clone() - .unwrap_or_else(|| self.translate("entity.minecraft.wither", "Wither")); - bars.push(hud_overlays::BossBar { - name: Text::literal(name), - progress, - color: 5, - overlay: 0, - }); - } - } - pub(super) fn wither_near(&self) -> bool { - self.player.as_ref().is_some_and(|p| { - self.mobs.iter().any(|m| { - m.species() == Species::Wither - && m.alive() - && m.position.distance_squared(p.position) <= 64.0 * 64.0 - }) - }) - } /// `WitherSkull.onHitEntity` / `onHit`: 8 damage (healing the wither 5 /// when it kills), withering for 10 seconds, then a power 1 blast. pub(super) fn wither_skull_hit( diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index c369ee1c7..005e9ce90 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -268,6 +268,8 @@ pub struct Frame<'a> { pub night_vision: f32, /// Torch flicker added to the block light factor of 1.4. pub block_flicker: f32, + /// `lightmap.fsh` BossOverlayWorldDarkeningFactor (a wither's bar). + pub boss_darken: f32, /// `Screen.extractBlurredBackground`: blur the frame by this radius /// (`menuBackgroundBlurriness`) before the screen is drawn over it. pub menu_blur: Option, @@ -2778,6 +2780,7 @@ impl Renderer { gamma: f32, night_vision: f32, flicker: f32, + boss_darken: f32, ) { // lightmap.fsh: per (block, sky) level. let brightness = |level: f32| level / (4.0 - 3.0 * level); @@ -2795,6 +2798,8 @@ impl Renderer { let parabolic = (2.0 * block_level - 1.0).powi(2); let block_color = Vec3::from(sky.block_light_tint).lerp(Vec3::ONE, 0.9 * parabolic); color += block_color * block_brightness; + // lightmap.fsh: a boss bar mixes the light toward 70/60/60%. + color = color.lerp(color * Vec3::new(0.7, 0.6, 0.6), boss_darken); color -= Vec3::splat(darkness); color = color.clamp(Vec3::ZERO, Vec3::ONE); let max = color.max_element().max(1e-6); @@ -2909,6 +2914,7 @@ impl Renderer { (self.gamma - frame.darkness.0).max(0.0), frame.night_vision, frame.block_flicker, + frame.boss_darken, ); let view_proj = self.view_projection(frame); if frame.title { diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 3c741e963..43a399ef0 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -24,6 +24,7 @@ pub mod block_entity_render; pub mod block_transform; pub mod blocks; pub mod border_render; +pub mod boss_overlay; pub mod bossbar; pub mod breaking; pub mod brewing; diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 206ed9aff..7dd8156c4 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -1580,6 +1580,125 @@ impl Codec> for StatList { } } +/// `ClientboundBossEventPacket` (`boss_event`). +#[derive(Clone, Debug, PartialEq)] +pub enum BossAction { + Add { + name: Tag, + progress: f32, + /// `BossBarColor` ordinal. + color: i32, + /// `BossBarOverlay` ordinal. + overlay: i32, + darken: bool, + music: bool, + fog: bool, + }, + Remove, + UpdateProgress { + progress: f32, + }, + UpdateName { + name: Tag, + }, + UpdateStyle { + color: i32, + overlay: i32, + }, + UpdateProperties { + darken: bool, + music: bool, + fog: bool, + }, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct BossEvent { + pub id: u128, + pub action: BossAction, +} +fn boss_flags(darken: bool, music: bool, fog: bool) -> u8 { + u8::from(darken) | (u8::from(music) << 1) | (u8::from(fog) << 2) +} +fn split_flags(flags: u8) -> (bool, bool, bool) { + (flags & 1 != 0, flags & 2 != 0, flags & 4 != 0) +} +impl Codec for BossEvent { + fn read(r: &mut Reader) -> Result { + let id = r.uuid()?; + let action = match r.varint()? { + 0 => { + let name = r.nbt()?; + let progress = r.f32()?; + let color = r.varint()?; + let overlay = r.varint()?; + let (darken, music, fog) = split_flags(r.u8()?); + BossAction::Add { + name, + progress, + color, + overlay, + darken, + music, + fog, + } + } + 1 => BossAction::Remove, + 2 => BossAction::UpdateProgress { progress: r.f32()? }, + 3 => BossAction::UpdateName { name: r.nbt()? }, + 4 => BossAction::UpdateStyle { + color: r.varint()?, + overlay: r.varint()?, + }, + 5 => { + let (darken, music, fog) = split_flags(r.u8()?); + BossAction::UpdateProperties { darken, music, fog } + } + op => return Err(Error::new(format!("unknown boss event operation {op}"))), + }; + Ok(BossEvent { id, action }) + } + fn write(v: &BossEvent, w: &mut Writer) { + w.uuid(v.id); + match &v.action { + BossAction::Add { + name, + progress, + color, + overlay, + darken, + music, + fog, + } => { + w.varint(0); + w.nbt(name); + w.f32(*progress); + w.varint(*color); + w.varint(*overlay); + w.u8(boss_flags(*darken, *music, *fog)); + } + BossAction::Remove => w.varint(1), + BossAction::UpdateProgress { progress } => { + w.varint(2); + w.f32(*progress); + } + BossAction::UpdateName { name } => { + w.varint(3); + w.nbt(name); + } + BossAction::UpdateStyle { color, overlay } => { + w.varint(4); + w.varint(*color); + w.varint(*overlay); + } + BossAction::UpdateProperties { darken, music, fog } => { + w.varint(5); + w.u8(boss_flags(*darken, *music, *fog)); + } + } + } +} + packet_enum!(Clientbound, crate::ids::play::clientbound { BundleDelimiter(Empty) = BUNDLE_DELIMITER, AddEntity(AddEntity) = ADD_ENTITY, @@ -1590,6 +1709,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { BlockEntityData(BlockEntityData) = BLOCK_ENTITY_DATA, BlockEvent(BlockEvent) = BLOCK_EVENT, BlockUpdate(BlockUpdate) = BLOCK_UPDATE, + BossEvent(BossEvent) = BOSS_EVENT, ChangeDifficulty(ChangeDifficulty) = CHANGE_DIFFICULTY, ChunkBatchFinished(ChunkBatchFinished) = CHUNK_BATCH_FINISHED, ChunkBatchStart(Empty) = CHUNK_BATCH_START, @@ -2860,4 +2980,40 @@ mod tests { w.varint(101); assert!(BookPages::read(&mut Reader::new(&w.data)).is_err()); } + fn boss_event_round_trips() { + let add = Clientbound::BossEvent(BossEvent { + id: 0x0123_4567_89ab_cdef_fedc_ba98_7654_3210, + action: BossAction::Add { + name: Tag::String("Wither".into()), + progress: 0.5, + color: 5, + overlay: 0, + darken: true, + music: false, + fog: true, + }, + }); + let body = add.encode(); + // Packet id 9, then the uuid, operation 0, and the property byte + // (darken 1, fog 4). + assert_eq!(body[0], 9); + assert_eq!(*body.last().unwrap(), 5); + round_trip(add, Clientbound::encode, Clientbound::decode); + round_trip( + Clientbound::BossEvent(BossEvent { + id: 7, + action: BossAction::UpdateProgress { progress: 0.25 }, + }), + Clientbound::encode, + Clientbound::decode, + ); + round_trip( + Clientbound::BossEvent(BossEvent { + id: 7, + action: BossAction::Remove, + }), + Clientbound::encode, + Clientbound::decode, + ); + } } From 90b5e162ae0f586d9494a68a86319400bb75db9c Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Sun, 25 Oct 2026 00:38:39 +0500 Subject: [PATCH 03/16] Play a placed block's sound once for its placer BlockItem.place plays it with playSound(player, ...): the server sends it to the others, and the placer's client plays it as its block appears. The server sent it to the placer too, so each block sounded twice. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/lan_actions.rs | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 5bee2af96..dabd5c2a6 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -2439,6 +2439,32 @@ impl Game<'_> { .map_or(&[][..], |log| log.get(logged..).unwrap_or(&[])) .to_vec(); let facts = self.res.facts(); + // BlockItem.place: `playSound(player, ...)`, for the others only. The + // placer's client plays it as its block appears. + let placed: Vec<([f64; 3], String)> = changed + .iter() + .map(|&(x, y, z)| { + let at = [f64::from(x) + 0.5, f64::from(y) + 0.5, f64::from(z) + 0.5]; + let name = &facts.get(self.world.block(x, y, z)).sounds.place; + (at, name.trim_start_matches("minecraft:").to_owned()) + }) + .collect(); + if let Some(capture) = self.audio.capture.as_mut() { + let mut i = heard.min(capture.len()); + while i < capture.len() { + let (name, at, ..) = &capture[i]; + let place = placed + .iter() + .any(|(p, n)| p == at && name.trim_start_matches("minecraft:") == n.as_str()); + if place { + let (name, at, volume, pitch) = capture.remove(i); + let source = horizon_client::settings::sound_source(&name) as i32; + host.hub.sound(&name, at, volume, pitch, source, Some(conn)); + } else { + i += 1; + } + } + } if changed.is_empty() || !changed.iter().all(|&(x, y, z)| { super::remote::hand_operated(&facts.get(self.world.block(x, y, z)).name) From a5f5d8df34293f561e0bb102d1e74f1ae1fce55d Mon Sep 17 00:00:00 2001 From: socksprox Date: Sat, 24 Oct 2026 21:22:42 +0200 Subject: [PATCH 04/16] Server packs: the download progress toast #1570 landed the client pack manager without vanilla's PackDownloadNotificationComponent: the SystemToast that follows a download with download.pack.progress.percent or .bytes and stays as download.pack.failed when a batch fails. The download queue reports requestStart/downloadedBytes/downloadFinished on a channel (vanilla's DownloadProgressListener), the game ticks them into a toast it slides in for the vanilla 5 seconds with the toast in/out sounds. Co-Authored-By: Devin --- crates/horizon-client/src/game.rs | 1 + .../horizon-client/src/game/server_packs.rs | 139 +++++++++++++++++- .../src/server_packs/download.rs | 81 ++++++++-- crates/horizon-client/src/title.rs | 2 +- 4 files changed, 204 insertions(+), 19 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index bf8327cc1..e162c9e0f 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5034,6 +5034,7 @@ impl Game<'_> { Screen::Playing | Screen::Options | Screen::Win => {} } self.draw_toasts(&mut batch); + self.draw_pack_toast(&mut batch); self.remote_hud(&mut batch); self.draw_sign_editor(&mut batch); self.draw_book(&mut batch); diff --git a/crates/horizon-client/src/game/server_packs.rs b/crates/horizon-client/src/game/server_packs.rs index 6c891a831..6fdec751e 100644 --- a/crates/horizon-client/src/game/server_packs.rs +++ b/crates/horizon-client/src/game/server_packs.rs @@ -12,10 +12,11 @@ use horizon_client::{ scoreboard::{comp_text, tag_to_json}, server_packs::{Prompt, ServerPacks, action, download, parse_sha1, valid_url}, text::{Text, named_color}, + toasts::Slide, ui, }; use horizon_protocol::{packets::configuration::ResourcePackPush, servers}; -use std::path::PathBuf; +use std::{path::PathBuf, sync::mpsc::Receiver}; /// `ClientCommonPacketListenerImpl.PackConfirmScreen`: the packs it asks /// about, whether the last one is required, and the server's message. @@ -75,6 +76,32 @@ pub(super) struct ServerPackState { user: (String, u128), /// The packs loaded on top of the player's own, bottom first. pub(super) active: Vec, + /// `packDownloadNotifier` (`PackDownloadNotificationComponent`): the + /// toast while packs download; `downloadFinished` hides it, a failed + /// batch turns it into `download.pack.failed` until it slides out. + toast: Option, + toast_rx: Option>, +} +/// The download toast: vanilla's `SystemToast` `download.pack.title` with the +/// running progress, `download.pack.failed` when a batch fails. +#[derive(Default)] +struct PackToast { + slide: Slide, + /// `downloadedBytes`: the bytes the request in flight has written. + bytes: u64, + /// Its Content-Length — the progress is a percent, else a byte count. + size: Option, + failed: bool, +} +/// `Unit.humanReadable`, for `download.pack.progress.bytes`. +fn human_readable(bytes: u64) -> String { + const UNITS: [&str; 7] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"]; + let (mut value, mut unit) = (bytes as f64, 0); + while value >= 1024.0 && unit < UNITS.len() - 1 { + value /= 1024.0; + unit += 1; + } + format!("{value:.1} {}", UNITS[unit]) } fn saves() -> PathBuf { @@ -89,6 +116,8 @@ impl Game<'_> { let state = &mut self.server_packs; state.user = user; state.prompt = None; + state.toast = None; + state.toast_rx = None; let Some(address) = address else { state.address = None; state.packs.local_world(); @@ -103,6 +132,8 @@ impl Game<'_> { /// `Minecraft.clearDownloadedResourcePacks`: every server pack goes at once. pub(super) fn server_packs_disconnect(&mut self) { self.server_packs.prompt = None; + self.server_packs.toast = None; + self.server_packs.toast_rx = None; self.server_packs.packs.disconnect(); self.tick_server_packs(); } @@ -197,10 +228,56 @@ impl Game<'_> { /// that finished, the ones to start, a resource reload when the active /// packs change, and the statuses for the server. pub(super) fn tick_server_packs(&mut self) { + // SystemToast.update: the toast slides for 5000 ms fully shown. + if let Some(toast) = &mut self.server_packs.toast { + let (sound, finished) = toast.slide.update_now(|fully| fully < 5000); + if let Some(sound) = sound { + self.audio.play( + if sound { + "minecraft:ui.toast.in" + } else { + "minecraft:ui.toast.out" + }, + None, + 1.0, + 1.0, + ); + } + if finished { + self.server_packs.toast = None; + } + } // A reload waits for the world's resources (`reload_packs`). if self.rest_loader.is_some() || self.world_loader.is_some() { return; } + let progress = self + .server_packs + .toast_rx + .as_ref() + .map(|rx| rx.try_iter().collect::>()) + .unwrap_or_default(); + for p in progress { + let toast = &mut self.server_packs.toast; + match p { + download::Progress::RequestStart(size) => { + if let Some(t) = toast { + t.bytes = 0; + t.size = size; + } + } + download::Progress::Bytes(done) => { + if let Some(t) = toast { + t.bytes = done; + } + } + download::Progress::Finished => { + if toast.as_ref().is_some_and(|t| !t.failed) { + self.server_packs.toast = None; + } + } + } + } let finished = self .server_packs .queue @@ -208,7 +285,16 @@ impl Game<'_> { .map(download::Queue::finished) .unwrap_or_default(); for batch in finished { + let failed = !batch.failed.is_empty(); self.server_packs.packs.downloaded(batch); + if failed { + // PackDownloadNotificationComponent.onFailure: the failure + // toast replaces the progress one and stays its 5 seconds. + self.server_packs.toast = Some(PackToast { + failed: true, + ..PackToast::default() + }); + } } while self.server_packs.packs.wants_tick() { let tick = self.server_packs.packs.tick(); @@ -238,6 +324,10 @@ impl Game<'_> { Ok(queue) => state.queue = Some(queue), Err(e) => { log::error!("Horizon: failed to open the download queue: {e}"); + state.toast = Some(PackToast { + failed: true, + ..PackToast::default() + }); let failed = requests.iter().map(|r| r.id).collect(); state.packs.downloaded(horizon_client::server_packs::Batch { downloaded: Vec::new(), @@ -248,8 +338,12 @@ impl Game<'_> { } } let headers = download::headers(&state.user.0, state.user.1); + // PackDownloadNotificationComponent: a toast follows the download. + let (progress, rx) = std::sync::mpsc::channel(); + state.toast = Some(PackToast::default()); + state.toast_rx = Some(rx); if let Some(queue) = &state.queue { - queue.download(requests, headers); + queue.download(requests, headers, progress); } } /// `DownloadedPackSource.startReload`: the packs on top of the player's @@ -297,6 +391,47 @@ impl Game<'_> { .layout(atlas, (w, h)) .draw(batch, atlas, self.cursor, [&yes, &no]); } + /// `PackDownloadNotificationComponent`'s toast: `download.pack.title` + /// with the running progress, or `download.pack.failed` alone. + pub(super) fn draw_pack_toast(&self, batch: &mut HudBatch) { + let Some(toast) = &self.server_packs.toast else { + return; + }; + let atlas = &self.gui.atlas; + let t = |key: &str| Text::translate(key, &[]).plain(); + let title = if toast.failed { + t("download.pack.failed") + } else { + t("download.pack.title") + }; + let body = (!toast.failed).then(|| { + if let Some(size) = toast.size.filter(|s| *s > 0) { + Text::tr( + "download.pack.progress.percent", + &[&(toast.bytes * 100 / size)], + ) + .plain() + } else { + Text::tr( + "download.pack.progress.bytes", + &[&human_readable(toast.bytes)], + ) + .plain() + } + }); + let width = body.as_ref().map_or_else( + || HudBatch::text_width(atlas, &title), + |body| HudBatch::text_width(atlas, &title).max(HudBatch::text_width(atlas, body)), + ); + let width = width.ceil().max(160.0) + 30.0; + // Toast.xPos: in from the right edge by the visible portion. + let x = batch.width - width * toast.slide.portion; + horizon_client::title::toast_background(atlas, batch, x, width); + batch.text(atlas, &title, x + 18.0, 7.0, u32::MAX, false); + if let Some(body) = &body { + batch.text(atlas, body, x + 18.0, 19.0, u32::MAX, false); + } + } /// A left click on the prompt: its answer when it hit a button. pub(super) fn pack_prompt_click(&mut self) -> Result<()> { let Some(prompt) = &self.server_packs.prompt else { diff --git a/crates/horizon-client/src/server_packs/download.rs b/crates/horizon-client/src/server_packs/download.rs index 595612df8..c299db9b9 100644 --- a/crates/horizon-client/src/server_packs/download.rs +++ b/crates/horizon-client/src/server_packs/download.rs @@ -34,7 +34,19 @@ pub fn headers(name: &str, uuid: u128) -> Vec<(&'static str, String)> { ] } -type Job = (Vec, Vec<(&'static str, String)>); +/// `DownloadProgressListener`, on the channel a download was given. +#[derive(Clone, Copy, Debug)] +pub enum Progress { + /// `requestStart`: a request began; its Content-Length when the + /// response said one. + RequestStart(Option), + /// `downloadedBytes`: the bytes this request has written so far. + Bytes(u64), + /// `downloadFinished`: the batch ran, whatever it downloaded. + Finished, +} + +type Job = (Vec, Vec<(&'static str, String)>, Sender); /// `DownloadQueue`: batches download in order, on one thread. pub struct Queue { @@ -50,16 +62,24 @@ impl Queue { std::thread::Builder::new() .name("download-queue".into()) .spawn(move || { - for (requests, headers) in todo { - if finished.send(run(&dir, &requests, &headers)).is_err() { + for (requests, headers, progress) in todo { + if finished + .send(run(&dir, &requests, &headers, &progress)) + .is_err() + { break; } } })?; Ok(Self { jobs, done }) } - pub fn download(&self, requests: Vec, headers: Vec<(&'static str, String)>) { - let _ = self.jobs.send((requests, headers)); + pub fn download( + &self, + requests: Vec, + headers: Vec<(&'static str, String)>, + progress: Sender, + ) { + let _ = self.jobs.send((requests, headers, progress)); } /// The batches finished since the last call. pub fn finished(&self) -> Vec { @@ -68,11 +88,16 @@ impl Queue { } /// `DownloadQueue.runDownload`: each pack into `//`, logged. -fn run(dir: &Path, requests: &[Request], headers: &[(&'static str, String)]) -> Batch { +fn run( + dir: &Path, + requests: &[Request], + headers: &[(&'static str, String)], + progress: &Sender, +) -> Batch { let mut batch = Batch::default(); for request in requests { let id = horizon_protocol::crypto::uuid_string(request.id); - let result = download_file(&dir.join(&id), request, headers, MAX_SIZE); + let result = download_file(&dir.join(&id), request, headers, MAX_SIZE, progress); // DownloadQueue.LogEntry, its fields in the codec's order. let mut entry = vec![ ("id", serde_json::Value::from(id)), @@ -112,6 +137,7 @@ fn run(dir: &Path, requests: &[Request], headers: &[(&'static str, String)]) -> Err(_) => batch.failed.push(request.id), } } + let _ = progress.send(Progress::Finished); batch } @@ -165,6 +191,7 @@ pub fn download_file( request: &Request, headers: &[(&'static str, String)], max_size: u64, + progress: &Sender, ) -> Result { let target = request.sha1.as_ref().map(|sha1| dir.join(sha1)); if let (Some(target), Some(sha1)) = (&target, &request.sha1) { @@ -205,10 +232,15 @@ pub fn download_file( "Filesize is bigger than maximum allowed (file is {size}, limit is {max_size})" )); } + let _ = progress.send(Progress::RequestStart(size)); let mut input = response.into_reader(); + let mut report = |written: u64| { + let _ = progress.send(Progress::Bytes(written)); + }; match (&target, &request.sha1) { (Some(target), Some(sha1)) => { - let actual = save_hashed(&mut input, target, max_size).map_err(|e| e.to_string())?; + let actual = save_hashed(&mut input, target, max_size, &mut report) + .map_err(|e| e.to_string())?; if &actual != sha1 { return Err(format!( "Hash of downloaded file ({actual}) did not match requested ({sha1})" @@ -218,7 +250,7 @@ pub fn download_file( } _ => { let tmp = dir.join(format!("download{:016x}.tmp", rand_suffix())); - let result = save_hashed(&mut input, &tmp, max_size).and_then(|actual| { + let result = save_hashed(&mut input, &tmp, max_size, &mut report).and_then(|actual| { let path = dir.join(&actual); if matches(&path, &actual) { touch(&path); @@ -237,7 +269,12 @@ fn rand_suffix() -> u64 { RandomState::new().hash_one(std::time::Instant::now()) } /// `downloadAndHash`: write what comes, at most `max_size` bytes. -fn save_hashed(input: &mut dyn Read, path: &Path, max_size: u64) -> io::Result { +fn save_hashed( + input: &mut dyn Read, + path: &Path, + max_size: u64, + progress: &mut dyn FnMut(u64), +) -> io::Result { let mut out = fs::File::create(path)?; let mut hasher = Sha1::new(); let mut buffer = [0u8; 8196]; @@ -248,6 +285,7 @@ fn save_hashed(input: &mut dyn Read, path: &Path, max_size: u64) -> io::Result max_size { return Err(io::Error::other(format!( "Filesize was bigger than maximum allowed (got >= {read_so_far}, limit was {max_size})" @@ -366,7 +404,14 @@ mod tests { url, sha1: Some(sha1(&body)), }; - let path = download_file(&dir, &request, &headers("Alex", 0xab), MAX_SIZE).unwrap(); + let path = download_file( + &dir, + &request, + &headers("Alex", 0xab), + MAX_SIZE, + &channel().0, + ) + .unwrap(); assert_eq!(path, dir.join(sha1(&body))); assert_eq!(fs::read(&path).unwrap(), body); let sent = server.join().unwrap(); @@ -377,7 +422,10 @@ mod tests { url: "http://127.0.0.1:9/gone.zip".into(), ..request }; - assert_eq!(download_file(&dir, &cached, &[], MAX_SIZE).unwrap(), path); + assert_eq!( + download_file(&dir, &cached, &[], MAX_SIZE, &channel().0).unwrap(), + path + ); fs::remove_dir_all(dir).unwrap(); } @@ -390,7 +438,7 @@ mod tests { url, sha1: Some("0".repeat(40)), }; - let err = download_file(&dir, &wrong, &[], MAX_SIZE).unwrap_err(); + let err = download_file(&dir, &wrong, &[], MAX_SIZE, &channel().0).unwrap_err(); assert!(err.contains("did not match requested"), "{err}"); server.join().unwrap(); let dead = Request { @@ -398,7 +446,7 @@ mod tests { url: "http://127.0.0.1:9/pack.zip".into(), sha1: None, }; - assert!(download_file(&dir.join("dead"), &dead, &[], MAX_SIZE).is_err()); + assert!(download_file(&dir.join("dead"), &dead, &[], MAX_SIZE, &channel().0).is_err()); assert!(!dir.join("dead").exists()); let (url, server) = serve("200 OK", vec![0; 100]); let large = Request { @@ -406,7 +454,7 @@ mod tests { url, sha1: None, }; - let err = download_file(&dir, &large, &[], 10).unwrap_err(); + let err = download_file(&dir, &large, &[], 10, &channel().0).unwrap_err(); assert!(err.contains("bigger than maximum"), "{err}"); let _ = server.join(); let (url, server) = serve("404 Not Found", Vec::new()); @@ -415,7 +463,7 @@ mod tests { url, sha1: None, }; - assert!(download_file(&dir, &missing, &[], MAX_SIZE).is_err()); + assert!(download_file(&dir, &missing, &[], MAX_SIZE, &channel().0).is_err()); server.join().unwrap(); fs::remove_dir_all(dir).unwrap(); } @@ -433,6 +481,7 @@ mod tests { sha1: None, }], Vec::new(), + channel().0, ); let batch = loop { if let Some(b) = queue.finished().pop() { diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index f77ac93eb..94b1ba2e8 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -1554,7 +1554,7 @@ impl Title { } } /// SystemToast's 32-pixel background keeps the notice icon and borders intact. -fn toast_background(atlas: &HudAtlas, batch: &mut HudBatch, x: f32, width: f32) { +pub fn toast_background(atlas: &HudAtlas, batch: &mut HudBatch, x: f32, width: f32) { let Some(rect) = atlas.sprites.get("gui/sprites/toast/system").copied() else { return; }; From 3f1a7b28af0ba3fac58ad43194d06912ae969cd0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 22:39:13 +0200 Subject: [PATCH 05/16] Placement prediction: one helper for predicted blocks, the sound where the block went - predict_use and predict_place set their blocks through one predict_blocks (retainKnownServerState), instead of two copies of the loop. - remote_can_place returns where BlockItem.place put the block, and the placer hears the place sound there: before, set_block only played it at the clicked face's neighbour, so a block that replaced grass or snow where the player clicked made no sound for its placer now that the server leaves the placer out. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/remote.rs | 83 +++++++++++------------- 1 file changed, 39 insertions(+), 44 deletions(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index e54b33b02..11eb3baed 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3932,18 +3932,7 @@ impl Game<'_> { { return; } - for &(p, state) in changes { - let pos = [p.x, p.y, p.z]; - let before = self.world.block(p.x, p.y, p.z); - // BlockStatePredictionHandler.retainKnownServerState. - if let Some(r) = self.remote.as_mut() { - r.predictions - .entry(pos) - .and_modify(|e| e.0 = seq) - .or_insert((seq, before.0 as i32)); - } - self.set_block(pos, state.0 as i32); - } + self.predict_blocks(changes, seq); // `level.playSound(player, ...)`: the clicker hears it from its own use; the // server sends it to the others only. for (pos, sound, volume, pitch) in sounds { @@ -4004,20 +3993,27 @@ impl Game<'_> { } /// MultiPlayerGameMode.useItemOn inside startPrediction, for a block item: - /// the blocks `BlockItem.place` set are placed on this client's level at - /// once, each kept as predicted under the use's sequence until the server - /// acknowledges it (a placement the server refused goes back). Without - /// this, the next click of a fast bridge aims past the block still on its - /// way from the server, and the server refuses it. - fn predict_place( - &mut self, - changes: &[(horizon_core::position::BlockPos, BlockStateId)], - seq: i32, - ) { + /// the blocks `BlockItem.place` set at `pos` are placed on this client's + /// level at once, so the next click of a fast bridge aims at them rather + /// than past them (the server would refuse it). Its place sound is the + /// placer's own (`playSound(player, ...)`: the server sends it to the + /// others only). + fn predict_place(&mut self, (pos, changes): &DryPlace, seq: i32) { + let ticks = self.ticks; + if let Some(r) = self.remote.as_mut() { + // set_block plays the place sound of the block at `placing`. + r.placing = Some(([pos.x, pos.y, pos.z], ticks)); + } + self.predict_blocks(changes, seq); + } + /// The blocks a use changed, set on this client's level and kept as + /// predicted under the use's sequence until the server acknowledges it + /// (`BlockStatePredictionHandler.retainKnownServerState`): a use the + /// server refused goes back. + fn predict_blocks(&mut self, changes: &DryChanges, seq: i32) { for &(p, state) in changes { let pos = [p.x, p.y, p.z]; let before = self.world.block(p.x, p.y, p.z); - // BlockStatePredictionHandler.retainKnownServerState. if let Some(r) = self.remote.as_mut() { r.predictions .entry(pos) @@ -4028,14 +4024,11 @@ impl Game<'_> { } } - /// Run BlockItem.place on a disposable level: the blocks it set, if it - /// placed. The real level supplies collision shapes and building-blocking - /// entities; random draws, scheduled ticks and events stay in the preview. - fn remote_can_place( - &mut self, - hit: &super::Hit, - stack: &ItemStack, - ) -> Option> { + /// Run BlockItem.place on a disposable level: where it placed and the + /// blocks it set. The real level supplies collision shapes and + /// building-blocking entities; random draws, scheduled ticks and events + /// stay in the preview. + fn remote_can_place(&mut self, hit: &super::Hit, stack: &ItemStack) -> Option { if !self.may_build() { return None; } @@ -4052,15 +4045,16 @@ impl Game<'_> { }; self.with_level(|b, level, _| { let mut level = DryLevel::new(level); - matches!( - b.place_block( - &mut level, - &mut horizon_world::level::Ticks::default(), - &ctx - ), - horizon_world::level::PlaceOutcome::Placed { .. } - ) - .then(|| level.changed.into_iter().collect()) + match b.place_block( + &mut level, + &mut horizon_world::level::Ticks::default(), + &ctx, + ) { + horizon_world::level::PlaceOutcome::Placed { pos, .. } => { + Some((pos, level.changed.into_iter().collect())) + } + horizon_world::level::PlaceOutcome::Failed => None, + } }) } @@ -5109,11 +5103,12 @@ type DrySound = ( f32, f32, ); +/// The blocks a use on the dry level set. +type DryChanges = Vec<(horizon_core::position::BlockPos, BlockStateId)>; /// What a use on the dry level changed, and the sounds it played. -type DryUse = ( - Vec<(horizon_core::position::BlockPos, BlockStateId)>, - Vec, -); +type DryUse = (DryChanges, Vec); +/// Where `BlockItem.place` on the dry level placed, and the blocks it set. +type DryPlace = (horizon_core::position::BlockPos, DryChanges); /// The blocks a guest's hand flips that its use predicts (and hears at once): a wooden or /// copper door, trapdoor or fence gate, a lever or a button. An iron door or trapdoor has From 7b56b59e7c08af912cba137148c958cb6da8ce2e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 22:04:36 +0200 Subject: [PATCH 06/16] Mod registry: the submission form's service (crates/horizon-mod-registry) Its own workspace, as the telemetry server's, for its own Railway service. GitHub sign-in with no scope (the user's token reads the login once and is dropped), signed-cookie sessions, an origin check and a CSRF token, six submissions per account and sixty in all per hour. A submission runs the file's own checks (horizon_mods::index::inspect, the signature, the entry's fields through registry::project), uploads it to the registry's `staging` release as ., writes mods/.toml on a new branch with the submitter as co-author, and opens the pull request. Only an entry's owners publish updates; a key change is a pull request by hand. Shader packs are refused until their format exists. Tested end to end against a mock GitHub: sign-in, the signed sample mod, what lands on GitHub, and what is refused. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/mod-registry.yml | 34 + Cargo.toml | 2 +- crates/horizon-mod-registry/Cargo.lock | 1352 +++++++++++++++++++ crates/horizon-mod-registry/Cargo.toml | 33 + crates/horizon-mod-registry/Dockerfile | 14 + crates/horizon-mod-registry/README.md | 44 + crates/horizon-mod-registry/railway.json | 21 + crates/horizon-mod-registry/src/github.rs | 276 ++++ crates/horizon-mod-registry/src/lib.rs | 675 +++++++++ crates/horizon-mod-registry/src/main.rs | 25 + crates/horizon-mod-registry/tests/submit.rs | 373 +++++ docs/api/mod-index.md | 2 + 12 files changed, 2850 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/mod-registry.yml create mode 100644 crates/horizon-mod-registry/Cargo.lock create mode 100644 crates/horizon-mod-registry/Cargo.toml create mode 100644 crates/horizon-mod-registry/Dockerfile create mode 100644 crates/horizon-mod-registry/README.md create mode 100644 crates/horizon-mod-registry/railway.json create mode 100644 crates/horizon-mod-registry/src/github.rs create mode 100644 crates/horizon-mod-registry/src/lib.rs create mode 100644 crates/horizon-mod-registry/src/main.rs create mode 100644 crates/horizon-mod-registry/tests/submit.rs diff --git a/.github/workflows/mod-registry.yml b/.github/workflows/mod-registry.yml new file mode 100644 index 000000000..0f252bb68 --- /dev/null +++ b/.github/workflows/mod-registry.yml @@ -0,0 +1,34 @@ +name: mod-registry +# The submission service is its own workspace (crates/horizon-mod-registry), so the checks job doesn't build +# it: this one does, when it or horizon-mods (the checks it shares with the launcher and the game) changes. +on: + push: + branches: [main] + paths: + - 'crates/horizon-mods/**' + - 'crates/horizon-mod-registry/**' + - '.github/workflows/mod-registry.yml' + pull_request: + paths: + - 'crates/horizon-mods/**' + - 'crates/horizon-mod-registry/**' + - '.github/workflows/mod-registry.yml' +permissions: + contents: read +jobs: + check: + runs-on: ubuntu-latest + timeout-minutes: 20 + defaults: + run: + working-directory: crates/horizon-mod-registry + steps: + - uses: actions/checkout@v4 + - run: rustup toolchain install stable --profile minimal --component rustfmt --component clippy + - uses: Swatinem/rust-cache@v2 + with: + workspaces: crates/horizon-mod-registry + save-if: ${{ github.ref == 'refs/heads/main' }} + - run: cargo +stable fmt --check + - run: cargo +stable clippy --all-targets --locked -- -D warnings + - run: cargo +stable test --locked diff --git a/Cargo.toml b/Cargo.toml index f197c34fe..6271b9673 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -exclude = ["launcher", "crates/horizon-telemetry-server", "third_party/wgpu-hal"] +exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"] members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] resolver = "2" diff --git a/crates/horizon-mod-registry/Cargo.lock b/crates/horizon-mod-registry/Cargo.lock new file mode 100644 index 000000000..44ef1e078 --- /dev/null +++ b/crates/horizon-mod-registry/Cargo.lock @@ -0,0 +1,1352 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" +dependencies = [ + "derive_arbitrary", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "multer", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "derive_arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", + "subtle", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "encoding_rs" +version = "0.8.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasip2", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "horizon-mod-registry" +version = "0.1.0" +dependencies = [ + "axum", + "base64", + "getrandom 0.3.4", + "hmac", + "horizon-mods", + "http-body-util", + "serde", + "serde_json", + "sha2", + "tokio", + "toml", + "tower", + "ureq", +] + +[[package]] +name = "horizon-mods" +version = "0.1.0" +dependencies = [ + "log", + "minisign-verify", + "serde", + "serde_json", + "sha2", + "toml", + "zip", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "minisign-verify" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "871285dc19d8d0ebe0eef3d0e99a205f2a71363b122632cbbfa4a6c370a960ce" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "multer" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http", + "httparse", + "memchr", + "mime", + "spin", + "version_check", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d" +dependencies = [ + "base64", + "log", + "once_cell", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "url", + "webpki-roots 0.26.11", +] + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.11", +] + +[[package]] +name = "webpki-roots" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zip" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dcb24d0152526ae49b9b96c1dcf71850ca1e0b882e4e28ed898a93c41334744" +dependencies = [ + "arbitrary", + "crc32fast", + "crossbeam-utils", + "flate2", + "indexmap", + "memchr", + "zopfli", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] diff --git a/crates/horizon-mod-registry/Cargo.toml b/crates/horizon-mod-registry/Cargo.toml new file mode 100644 index 000000000..affc08f62 --- /dev/null +++ b/crates/horizon-mod-registry/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "horizon-mod-registry" +version = "0.1.0" +edition = "2024" +license = "MIT" +rust-version = "1.90" +publish = false +description = "The registry's submission service: GitHub sign-in, the file's checks, staging, and a pull request (docs/api/mod-index.md)" + +# Its own workspace, as the telemetry server's: the game's workspace never builds a web server. +[workspace] + +[dependencies] +horizon-mods = { path = "../horizon-mods", default-features = false, features = ["index"] } +axum = { version = "0.8", default-features = false, features = ["http1", "tokio", "json", "query", "multipart"] } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "signal", "fs", "io-util"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +toml = "1" +# GitHub's API, blocking, on tokio's blocking pool: the launcher's HTTP client. +ureq = { version = "2", default-features = false, features = ["json", "tls"] } +hmac = "0.12" +sha2 = "0.10" +base64 = "0.22" +getrandom = "0.3" + +[dev-dependencies] +tower = { version = "0.5", features = ["util"] } +http-body-util = "0.1" + +[profile.release] +strip = true +lto = "thin" diff --git a/crates/horizon-mod-registry/Dockerfile b/crates/horizon-mod-registry/Dockerfile new file mode 100644 index 000000000..13522165a --- /dev/null +++ b/crates/horizon-mod-registry/Dockerfile @@ -0,0 +1,14 @@ +# Built from the repository root: docker build -f crates/horizon-mod-registry/Dockerfile . +FROM rust:1-slim AS build +WORKDIR /src +# The root manifest only for the shared crate's workspace settings (edition, lints). +COPY Cargo.toml Cargo.toml +COPY crates/horizon-mods crates/horizon-mods +COPY crates/horizon-mod-registry crates/horizon-mod-registry +RUN cargo build --release --locked --manifest-path crates/horizon-mod-registry/Cargo.toml + +FROM debian:stable-slim +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/* +COPY --from=build /src/crates/horizon-mod-registry/target/release/horizon-mod-registry /usr/local/bin/ +USER nobody +CMD ["horizon-mod-registry"] diff --git a/crates/horizon-mod-registry/README.md b/crates/horizon-mod-registry/README.md new file mode 100644 index 000000000..936fe5acf --- /dev/null +++ b/crates/horizon-mod-registry/README.md @@ -0,0 +1,44 @@ +# horizon-mod-registry + +The service behind the registry's submission form (`playhorizon.dev/mods/submit`). A creator signs in with GitHub and +sends a file with its page; the service runs the file's own checks (`horizon_mods::index::inspect`, the signature, the +entry's fields), uploads it to the `staging` release of +[ludovic111/horizon-mods](https://github.com/ludovic111/horizon-mods) as `.`, and opens a pull +request adding or updating `mods/.toml`. That repository's CI checks it again, with a trial run of a mod in the +sandbox; reviewers decide, and merging publishes. Formats and rules: [docs/api/mod-index.md](../../docs/api/mod-index.md). + +It keeps no data: a session is a signed cookie holding the GitHub login, and the user's OAuth token is used once, to +read that login, and dropped. The sign-in asks for no scope. + +| Route | | +| --- | --- | +| `GET /api/mods/auth/login` | Starts the GitHub sign-in | +| `GET /api/mods/auth/callback` | GitHub's redirect: sets the session, back to `/mods/submit` | +| `POST /api/mods/auth/logout` | Ends it | +| `GET /api/mods/me` | `{login, csrf}`, or 401 | +| `POST /api/mods/submit` | Multipart: `entry` (JSON: `id kind name summary description authors license source icon key signature version game changelog`) and `file`; `{pull_request}` or `{error}` | +| `GET /healthz` | `ok` | + +A submission must come from `REGISTRY_PUBLIC_URL`'s origin with the session's `X-CSRF-Token`. Six per account and sixty +in all per hour. Only an entry's `owners` publish its updates; a key change, an icon in the repository or anything else +is a pull request by hand. + +## Running it + +```sh +cargo test # against a mock GitHub (tests/submit.rs) +REGISTRY_PUBLIC_URL=http://localhost:4173 REGISTRY_SESSION_KEY=... GITHUB_CLIENT_ID=... GITHUB_CLIENT_SECRET=... \ + GITHUB_BOT_TOKEN=... REGISTRY_REPO=you/horizon-mods-test cargo run +``` + +| Variable | | +| --- | --- | +| `REGISTRY_PUBLIC_URL` | The site, `https://playhorizon.dev`: the OAuth callback is `/api/mods/auth/callback` | +| `REGISTRY_SESSION_KEY` | 32 characters or more, random: signs sessions | +| `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET` | The OAuth app | +| `GITHUB_BOT_TOKEN` | Fine-grained, the registry repository only: Contents and Pull requests read and write | +| `REGISTRY_REPO` | Default `ludovic111/horizon-mods` | +| `PORT` | Default 8080 | + +On Railway it is its own service (`railway.json`, built with the `Dockerfile` from the repository root); the website's +Caddy sends `/api/mods/*` to it over Railway's private network. diff --git a/crates/horizon-mod-registry/railway.json b/crates/horizon-mod-registry/railway.json new file mode 100644 index 000000000..cfafe4367 --- /dev/null +++ b/crates/horizon-mod-registry/railway.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://railway.com/railway.schema.json", + "build": { + "builder": "DOCKERFILE", + "dockerfilePath": "crates/horizon-mod-registry/Dockerfile", + "watchPatterns": [ + "/crates/horizon-mods/**", + "/crates/horizon-mod-registry/**", + "/Cargo.toml" + ] + }, + "deploy": { + "healthcheckPath": "/healthz", + "healthcheckTimeout": 60, + "restartPolicyType": "ON_FAILURE", + "restartPolicyMaxRetries": 5, + "multiRegionConfig": { + "europe-west4-drams3a": { "numReplicas": 1 } + } + } +} diff --git a/crates/horizon-mod-registry/src/github.rs b/crates/horizon-mod-registry/src/github.rs new file mode 100644 index 000000000..01a1b1bdb --- /dev/null +++ b/crates/horizon-mod-registry/src/github.rs @@ -0,0 +1,276 @@ +//! What the service asks of GitHub: the sign-in (OAuth, no scope: only the +//! public profile), and with the bot's token on the registry repository +//! alone, an entry, the `staging` release, a branch, a file, a pull request. +//! Blocking (ureq): called from tokio's blocking pool. +use base64::{Engine, engine::general_purpose::STANDARD}; +use horizon_mods::index::registry::Entry; +use serde_json::{Value, json}; +use std::{path::Path, time::Duration}; + +/// Where GitHub is: the real one, or a test's mock. +#[derive(Clone, Debug)] +pub struct Endpoints { + /// `https://github.com`: OAuth. + pub web: String, + /// `https://api.github.com`. + pub api: String, + /// `https://uploads.github.com`: release assets. + pub uploads: String, +} + +impl Default for Endpoints { + fn default() -> Self { + Endpoints { + web: "https://github.com".into(), + api: "https://api.github.com".into(), + uploads: "https://uploads.github.com".into(), + } + } +} + +#[derive(Clone)] +pub struct GitHub { + pub at: Endpoints, + /// `owner/name` of the registry repository. + pub repo: String, + pub client_id: String, + pub client_secret: String, + /// Fine-grained, this repository only: contents and pull requests. + pub bot_token: String, + agent: ureq::Agent, +} + +/// A failed call: `status` is GitHub's, 0 when it wasn't reached. +#[derive(Debug)] +pub struct Failure { + pub status: u16, + pub message: String, +} + +type Result = std::result::Result; + +fn failure(e: ureq::Error) -> Failure { + match e { + ureq::Error::Status(status, response) => Failure { + status, + message: response + .into_string() + .unwrap_or_default() + .chars() + .take(300) + .collect(), + }, + other => Failure { + status: 0, + message: other.to_string(), + }, + } +} + +fn read(response: ureq::Response) -> Result { + response.into_json().map_err(|e| Failure { + status: 0, + message: e.to_string(), + }) +} + +impl GitHub { + pub fn new( + at: Endpoints, + repo: String, + client_id: String, + client_secret: String, + bot_token: String, + ) -> GitHub { + let agent = ureq::AgentBuilder::new() + .timeout(Duration::from_secs(60)) + .user_agent("horizon-mod-registry") + .build(); + GitHub { + at, + repo, + client_id, + client_secret, + bot_token, + agent, + } + } + + /// Where the sign-in starts. + pub fn authorize_url(&self, redirect: &str, state: &str) -> String { + format!( + "{}/login/oauth/authorize?client_id={}&redirect_uri={}&state={state}&allow_signup=true", + self.at.web, + self.client_id, + encode(redirect) + ) + } + + /// The signed-in account (login, id) for an OAuth `code`. Its token is + /// used once and dropped. + pub fn sign_in(&self, code: &str, redirect: &str) -> Result<(String, u64)> { + let token = self + .agent + .post(&format!("{}/login/oauth/access_token", self.at.web)) + .set("Accept", "application/json") + .send_json(json!({ + "client_id": self.client_id, + "client_secret": self.client_secret, + "code": code, + "redirect_uri": redirect, + })) + .map_err(failure) + .and_then(read)?; + let Some(token) = token["access_token"].as_str() else { + return Err(Failure { + status: 401, + message: "GitHub refused the sign-in".into(), + }); + }; + let user = self + .agent + .get(&format!("{}/user", self.at.api)) + .set("Authorization", &format!("Bearer {token}")) + .set("Accept", "application/vnd.github+json") + .call() + .map_err(failure) + .and_then(read)?; + match (user["login"].as_str(), user["id"].as_u64()) { + (Some(login), Some(id)) => Ok((login.to_owned(), id)), + _ => Err(Failure { + status: 0, + message: "GitHub sent no login".into(), + }), + } + } + + fn call(&self, method: &str, path: &str) -> ureq::Request { + self.agent + .request( + method, + &format!("{}/repos/{}{path}", self.at.api, self.repo), + ) + .set("Authorization", &format!("Bearer {}", self.bot_token)) + .set("Accept", "application/vnd.github+json") + .set("X-GitHub-Api-Version", "2022-11-28") + } + + /// `mods/.toml` on main, with its blob sha; None when it isn't there. + pub fn entry(&self, id: &str) -> Result> { + let response = self + .call("GET", &format!("/contents/mods/{id}.toml")) + .query("ref", "main") + .call(); + let file = match response { + Ok(r) => read(r)?, + Err(ureq::Error::Status(404, _)) => return Ok(None), + Err(e) => return Err(failure(e)), + }; + let bytes = file["content"] + .as_str() + .map(|c| c.replace('\n', "")) + .and_then(|c| STANDARD.decode(c).ok()) + .unwrap_or_default(); + let entry = toml::from_str(&String::from_utf8_lossy(&bytes)).map_err(|e| Failure { + status: 0, + message: format!("mods/{id}.toml on main: {e}"), + })?; + Ok(Some((entry, file["sha"].as_str().unwrap_or("").to_owned()))) + } + + /// Uploads `path` as asset `name` of the `staging` prerelease, unless it + /// is already there (the same file submitted again). + pub fn stage(&self, name: &str, path: &Path) -> Result<()> { + let release = self + .call("GET", "/releases/tags/staging") + .call() + .map_err(failure) + .and_then(read)?; + let there = release["assets"] + .as_array() + .is_some_and(|a| a.iter().any(|x| x["name"] == name)); + if there { + return Ok(()); + } + let id = release["id"].as_u64().unwrap_or(0); + let bytes = std::fs::read(path).map_err(|e| Failure { + status: 0, + message: e.to_string(), + })?; + self.agent + .post(&format!( + "{}/repos/{}/releases/{id}/assets", + self.at.uploads, self.repo + )) + .query("name", name) + .set("Authorization", &format!("Bearer {}", self.bot_token)) + .set("Accept", "application/vnd.github+json") + .set("Content-Type", "application/octet-stream") + .send_bytes(&bytes) + .map_err(failure)?; + Ok(()) + } + + /// Makes branch `name` from main; false when it already exists. + pub fn branch(&self, name: &str) -> Result { + let main = self + .call("GET", "/git/ref/heads/main") + .call() + .map_err(failure) + .and_then(read)?; + let sha = main["object"]["sha"].as_str().unwrap_or(""); + match self + .call("POST", "/git/refs") + .send_json(json!({"ref": format!("refs/heads/{name}"), "sha": sha})) + { + Ok(_) => Ok(true), + Err(ureq::Error::Status(422, _)) => Ok(false), + Err(e) => Err(failure(e)), + } + } + + /// Writes `path` on `branch` in one commit; `sha` is the blob it replaces. + pub fn put( + &self, + path: &str, + text: &str, + branch: &str, + sha: Option<&str>, + message: &str, + ) -> Result<()> { + let mut body = json!({ + "message": message, + "content": STANDARD.encode(text), + "branch": branch, + }); + if let Some(sha) = sha { + body["sha"] = json!(sha); + } + self.call("PUT", &format!("/contents/{path}")) + .send_json(body) + .map_err(failure)?; + Ok(()) + } + + /// Opens the pull request; its address. + pub fn pull(&self, title: &str, head: &str, body: &str) -> Result { + let pr = self + .call("POST", "/pulls") + .send_json(json!({"title": title, "head": head, "base": "main", "body": body})) + .map_err(failure) + .and_then(read)?; + Ok(pr["html_url"].as_str().unwrap_or("").to_owned()) + } +} + +/// Percent-encodes a query value. +fn encode(s: &str) -> String { + s.bytes() + .map(|b| match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => { + (b as char).to_string() + } + _ => format!("%{b:02X}"), + }) + .collect() +} diff --git a/crates/horizon-mod-registry/src/lib.rs b/crates/horizon-mod-registry/src/lib.rs new file mode 100644 index 000000000..9799bace8 --- /dev/null +++ b/crates/horizon-mod-registry/src/lib.rs @@ -0,0 +1,675 @@ +//! `horizon-mod-registry`: the submission form's service at +//! `playhorizon.dev/api/mods/*` (docs/api/mod-index.md). A creator signs in +//! with GitHub, sends a file and its page; the service runs the file's own +//! checks, uploads it to the registry's `staging` release and opens a pull +//! request with the entry. Reviewers decide; merging publishes. It keeps no +//! data: sessions are signed cookies, and GitHub holds everything else. +pub mod github; + +use axum::{ + Json, Router, + extract::{DefaultBodyLimit, Multipart, Query, State}, + http::{HeaderMap, StatusCode, header}, + response::{IntoResponse, Redirect, Response}, + routing::{get, post}, +}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use github::GitHub; +use hmac::{Hmac, Mac}; +use horizon_mods::index::{ + self, Kind, + registry::{self, Entry, EntryVersion, Sources}, +}; +use serde::Deserialize; +use serde_json::json; +use sha2::Sha256; +use std::{ + collections::{HashMap, VecDeque}, + path::{Path, PathBuf}, + sync::{Arc, Mutex}, + time::{Duration, Instant, SystemTime, UNIX_EPOCH}, +}; + +/// How long a sign-in lasts. +const SESSION: u64 = 12 * 3600; +/// Submissions per account per hour, and from everyone. +const PER_ACCOUNT: usize = 6; +const PER_HOUR: usize = 60; +/// The page's JSON. +const MAX_FORM: usize = 64 << 10; + +pub struct Config { + /// `https://playhorizon.dev`: where the form is, and the only origin it + /// takes submissions from. + pub public_url: String, + /// At least 32 bytes: signs sessions. + pub session_key: Vec, + pub github: GitHub, + /// Where files wait during a submission. + pub scratch: PathBuf, +} + +impl Config { + /// `REGISTRY_PUBLIC_URL`, `REGISTRY_SESSION_KEY`, `REGISTRY_REPO`, + /// `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `GITHUB_BOT_TOKEN`. + pub fn from_env() -> Result { + let var = |name: &str| std::env::var(name).map_err(|_| format!("{name} is not set")); + let key = var("REGISTRY_SESSION_KEY")?; + if key.len() < 32 { + return Err("REGISTRY_SESSION_KEY needs at least 32 characters".into()); + } + Ok(Config { + public_url: var("REGISTRY_PUBLIC_URL")?.trim_end_matches('/').to_owned(), + session_key: key.into_bytes(), + github: GitHub::new( + github::Endpoints::default(), + std::env::var("REGISTRY_REPO").unwrap_or_else(|_| "ludovic111/horizon-mods".into()), + var("GITHUB_CLIENT_ID")?, + var("GITHUB_CLIENT_SECRET")?, + var("GITHUB_BOT_TOKEN")?, + ), + scratch: std::env::temp_dir().join("horizon-mod-registry"), + }) + } + + fn callback(&self) -> String { + format!("{}/api/mods/auth/callback", self.public_url) + } +} + +#[derive(Clone)] +pub struct App(Arc); + +struct Inner { + config: Config, + recent: Mutex>>, +} + +impl App { + pub fn new(config: Config) -> App { + App(Arc::new(Inner { + config, + recent: Mutex::new(HashMap::new()), + })) + } +} + +pub fn router(app: App) -> Router { + Router::new() + .route("/healthz", get(|| async { "ok" })) + .route("/api/mods/auth/login", get(login)) + .route("/api/mods/auth/callback", get(callback)) + .route("/api/mods/auth/logout", post(logout)) + .route("/api/mods/me", get(me)) + .route( + "/api/mods/submit", + post(submit).layer(DefaultBodyLimit::max( + index::MAX_FILE as usize + MAX_FORM * 2, + )), + ) + .with_state(app) +} + +/// An error players read in the form. +#[derive(Debug)] +pub struct Refusal(StatusCode, String); + +impl Refusal { + fn new(status: StatusCode, message: impl Into) -> Refusal { + Refusal(status, message.into()) + } +} + +impl IntoResponse for Refusal { + fn into_response(self) -> Response { + (self.0, Json(json!({"error": self.1}))).into_response() + } +} + +fn bad(message: impl Into) -> Refusal { + Refusal::new(StatusCode::BAD_REQUEST, message) +} + +fn github_down(e: github::Failure) -> Refusal { + eprintln!("horizon-mod-registry: GitHub {}: {}", e.status, e.message); + Refusal::new( + StatusCode::BAD_GATEWAY, + "GitHub didn't answer as expected: try again in a minute", + ) +} + +// Signed values: `.`, both base64url. + +fn sign(key: &[u8], payload: &str) -> String { + let mut mac = Hmac::::new_from_slice(key).expect("any key length"); + mac.update(payload.as_bytes()); + format!( + "{}.{}", + URL_SAFE_NO_PAD.encode(payload), + URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes()) + ) +} + +fn unsign(key: &[u8], value: &str) -> Option { + let (payload, tag) = value.split_once('.')?; + let payload = String::from_utf8(URL_SAFE_NO_PAD.decode(payload).ok()?).ok()?; + let mut mac = Hmac::::new_from_slice(key).ok()?; + mac.update(payload.as_bytes()); + mac.verify_slice(&URL_SAFE_NO_PAD.decode(tag).ok()?).ok()?; + Some(payload) +} + +fn now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs() +} + +fn random_hex() -> String { + let mut bytes = [0u8; 16]; + getrandom::fill(&mut bytes).expect("the system's random numbers"); + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +fn cookie(headers: &HeaderMap, name: &str) -> Option { + headers + .get_all(header::COOKIE) + .iter() + .filter_map(|v| v.to_str().ok()) + .flat_map(|v| v.split(';')) + .filter_map(|c| c.trim().split_once('=')) + .find(|(k, _)| *k == name) + .map(|(_, v)| v.to_owned()) +} + +fn set_cookie(name: &str, value: &str, max_age: u64) -> String { + format!("{name}={value}; Path=/api/mods; HttpOnly; Secure; SameSite=Lax; Max-Age={max_age}") +} + +/// The signed-in account: (login, id). +fn session(app: &Inner, headers: &HeaderMap) -> Option<(String, u64)> { + let payload = unsign(&app.config.session_key, &cookie(headers, "hm_session")?)?; + let mut parts = payload.split('\n'); + let (login, id, until) = (parts.next()?, parts.next()?, parts.next()?); + (until.parse::().ok()? > now()).then(|| (login.to_owned(), id.parse().unwrap_or(0))) +} + +/// The form sends this with each submission: a page on another site can't +/// read it, so it can't submit in a signed-in creator's name. +fn csrf(app: &Inner, headers: &HeaderMap) -> Option { + let session = cookie(headers, "hm_session")?; + let signed = sign(&app.config.session_key, &format!("csrf\n{session}")); + Some(signed.rsplit('.').next()?.chars().take(32).collect()) +} + +async fn login(State(app): State) -> Response { + let state = random_hex(); + let signed = sign(&app.0.config.session_key, &state); + let url = app + .0 + .config + .github + .authorize_url(&app.0.config.callback(), &state); + ( + [(header::SET_COOKIE, set_cookie("hm_state", &signed, 600))], + Redirect::to(&url), + ) + .into_response() +} + +#[derive(Deserialize)] +struct Callback { + code: String, + state: String, +} + +async fn callback( + State(app): State, + headers: HeaderMap, + Query(q): Query, +) -> Result { + let expected = cookie(&headers, "hm_state").and_then(|v| unsign(&app.0.config.session_key, &v)); + if expected.as_deref() != Some(q.state.as_str()) { + return Err(Refusal::new( + StatusCode::FORBIDDEN, + "the sign-in expired or didn't start here: try again", + )); + } + let inner = app.0.clone(); + let (login, id) = tokio::task::spawn_blocking(move || { + inner + .config + .github + .sign_in(&q.code, &inner.config.callback()) + }) + .await + .map_err(|_| Refusal::new(StatusCode::INTERNAL_SERVER_ERROR, "sign-in failed"))? + .map_err(github_down)?; + let value = sign( + &app.0.config.session_key, + &format!("{login}\n{id}\n{}", now() + SESSION), + ); + let back = format!("{}/mods/submit", app.0.config.public_url); + let mut response = Redirect::to(&back).into_response(); + let headers = response.headers_mut(); + headers.append( + header::SET_COOKIE, + set_cookie("hm_session", &value, SESSION).parse().unwrap(), + ); + headers.append( + header::SET_COOKIE, + set_cookie("hm_state", "", 0).parse().unwrap(), + ); + Ok(response) +} + +async fn logout() -> Response { + ( + [(header::SET_COOKIE, set_cookie("hm_session", "", 0))], + StatusCode::NO_CONTENT, + ) + .into_response() +} + +async fn me( + State(app): State, + headers: HeaderMap, +) -> Result, Refusal> { + let (login, _) = session(&app.0, &headers) + .ok_or_else(|| Refusal::new(StatusCode::UNAUTHORIZED, "not signed in"))?; + Ok(Json( + json!({"login": login, "csrf": csrf(&app.0, &headers)}), + )) +} + +/// The page a submission fills in: a project's fields, and the version's. +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Form { + pub id: String, + pub kind: String, + pub name: String, + pub summary: String, + #[serde(default)] + pub description: String, + #[serde(default)] + pub authors: Vec, + pub license: String, + pub source: String, + /// `https://` only; an icon in the repository is a pull request by hand. + #[serde(default)] + pub icon: Option, + /// A new project's minisign public key. + #[serde(default)] + pub key: Option, + /// The `.minisig` text. + #[serde(default)] + pub signature: Option, + pub version: String, + pub game: String, + #[serde(default)] + pub changelog: String, +} + +fn take(window: &mut VecDeque, max: usize) -> bool { + while window + .front() + .is_some_and(|t| t.elapsed() > Duration::from_secs(3600)) + { + window.pop_front(); + } + window.len() < max +} + +async fn submit( + State(app): State, + headers: HeaderMap, + mut multipart: Multipart, +) -> Result, Refusal> { + let inner = app.0.clone(); + let origin = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()); + if origin != Some(inner.config.public_url.as_str()) { + return Err(Refusal::new( + StatusCode::FORBIDDEN, + "submit from the registry's form", + )); + } + let (login, user_id) = session(&inner, &headers) + .ok_or_else(|| Refusal::new(StatusCode::UNAUTHORIZED, "sign in with GitHub first"))?; + let sent = headers.get("x-csrf-token").and_then(|v| v.to_str().ok()); + if sent.is_none() || sent.map(str::to_owned) != csrf(&inner, &headers) { + return Err(Refusal::new( + StatusCode::FORBIDDEN, + "reload the form and try again", + )); + } + { + let mut recent = inner.recent.lock().unwrap(); + let ok = take(recent.entry(String::new()).or_default(), PER_HOUR) + && take(recent.entry(login.to_lowercase()).or_default(), PER_ACCOUNT); + if !ok { + return Err(Refusal::new( + StatusCode::TOO_MANY_REQUESTS, + "too many submissions this hour: try again later", + )); + } + let at = Instant::now(); + recent.entry(String::new()).or_default().push_back(at); + recent + .entry(login.to_lowercase()) + .or_default() + .push_back(at); + } + let dir = inner.config.scratch.join(random_hex()); + std::fs::create_dir_all(&dir) + .map_err(|e| Refusal::new(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; + let result = receive(&mut multipart, &dir).await; + let result = match result { + Ok((form, file)) => { + let inner = inner.clone(); + tokio::task::spawn_blocking(move || { + publish(&inner.config, &login, user_id, &form, &file) + }) + .await + .unwrap_or_else(|_| { + Err(Refusal::new( + StatusCode::INTERNAL_SERVER_ERROR, + "the check crashed", + )) + }) + } + Err(e) => Err(e), + }; + let _ = std::fs::remove_dir_all(&dir); + result.map(|url| Json(json!({"pull_request": url}))) +} + +/// Reads the form's two parts: `entry` (JSON) and `file`, streamed to `dir`. +async fn receive(multipart: &mut Multipart, dir: &Path) -> Result<(Form, PathBuf), Refusal> { + use tokio::io::AsyncWriteExt; + let (mut form, mut file) = (None, None); + while let Some(mut field) = multipart + .next_field() + .await + .map_err(|e| bad(e.body_text()))? + { + match field.name() { + Some("entry") => { + let text = field.text().await.map_err(|e| bad(e.body_text()))?; + if text.len() > MAX_FORM { + return Err(bad("the page's text is too long")); + } + form = Some(serde_json::from_str::
(&text).map_err(|e| bad(e.to_string()))?); + } + Some("file") => { + let path = dir.join("upload"); + let mut out = tokio::fs::File::create(&path) + .await + .map_err(|e| Refusal::new(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; + let mut size = 0u64; + while let Some(chunk) = field.chunk().await.map_err(|e| bad(e.body_text()))? { + size += chunk.len() as u64; + if size > index::MAX_FILE { + return Err(bad(format!( + "the file is over {} MiB", + index::MAX_FILE >> 20 + ))); + } + out.write_all(&chunk).await.map_err(|e| { + Refusal::new(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()) + })?; + } + out.flush().await.ok(); + file = Some(path); + } + _ => {} + } + } + match (form, file) { + (Some(form), Some(file)) => Ok((form, file)), + _ => Err(bad("send the page and the file")), + } +} + +/// `YYYY-MM-DD` of a Unix time (UTC). +fn date(secs: u64) -> String { + // Howard Hinnant's days-to-civil. + let z = (secs / 86400) as i64 + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = yoe + era * 400 + i64::from(m <= 2); + format!("{y:04}-{m:02}-{d:02}") +} + +/// The submission, past its checks: the entry written on a new branch and a +/// pull request opened. Returns the pull request's address. +pub fn publish( + config: &Config, + login: &str, + user_id: u64, + form: &Form, + file: &Path, +) -> Result { + let gh = &config.github; + let kind = Kind::from(form.kind.clone()); + registry::open(&kind).map_err(bad)?; + if !index::valid_id(&form.id) { + return Err(bad("an id is 1 to 64 of a-z, 0-9 and _")); + } + if form + .icon + .as_ref() + .is_some_and(|i| !i.starts_with("https://")) + { + return Err(bad("the icon must be an https:// address")); + } + if !form.source.trim().starts_with("https://") { + return Err(bad("the source must be an https:// address of the code")); + } + if form.name.trim().is_empty() || form.license.trim().is_empty() { + return Err(bad("a project needs a name and a licence")); + } + // The file's own checks first: a wrong file never reaches GitHub. + let facts = index::inspect(&kind, file).map_err(bad)?; + if let Some(id) = facts.id.as_ref().filter(|id| **id != form.id) { + return Err(bad(format!("the file's id is {id:?}, not {:?}", form.id))); + } + if let Some(v) = facts + .version + .as_ref() + .filter(|v| **v != form.version.trim()) + { + return Err(bad(format!( + "the file says version {v:?}, not {:?}", + form.version.trim() + ))); + } + let sha256 = index::sha256_file(file).map_err(bad)?; + let extension = kind.extension().unwrap_or("zip"); + let version = EntryVersion { + version: form.version.trim().to_owned(), + published: date(now()), + game: form.game.trim().to_owned(), + file: format!("{}-{}.{extension}", form.id, form.version.trim()), + sha256: sha256.clone(), + signature: form.signature.clone().filter(|s| !s.trim().is_empty()), + changelog: form.changelog.clone(), + }; + let existing = gh.entry(&form.id).map_err(github_down)?; + let is_new = existing.is_none(); + let (entry, blob) = match existing { + None => ( + Entry { + id: form.id.clone(), + kind: kind.clone(), + name: form.name.trim().to_owned(), + summary: form.summary.trim().to_owned(), + description: form.description.clone(), + authors: form.authors.clone(), + owners: vec![login.to_owned()], + license: form.license.trim().to_owned(), + source: form.source.trim().to_owned(), + icon: form.icon.clone(), + key: form.key.clone().filter(|k| !k.trim().is_empty()), + versions: vec![version.clone()], + }, + None, + ), + Some((mut entry, blob)) => { + if !entry.owners.iter().any(|o| o.eq_ignore_ascii_case(login)) { + return Err(Refusal::new( + StatusCode::FORBIDDEN, + format!( + "{} is {}'s: only its owners publish its updates", + form.id, + entry.owners.join(", ") + ), + )); + } + if entry.kind != kind { + return Err(bad(format!("{} is a {}", form.id, entry.kind.name()))); + } + if entry.versions.iter().any(|v| v.version == version.version) { + return Err(Refusal::new( + StatusCode::CONFLICT, + format!( + "{} {} is already published: give this file a new version", + form.id, version.version + ), + )); + } + let key = form.key.clone().filter(|k| !k.trim().is_empty()); + if key.is_some() && key != entry.key { + return Err(bad( + "changing a project's key is a pull request by hand, reviewed on its own", + )); + } + entry.name = form.name.trim().to_owned(); + entry.summary = form.summary.trim().to_owned(); + entry.description = form.description.clone(); + entry.authors = form.authors.clone(); + entry.license = form.license.trim().to_owned(); + entry.source = form.source.trim().to_owned(); + if form.icon.is_some() { + entry.icon = form.icon.clone(); + } + entry.versions.insert(0, version.clone()); + (entry, Some(blob)) + } + }; + // Every check CI runs but the trial run: the file as its kind, its id and + // version, its signature, the entry's fields. CI runs it all again. + let files = file.parent().unwrap_or(Path::new(".")); + std::fs::copy(file, files.join(&sha256)).map_err(|e| bad(e.to_string()))?; + let mut checked = entry.clone(); + checked.versions.truncate(1); + if checked + .icon + .as_ref() + .is_some_and(|i| !i.starts_with("https://")) + { + checked.icon = None; + } + let project = registry::project( + &checked, + &Sources { + registry: files, + files, + release: index::FILE_HOST, + site: "https://example.invalid/", + generated: String::new(), + }, + ) + .map_err(|errors| bad(errors.join("; ")))?; + let text = entry.to_toml().map_err(bad)?; + gh.stage(&format!("{sha256}.{extension}"), file) + .map_err(github_down)?; + let branch = format!("submit/{}-{}", form.id, version.version); + if !gh.branch(&branch).map_err(github_down)? { + return Err(Refusal::new( + StatusCode::CONFLICT, + format!( + "{} {} was already submitted: its pull request is open", + form.id, version.version + ), + )); + } + let what = if is_new { "Add" } else { "Update" }; + let message = format!( + "{what} {} {}\n\nSubmitted by @{login} through the form.\n\nCo-authored-by: {login} <{user_id}+{login}@users.noreply.github.com>", + form.id, version.version + ); + gh.put( + &format!("mods/{}.toml", form.id), + &text, + &branch, + blob.as_deref(), + &message, + ) + .map_err(github_down)?; + let v = &project.versions[0]; + let capabilities: Vec = v + .capabilities + .iter() + .map(|c| format!("- may {}", c.describe())) + .collect(); + let requires: Vec = v + .requires + .iter() + .map(|r| format!("- needs {} {}", r.id, r.version)) + .collect(); + let body = format!( + "\nSubmitted by @{login} through [the form]({public}/mods/submit).\n\n\ + | | |\n|---|---|\n| Project | `{id}` ({kind}, {new}) |\n| Version | {version} for {game} |\n| File | `{file}`, {size} bytes, SHA-256 `{sha256}` |\n| Signed | {signed} |\n| Source | {source} |\n\n{lists}\n\n\ + The checks below run the file's own checks again and, for a mod, a trial run in the sandbox. \ + Reviewers: read the source and the checks' report before you approve.", + public = config.public_url, + id = form.id, + kind = kind.name(), + new = if is_new { "new" } else { "update" }, + version = v.version, + game = v.game, + file = v.file.name, + size = v.file.size, + signed = if entry.key.is_some() { + "yes, with the project's key" + } else { + "no" + }, + source = entry.source, + lists = [capabilities, requires].concat().join("\n"), + ); + gh.pull( + &format!("{what} {} {}", form.id, version.version), + &branch, + &body, + ) + .map_err(github_down) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dates_and_signatures() { + assert_eq!(date(0), "1970-01-01"); + assert_eq!(date(1_792_800_000), "2026-10-24"); + let key = b"0123456789abcdef0123456789abcdef"; + let signed = sign(key, "alice\n7\n99"); + assert_eq!(unsign(key, &signed).as_deref(), Some("alice\n7\n99")); + assert_eq!(unsign(b"another key, another key, another", &signed), None); + let forged = format!( + "{}.{}", + URL_SAFE_NO_PAD.encode("mallory\n8\n99"), + signed.split_once('.').unwrap().1 + ); + assert_eq!(unsign(key, &forged), None); + } +} diff --git a/crates/horizon-mod-registry/src/main.rs b/crates/horizon-mod-registry/src/main.rs new file mode 100644 index 000000000..81fe1b7b6 --- /dev/null +++ b/crates/horizon-mod-registry/src/main.rs @@ -0,0 +1,25 @@ +//! `horizon-mod-registry`: serves on `PORT` (default 8080). Configured by the +//! environment (see `Config::from_env`); keeps no data. +use std::net::SocketAddr; + +use horizon_mod_registry::{App, Config, router}; + +#[tokio::main(flavor = "multi_thread", worker_threads = 2)] +async fn main() { + let port: u16 = std::env::var("PORT") + .ok() + .and_then(|p| p.parse().ok()) + .unwrap_or(8080); + let config = Config::from_env().unwrap_or_else(|e| panic!("horizon-mod-registry: {e}")); + let repo = config.github.repo.clone(); + let listener = tokio::net::TcpListener::bind(SocketAddr::from(([0, 0, 0, 0], port))) + .await + .unwrap_or_else(|e| panic!("port {port}: {e}")); + eprintln!("horizon-mod-registry: listening on {port}, submitting to {repo}"); + axum::serve(listener, router(App::new(config))) + .with_graceful_shutdown(async { + let _ = tokio::signal::ctrl_c().await; + }) + .await + .unwrap_or_else(|e| panic!("{e}")); +} diff --git a/crates/horizon-mod-registry/tests/submit.rs b/crates/horizon-mod-registry/tests/submit.rs new file mode 100644 index 000000000..77487089d --- /dev/null +++ b/crates/horizon-mod-registry/tests/submit.rs @@ -0,0 +1,373 @@ +//! The whole submission against a mock GitHub: sign in, submit the sample +//! signed mod (`crates/horizon-mods/tests/index`), and what lands on GitHub; +//! then what is refused. +use axum::{ + Json, Router, + body::{Body, Bytes}, + extract::{Path as UrlPath, Query, State}, + http::{Request, StatusCode, header}, + routing::{get, post}, +}; +use base64::{Engine, engine::general_purpose::STANDARD}; +use horizon_mod_registry::{App, Config, github, router}; +use horizon_mods::index::registry::Entry; +use http_body_util::BodyExt; +use serde_json::{Value, json}; +use std::{ + collections::HashMap, + path::PathBuf, + sync::{Arc, Mutex}, +}; +use tower::ServiceExt; + +const PUBLIC: &str = "https://playhorizon.test"; +const HMOD_SHA: &str = "e1135345692f6dd8fd4c51920151944b82333e17049c9bb7d756f27b8deefc53"; + +#[derive(Default)] +struct Mock { + /// Path -> text on main. + main: HashMap, + assets: Vec<(String, usize)>, + branches: Vec, + /// (branch, path) -> (text, message, replaced blob). + commits: HashMap<(String, String), (String, String, Option)>, + pulls: Vec, + /// The account the next sign-in gets. + login: String, +} + +type Shared = Arc>; + +async fn mock_github() -> (String, Shared) { + let state: Shared = Arc::default(); + state.lock().unwrap().login = "alice".into(); + let app = Router::new() + .route( + "/login/oauth/access_token", + post(|Json(body): Json| async move { + Json(if body["code"] == "good" { + json!({"access_token": "gho_user"}) + } else { + json!({"error": "bad_verification_code"}) + }) + }), + ) + .route( + "/user", + get(|State(s): State| async move { + Json(json!({"login": s.lock().unwrap().login, "id": 7})) + }), + ) + .route( + "/repos/o/r/contents/mods/{file}", + get( + |State(s): State, UrlPath(file): UrlPath| async move { + let s = s.lock().unwrap(); + match s.main.get(&format!("mods/{file}")) { + Some(text) => Ok(Json(json!({"content": STANDARD.encode(text), "sha": "blob1"}))), + None => Err(StatusCode::NOT_FOUND), + } + }, + ) + .put( + |State(s): State, UrlPath(file): UrlPath, Json(b): Json| async move { + let text = String::from_utf8(STANDARD.decode(b["content"].as_str().unwrap()).unwrap()).unwrap(); + let key = (b["branch"].as_str().unwrap().to_owned(), format!("mods/{file}")); + let value = (text, b["message"].as_str().unwrap().to_owned(), b["sha"].as_str().map(str::to_owned)); + s.lock().unwrap().commits.insert(key, value); + Json(json!({})) + }, + ), + ) + .route( + "/repos/o/r/releases/tags/staging", + get(|State(s): State| async move { + let names: Vec = s.lock().unwrap().assets.iter().map(|(n, _)| json!({"name": n})).collect(); + Json(json!({"id": 42, "assets": names})) + }), + ) + .route( + "/repos/o/r/releases/42/assets", + post( + |State(s): State, Query(q): Query>, body: Bytes| async move { + s.lock().unwrap().assets.push((q["name"].clone(), body.len())); + Json(json!({})) + }, + ), + ) + .route( + "/repos/o/r/git/ref/heads/main", + get(|| async { Json(json!({"object": {"sha": "abc123"}})) }), + ) + .route( + "/repos/o/r/git/refs", + post(|State(s): State, Json(b): Json| async move { + assert_eq!(b["sha"], "abc123"); + let name = b["ref"].as_str().unwrap().trim_start_matches("refs/heads/").to_owned(); + let mut s = s.lock().unwrap(); + if s.branches.contains(&name) { + return Err(StatusCode::UNPROCESSABLE_ENTITY); + } + s.branches.push(name); + Ok(Json(json!({}))) + }), + ) + .route( + "/repos/o/r/pulls", + post(|State(s): State, Json(b): Json| async move { + let mut s = s.lock().unwrap(); + s.pulls.push(b); + Json(json!({"html_url": format!("https://github.com/o/r/pull/{}", s.pulls.len())})) + }), + ) + .with_state(state.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + (base, state) +} + +fn fixtures() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../horizon-mods/tests/index") +} + +struct Client { + app: Router, + cookies: HashMap, +} + +impl Client { + async fn send(&mut self, request: Request) -> (StatusCode, Value, Option) { + let response = self.app.clone().oneshot(request).await.unwrap(); + let status = response.status(); + for c in response.headers().get_all(header::SET_COOKIE) { + let (pair, _) = c.to_str().unwrap().split_once(';').unwrap(); + let (k, v) = pair.split_once('=').unwrap(); + self.cookies.insert(k.into(), v.into()); + } + let location = response + .headers() + .get(header::LOCATION) + .map(|l| l.to_str().unwrap().to_owned()); + let bytes = response.into_body().collect().await.unwrap().to_bytes(); + ( + status, + serde_json::from_slice(&bytes).unwrap_or(Value::Null), + location, + ) + } + + fn cookie_header(&self) -> String { + self.cookies + .iter() + .filter(|(_, v)| !v.is_empty()) + .map(|(k, v)| format!("{k}={v}")) + .collect::>() + .join("; ") + } + + fn get(&self, uri: &str) -> Request { + Request::get(uri) + .header(header::COOKIE, self.cookie_header()) + .body(Body::empty()) + .unwrap() + } + + async fn sign_in(&mut self) -> String { + let (status, _, location) = self.send(self.get("/api/mods/auth/login")).await; + assert_eq!(status, StatusCode::SEE_OTHER); + let location = location.unwrap(); + assert!(location.contains( + "redirect_uri=https%3A%2F%2Fplayhorizon.test%2Fapi%2Fmods%2Fauth%2Fcallback" + )); + let state = location + .split("state=") + .nth(1) + .unwrap() + .split('&') + .next() + .unwrap() + .to_owned(); + // Another state than the one this browser started with is refused. + let (status, ..) = self + .send(self.get("/api/mods/auth/callback?code=good&state=other")) + .await; + assert_eq!(status, StatusCode::FORBIDDEN); + let (status, _, location) = self + .send(self.get(&format!("/api/mods/auth/callback?code=good&state={state}"))) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!( + location.as_deref(), + Some("https://playhorizon.test/mods/submit") + ); + let (status, me, _) = self.send(self.get("/api/mods/me")).await; + assert_eq!(status, StatusCode::OK); + me["csrf"].as_str().unwrap().to_owned() + } + + async fn submit(&mut self, csrf: &str, form: &Value, file: &[u8]) -> (StatusCode, Value) { + let boundary = "XhorizonX"; + let mut body = format!( + "--{boundary}\r\nContent-Disposition: form-data; name=\"entry\"\r\n\r\n{form}\r\n--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"f\"\r\nContent-Type: application/octet-stream\r\n\r\n" + ) + .into_bytes(); + body.extend_from_slice(file); + body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes()); + let request = Request::post("/api/mods/submit") + .header(header::COOKIE, self.cookie_header()) + .header(header::ORIGIN, PUBLIC) + .header("x-csrf-token", csrf) + .header( + header::CONTENT_TYPE, + format!("multipart/form-data; boundary={boundary}"), + ) + .body(Body::from(body)) + .unwrap(); + let (status, json, _) = self.send(request).await; + (status, json) + } +} + +fn form() -> Value { + let key = std::fs::read_to_string(fixtures().join("test.pub")).unwrap(); + json!({ + "id": "coords_hud", + "kind": "mod", + "name": "Coordinates HUD", + "summary": "Your coordinates in a corner.", + "authors": ["Alice"], + "license": "MIT", + "source": "https://github.com/alice/coords", + "key": key.lines().last().unwrap(), + "signature": std::fs::read_to_string(fixtures().join("coords_hud-0.1.0.hmod.minisig")).unwrap(), + "version": "0.1.0", + "game": "26.3", + }) +} + +async fn setup() -> (Client, Shared) { + let (base, mock) = mock_github().await; + let scratch = + std::env::temp_dir().join(format!("horizon-mod-registry-test-{}", std::process::id())); + let config = Config { + public_url: PUBLIC.into(), + session_key: b"a test key of at least thirty-two bytes".to_vec(), + github: github::GitHub::new( + github::Endpoints { + web: base.clone(), + api: base.clone(), + uploads: base, + }, + "o/r".into(), + "client".into(), + "secret".into(), + "bot".into(), + ), + scratch, + }; + let client = Client { + app: router(App::new(config)), + cookies: HashMap::new(), + }; + (client, mock) +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_submission_becomes_a_pull_request() { + let (mut client, mock) = setup().await; + let file = std::fs::read(fixtures().join("coords_hud-0.1.0.hmod")).unwrap(); + // Not signed in. + let (status, _) = client.submit("x", &form(), &file).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + let csrf = client.sign_in().await; + let (status, _) = client.submit("wrong", &form(), &file).await; + assert_eq!(status, StatusCode::FORBIDDEN); + + let (status, json) = client.submit(&csrf, &form(), &file).await; + assert_eq!(status, StatusCode::OK, "{json}"); + assert_eq!(json["pull_request"], "https://github.com/o/r/pull/1"); + { + let m = mock.lock().unwrap(); + assert_eq!(m.assets, [(format!("{HMOD_SHA}.hmod"), file.len())]); + assert_eq!(m.branches, ["submit/coords_hud-0.1.0"]); + let (text, message, replaced) = &m.commits[&( + "submit/coords_hud-0.1.0".into(), + "mods/coords_hud.toml".into(), + )]; + let entry: Entry = toml::from_str(text).unwrap(); + assert_eq!(entry.owners, ["alice"]); + assert_eq!(entry.versions[0].sha256, HMOD_SHA); + assert_eq!(entry.versions[0].file, "coords_hud-0.1.0.hmod"); + assert!(entry.versions[0].signature.is_some() && entry.key.is_some()); + assert!(message.contains("Co-authored-by: alice <7+alice@users.noreply.github.com>")); + assert_eq!(replaced, &None); + let body = m.pulls[0]["body"].as_str().unwrap(); + assert!(body.starts_with(""), "{body}"); + assert!(body.contains("may draw text on your screen"), "{body}"); + } + // The same version again: its branch is there. + let (status, json) = client.submit(&csrf, &form(), &file).await; + assert_eq!(status, StatusCode::CONFLICT, "{json}"); + assert_eq!(mock.lock().unwrap().assets.len(), 1, "uploaded once"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn what_the_form_refuses() { + let (mut client, mock) = setup().await; + let file = std::fs::read(fixtures().join("coords_hud-0.1.0.hmod")).unwrap(); + let csrf = client.sign_in().await; + let refused = |status: StatusCode, json: &Value, part: &str| { + assert!( + json["error"].as_str().unwrap_or("").contains(part), + "{status} {json}" + ); + }; + // A file that isn't what the page says. + let mut f = form(); + f["id"] = json!("other_mod"); + let (status, json) = client.submit(&csrf, &f, &file).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + refused(status, &json, "the file's id is \"coords_hud\""); + // A broken signature. + let mut f = form(); + f["signature"] = json!( + std::fs::read_to_string(fixtures().join("coords_hud-0.1.0.hmod.minisig")) + .unwrap() + .replace("RUTV", "RUTW") + ); + let (status, json) = client.submit(&csrf, &f, &file).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{json}"); + // Shader packs aren't open. + let mut f = form(); + f["kind"] = json!("shader"); + let (status, json) = client.submit(&csrf, &f, &file).await; + refused(status, &json, "shader packs open"); + // An update by someone who isn't an owner. + let owned = "id = \"coords_hud\"\nkind = \"mod\"\nname = \"C\"\nsummary = \"s\"\nowners = [\"bob\"]\nlicense = \"MIT\"\nsource = \"https://x.test\"\n\n[[versions]]\nversion = \"0.0.1\"\npublished = \"2026-01-01\"\ngame = \"26.3\"\nfile = \"coords_hud-0.0.1.hmod\"\nsha256 = \"0000000000000000000000000000000000000000000000000000000000000000\"\n"; + mock.lock() + .unwrap() + .main + .insert("mods/coords_hud.toml".into(), owned.into()); + let (status, json) = client.submit(&csrf, &form(), &file).await; + assert_eq!(status, StatusCode::FORBIDDEN); + refused(status, &json, "bob's"); + // From another site. + let mut request = Request::post("/api/mods/submit") + .header(header::COOKIE, client.cookie_header()) + .header(header::ORIGIN, "https://evil.test") + .header("x-csrf-token", &csrf) + .body(Body::empty()) + .unwrap(); + request.headers_mut().insert( + header::CONTENT_TYPE, + "multipart/form-data; boundary=x".parse().unwrap(), + ); + let (status, ..) = client.send(request).await; + assert_eq!(status, StatusCode::FORBIDDEN); + let m = mock.lock().unwrap(); + assert!( + m.assets.is_empty() && m.pulls.is_empty(), + "nothing reached GitHub" + ); +} diff --git a/docs/api/mod-index.md b/docs/api/mod-index.md index afa6e8944..beb6ec2c8 100644 --- a/docs/api/mod-index.md +++ b/docs/api/mod-index.md @@ -129,6 +129,8 @@ reason = "Sent chat messages it didn't declare." date = "2026-10-24" ``` +The submission form's service (`crates/horizon-mod-registry`) writes these entries: it signs the creator in with GitHub, runs the file's checks, uploads the file to the repository's `staging` release as `.` and opens the pull request. Only an entry's `owners` publish updates through it. + Unknown keys are refused. Its CI runs `cargo-horizon-mod` (`crates/cargo-horizon-mod`): | Command | What it does | From 282ecf16a974bc0c6de5c18b35d7f278ea9279c8 Mon Sep 17 00:00:00 2001 From: socksprox Date: Sun, 25 Oct 2026 00:45:16 +0200 Subject: [PATCH 07/16] Tests: fix boss-event verify failures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit boss_event_round_trips missed its #[test] attribute, failing clippy's dead-code lint; unknown_packets_keep_their_payload decoded boss_event, which this PR gives a real decoder, so the garbage payload no longer comes back Unknown — it uses player_look_at, which still has none. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/horizon-protocol/src/packets/play.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 7dd8156c4..1a2880f5e 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -2880,10 +2880,11 @@ mod tests { #[test] fn unknown_packets_keep_their_payload() { - let p = Clientbound::decode(crate::ids::play::clientbound::BOSS_EVENT, &[1, 2, 3]).unwrap(); + let p = + Clientbound::decode(crate::ids::play::clientbound::PLAYER_LOOK_AT, &[1, 2, 3]).unwrap(); assert_eq!( p, - Clientbound::Unknown(crate::ids::play::clientbound::BOSS_EVENT, vec![1, 2, 3]) + Clientbound::Unknown(crate::ids::play::clientbound::PLAYER_LOOK_AT, vec![1, 2, 3]) ); assert_eq!(p.encode()[1..], [1, 2, 3]); } @@ -2980,6 +2981,7 @@ mod tests { w.varint(101); assert!(BookPages::read(&mut Reader::new(&w.data)).is_err()); } + #[test] fn boss_event_round_trips() { let add = Clientbound::BossEvent(BossEvent { id: 0x0123_4567_89ab_cdef_fedc_ba98_7654_3210, From 977ef7181f5b38d4d11e7791653690fc876f40ae Mon Sep 17 00:00:00 2001 From: Alexander Krylov Date: Sun, 25 Oct 2026 01:51:47 +0300 Subject: [PATCH 08/16] Data: `/data get entity` writes a mob's live riders A mounted mob answered "Found no elements matching Passengers": the command built the entity with the flat serializer, so `Passengers` was never in the tag, even though the game had the relationship and saving a world kept it. Persistence already writes the tree (`Game::mob_tree_nbt`, which also carries the leash), and vanilla's command path uses the same one, so the command reads it now. Fixes #1519. Co-Authored-By: Hermes Agent (Nous Research) --- crates/horizon-client/src/game/commands/data.rs | 7 ++++--- tools/command_exec_corpus.py | 6 ++++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/commands/data.rs b/crates/horizon-client/src/game/commands/data.rs index 89e3d6397..6e4c9825f 100644 --- a/crates/horizon-client/src/game/commands/data.rs +++ b/crates/horizon-client/src/game/commands/data.rs @@ -65,9 +65,10 @@ impl Game<'_> { tag } Target::Mob(id) => { - let uuid = self.uuid_for(id); - let m = self.mobs.iter().find(|m| m.id == id)?; - entity_nbt::mob_to_nbt(m, uuid, self.persist.raw.get(&id)) + // `saveWithoutId` writes the entity as saved, riders under + // `Passengers`: `/data get` reads the same tree persistence does (#1519). + let i = self.mobs.iter().position(|m| m.id == id)?; + self.mob_tree_nbt(i) } Target::Item(id) => { let uuid = self.uuid_for(id); diff --git a/tools/command_exec_corpus.py b/tools/command_exec_corpus.py index 2b2a0afd1..eacc52a32 100644 --- a/tools/command_exec_corpus.py +++ b/tools/command_exec_corpus.py @@ -280,6 +280,12 @@ def entities(): cmd('/execute as @e[tag=h] run say mob'), cmd('/execute store result score @s harness_score run data get entity @s SelectedItemSlot'), cmd('/kill @e[tag=h]'), + # A live rider travels with its vehicle in `/data get`, the way `saveWithoutId` + # writes it (#1519): the pig is mounted, so its health is the nested value. + cmd('/summon minecraft:cow 4.5 210 8.5 {Tags:["root"],NoAI:1b,Passengers:[{id:"minecraft:pig",NoAI:1b}]}'), + cmd('/data get entity @e[tag=root,limit=1] Passengers[0].Health'), + cmd('/data get entity @e[tag=root,limit=1] Passengers[0].id'), + cmd('/kill @e[tag=root]'), *setup('/kill @e[type=minecraft:armor_stand]'), {'op': 'tick', 'n': 25}, cmd('/execute if entity @e[tag=h]'), From 0d1736da8ffd016b4e66624d4ea87c34015cf1a7 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:53:00 +0100 Subject: [PATCH 09/16] Make startup and world-loading execution roles explicit Separate client, integrated-server and dedicated-server roles from connection state. Use roles for startup, presentation work and server dimension loading while preserving in-frame client simulation. Co-Authored-By: OpenAI Codex (GPT-6.1) --- crates/horizon-client/src/game.rs | 32 +++++++++------ .../horizon-client/src/game/execution_role.rs | 39 +++++++++++++++++++ crates/horizon-client/src/game/integrated.rs | 10 ++--- crates/horizon-client/src/game/levels.rs | 4 +- .../horizon-client/src/game/world_loading.rs | 2 +- docs/server-levels.md | 16 +++++--- 6 files changed, 76 insertions(+), 27 deletions(-) create mode 100644 crates/horizon-client/src/game/execution_role.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c46b86032..fbf5d17ab 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -43,6 +43,7 @@ mod enchant_effects; mod end; mod entity_culling; mod events; +mod execution_role; mod explosion; mod extras; mod falling_damage; @@ -289,8 +290,8 @@ struct Options { /// as vanilla's does: the default. `--in-frame` (or `--no-server-thread`, /// or `HORIZON_SERVER_THREAD=0`) runs the world in the frame instead. server_thread: bool, - /// Set on the integrated server's own options: it draws nothing, so it skips meshing. - integrated: bool, + /// What this Game executes; independent of its current server connection. + execution_role: execution_role::ExecutionRole, } impl Options { /// The name to join servers with: the one given, else the offline name kept @@ -347,7 +348,7 @@ impl Options { // itself, without the event loop: it stays in the frame. server_thread: std::env::var("HORIZON_SERVER_THREAD").map_or(true, |v| v != "0") && std::env::var_os("HORIZON_COMMAND_SCRIPT").is_none(), - integrated: false, + execution_role: execution_role::ExecutionRole::Client, }; let mut session_file = std::env::var("HORIZON_SESSION_FILE").ok(); let mut args = std::env::args().skip(1); @@ -361,6 +362,7 @@ impl Options { return Ok(None); } "--dedicated" => { + o.execution_role = execution_role::ExecutionRole::DedicatedServer; o.dedicated = Some(args.by_ref().collect()); break; } @@ -7521,7 +7523,11 @@ impl Game<'_> { } self.join_world_rest()?; let save_root = std::env::current_dir()?.join("saves").join(folder); - if integrated::wanted(&self.options, &save_root) { + if self + .options + .execution_role + .starts_integrated_server(self.options.server_thread) + { return self.open_integrated(folder, name, seed, creative, create); } self.perf.world_opening(); @@ -10556,7 +10562,7 @@ impl Game<'_> { } // The loading screen's chunk map fills ring by ring, as vanilla's. self.streaming.loading = - self.options.dedicated.is_none() && self.loading_reason().is_some(); + self.options.execution_role.is_client() && self.loading_reason().is_some(); let (uploads, unloaded) = horizon_client::spans::time("streaming", || self.streaming.update(&mut self.world)); if let Some(lod) = &mut self.lod { @@ -12243,7 +12249,7 @@ fn synchronous_startup(options: &Options) -> bool { || options.world_frames.is_some() || options.benchmark.is_some() || options.control.is_some() - || options.dedicated.is_some() + || !options.execution_role.is_client() || std::env::var_os("HORIZON_DISPENSE_FIXTURE").is_some() || std::env::var_os("HORIZON_SCULK_FIXTURE").is_some() || std::env::var_os("HORIZON_COMMAND_SCRIPT").is_some() @@ -12784,7 +12790,7 @@ fn start_game<'a>( game.sculk_fixture(&spec)?; return Ok(None); } - if game.options.dedicated.is_some() { + if game.options.execution_role == execution_role::ExecutionRole::DedicatedServer { game.run_dedicated()?; return Ok(None); } @@ -13061,7 +13067,7 @@ impl Loading { ); let renderer_ms = renderer_at.elapsed().as_millis(); // Audio is created on the main thread, after the core is ready. - let audio = if options.dedicated.is_some() { + let audio = if !options.execution_role.is_client() { Audio::silent(&options.resources) } else { Audio::new(&options.resources) @@ -13236,13 +13242,15 @@ pub fn run() -> Result<()> { let Some(mut options) = Options::read()? else { return Ok(()); }; - if options.dedicated.is_some() && !dedicated::preflight(&mut options)? { + if options.execution_role == execution_role::ExecutionRole::DedicatedServer + && !dedicated::preflight(&mut options)? + { return Ok(()); } // Before any worker starts: on Linux they go behind the server thread // and the render thread. horizon_threads::put_helpers_behind(); - if options.dedicated.is_none() { + if options.execution_role.is_client() { // The render thread, like the server thread, ahead of the workers on // macOS and Windows. While terrain loads, the worker pools (two with // single player's server thread) and other programs outnumber the @@ -13252,7 +13260,7 @@ pub fn run() -> Result<()> { } // Someone is playing: the anonymous ping behind the launcher's "N playing now". Not for a // server, a benchmark or a run that quits by itself. - if options.dedicated.is_none() + if options.execution_role.is_client() && options.benchmark.is_none() && !options.offscreen && options.frames.is_none() @@ -13293,7 +13301,7 @@ pub fn run() -> Result<()> { )?; let gui = loaded.gui.ok_or("missing menu bundle")?; options.resources = loaded.root.clone(); - let audio = if options.dedicated.is_some() { + let audio = if !options.execution_role.is_client() { Audio::silent(&options.resources) } else { Audio::new(&options.resources) diff --git a/crates/horizon-client/src/game/execution_role.rs b/crates/horizon-client/src/game/execution_role.rs new file mode 100644 index 000000000..e9054576d --- /dev/null +++ b/crates/horizon-client/src/game/execution_role.rs @@ -0,0 +1,39 @@ +//! A Game's execution role is fixed at construction. Connecting or disconnecting +//! changes `remote`, not this role. A client may simulate a world in-frame. + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum ExecutionRole { + Client, + IntegratedServer, + DedicatedServer, +} + +impl ExecutionRole { + /// Only a client owns presentation work (audio, loading UI, chunk meshes). + pub fn is_client(self) -> bool { + self == Self::Client + } + + /// The optional in-frame simulation remains a client execution mode. + pub fn starts_integrated_server(self, server_thread: bool) -> bool { + self.is_client() && server_thread + } +} + +#[cfg(test)] +mod tests { + use super::ExecutionRole::*; + + #[test] + fn world_loading_keeps_in_frame_clients_and_server_roles_separate() { + for (role, client, threaded) in [ + (Client, true, true), + (IntegratedServer, false, false), + (DedicatedServer, false, false), + ] { + assert_eq!(role.is_client(), client); + assert_eq!(role.starts_integrated_server(true), threaded); + assert!(!role.starts_integrated_server(false)); + } + } +} diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index 44df5fe20..f70c90432 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -12,6 +12,7 @@ //! way. use super::{ Game, Options, PackResources, Resources, UiResources, + execution_role::ExecutionRole, lan::{LanSettings, Owner}, }; use horizon_client::{ @@ -26,7 +27,6 @@ use horizon_protocol::connection::Pipe; use horizon_protocol::{crypto::offline_uuid, text::translatable}; use std::{ net::TcpListener, - path::Path, sync::{ Arc, Mutex, atomic::{AtomicBool, AtomicI32, AtomicU16, AtomicU32, Ordering}, @@ -170,11 +170,6 @@ struct Launch { player: String, } -/// Whether this world opens on a server thread: asked for. -pub(super) fn wanted(options: &Options, _world: &Path) -> bool { - options.server_thread && options.dedicated.is_none() -} - impl Game<'_> { /// `Minecraft.hasSingleplayerServer`: a world of this window's own, run /// in the frame or on its server thread. @@ -215,9 +210,10 @@ impl Game<'_> { }; let mut options = self.options.clone(); // A server without a console: no local player, no window, no control socket. + // Compatibility for gameplay checks outside startup/world loading. options.dedicated = Some(Vec::new()); options.server_thread = false; - options.integrated = true; + options.execution_role = ExecutionRole::IntegratedServer; options.control = None; options.benchmark = None; options.frames = None; diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index 895cda08c..d5b9c8d90 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -221,7 +221,7 @@ impl Game<'_> { /// holds it (`self.lan` is taken during the network tick). pub(super) fn enter_level(&mut self, host: Option<&mut LanHost>, target: Dim) -> Result<()> { // The in-frame game keeps its one level (`enter_dimension`). - if self.options.dedicated.is_none() { + if self.options.execution_role.is_client() { return Ok(()); } if target != self.dim { @@ -261,7 +261,7 @@ impl Game<'_> { /// nobody is in it; returns the level to put back afterwards. Only a /// server holds other levels. pub(super) fn enter_command_level(&mut self, dim: Dim) -> Option { - if self.options.dedicated.is_none() || dim == self.dim { + if self.options.execution_role.is_client() || dim == self.dim { return None; } let back = self.dim; diff --git a/crates/horizon-client/src/game/world_loading.rs b/crates/horizon-client/src/game/world_loading.rs index bd9ae7caa..91c375322 100644 --- a/crates/horizon-client/src/game/world_loading.rs +++ b/crates/horizon-client/src/game/world_loading.rs @@ -250,7 +250,7 @@ pub(super) fn make_streaming( streaming.nether_shading = dim == Dim::Nether; // A server draws nothing: neither the integrated server nor the // dedicated one meshes sections. - streaming.mesh = !options.integrated && options.dedicated.is_none(); + streaming.mesh = options.execution_role.is_client(); Ok((streaming, save, locator)) } diff --git a/docs/server-levels.md b/docs/server-levels.md index df45efc1f..36571d6b6 100644 --- a/docs/server-levels.md +++ b/docs/server-levels.md @@ -32,11 +32,17 @@ stay in the host's dimension. That mode is the escape hatch, so it gets no multi ## One code path for both -The dedicated server and the server thread are the same code. The server thread runs a `Game` with -`options.dedicated` set and a hub without a host player. The window joins it through memory as one -more player. Everything above serves both, and `server_dimension_players` (vanilla clients on Horizon's -dedicated server) and `lan_e2e --server-thread` (Horizon clients on the server thread) check it from -the two sides. +The dedicated server and the server thread are the same code. Each `Game` has an explicit +`ExecutionRole`: `Client`, `IntegratedServer` or `DedicatedServer`, selected before construction in +`Options.execution_role`. Startup, world loading and opening other dimensions use that role. Only +clients mesh chunks and show loading progress; a client can still run its simulation in-frame. +Connecting or disconnecting changes `remote`, independently of the execution role. + +The server thread has a hub without a host player. The window joins it through memory as one +more player. It still sets `options.dedicated` for gameplay checks outside the role migration's +startup/world-loading scope. Everything above serves both servers, and `server_dimension_players` +(vanilla clients on Horizon's dedicated server) and `lan_e2e --server-thread` (Horizon clients on the +server thread) check it from the two sides. ## Cost of an extra level From c41a053c15526b3273365a887c39962991186453 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:53:29 +0100 Subject: [PATCH 10/16] refactor: separate client world entry from authoritative loading Give integrated and dedicated startup a synchronous loading entry point without client deferral or integrated-server selection. Keep client orchestration and background loading unchanged. Co-Authored-By: OpenAI Codex GPT-6.1 --- crates/horizon-client/src/game.rs | 21 ++++++++++--------- crates/horizon-client/src/game/dedicated.rs | 6 +++--- crates/horizon-client/src/game/integrated.rs | 5 +++-- .../horizon-client/src/game/world_loading.rs | 17 +++++++++++++++ 4 files changed, 34 insertions(+), 15 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c46b86032..38fdb9e37 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -7501,7 +7501,7 @@ impl Game<'_> { (sky.star_brightness > 0.0).then(|| (frame(sky.star_angle), sky.star_brightness)); (out, stars) } - /// Load (or create) a world folder under saves/ and start streaming it. + /// Enter a local world from the client, selecting its simulation mode. fn open_world( &mut self, folder: &str, @@ -7524,16 +7524,9 @@ impl Game<'_> { if integrated::wanted(&self.options, &save_root) { return self.open_integrated(folder, name, seed, creative, create); } - self.perf.world_opening(); - let request = world_loading::WorldRequest { - save_root, - folder: folder.to_owned(), - name: name.map(str::to_owned), - seed, - creative, - create: create.cloned(), - }; + let request = world_loading::WorldRequest::new(folder, name, seed, creative, create)?; if self.window.is_some() { + self.perf.world_opening(); if self.title.is_none() { self.title = Some(Title::new( std::env::current_dir()?.join("saves"), @@ -7549,6 +7542,14 @@ impl Game<'_> { )?); return Ok(()); } + self.load_world(request) + } + + /// Load authoritative world state synchronously, without client entry or + /// integrated-server selection. Server startup must use this entry point. + fn load_world(&mut self, request: world_loading::WorldRequest) -> Result<()> { + self.join_world_rest()?; + self.perf.world_opening(); let prepared = request.prepare(&self.res, &self.pack, &self.options, &self.settings)?; self.finish_open_world(prepared) } diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index eee12fe3f..4c436c60c 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -6,7 +6,7 @@ //! its simulation and the play-state hub that LAN hosting uses, configured //! from server.properties, with the operator, whitelist and ban lists and a //! console on standard input. -use super::{Game, Options, lan::LanSettings}; +use super::{Game, Options, lan::LanSettings, world_loading::WorldRequest}; use horizon_client::{ Result, lan::{LoginGate, NetConfig, NetLog, OnlineMode, hub::HubConfig}, @@ -546,13 +546,13 @@ impl Game<'_> { let lists = Arc::new(Mutex::new(lists)); log("INFO", &format!("Preparing level \"{level_name}\"")); let folder = world_dir.to_string_lossy().into_owned(); - self.open_world( + self.load_world(WorldRequest::new( &folder, Some(&level_name), Some(props.seed), game_mode == 1, None, - )?; + )?)?; if new_world { self.level.hardcore = props.hardcore; } diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index 44df5fe20..4cbe41ccf 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -13,6 +13,7 @@ use super::{ Game, Options, PackResources, Resources, UiResources, lan::{LanSettings, Owner}, + world_loading::WorldRequest, }; use horizon_client::{ Result, @@ -287,13 +288,13 @@ impl Game<'_> { tasks: Receiver, ready: &Sender, ) -> Result<()> { - self.open_world( + self.load_world(WorldRequest::new( &launch.folder, launch.name.as_deref(), launch.seed, launch.creative, launch.create.as_ref(), - )?; + )?)?; let saved = Box::new(self.level.clone()); // Math.max(2, options.renderDistance): past vanilla's 32 when the // window's render distance is (Horizon's options go to 64). diff --git a/crates/horizon-client/src/game/world_loading.rs b/crates/horizon-client/src/game/world_loading.rs index bd9ae7caa..3db3b733d 100644 --- a/crates/horizon-client/src/game/world_loading.rs +++ b/crates/horizon-client/src/game/world_loading.rs @@ -22,6 +22,23 @@ pub(super) struct PreparedWorld { } impl WorldRequest { + pub fn new( + folder: &str, + name: Option<&str>, + seed: Option, + creative: bool, + create: Option<&horizon_client::title::WorldOptions>, + ) -> Result { + Ok(Self { + save_root: std::env::current_dir()?.join("saves").join(folder), + folder: folder.to_owned(), + name: name.map(str::to_owned), + seed, + creative, + create: create.cloned(), + }) + } + pub fn prepare( self, res: &Resources, From 6d735c26d31f060623fb2b7835925555e0105158 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 01:40:53 +0200 Subject: [PATCH 11/16] Server packs: the download toast follows DownloadedPackSource's notifier What the toast showed differed from vanilla 26.3 in several ways: - the title and the failure line had no arguments: download.pack.title takes the request number and the batch size, download.pack.failed the failures and the batch size; - sizes read "1.3 KiB" style; com.mojang.realmsclient.Unit.humanReadable gives "1.3 KB" ("512 B" below 1 KiB, half-up rounding), checked against the jar; - each update didn't restart SystemToast's 5 s display time, so a download longer than 5 s lost its toast, and the Notification Time option was ignored; - a finished batch removed the toast at once instead of forceHide's slide out; - the failure title sat at y 7 in white; SystemToast draws titles yellow, and a title without a message at y 12; - a second batch replaced the first one's channel and lost its events. The download thread now reports HttpUtil's listener calls (requestStart, downloadStart with the Content-Length, downloadedBytes, requestFinished), and each batch gets a PackNotifier (createDownloadNotifier) with its own toast. The toast is a shared toasts::SystemToast; the system background moved to toasts.rs with a y, so the pack toasts stack under an advancement toast. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 2 +- .../horizon-client/src/game/server_packs.rs | 368 +++++++++++------- .../src/server_packs/download.rs | 36 +- crates/horizon-client/src/title.rs | 32 +- crates/horizon-client/src/toasts.rs | 102 +++++ 5 files changed, 367 insertions(+), 173 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index e162c9e0f..3b9aee231 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5034,7 +5034,7 @@ impl Game<'_> { Screen::Playing | Screen::Options | Screen::Win => {} } self.draw_toasts(&mut batch); - self.draw_pack_toast(&mut batch); + self.draw_pack_toasts(&mut batch); self.remote_hud(&mut batch); self.draw_sign_editor(&mut batch); self.draw_book(&mut batch); diff --git a/crates/horizon-client/src/game/server_packs.rs b/crates/horizon-client/src/game/server_packs.rs index 6fdec751e..58d25de0e 100644 --- a/crates/horizon-client/src/game/server_packs.rs +++ b/crates/horizon-client/src/game/server_packs.rs @@ -8,15 +8,19 @@ use horizon_client::{ Result, confirm_screen::Confirm, hud::{HudAtlas, HudBatch}, - multiplayer, packs, + java_text, multiplayer, packs, scoreboard::{comp_text, tag_to_json}, server_packs::{Prompt, ServerPacks, action, download, parse_sha1, valid_url}, text::{Text, named_color}, - toasts::Slide, + toasts::SystemToast, ui, }; +use horizon_core::jmath; use horizon_protocol::{packets::configuration::ResourcePackPush, servers}; -use std::{path::PathBuf, sync::mpsc::Receiver}; +use std::{ + path::PathBuf, + sync::mpsc::{Receiver, TryRecvError}, +}; /// `ClientCommonPacketListenerImpl.PackConfirmScreen`: the packs it asks /// about, whether the last one is required, and the server's message. @@ -76,32 +80,111 @@ pub(super) struct ServerPackState { user: (String, u128), /// The packs loaded on top of the player's own, bottom first. pub(super) active: Vec, - /// `packDownloadNotifier` (`PackDownloadNotificationComponent`): the - /// toast while packs download; `downloadFinished` hides it, a failed - /// batch turns it into `download.pack.failed` until it slides out. - toast: Option, - toast_rx: Option>, + /// The download batches' notifiers, oldest first. + notifiers: Vec, } -/// The download toast: vanilla's `SystemToast` `download.pack.title` with the -/// running progress, `download.pack.failed` when a batch fails. -#[derive(Default)] -struct PackToast { - slide: Slide, - /// `downloadedBytes`: the bytes the request in flight has written. - bytes: u64, - /// Its Content-Length — the progress is a percent, else a byte count. +/// `DownloadedPackSource.createDownloadNotifier`: one batch's progress in its +/// own `SystemToast`. +struct PackNotifier { + progress: Receiver, + total: usize, + /// `count`: the requests started. + count: usize, + /// `failCount`. + failed: usize, + /// `totalBytes`: the Content-Length of the request in flight. size: Option, - failed: bool, + /// The bytes it has written so far: none before the first response. + bytes: Option, + /// The last request has finished. + done: bool, + toast: Option, } -/// `Unit.humanReadable`, for `download.pack.progress.bytes`. -fn human_readable(bytes: u64) -> String { - const UNITS: [&str; 7] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"]; - let (mut value, mut unit) = (bytes as f64, 0); - while value >= 1024.0 && unit < UNITS.len() - 1 { - value /= 1024.0; - unit += 1; +impl PackNotifier { + fn new(progress: Receiver, total: usize) -> Self { + Self { + progress, + total, + count: 0, + failed: 0, + size: None, + bytes: None, + done: false, + toast: None, + } } - format!("{value:.1} {}", UNITS[unit]) + /// The batch's events since the last call, with the toast updated once + /// for all of them. False once the batch has ended and its toast is gone. + fn poll(&mut self) -> bool { + let (mut changed, mut hide) = (false, false); + let ended = loop { + let event = match self.progress.try_recv() { + Ok(event) => event, + Err(e) => break e == TryRecvError::Disconnected, + }; + changed |= match event { + download::Progress::RequestStart => { + self.count += 1; + true + } + download::Progress::DownloadStart(size) => { + self.size = size; + self.bytes = Some(0); + true + } + download::Progress::Bytes(bytes) => { + self.bytes = Some(bytes); + true + } + download::Progress::RequestFinished(ok) => { + self.failed += usize::from(!ok); + self.done = self.count == self.total; + // Every pack came: forceHide; else the failure title. + hide |= self.done && self.failed == 0; + self.done && self.failed > 0 + } + }; + }; + if changed { + let (title, message) = self.text(); + let (title, message) = (title.plain(), message.map(|m| m.plain())); + // SystemToast.addOrUpdate. + match &mut self.toast { + Some(toast) => toast.reset(title, message), + None => self.toast = Some(SystemToast::new(title, message)), + } + } + if hide && let Some(toast) = &mut self.toast { + toast.force_hide(); + } + !ended || self.toast.is_some() + } + /// The toast's title and message. + fn text(&self) -> (Text, Option) { + if self.done && self.failed > 0 { + let failed = Text::tr("download.pack.failed", &[&self.failed, &self.total]); + return (failed, None); + } + let title = Text::tr("download.pack.title", &[&self.count, &self.total]); + let message = self.bytes.map(|bytes| match self.size { + Some(size) if size > 0 => { + Text::tr("download.pack.progress.percent", &[&(bytes * 100 / size)]) + } + _ => Text::tr("download.pack.progress.bytes", &[&human_readable(bytes)]), + }); + (title, message) + } +} +/// `com.mojang.realmsclient.Unit.humanReadable`, for +/// `download.pack.progress.bytes`. +fn human_readable(bytes: u64) -> String { + if bytes < 1024 { + return format!("{bytes} B"); + } + let exp = (jmath::log(bytes as f64) / jmath::log(1024.0)) as i32; + let prefix = &"KMGTPE"[exp as usize - 1..exp as usize]; + let value = bytes as f64 / 1024f64.powi(exp); + format!("{} {prefix}B", java_text::format_fixed(value, 1)) } fn saves() -> PathBuf { @@ -116,8 +199,7 @@ impl Game<'_> { let state = &mut self.server_packs; state.user = user; state.prompt = None; - state.toast = None; - state.toast_rx = None; + state.notifiers.clear(); let Some(address) = address else { state.address = None; state.packs.local_world(); @@ -132,8 +214,7 @@ impl Game<'_> { /// `Minecraft.clearDownloadedResourcePacks`: every server pack goes at once. pub(super) fn server_packs_disconnect(&mut self) { self.server_packs.prompt = None; - self.server_packs.toast = None; - self.server_packs.toast_rx = None; + self.server_packs.notifiers.clear(); self.server_packs.packs.disconnect(); self.tick_server_packs(); } @@ -228,56 +309,11 @@ impl Game<'_> { /// that finished, the ones to start, a resource reload when the active /// packs change, and the statuses for the server. pub(super) fn tick_server_packs(&mut self) { - // SystemToast.update: the toast slides for 5000 ms fully shown. - if let Some(toast) = &mut self.server_packs.toast { - let (sound, finished) = toast.slide.update_now(|fully| fully < 5000); - if let Some(sound) = sound { - self.audio.play( - if sound { - "minecraft:ui.toast.in" - } else { - "minecraft:ui.toast.out" - }, - None, - 1.0, - 1.0, - ); - } - if finished { - self.server_packs.toast = None; - } - } + self.server_packs.notifiers.retain_mut(PackNotifier::poll); // A reload waits for the world's resources (`reload_packs`). if self.rest_loader.is_some() || self.world_loader.is_some() { return; } - let progress = self - .server_packs - .toast_rx - .as_ref() - .map(|rx| rx.try_iter().collect::>()) - .unwrap_or_default(); - for p in progress { - let toast = &mut self.server_packs.toast; - match p { - download::Progress::RequestStart(size) => { - if let Some(t) = toast { - t.bytes = 0; - t.size = size; - } - } - download::Progress::Bytes(done) => { - if let Some(t) = toast { - t.bytes = done; - } - } - download::Progress::Finished => { - if toast.as_ref().is_some_and(|t| !t.failed) { - self.server_packs.toast = None; - } - } - } - } let finished = self .server_packs .queue @@ -285,16 +321,7 @@ impl Game<'_> { .map(download::Queue::finished) .unwrap_or_default(); for batch in finished { - let failed = !batch.failed.is_empty(); self.server_packs.packs.downloaded(batch); - if failed { - // PackDownloadNotificationComponent.onFailure: the failure - // toast replaces the progress one and stays its 5 seconds. - self.server_packs.toast = Some(PackToast { - failed: true, - ..PackToast::default() - }); - } } while self.server_packs.packs.wants_tick() { let tick = self.server_packs.packs.tick(); @@ -324,10 +351,15 @@ impl Game<'_> { Ok(queue) => state.queue = Some(queue), Err(e) => { log::error!("Horizon: failed to open the download queue: {e}"); - state.toast = Some(PackToast { - failed: true, - ..PackToast::default() - }); + // Every request failed, as the notifier would hear it. + let (progress, events) = std::sync::mpsc::channel(); + for _ in &requests { + let _ = progress.send(download::Progress::RequestStart); + let _ = progress.send(download::Progress::RequestFinished(false)); + } + state + .notifiers + .push(PackNotifier::new(events, requests.len())); let failed = requests.iter().map(|r| r.id).collect(); state.packs.downloaded(horizon_client::server_packs::Batch { downloaded: Vec::new(), @@ -338,10 +370,10 @@ impl Game<'_> { } } let headers = download::headers(&state.user.0, state.user.1); - // PackDownloadNotificationComponent: a toast follows the download. - let (progress, rx) = std::sync::mpsc::channel(); - state.toast = Some(PackToast::default()); - state.toast_rx = Some(rx); + let (progress, events) = std::sync::mpsc::channel(); + state + .notifiers + .push(PackNotifier::new(events, requests.len())); if let Some(queue) = &state.queue { queue.download(requests, headers, progress); } @@ -391,45 +423,27 @@ impl Game<'_> { .layout(atlas, (w, h)) .draw(batch, atlas, self.cursor, [&yes, &no]); } - /// `PackDownloadNotificationComponent`'s toast: `download.pack.title` - /// with the running progress, or `download.pack.failed` alone. - pub(super) fn draw_pack_toast(&self, batch: &mut HudBatch) { - let Some(toast) = &self.server_packs.toast else { - return; - }; - let atlas = &self.gui.atlas; - let t = |key: &str| Text::translate(key, &[]).plain(); - let title = if toast.failed { - t("download.pack.failed") - } else { - t("download.pack.title") - }; - let body = (!toast.failed).then(|| { - if let Some(size) = toast.size.filter(|s| *s > 0) { - Text::tr( - "download.pack.progress.percent", - &[&(toast.bytes * 100 / size)], - ) - .plain() - } else { - Text::tr( - "download.pack.progress.bytes", - &[&human_readable(toast.bytes)], - ) - .plain() + /// The download notifiers' toasts, each in the next 32-pixel slot + /// below an advancement or recipe toast (`ToastManager`). + pub(super) fn draw_pack_toasts(&mut self, batch: &mut HudBatch) { + let multiplier = f64::from(self.settings.notification_display_time); + let mut slot = usize::from(!self.adv.toasts.is_empty()); + for notifier in &mut self.server_packs.notifiers { + let Some(toast) = &mut notifier.toast else { + continue; + }; + let (sound, finished) = toast.update(multiplier); + if let Some(show) = sound { + let event = if show { "ui.toast.in" } else { "ui.toast.out" }; + self.audio + .play(&format!("minecraft:{event}"), None, 1.0, 1.0); } - }); - let width = body.as_ref().map_or_else( - || HudBatch::text_width(atlas, &title), - |body| HudBatch::text_width(atlas, &title).max(HudBatch::text_width(atlas, body)), - ); - let width = width.ceil().max(160.0) + 30.0; - // Toast.xPos: in from the right edge by the visible portion. - let x = batch.width - width * toast.slide.portion; - horizon_client::title::toast_background(atlas, batch, x, width); - batch.text(atlas, &title, x + 18.0, 7.0, u32::MAX, false); - if let Some(body) = &body { - batch.text(atlas, body, x + 18.0, 19.0, u32::MAX, false); + if finished { + notifier.toast = None; + continue; + } + toast.draw(&self.gui.atlas, batch, 32.0 * slot as f32); + slot += 1; } } /// A left click on the prompt: its answer when it hit a button. @@ -449,3 +463,97 @@ impl Game<'_> { } } } + +#[cfg(test)] +mod tests { + use super::*; + use download::Progress::*; + + fn notifier(total: usize, events: &[download::Progress]) -> PackNotifier { + let (send, receive) = std::sync::mpsc::channel(); + for event in events { + send.send(*event).unwrap(); + } + let mut notifier = PackNotifier::new(receive, total); + assert!(notifier.poll()); + notifier + } + fn texts(n: &PackNotifier) -> (serde_json::Value, Option) { + let (title, message) = n.text(); + (title.component(), message.map(|m| m.component())) + } + + #[test] + fn the_toast_counts_requests_and_shows_progress() { + let n = notifier(2, &[RequestStart]); + let (title, message) = texts(&n); + assert_eq!(title["translate"], "download.pack.title"); + assert_eq!(title["with"], serde_json::json!([1, 2])); + assert_eq!(message, None); + let n = notifier(2, &[RequestStart, DownloadStart(Some(400)), Bytes(100)]); + assert_eq!( + texts(&n).1.unwrap(), + serde_json::json!({"translate": "download.pack.progress.percent", "with": [25]}) + ); + let n = notifier(1, &[RequestStart, DownloadStart(None), Bytes(1280)]); + assert_eq!( + texts(&n).1.unwrap()["with"], + serde_json::json!([{"text": "1.3 KB"}]) + ); + } + + #[test] + fn a_failed_pack_turns_the_toast_into_the_failure_count() { + let events = [ + RequestStart, + RequestFinished(false), + RequestStart, + DownloadStart(Some(3)), + Bytes(3), + ]; + let (send, receive) = std::sync::mpsc::channel(); + for event in events { + send.send(event).unwrap(); + } + let mut n = PackNotifier::new(receive, 2); + assert!(n.poll()); + // Not the last request yet: still downloading. + assert_eq!(texts(&n).0["translate"], "download.pack.title"); + send.send(RequestFinished(true)).unwrap(); + drop(send); + assert!(n.poll(), "the failure toast stays until it slides out"); + let (title, message) = texts(&n); + assert_eq!( + title, + serde_json::json!({"translate": "download.pack.failed", "with": [1, 2]}) + ); + assert_eq!(message, None); + } + + #[test] + fn a_finished_batch_without_a_toast_is_dropped() { + let (send, receive) = std::sync::mpsc::channel::(); + drop(send); + assert!(!PackNotifier::new(receive, 1).poll()); + } + + #[test] + fn sizes_read_as_realms_unit_human_readable() { + // com.mojang.realmsclient.Unit.humanReadable, run on the 26.3 jar. + for (bytes, text) in [ + (0, "0 B"), + (1023, "1023 B"), + (1024, "1.0 KB"), + (1280, "1.3 KB"), + (1535, "1.5 KB"), + (10_000, "9.8 KB"), + (1_048_575, "1024.0 KB"), + (1_048_576, "1.0 MB"), + (52_428_800, "50.0 MB"), + (262_144_000, "250.0 MB"), + (1_073_741_824, "1.0 GB"), + ] { + assert_eq!(human_readable(bytes), text, "{bytes}"); + } + } +} diff --git a/crates/horizon-client/src/server_packs/download.rs b/crates/horizon-client/src/server_packs/download.rs index c299db9b9..4b075962f 100644 --- a/crates/horizon-client/src/server_packs/download.rs +++ b/crates/horizon-client/src/server_packs/download.rs @@ -34,16 +34,18 @@ pub fn headers(name: &str, uuid: u128) -> Vec<(&'static str, String)> { ] } -/// `DownloadProgressListener`, on the channel a download was given. -#[derive(Clone, Copy, Debug)] +/// `HttpUtil.DownloadProgressListener`, on the channel a batch was given. +#[derive(Clone, Copy, Debug, PartialEq)] pub enum Progress { - /// `requestStart`: a request began; its Content-Length when the - /// response said one. - RequestStart(Option), - /// `downloadedBytes`: the bytes this request has written so far. + /// `requestStart`: the batch's next request begins. + RequestStart, + /// `downloadStart`: the response came, with its Content-Length if it + /// said one. + DownloadStart(Option), + /// `downloadedBytes`: what this request has written so far. Bytes(u64), - /// `downloadFinished`: the batch ran, whatever it downloaded. - Finished, + /// `requestFinished`: whether it succeeded. + RequestFinished(bool), } type Job = (Vec, Vec<(&'static str, String)>, Sender); @@ -97,7 +99,9 @@ fn run( let mut batch = Batch::default(); for request in requests { let id = horizon_protocol::crypto::uuid_string(request.id); + let _ = progress.send(Progress::RequestStart); let result = download_file(&dir.join(&id), request, headers, MAX_SIZE, progress); + let _ = progress.send(Progress::RequestFinished(result.is_ok())); // DownloadQueue.LogEntry, its fields in the codec's order. let mut entry = vec![ ("id", serde_json::Value::from(id)), @@ -137,7 +141,6 @@ fn run( Err(_) => batch.failed.push(request.id), } } - let _ = progress.send(Progress::Finished); batch } @@ -225,6 +228,7 @@ pub fn download_file( .header("Content-Length") .and_then(|v| v.trim().parse::().ok()); fs::create_dir_all(dir).map_err(|e| e.to_string())?; + let _ = progress.send(Progress::DownloadStart(size)); if let Some(size) = size && size > max_size { @@ -232,7 +236,6 @@ pub fn download_file( "Filesize is bigger than maximum allowed (file is {size}, limit is {max_size})" )); } - let _ = progress.send(Progress::RequestStart(size)); let mut input = response.into_reader(); let mut report = |written: u64| { let _ = progress.send(Progress::Bytes(written)); @@ -473,6 +476,7 @@ mod tests { let dir = scratch(); let (url, server) = serve("200 OK", b"zip".to_vec()); let queue = Queue::open(dir.clone()).unwrap(); + let (progress, events) = channel(); let id = 0x5b2c_7a4e_1f3d_4c8b_9a6e_2d4f_8b1c_3e5a; queue.download( vec![Request { @@ -481,7 +485,7 @@ mod tests { sha1: None, }], Vec::new(), - channel().0, + progress, ); let batch = loop { if let Some(b) = queue.finished().pop() { @@ -494,6 +498,16 @@ mod tests { .join("5b2c7a4e-1f3d-4c8b-9a6e-2d4f8b1c3e5a") .join(sha1(b"zip")); assert_eq!(batch.downloaded, [(id, file)]); + // HttpUtil.downloadFile's listener calls, in order. + assert_eq!( + events.iter().collect::>(), + [ + Progress::RequestStart, + Progress::DownloadStart(Some(3)), + Progress::Bytes(3), + Progress::RequestFinished(true), + ] + ); let log = fs::read_to_string(dir.join("log.json")).unwrap(); let entry: serde_json::Value = serde_json::from_str(log.trim()).unwrap(); assert_eq!(entry["id"], "5b2c7a4e-1f3d-4c8b-9a6e-2d4f8b1c3e5a"); diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index 94b1ba2e8..ce1c8abf8 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -1150,7 +1150,7 @@ impl Title { + 30.0; // Toast.xPos: in from the right edge by the visible portion. let x = w - width * slide.portion; - toast_background(atlas, batch, x, width); + crate::toasts::background(atlas, batch, x, 0.0, width); batch.text(atlas, &title, x + 18.0, 7.0, rgba(255, 255, 0, 255), false); batch.text(atlas, &message, x + 18.0, 19.0, u32::MAX, false); } @@ -1553,36 +1553,6 @@ impl Title { } } } -/// SystemToast's 32-pixel background keeps the notice icon and borders intact. -pub fn toast_background(atlas: &HudAtlas, batch: &mut HudBatch, x: f32, width: f32) { - let Some(rect) = atlas.sprites.get("gui/sprites/toast/system").copied() else { - return; - }; - let source_x = [0.0, 17.0, rect.w as f32 - 4.0, rect.w as f32]; - let target_x = [x, x + 17.0, x + width - 4.0, x + width]; - for col in 0..3 { - for (sy, sh, y, h) in [ - (0.0, 28.0, 0.0, 28.0), - (rect.h as f32 - 4.0, 4.0, 28.0, 4.0), - ] { - let mut piece = rect; - let du = (rect.u1 - rect.u0) / rect.w as f32; - let dv = (rect.v1 - rect.v0) / rect.h as f32; - piece.u0 = rect.u0 + source_x[col] * du; - piece.u1 = rect.u0 + source_x[col + 1] * du; - piece.v0 = rect.v0 + sy * dv; - piece.v1 = rect.v0 + (sy + sh) * dv; - batch.rect_uv( - target_x[col], - y, - target_x[col + 1] - target_x[col], - h, - piece, - u32::MAX, - ); - } - } -} fn centered(atlas: &HudAtlas, batch: &mut HudBatch, text: &str, y: f32, color: u32) { batch.text( atlas, diff --git a/crates/horizon-client/src/toasts.rs b/crates/horizon-client/src/toasts.rs index 26807100a..b70a37036 100644 --- a/crates/horizon-client/src/toasts.rs +++ b/crates/horizon-client/src/toasts.rs @@ -1,5 +1,6 @@ //! `ToastManager`'s slide, shared by the game's toasts and the title //! screens' system toasts. +use crate::hud::{HudAtlas, HudBatch}; use std::time::Instant; /// `ToastManager.ToastInstance`: slides a toast in and out over 600 ms, @@ -56,3 +57,104 @@ impl Slide { self.update(origin.elapsed().as_millis() as i64, wants_show) } } + +/// `SystemToast`: a yellow title over a white message (or the title alone, +/// lower down) on the system background. It stays until its display time +/// has passed since its last change, or until it is hidden. +pub struct SystemToast { + pub slide: Slide, + title: String, + message: Option, + /// `changed`: the next update takes its time as `lastChanged`. + changed: bool, + last_changed: i64, + force_hide: bool, +} +impl SystemToast { + /// `SystemToastId.displayTime`'s default, in milliseconds. + const DISPLAY_TIME: f64 = 5000.0; + pub fn new(title: String, message: Option) -> Self { + Self { + slide: Slide::default(), + title, + message, + changed: false, + last_changed: 0, + force_hide: false, + } + } + /// `reset`: new text, and the display time starts again. + pub fn reset(&mut self, title: String, message: Option) { + self.title = title; + self.message = message; + self.changed = true; + } + pub fn force_hide(&mut self) { + self.force_hide = true; + } + /// `ToastInstance.update` with `SystemToast.update`, the display time + /// scaled by the Notification Time option: the visibility it switched + /// to (the sound to play), and whether it has slid out. + pub fn update(&mut self, multiplier: f64) -> (Option, bool) { + self.slide.update_now(|fully| { + if std::mem::take(&mut self.changed) { + self.last_changed = fully; + } + !self.force_hide + && ((fully - self.last_changed) as f64) < Self::DISPLAY_TIME * multiplier + }) + } + /// `extractRenderState` at `y`, in from the right edge by the visible + /// portion (`Toast.xPos`). + pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, y: f32) { + let width = std::iter::once(&self.title) + .chain(&self.message) + .map(|line| HudBatch::text_width(atlas, line)) + .fold(0.0, f32::max) + .ceil() + .max(160.0) + + 30.0; + let x = batch.width - width * self.slide.portion; + background(atlas, batch, x, y, width); + let yellow = crate::hud::rgba(255, 255, 0, 255); + match &self.message { + Some(message) => { + batch.text(atlas, &self.title, x + 18.0, y + 7.0, yellow, false); + batch.text(atlas, message, x + 18.0, y + 19.0, u32::MAX, false); + } + None => { + batch.text(atlas, &self.title, x + 18.0, y + 12.0, yellow, false); + } + } + } +} +/// SystemToast's 32-pixel background keeps the notice icon and borders intact. +pub fn background(atlas: &HudAtlas, batch: &mut HudBatch, x: f32, y: f32, width: f32) { + let Some(rect) = atlas.sprites.get("gui/sprites/toast/system").copied() else { + return; + }; + let source_x = [0.0, 17.0, rect.w as f32 - 4.0, rect.w as f32]; + let target_x = [x, x + 17.0, x + width - 4.0, x + width]; + for col in 0..3 { + for (sy, sh, y, h) in [ + (0.0, 28.0, y, 28.0), + (rect.h as f32 - 4.0, 4.0, y + 28.0, 4.0), + ] { + let mut piece = rect; + let du = (rect.u1 - rect.u0) / rect.w as f32; + let dv = (rect.v1 - rect.v0) / rect.h as f32; + piece.u0 = rect.u0 + source_x[col] * du; + piece.u1 = rect.u0 + source_x[col + 1] * du; + piece.v0 = rect.v0 + sy * dv; + piece.v1 = rect.v0 + (sy + sh) * dv; + batch.rect_uv( + target_x[col], + y, + target_x[col + 1] - target_x[col], + h, + piece, + u32::MAX, + ); + } + } +} From 75c009e3fc9ce99d3e6e31fa138a7c1656d89640 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 01:53:03 +0200 Subject: [PATCH 12/16] Boss events: one path from the host's diff to every overlay The host diffed each viewer's boss events into a Change enum, then turned the changes into packets for guests and, through a second match, into setter calls on the window's own overlay; the client turned packets into the same setters a third way. The diff now yields ClientboundBossEventPacket values, guests get them as packets and the local overlay applies them with BossOverlay::apply, the same function a server's packets reach. Gone: Change, Snap, Sent, apply_local, boss_packet and the overlay's nine-argument add and setters. UUIDUtil.uuidFromIntArray joins uuid_ints in lan::playerdata. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/boss_overlay.rs | 160 +++++++---- crates/horizon-client/src/game/bossbars.rs | 282 +++++--------------- crates/horizon-client/src/game/remote.rs | 2 +- crates/horizon-client/src/lan/playerdata.rs | 5 + 4 files changed, 178 insertions(+), 271 deletions(-) diff --git a/crates/horizon-client/src/boss_overlay.rs b/crates/horizon-client/src/boss_overlay.rs index e51a59668..12920e0d0 100644 --- a/crates/horizon-client/src/boss_overlay.rs +++ b/crates/horizon-client/src/boss_overlay.rs @@ -1,6 +1,11 @@ //! `BossHealthOverlay` and `LerpingBossEvent`: the boss bars a client is //! showing, in the order their add packets arrived. -use crate::{hud_overlays::BossBar, text::Text}; +use crate::{ + hud_overlays::BossBar, + scoreboard::{comp_text, tag_to_json}, + text::Text, +}; +use horizon_protocol::packets::play::{BossAction, BossEvent}; /// `LerpingBossEvent.LERP_MILLISECONDS`. const LERP_MS: u128 = 100; @@ -57,61 +62,62 @@ impl BossOverlay { pub fn reset(&mut self) { *self = Self::default(); } - /// `Handler.add`. An id already shown keeps its place. - pub fn add( - &mut self, - id: u128, - name: Text, - progress: f32, - color: u8, - overlay: u8, - darken: bool, - music: bool, - fog: bool, - now: u128, - ) { - let event = Event { - id, + /// `ClientboundBossEventPacket.dispatch` into `BossHealthOverlay`'s + /// handler. An id already shown keeps its place when added again. + pub fn apply(&mut self, packet: &BossEvent, now: u128) { + // An ordinal past the enum shows as its last value. + let color = |c: i32| c.clamp(0, 6) as u8; + let overlay = |o: i32| o.clamp(0, 4) as u8; + let id = packet.id; + if let BossAction::Add { name, progress, - target: progress, - set_at: now, - color: color.min(6), - overlay: overlay.min(4), + color: c, + overlay: o, darken, music, fog, + } = &packet.action + { + let event = Event { + id, + name: comp_text(&tag_to_json(name)), + progress: *progress, + target: *progress, + set_at: now, + color: color(*c), + overlay: overlay(*o), + darken: *darken, + music: *music, + fog: *fog, + }; + match self.events.iter_mut().find(|e| e.id == id) { + Some(slot) => *slot = event, + None => self.events.push(event), + } + return; + } + if let BossAction::Remove = packet.action { + self.events.retain(|e| e.id != id); + return; + } + let Some(e) = self.events.iter_mut().find(|e| e.id == id) else { + return; }; - if let Some(slot) = self.events.iter_mut().find(|e| e.id == id) { - *slot = event; - } else { - self.events.push(event); - } - } - pub fn remove(&mut self, id: u128) { - self.events.retain(|e| e.id != id); - } - pub fn set_progress(&mut self, id: u128, progress: f32, now: u128) { - if let Some(e) = self.events.iter_mut().find(|e| e.id == id) { - e.set_progress(progress, now); - } - } - pub fn set_name(&mut self, id: u128, name: Text) { - if let Some(e) = self.events.iter_mut().find(|e| e.id == id) { - e.name = name; - } - } - pub fn set_style(&mut self, id: u128, color: u8, overlay: u8) { - if let Some(e) = self.events.iter_mut().find(|e| e.id == id) { - e.color = color.min(6); - e.overlay = overlay.min(4); - } - } - pub fn set_properties(&mut self, id: u128, darken: bool, music: bool, fog: bool) { - if let Some(e) = self.events.iter_mut().find(|e| e.id == id) { - e.darken = darken; - e.music = music; - e.fog = fog; + match &packet.action { + BossAction::UpdateProgress { progress } => e.set_progress(*progress, now), + BossAction::UpdateName { name } => e.name = comp_text(&tag_to_json(name)), + BossAction::UpdateStyle { + color: c, + overlay: o, + } => { + e.color = color(*c); + e.overlay = overlay(*o); + } + BossAction::UpdateProperties { darken, music, fog } => { + (e.darken, e.music, e.fog) = (*darken, *music, *fog); + } + BossAction::Add { .. } | BossAction::Remove => {} } } /// `GameRenderer.tick` while the level runs. @@ -157,26 +163,54 @@ impl BossOverlay { #[cfg(test)] mod tests { use super::*; + use horizon_world::nbt::Tag; + + fn add(id: u128, name: &str, progress: f32, darken: bool, fog: bool) -> BossEvent { + BossEvent { + id, + action: BossAction::Add { + name: Tag::String(name.into()), + progress, + color: 5, + overlay: 0, + darken, + music: false, + fog, + }, + } + } + fn progress(id: u128, progress: f32) -> BossEvent { + BossEvent { + id, + action: BossAction::UpdateProgress { progress }, + } + } #[test] fn progress_lerps_over_a_tenth_of_a_second() { let mut overlay = BossOverlay::default(); - overlay.add(1, Text::literal("W"), 0.0, 5, 0, true, false, false, 0); - overlay.set_progress(1, 1.0, 0); + overlay.apply(&add(1, "W", 0.0, true, false), 0); + overlay.apply(&progress(1, 1.0), 0); assert!((overlay.bars(50)[0].progress - 0.5).abs() < 1.0e-5); assert!((overlay.bars(100)[0].progress - 1.0).abs() < 1.0e-5); // A new target starts from the value on screen. - overlay.set_progress(1, 0.0, 50); + overlay.apply(&progress(1, 0.0), 50); assert!((overlay.bars(150)[0].progress - 0.0).abs() < 1.0e-5); } #[test] fn darken_ramps_and_fades() { let mut overlay = BossOverlay::default(); - overlay.add(1, Text::literal("W"), 1.0, 5, 0, true, false, false, 0); + overlay.apply(&add(1, "W", 1.0, true, false), 0); overlay.tick_darken(true); assert!((overlay.darken_amount(1.0) - 0.05).abs() < 1.0e-5); - overlay.remove(1); + overlay.apply( + &BossEvent { + id: 1, + action: BossAction::Remove, + }, + 0, + ); overlay.tick_darken(true); assert!((overlay.darken - 0.0375).abs() < 1.0e-5); assert!(!overlay.should_play_music()); @@ -185,9 +219,11 @@ mod tests { #[test] fn bars_keep_arrival_order() { let mut overlay = BossOverlay::default(); - overlay.add(2, Text::literal("b"), 1.0, 0, 0, false, true, true, 0); - overlay.add(1, Text::literal("a"), 1.0, 0, 0, false, false, false, 0); - overlay.add(2, Text::literal("c"), 0.5, 1, 2, false, true, true, 0); + overlay.apply(&add(2, "b", 1.0, false, true), 0); + overlay.apply(&add(1, "a", 1.0, false, false), 0); + overlay.apply(&add(2, "c", 0.5, false, true), 0); + // An update for a bar this client never got is ignored. + overlay.apply(&progress(9, 0.5), 0); let names: Vec<_> = overlay .bars(0) .into_iter() @@ -195,7 +231,13 @@ mod tests { .collect(); assert_eq!(names, ["c", "a"]); assert!(overlay.should_create_world_fog()); - overlay.remove(2); + overlay.apply( + &BossEvent { + id: 2, + action: BossAction::Remove, + }, + 0, + ); assert!(!overlay.should_create_world_fog()); } } diff --git a/crates/horizon-client/src/game/bossbars.rs b/crates/horizon-client/src/game/bossbars.rs index 85638da4a..d747fd749 100644 --- a/crates/horizon-client/src/game/bossbars.rs +++ b/crates/horizon-client/src/game/bossbars.rs @@ -9,7 +9,7 @@ use horizon_client::{ command::{Arg, Context}, mobs::Species, save, - scoreboard::{self as sb, Comp, comp_text, json_to_tag, tag_to_json}, + scoreboard::{self as sb, Comp, json_to_tag}, scoreboard_cmd::format_list, text::Text, }; @@ -23,7 +23,7 @@ pub(super) struct BossState { pub bars: BossBars, loaded: bool, /// What each viewer was last sent, so a change becomes one packet. - sent: HashMap>, + sent: HashMap>, } fn num(n: impl std::fmt::Display) -> Text { @@ -418,12 +418,11 @@ impl Game<'_> { let mut packets = Vec::new(); for viewer in &viewers { let desired = self.boss_events_for(viewer); - let changes = self.diff_boss_events(viewer, &desired); - if viewer.local { - apply_local(&mut self.boss_overlay, &changes, now); - } else if let Some(conn) = viewer.conn { - for change in changes { - packets.push((conn, boss_packet(change))); + for event in self.diff_boss_events(viewer, desired) { + if viewer.local { + self.boss_overlay.apply(&event, now); + } else if let Some(conn) = viewer.conn { + packets.push((conn, C::BossEvent(event))); } } } @@ -446,7 +445,7 @@ impl Game<'_> { if local && let Some(p) = &self.player { let ints = self.level.player_uuid.unwrap_or_else(|| self.acting_uuid()); out.push(Viewer { - uuid: ints_to_uuid(ints), + uuid: horizon_client::lan::playerdata::ints_uuid(ints), ints, at: [p.position.x, p.position.y, p.position.z], alive: !p.health.dead_or_dying(), @@ -552,8 +551,8 @@ impl Game<'_> { id: b.uuid, name: json_to_tag(&b.name), progress: b.progress(), - color: color_index(&b.color) as u8, - overlay: style_index(&b.style) as u8, + color: color_index(&b.color), + overlay: style_index(&b.style), darken: b.darken, music: b.music, fog: b.fog, @@ -562,108 +561,66 @@ impl Game<'_> { } out } - fn diff_boss_events(&mut self, viewer: &Viewer, desired: &[Offer]) -> Vec { + /// The packets that take `viewer` from what it was last sent to `desired` + /// (`ServerBossEvent`'s broadcasts). + fn diff_boss_events(&mut self, viewer: &Viewer, desired: Vec) -> Vec { let full = viewer.local; let dim = self.dim; let sent = self.bosses.sent.entry(viewer.uuid).or_default(); - let mut changes = Vec::new(); - let gone: Vec = sent - .iter() - .filter(|(id, prev)| { - let owned = full || prev.scope == Scope::Global || prev.scope == Scope::Level(dim); - owned && !desired.iter().any(|e| e.id == **id) - }) - .map(|(id, _)| *id) - .collect(); - for id in gone { - sent.remove(&id); - changes.push(Change::Remove(id)); - } - for event in desired { - let snap = event.snap(); - match sent.get(&event.id).map(|s| s.snap.clone()) { - None => { - sent.insert( - event.id, - Sent { - snap, - scope: event.scope, - }, - ); - changes.push(Change::Add(event.clone())); - } - Some(prev) => { - if prev.progress != snap.progress { - changes.push(Change::Progress(event.id, snap.progress)); - } - if prev.name != snap.name { - changes.push(Change::Name(event.id, snap.name.clone())); - } - if prev.color != snap.color || prev.overlay != snap.overlay { - changes.push(Change::Style(event.id, snap.color, snap.overlay)); - } - if prev.darken != snap.darken - || prev.music != snap.music - || prev.fog != snap.fog - { - changes.push(Change::Properties( - event.id, - snap.darken, - snap.music, - snap.fog, - )); - } - sent.insert( - event.id, - Sent { - snap, - scope: event.scope, - }, - ); - } + let mut out = Vec::new(); + let event = |id, action| play::BossEvent { id, action }; + sent.retain(|id, prev| { + let owned = full || prev.scope == Scope::Global || prev.scope == Scope::Level(dim); + let keep = !owned || desired.iter().any(|e| e.id == *id); + if !keep { + out.push(event(*id, BossAction::Remove)); } + keep + }); + for offer in desired { + let Some(prev) = sent.get(&offer.id) else { + out.push(event( + offer.id, + BossAction::Add { + name: offer.name.clone(), + progress: offer.progress, + color: offer.color, + overlay: offer.overlay, + darken: offer.darken, + music: offer.music, + fog: offer.fog, + }, + )); + sent.insert(offer.id, offer); + continue; + }; + let id = offer.id; + if prev.progress != offer.progress { + let progress = offer.progress; + out.push(event(id, BossAction::UpdateProgress { progress })); + } + if prev.name != offer.name { + let name = offer.name.clone(); + out.push(event(id, BossAction::UpdateName { name })); + } + if (prev.color, prev.overlay) != (offer.color, offer.overlay) { + let (color, overlay) = (offer.color, offer.overlay); + out.push(event(id, BossAction::UpdateStyle { color, overlay })); + } + if (prev.darken, prev.music, prev.fog) != (offer.darken, offer.music, offer.fog) { + let (darken, music, fog) = (offer.darken, offer.music, offer.fog); + out.push(event( + id, + BossAction::UpdateProperties { darken, music, fog }, + )); + } + sent.insert(id, offer); } - changes + out } /// `ClientPacketListener.handleBossUpdate`. - pub(super) fn apply_boss_event(&mut self, packet: play::BossEvent) { - let now = boss_overlay::now_millis(); - let ord = |v: i32| v.clamp(0, 255) as u8; - match packet.action { - BossAction::Add { - name, - progress, - color, - overlay, - darken, - music, - fog, - } => self.boss_overlay.add( - packet.id, - component_text(&name), - progress, - ord(color), - ord(overlay), - darken, - music, - fog, - now, - ), - BossAction::Remove => self.boss_overlay.remove(packet.id), - BossAction::UpdateProgress { progress } => { - self.boss_overlay.set_progress(packet.id, progress, now) - } - BossAction::UpdateName { name } => { - self.boss_overlay.set_name(packet.id, component_text(&name)) - } - BossAction::UpdateStyle { color, overlay } => { - self.boss_overlay - .set_style(packet.id, ord(color), ord(overlay)) - } - BossAction::UpdateProperties { darken, music, fog } => self - .boss_overlay - .set_properties(packet.id, darken, music, fog), - } + pub(super) fn apply_boss_event(&mut self, packet: &play::BossEvent) { + self.boss_overlay.apply(packet, boss_overlay::now_millis()); } } @@ -673,27 +630,20 @@ fn insecure_uuid(random: &mut impl RandomSource) -> u128 { let least = random.next_long() & 4_611_686_018_427_387_903 | i64::MIN; ((most as u64 as u128) << 64) | (least as u64 as u128) } -fn ints_to_uuid(ints: [i32; 4]) -> u128 { - ints.iter() - .fold(0u128, |acc, &i| (acc << 32) | u128::from(i as u32)) -} fn translate_tag(key: &str) -> Tag { Tag::compound([("translate", Tag::String(key.into()))]) } -fn color_index(color: &str) -> usize { +fn color_index(color: &str) -> i32 { bossbar::COLORS .iter() .position(|c| *c == color) - .unwrap_or(6) + .unwrap_or(6) as i32 } -fn style_index(style: &str) -> usize { +fn style_index(style: &str) -> i32 { bossbar::STYLES .iter() .position(|s| *s == style) - .unwrap_or(0) -} -fn component_text(tag: &Tag) -> Text { - comp_text(&tag_to_json(tag)) + .unwrap_or(0) as i32 } #[derive(Clone, Copy, PartialEq, Eq)] @@ -701,20 +651,6 @@ enum Scope { Global, Level(Dim), } -#[derive(Clone)] -struct Snap { - name: Tag, - progress: f32, - color: u8, - overlay: u8, - darken: bool, - music: bool, - fog: bool, -} -struct Sent { - snap: Snap, - scope: Scope, -} struct Viewer { uuid: u128, ints: [i32; 4], @@ -725,92 +661,16 @@ struct Viewer { conn: Option, view_chunks: i32, } -#[derive(Clone)] +/// A boss event as one viewer should see it, and as it was last sent. struct Offer { id: u128, name: Tag, progress: f32, - color: u8, - overlay: u8, + /// `BossBarColor` and `BossBarOverlay` ordinals. + color: i32, + overlay: i32, darken: bool, music: bool, fog: bool, scope: Scope, } -impl Offer { - fn snap(&self) -> Snap { - Snap { - name: self.name.clone(), - progress: self.progress, - color: self.color, - overlay: self.overlay, - darken: self.darken, - music: self.music, - fog: self.fog, - } - } -} -enum Change { - Add(Offer), - Remove(u128), - Progress(u128, f32), - Name(u128, Tag), - Style(u128, u8, u8), - Properties(u128, bool, bool, bool), -} -fn apply_local(overlay: &mut boss_overlay::BossOverlay, changes: &[Change], now: u128) { - for change in changes { - match change { - Change::Add(e) => overlay.add( - e.id, - component_text(&e.name), - e.progress, - e.color, - e.overlay, - e.darken, - e.music, - e.fog, - now, - ), - Change::Remove(id) => overlay.remove(*id), - Change::Progress(id, progress) => overlay.set_progress(*id, *progress, now), - Change::Name(id, name) => overlay.set_name(*id, component_text(name)), - Change::Style(id, color, overlay_style) => { - overlay.set_style(*id, *color, *overlay_style) - } - Change::Properties(id, darken, music, fog) => { - overlay.set_properties(*id, *darken, *music, *fog) - } - } - } -} -fn boss_packet(change: Change) -> C { - let (id, action) = match change { - Change::Add(e) => ( - e.id, - BossAction::Add { - name: e.name, - progress: e.progress, - color: i32::from(e.color), - overlay: i32::from(e.overlay), - darken: e.darken, - music: e.music, - fog: e.fog, - }, - ), - Change::Remove(id) => (id, BossAction::Remove), - Change::Progress(id, progress) => (id, BossAction::UpdateProgress { progress }), - Change::Name(id, name) => (id, BossAction::UpdateName { name }), - Change::Style(id, color, overlay) => ( - id, - BossAction::UpdateStyle { - color: i32::from(color), - overlay: i32::from(overlay), - }, - ), - Change::Properties(id, darken, music, fog) => { - (id, BossAction::UpdateProperties { darken, music, fog }) - } - }; - C::BossEvent(play::BossEvent { id, action }) -} diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 9c0504a2c..0b11a0882 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2642,7 +2642,7 @@ impl Game<'_> { } // ClientPacketListener.setActionBarText, setTitleText, // setSubtitleText, setTitlesAnimation and handleTitlesClear. - C::BossEvent(p) => self.apply_boss_event(p), + C::BossEvent(p) => self.apply_boss_event(&p), C::SetActionBarText(p) => self.titles.set_overlay(remote_text(&p.text), false), C::SetTitleText(p) => self.titles.set_title(remote_text(&p.text)), C::SetSubtitleText(p) => self.titles.set_subtitle(remote_text(&p.text)), diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index 62102ade1..90fe0bcfe 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -27,6 +27,11 @@ pub fn uuid_ints(uuid: u128) -> [i32; 4] { uuid as i32, ] } +/// `UUIDUtil.uuidFromIntArray`. +pub fn ints_uuid(ints: [i32; 4]) -> u128 { + ints.iter() + .fold(0, |acc, &i| acc << 32 | u128::from(i as u32)) +} /// Whether a saved file exists for this player. pub fn exists(world: &Path, uuid: u128) -> bool { From 42afd721e7497b63c1195f64012816e24b3318ff Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 02:04:39 +0200 Subject: [PATCH 13/16] Server packs: the download toast shows over the connection screen A server sends its packs in the configuration phase, while the joining screen covers the frame; vanilla's ToastManager draws over every screen. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 3b9aee231..ee86ba3cf 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4818,11 +4818,15 @@ impl Game<'_> { } let atlas_ptr: *const HudAtlas = &self.gui.atlas; let _ = atlas_ptr; + // The ToastManager draws over every screen: a server's packs + // download while the connection screen shows. if self.remote_overlay(&mut batch) { + self.draw_pack_toasts(&mut batch); return batch; } if let Some(reason) = self.loading_reason() { self.draw_level_loading(&mut batch, reason); + self.draw_pack_toasts(&mut batch); return batch; } // Hud.extractRenderState: F1 (keyToggleGui) hides camera overlays, the From e55b5b7c00fc05667eaa431af0e1626957565b86 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 02:21:03 +0200 Subject: [PATCH 14/16] Boss events: custom bars first, as a joining player gets them CustomBossEvents.onPlayerConnect adds a joining player to its bars before any entity, dragon fight or raid tells it about theirs. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/bossbars.rs | 35 +++++++++++----------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/crates/horizon-client/src/game/bossbars.rs b/crates/horizon-client/src/game/bossbars.rs index d747fd749..51b64604f 100644 --- a/crates/horizon-client/src/game/bossbars.rs +++ b/crates/horizon-client/src/game/bossbars.rs @@ -474,9 +474,26 @@ impl Game<'_> { } out } - /// Dragon, withers, the raid and custom bars, in that order. + /// Custom bars (`CustomBossEvents.onPlayerConnect` sends them as a player + /// joins), then the dragon, withers and the raid. fn boss_events_for(&self, viewer: &Viewer) -> Vec { let mut out = Vec::new(); + for b in &self.bosses.bars.bars { + if !b.visible || !b.players.contains(&viewer.ints) { + continue; + } + out.push(Offer { + id: b.uuid, + name: json_to_tag(&b.name), + progress: b.progress(), + color: color_index(&b.color), + overlay: style_index(&b.style), + darken: b.darken, + music: b.music, + fog: b.fog, + scope: Scope::Global, + }); + } if viewer.here && let Some(progress) = self.dragon_boss_progress(viewer.at, viewer.alive) { @@ -543,22 +560,6 @@ impl Game<'_> { scope: Scope::Level(self.dim), }); } - for b in &self.bosses.bars.bars { - if !b.visible || !b.players.contains(&viewer.ints) { - continue; - } - out.push(Offer { - id: b.uuid, - name: json_to_tag(&b.name), - progress: b.progress(), - color: color_index(&b.color), - overlay: style_index(&b.style), - darken: b.darken, - music: b.music, - fog: b.fog, - scope: Scope::Global, - }); - } out } /// The packets that take `viewer` from what it was last sent to `desired` From f3213aa158a7ea4f7cc48a843b622c9f6ffeb2e4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 11:02:06 +0100 Subject: [PATCH 15/16] Docs: how players benchmark their computer and share the report The Performance page now gives the launcher command (horizon-launcher play --arg=--benchmark --arg=standard), where the report lands on each system, what it holds, and the two ways to share it: horizon-launcher data benchmark, or the Discord. Co-Authored-By: Claude Opus 5.5 --- website/docs/performance.md | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/website/docs/performance.md b/website/docs/performance.md index 3d53261ec..b0b6b33d8 100644 --- a/website/docs/performance.md +++ b/website/docs/performance.md @@ -23,13 +23,37 @@ The full tables, with the method and the Linux software-rendering run, are in [d **Horizon against vanilla.** The benchmark exists: `tools/perf_bench.py` starts Horizon, vanilla 26.3 and vanilla with Sodium, Lithium, FerriteCore and ImmediatelyFast on the same machine, world, camera path and settings, and computes every number the same way. [docs/benchmark.md](https://github.com/ludovic111/horizon/blob/main/docs/benchmark.md) says how it keeps the comparison fair. Its results for the client, measured on the project's own machines, are on the [Benchmarks page](/benchmarks), with the places where Java is faster. It also estimates other hardware from them, as a range, and shows players' uploaded results once at least three installs share a graphics card and processor. -**Measure your own computer.** Horizon's half of that benchmark runs on its own: +**Measure your own computer.** Horizon's half of that benchmark is built into the game. Close other heavy apps, +plug in a laptop, and run in a terminal: ```sh -horizon-client --benchmark standard --render-distance 16 +horizon-launcher play --arg=--benchmark --arg=standard ``` -It creates a world, flies the four scenes and writes a report to the `benchmarks` folder in the game folder. If you allow benchmark uploads in the launcher's data collection settings, you can share it. See [Privacy](/privacy). +Add `--arg=--render-distance --arg=16` to choose the render distance; your other settings are used as they are and +stored in the report. The game creates its own world, `horizon-benchmark` (it never touches your saves), flies over a +village, a forest, the ocean and a mountain, and quits by itself. `--arg=village` (or `forest`, `ocean`, `mountain`) +instead of `--arg=standard` flies one scene. For the run only, VSync is off and the frame rate unlimited; your options +are not changed. + +The report is a `.json` file in the `benchmarks` folder of the game folder: + +| System | Folder | +|---|---| +| Windows | `%APPDATA%\horizon\benchmarks` | +| macOS | `~/Library/Application Support/horizon/benchmarks` | +| Linux | `~/.local/share/horizon/benchmarks` | + +It holds startup times, each scene's chunk load time, the frame rate with its 1% and 0.1% lows, memory, and your +machine (operating system, processor, memory, graphics card and driver). Its format is +[docs/benchmark-report.md](https://github.com/ludovic111/horizon/blob/main/docs/benchmark-report.md). + +**Share it.** To add your computer to the [Benchmarks page](/benchmarks), either: + +- upload it from the launcher: `horizon-launcher data benchmark ` shows exactly what would be sent, + without your file paths, and asks before sending. Or allow benchmark uploads once (`horizon-launcher data allow + benchmarks`), and every later report is sent for you. See [Privacy](/privacy); +- or post the `.json` file in the Discord. ## Servers From d33f84ef73a54c2973869e1d29c36b34ce72e91d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 13:24:35 +0100 Subject: [PATCH 16/16] Fix main's build: drop the unused save_root left in open_world #1665 moved the save path into finish_open_world and #1666's merge kept the old line, so clippy -D warnings fails on main (unused variable) since 7d0ae5658. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 653a1d038..676f1aea6 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -7530,7 +7530,6 @@ impl Game<'_> { return Ok(()); } self.join_world_rest()?; - let save_root = std::env::current_dir()?.join("saves").join(folder); if self .options .execution_role