Merge main (the save_root lint fix, #1789)
This commit is contained in:
@@ -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
|
||||
+1
-1
@@ -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-shaders", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"]
|
||||
resolver = "2"
|
||||
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
//! `BossHealthOverlay` and `LerpingBossEvent`: the boss bars a client is
|
||||
//! showing, in the order their add packets arrived.
|
||||
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;
|
||||
|
||||
/// `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<Event>,
|
||||
/// `bossOverlayWorldDarkening` and the previous tick's value.
|
||||
darken: f32,
|
||||
darken_o: f32,
|
||||
}
|
||||
impl BossOverlay {
|
||||
pub fn reset(&mut self) {
|
||||
*self = Self::default();
|
||||
}
|
||||
/// `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,
|
||||
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;
|
||||
};
|
||||
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.
|
||||
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<BossBar> {
|
||||
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::*;
|
||||
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.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.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.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.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());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bars_keep_arrival_order() {
|
||||
let mut overlay = BossOverlay::default();
|
||||
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()
|
||||
.map(|b| b.name.plain())
|
||||
.collect();
|
||||
assert_eq!(names, ["c", "a"]);
|
||||
assert!(overlay.should_create_world_fog());
|
||||
overlay.apply(
|
||||
&BossEvent {
|
||||
id: 2,
|
||||
action: BossAction::Remove,
|
||||
},
|
||||
0,
|
||||
);
|
||||
assert!(!overlay.should_create_world_fog());
|
||||
}
|
||||
}
|
||||
@@ -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<String> {
|
||||
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());
|
||||
}
|
||||
|
||||
@@ -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<f32>,
|
||||
/// `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,
|
||||
|
||||
@@ -44,6 +44,7 @@ mod enchant_effects;
|
||||
mod end;
|
||||
mod entity_culling;
|
||||
mod events;
|
||||
mod execution_role;
|
||||
mod explosion;
|
||||
mod extras;
|
||||
mod falling_damage;
|
||||
@@ -291,8 +292,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
|
||||
@@ -349,7 +350,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);
|
||||
@@ -363,6 +364,7 @@ impl Options {
|
||||
return Ok(None);
|
||||
}
|
||||
"--dedicated" => {
|
||||
o.execution_role = execution_role::ExecutionRole::DedicatedServer;
|
||||
o.dedicated = Some(args.by_ref().collect());
|
||||
break;
|
||||
}
|
||||
@@ -1569,6 +1571,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,
|
||||
@@ -4081,6 +4085,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") {
|
||||
@@ -4440,6 +4446,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
|
||||
@@ -4820,11 +4828,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
|
||||
@@ -5036,6 +5048,7 @@ impl Game<'_> {
|
||||
Screen::Playing | Screen::Options | Screen::Win => {}
|
||||
}
|
||||
self.draw_toasts(&mut batch);
|
||||
self.draw_pack_toasts(&mut batch);
|
||||
self.remote_hud(&mut batch);
|
||||
self.draw_sign_editor(&mut batch);
|
||||
self.draw_book(&mut batch);
|
||||
@@ -7504,7 +7517,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,
|
||||
@@ -7523,20 +7536,16 @@ impl Game<'_> {
|
||||
return Ok(());
|
||||
}
|
||||
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();
|
||||
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"),
|
||||
@@ -7552,6 +7561,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)
|
||||
}
|
||||
@@ -7965,6 +7982,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;
|
||||
@@ -10098,7 +10117,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
|
||||
{
|
||||
@@ -10169,6 +10188,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() {
|
||||
@@ -10559,7 +10581,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 {
|
||||
@@ -11975,6 +11997,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(),
|
||||
@@ -12248,7 +12271,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()
|
||||
@@ -12702,6 +12725,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,
|
||||
}
|
||||
}
|
||||
@@ -12789,7 +12813,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);
|
||||
}
|
||||
@@ -13066,7 +13090,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)
|
||||
@@ -13241,13 +13265,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
|
||||
@@ -13257,7 +13283,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()
|
||||
@@ -13298,7 +13324,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)
|
||||
|
||||
@@ -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, json_to_tag},
|
||||
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<u128, HashMap<u128, Offer>>,
|
||||
}
|
||||
|
||||
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<i32> {
|
||||
@@ -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 [<targets>]
|
||||
let include = if ctx.get("targets").is_some() {
|
||||
!self.entities(ctx, "targets", true)?.is_empty()
|
||||
// players [<targets>]: 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,316 @@ impl Game<'_> {
|
||||
Ok(self.resolve_component(value))
|
||||
}
|
||||
|
||||
// ---- drawing ------------------------------------------------------------------
|
||||
|
||||
/// The visible custom bars (`/bossbar`), after the built-in ones.
|
||||
pub(super) fn custom_bossbars(&self, bars: &mut Vec<hud_overlays::BossBar>) {
|
||||
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
|
||||
/// Names of the online players in a boss bar's set, in join order.
|
||||
fn bossbar_player_names(&self, players: &[[i32; 4]]) -> Vec<Text> {
|
||||
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()
|
||||
.position(|c| *c == b.color)
|
||||
.unwrap_or(0),
|
||||
overlay: bossbar::STYLES
|
||||
.iter()
|
||||
.position(|s| *s == b.style)
|
||||
.unwrap_or(0),
|
||||
});
|
||||
.find(|g| g.conn == conn)
|
||||
.map(|g| horizon_client::lan::playerdata::uuid_ints(g.uuid))
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 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<u128> = 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);
|
||||
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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
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<Viewer> {
|
||||
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: horizon_client::lan::playerdata::ints_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
|
||||
}
|
||||
/// 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<Offer> {
|
||||
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)
|
||||
{
|
||||
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),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
/// 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<Offer>) -> Vec<play::BossEvent> {
|
||||
let full = viewer.local;
|
||||
let dim = self.dim;
|
||||
let sent = self.bosses.sent.entry(viewer.uuid).or_default();
|
||||
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);
|
||||
}
|
||||
out
|
||||
}
|
||||
/// `ClientPacketListener.handleBossUpdate`.
|
||||
pub(super) fn apply_boss_event(&mut self, packet: &play::BossEvent) {
|
||||
self.boss_overlay.apply(packet, boss_overlay::now_millis());
|
||||
}
|
||||
}
|
||||
|
||||
/// `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 translate_tag(key: &str) -> Tag {
|
||||
Tag::compound([("translate", Tag::String(key.into()))])
|
||||
}
|
||||
fn color_index(color: &str) -> i32 {
|
||||
bossbar::COLORS
|
||||
.iter()
|
||||
.position(|c| *c == color)
|
||||
.unwrap_or(6) as i32
|
||||
}
|
||||
fn style_index(style: &str) -> i32 {
|
||||
bossbar::STYLES
|
||||
.iter()
|
||||
.position(|s| *s == style)
|
||||
.unwrap_or(0) as i32
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Scope {
|
||||
Global,
|
||||
Level(Dim),
|
||||
}
|
||||
struct Viewer {
|
||||
uuid: u128,
|
||||
ints: [i32; 4],
|
||||
at: [f64; 3],
|
||||
alive: bool,
|
||||
here: bool,
|
||||
local: bool,
|
||||
conn: Option<u32>,
|
||||
view_chunks: i32,
|
||||
}
|
||||
/// A boss event as one viewer should see it, and as it was last sent.
|
||||
struct Offer {
|
||||
id: u128,
|
||||
name: Tag,
|
||||
progress: f32,
|
||||
/// `BossBarColor` and `BossBarOverlay` ordinals.
|
||||
color: i32,
|
||||
overlay: i32,
|
||||
darken: bool,
|
||||
music: bool,
|
||||
fog: bool,
|
||||
scope: Scope,
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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<f32> {
|
||||
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 {
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,9 @@
|
||||
//! way.
|
||||
use super::{
|
||||
Game, Options, PackResources, Resources, UiResources,
|
||||
execution_role::ExecutionRole,
|
||||
lan::{LanSettings, Owner},
|
||||
world_loading::WorldRequest,
|
||||
};
|
||||
use horizon_client::{
|
||||
Result,
|
||||
@@ -26,7 +28,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 +171,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 +211,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;
|
||||
@@ -287,13 +284,13 @@ impl Game<'_> {
|
||||
tasks: Receiver<Task>,
|
||||
ready: &Sender<Ready>,
|
||||
) -> 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).
|
||||
|
||||
@@ -2449,6 +2449,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)
|
||||
|
||||
@@ -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<Dim> {
|
||||
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;
|
||||
|
||||
@@ -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<hud_overlays::BossBar>) {
|
||||
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::*;
|
||||
|
||||
@@ -383,6 +383,7 @@ impl Game<'_> {
|
||||
}
|
||||
self.apply_settings();
|
||||
self.clear_waypoints();
|
||||
self.boss_overlay.reset();
|
||||
self.remote = Some(Remote {
|
||||
session,
|
||||
brand: "unknown".into(),
|
||||
@@ -465,6 +466,7 @@ impl Game<'_> {
|
||||
self.extras_left();
|
||||
}
|
||||
self.clear_waypoints();
|
||||
self.boss_overlay.reset();
|
||||
if let Some(mut r) = self.remote.take() {
|
||||
r.session.disconnect();
|
||||
}
|
||||
@@ -2717,6 +2719,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)),
|
||||
@@ -3151,6 +3154,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();
|
||||
@@ -4000,11 +4004,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:
|
||||
@@ -4064,18 +4074,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 {
|
||||
@@ -4135,12 +4134,45 @@ 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 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);
|
||||
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: 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<DryPlace> {
|
||||
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]),
|
||||
@@ -4155,14 +4187,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 { .. }
|
||||
)
|
||||
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,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -5213,11 +5247,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<DrySound>,
|
||||
);
|
||||
type DryUse = (DryChanges, Vec<DrySound>);
|
||||
/// 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
|
||||
|
||||
@@ -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(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -8,14 +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::SystemToast,
|
||||
ui,
|
||||
};
|
||||
use horizon_core::jmath;
|
||||
use horizon_protocol::{packets::configuration::ResourcePackPush, servers};
|
||||
use std::path::PathBuf;
|
||||
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.
|
||||
@@ -75,6 +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<packs::Pack>,
|
||||
/// The download batches' notifiers, oldest first.
|
||||
notifiers: Vec<PackNotifier>,
|
||||
}
|
||||
/// `DownloadedPackSource.createDownloadNotifier`: one batch's progress in its
|
||||
/// own `SystemToast`.
|
||||
struct PackNotifier {
|
||||
progress: Receiver<download::Progress>,
|
||||
total: usize,
|
||||
/// `count`: the requests started.
|
||||
count: usize,
|
||||
/// `failCount`.
|
||||
failed: usize,
|
||||
/// `totalBytes`: the Content-Length of the request in flight.
|
||||
size: Option<u64>,
|
||||
/// The bytes it has written so far: none before the first response.
|
||||
bytes: Option<u64>,
|
||||
/// The last request has finished.
|
||||
done: bool,
|
||||
toast: Option<SystemToast>,
|
||||
}
|
||||
impl PackNotifier {
|
||||
fn new(progress: Receiver<download::Progress>, total: usize) -> Self {
|
||||
Self {
|
||||
progress,
|
||||
total,
|
||||
count: 0,
|
||||
failed: 0,
|
||||
size: None,
|
||||
bytes: None,
|
||||
done: false,
|
||||
toast: None,
|
||||
}
|
||||
}
|
||||
/// 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<Text>) {
|
||||
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 {
|
||||
@@ -89,6 +199,7 @@ impl Game<'_> {
|
||||
let state = &mut self.server_packs;
|
||||
state.user = user;
|
||||
state.prompt = None;
|
||||
state.notifiers.clear();
|
||||
let Some(address) = address else {
|
||||
state.address = None;
|
||||
state.packs.local_world();
|
||||
@@ -103,6 +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.notifiers.clear();
|
||||
self.server_packs.packs.disconnect();
|
||||
self.tick_server_packs();
|
||||
}
|
||||
@@ -197,6 +309,7 @@ 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) {
|
||||
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;
|
||||
@@ -238,6 +351,15 @@ impl Game<'_> {
|
||||
Ok(queue) => state.queue = Some(queue),
|
||||
Err(e) => {
|
||||
log::error!("Horizon: failed to open the download queue: {e}");
|
||||
// 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(),
|
||||
@@ -248,8 +370,12 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
let headers = download::headers(&state.user.0, state.user.1);
|
||||
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);
|
||||
queue.download(requests, headers, progress);
|
||||
}
|
||||
}
|
||||
/// `DownloadedPackSource.startReload`: the packs on top of the player's
|
||||
@@ -297,6 +423,29 @@ impl Game<'_> {
|
||||
.layout(atlas, (w, h))
|
||||
.draw(batch, atlas, self.cursor, [&yes, &no]);
|
||||
}
|
||||
/// 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);
|
||||
}
|
||||
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.
|
||||
pub(super) fn pack_prompt_click(&mut self) -> Result<()> {
|
||||
let Some(prompt) = &self.server_packs.prompt else {
|
||||
@@ -314,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<serde_json::Value>) {
|
||||
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::<download::Progress>();
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<hud_overlays::BossBar>) {
|
||||
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(
|
||||
|
||||
@@ -22,6 +22,23 @@ pub(super) struct PreparedWorld {
|
||||
}
|
||||
|
||||
impl WorldRequest {
|
||||
pub fn new(
|
||||
folder: &str,
|
||||
name: Option<&str>,
|
||||
seed: Option<i64>,
|
||||
creative: bool,
|
||||
create: Option<&horizon_client::title::WorldOptions>,
|
||||
) -> Result<Self> {
|
||||
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,
|
||||
@@ -250,7 +267,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))
|
||||
}
|
||||
|
||||
|
||||
@@ -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<f32>,
|
||||
@@ -2793,6 +2795,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);
|
||||
@@ -2810,6 +2813,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);
|
||||
@@ -2924,6 +2929,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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -34,7 +34,21 @@ pub fn headers(name: &str, uuid: u128) -> Vec<(&'static str, String)> {
|
||||
]
|
||||
}
|
||||
|
||||
type Job = (Vec<Request>, Vec<(&'static str, String)>);
|
||||
/// `HttpUtil.DownloadProgressListener`, on the channel a batch was given.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Progress {
|
||||
/// `requestStart`: the batch's next request begins.
|
||||
RequestStart,
|
||||
/// `downloadStart`: the response came, with its Content-Length if it
|
||||
/// said one.
|
||||
DownloadStart(Option<u64>),
|
||||
/// `downloadedBytes`: what this request has written so far.
|
||||
Bytes(u64),
|
||||
/// `requestFinished`: whether it succeeded.
|
||||
RequestFinished(bool),
|
||||
}
|
||||
|
||||
type Job = (Vec<Request>, Vec<(&'static str, String)>, Sender<Progress>);
|
||||
|
||||
/// `DownloadQueue`: batches download in order, on one thread.
|
||||
pub struct Queue {
|
||||
@@ -50,16 +64,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<Request>, headers: Vec<(&'static str, String)>) {
|
||||
let _ = self.jobs.send((requests, headers));
|
||||
pub fn download(
|
||||
&self,
|
||||
requests: Vec<Request>,
|
||||
headers: Vec<(&'static str, String)>,
|
||||
progress: Sender<Progress>,
|
||||
) {
|
||||
let _ = self.jobs.send((requests, headers, progress));
|
||||
}
|
||||
/// The batches finished since the last call.
|
||||
pub fn finished(&self) -> Vec<Batch> {
|
||||
@@ -68,11 +90,18 @@ impl Queue {
|
||||
}
|
||||
|
||||
/// `DownloadQueue.runDownload`: each pack into `<dir>/<id>/`, logged.
|
||||
fn run(dir: &Path, requests: &[Request], headers: &[(&'static str, String)]) -> Batch {
|
||||
fn run(
|
||||
dir: &Path,
|
||||
requests: &[Request],
|
||||
headers: &[(&'static str, String)],
|
||||
progress: &Sender<Progress>,
|
||||
) -> 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 _ = 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)),
|
||||
@@ -165,6 +194,7 @@ pub fn download_file(
|
||||
request: &Request,
|
||||
headers: &[(&'static str, String)],
|
||||
max_size: u64,
|
||||
progress: &Sender<Progress>,
|
||||
) -> Result<PathBuf, String> {
|
||||
let target = request.sha1.as_ref().map(|sha1| dir.join(sha1));
|
||||
if let (Some(target), Some(sha1)) = (&target, &request.sha1) {
|
||||
@@ -198,6 +228,7 @@ pub fn download_file(
|
||||
.header("Content-Length")
|
||||
.and_then(|v| v.trim().parse::<u64>().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
|
||||
{
|
||||
@@ -206,9 +237,13 @@ pub fn download_file(
|
||||
));
|
||||
}
|
||||
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 +253,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 +272,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<String> {
|
||||
fn save_hashed(
|
||||
input: &mut dyn Read,
|
||||
path: &Path,
|
||||
max_size: u64,
|
||||
progress: &mut dyn FnMut(u64),
|
||||
) -> io::Result<String> {
|
||||
let mut out = fs::File::create(path)?;
|
||||
let mut hasher = Sha1::new();
|
||||
let mut buffer = [0u8; 8196];
|
||||
@@ -248,6 +288,7 @@ fn save_hashed(input: &mut dyn Read, path: &Path, max_size: u64) -> io::Result<S
|
||||
break;
|
||||
}
|
||||
read_so_far += n as u64;
|
||||
progress(read_so_far);
|
||||
if read_so_far > max_size {
|
||||
return Err(io::Error::other(format!(
|
||||
"Filesize was bigger than maximum allowed (got >= {read_so_far}, limit was {max_size})"
|
||||
@@ -366,7 +407,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 +425,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 +441,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 +449,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 +457,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 +466,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();
|
||||
}
|
||||
@@ -425,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 {
|
||||
@@ -433,6 +485,7 @@ mod tests {
|
||||
sha1: None,
|
||||
}],
|
||||
Vec::new(),
|
||||
progress,
|
||||
);
|
||||
let batch = loop {
|
||||
if let Some(b) = queue.finished().pop() {
|
||||
@@ -445,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::<Vec<_>>(),
|
||||
[
|
||||
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");
|
||||
|
||||
@@ -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.
|
||||
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,
|
||||
|
||||
@@ -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<String>,
|
||||
/// `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<String>) -> 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<String>) {
|
||||
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>, 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,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+1352
File diff suppressed because it is too large
Load Diff
@@ -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"
|
||||
@@ -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"]
|
||||
@@ -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 `<sha256>.<extension>`, and opens a pull
|
||||
request adding or updating `mods/<id>.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 `<it>/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.
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<T> = std::result::Result<T, Failure>;
|
||||
|
||||
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<Value> {
|
||||
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/<id>.toml` on main, with its blob sha; None when it isn't there.
|
||||
pub fn entry(&self, id: &str) -> Result<Option<(Entry, String)>> {
|
||||
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<bool> {
|
||||
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<String> {
|
||||
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()
|
||||
}
|
||||
@@ -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<u8>,
|
||||
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<Config, String> {
|
||||
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<Inner>);
|
||||
|
||||
struct Inner {
|
||||
config: Config,
|
||||
recent: Mutex<HashMap<String, VecDeque<Instant>>>,
|
||||
}
|
||||
|
||||
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<String>) -> 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<String>) -> 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: `<payload>.<HMAC-SHA256>`, both base64url.
|
||||
|
||||
fn sign(key: &[u8], payload: &str) -> String {
|
||||
let mut mac = Hmac::<Sha256>::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<String> {
|
||||
let (payload, tag) = value.split_once('.')?;
|
||||
let payload = String::from_utf8(URL_SAFE_NO_PAD.decode(payload).ok()?).ok()?;
|
||||
let mut mac = Hmac::<Sha256>::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<String> {
|
||||
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::<u64>().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<String> {
|
||||
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<App>) -> 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<App>,
|
||||
headers: HeaderMap,
|
||||
Query(q): Query<Callback>,
|
||||
) -> Result<Response, Refusal> {
|
||||
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<App>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<serde_json::Value>, 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<String>,
|
||||
pub license: String,
|
||||
pub source: String,
|
||||
/// `https://` only; an icon in the repository is a pull request by hand.
|
||||
#[serde(default)]
|
||||
pub icon: Option<String>,
|
||||
/// A new project's minisign public key.
|
||||
#[serde(default)]
|
||||
pub key: Option<String>,
|
||||
/// The `.minisig` text.
|
||||
#[serde(default)]
|
||||
pub signature: Option<String>,
|
||||
pub version: String,
|
||||
pub game: String,
|
||||
#[serde(default)]
|
||||
pub changelog: String,
|
||||
}
|
||||
|
||||
fn take(window: &mut VecDeque<Instant>, 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<App>,
|
||||
headers: HeaderMap,
|
||||
mut multipart: Multipart,
|
||||
) -> Result<Json<serde_json::Value>, 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::<Form>(&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<String, Refusal> {
|
||||
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<String> = v
|
||||
.capabilities
|
||||
.iter()
|
||||
.map(|c| format!("- may {}", c.describe()))
|
||||
.collect();
|
||||
let requires: Vec<String> = v
|
||||
.requires
|
||||
.iter()
|
||||
.map(|r| format!("- needs {} {}", r.id, r.version))
|
||||
.collect();
|
||||
let body = format!(
|
||||
"<!-- submitted-by: {login} -->\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);
|
||||
}
|
||||
}
|
||||
@@ -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}"));
|
||||
}
|
||||
@@ -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<String, String>,
|
||||
assets: Vec<(String, usize)>,
|
||||
branches: Vec<String>,
|
||||
/// (branch, path) -> (text, message, replaced blob).
|
||||
commits: HashMap<(String, String), (String, String, Option<String>)>,
|
||||
pulls: Vec<Value>,
|
||||
/// The account the next sign-in gets.
|
||||
login: String,
|
||||
}
|
||||
|
||||
type Shared = Arc<Mutex<Mock>>;
|
||||
|
||||
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<Value>| async move {
|
||||
Json(if body["code"] == "good" {
|
||||
json!({"access_token": "gho_user"})
|
||||
} else {
|
||||
json!({"error": "bad_verification_code"})
|
||||
})
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/user",
|
||||
get(|State(s): State<Shared>| async move {
|
||||
Json(json!({"login": s.lock().unwrap().login, "id": 7}))
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/repos/o/r/contents/mods/{file}",
|
||||
get(
|
||||
|State(s): State<Shared>, UrlPath(file): UrlPath<String>| 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<Shared>, UrlPath(file): UrlPath<String>, Json(b): Json<Value>| 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<Shared>| async move {
|
||||
let names: Vec<Value> = 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<Shared>, Query(q): Query<HashMap<String, String>>, 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<Shared>, Json(b): Json<Value>| 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<Shared>, Json(b): Json<Value>| 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<String, String>,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
async fn send(&mut self, request: Request<Body>) -> (StatusCode, Value, Option<String>) {
|
||||
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::<Vec<_>>()
|
||||
.join("; ")
|
||||
}
|
||||
|
||||
fn get(&self, uri: &str) -> Request<Body> {
|
||||
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("<!-- submitted-by: alice -->"), "{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"
|
||||
);
|
||||
}
|
||||
@@ -1616,6 +1616,125 @@ impl Codec<Vec<(i32, i32, i32)>> 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<BossEvent> for BossEvent {
|
||||
fn read(r: &mut Reader) -> Result<BossEvent> {
|
||||
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,
|
||||
@@ -1626,6 +1745,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,
|
||||
@@ -2798,10 +2918,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]);
|
||||
}
|
||||
@@ -2898,4 +3019,41 @@ 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,
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 `<sha256>.<extension>` 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 |
|
||||
|
||||
+11
-5
@@ -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
|
||||
|
||||
|
||||
@@ -285,6 +285,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]'),
|
||||
|
||||
@@ -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 <the report's path>` 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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user