Merge main into fix/server-text-caret

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-26 16:01:24 +01:00
55 changed files with 2644 additions and 182 deletions
+2 -1
View File
@@ -17,4 +17,5 @@ by The Pixelify Sans Project Authors, licensed under the SIL Open Font License 1
`crates/horizon-theme/icons/pixel/*.svg` are icons from
[Pixelarticons](https://github.com/halfmage/pixelarticons) by Gerrit Halfmann, under the MIT
license (`crates/horizon-theme/icons/pixel/LICENSE-pixelarticons.txt`).
license (`crates/horizon-theme/icons/pixel/LICENSE-pixelarticons.txt`). `star.svg` is Horizon's own, drawn on
the same grid.
+203
View File
@@ -166,6 +166,38 @@ impl Contents {
Some(stack)
}
/// The stacks inside, in display order (the first is the next out).
pub fn items(&self) -> &[ItemStack] {
&self.items
}
/// `getNumberOfItemsToShow`: a full grid shows 11 and a `+N`, so the last
/// row keeps its fourth cell for the count.
pub fn shown_count(&self) -> usize {
let count = self.items.len();
let available: usize = if count > 12 { 11 } else { 12 };
let on_last_row = count % 4;
let empty = if on_last_row == 0 { 0 } else { 4 - on_last_row };
count.min(available.saturating_sub(empty))
}
/// The items the tooltip shows, and how many sit beyond them.
pub fn shown(&self) -> (&[ItemStack], u32) {
let n = self.shown_count();
let hidden = self.items[n..].iter().map(|s| s.count).sum();
(&self.items[..n], hidden)
}
/// The `Fraction` weight as the float the progress bar reads.
pub fn weight_fraction(&self) -> f32 {
self.weight.n as f32 / self.weight.d as f32
}
/// `Fraction.ONE`: a full bundle draws the full bar and says so.
pub fn is_full(&self) -> bool {
self.weight.n >= self.weight.d
}
/// `toImmutable`, written back into the bundle's component.
pub fn store(self, bundle: &mut ItemStack) {
bundle.data_mut().bundle_contents = self.items;
@@ -190,3 +222,174 @@ mod tests {
assert_eq!(over.how_many(Weight::new(1, 64)), 0);
}
}
// ------------------------------------------------------------- the tooltip
/// `ClientBundleTooltip`'s geometry, relative to the tooltip box's top-left:
/// the 96 pixel column of a 4 wide slot grid and the progress bar under it.
#[derive(Clone, Debug, PartialEq)]
pub struct TooltipLayout {
/// The component's own width (96) and height, the text's excluded.
pub width: f32,
pub height: f32,
/// Each slot's top-left and the stack in it, in reading order.
pub slots: Vec<([f32; 2], ItemStack)>,
/// The `+N` of the items past the grid: its top-left and the count.
pub overflow: Option<([f32; 2], u32)>,
/// The progress bar's top-left, its fill's width out of 94, and whether
/// the weight fills it (the full sprite).
pub bar: [f32; 2],
pub fill: f32,
pub full: bool,
/// `item.minecraft.bundle.empty` / `.full`, centred over the bar.
pub label: Option<&'static str>,
/// An empty bundle's description, wrapped at `width` from here.
pub empty_description: Option<[f32; 2]>,
}
/// The tooltip of a bundle's contents (`ClientBundleTooltip`), or None when
/// the stack is not a bundle. `x`/`y` are the box's top-left, `box_width` the
/// tooltip's width, which the component is centred in.
pub fn tooltip_layout(
items: &Items,
stack: &ItemStack,
x: f32,
y: f32,
box_width: f32,
) -> Option<TooltipLayout> {
let contents = Contents::of(items, stack)?;
let offset = ((box_width - 96.0) / 2.0).floor();
if contents.items().is_empty() {
// The description takes the top; the bar follows it.
let description_height = 9.0 * 2.0;
return Some(TooltipLayout {
width: 96.0,
height: description_height + 13.0 + 8.0,
slots: Vec::new(),
overflow: None,
bar: [x + offset, y + description_height + 4.0],
fill: 0.0,
full: false,
label: Some("item.minecraft.bundle.empty"),
empty_description: Some([x + offset, y]),
});
}
let (shown, hidden) = contents.shown();
// `gridSizeY` counts `slotCount()` (at most twelve), not the slots the
// overflow count leaves room for.
let rows = contents.items().len().min(12).div_ceil(4).max(1);
let grid_height = rows as f32 * 24.0;
let x_start = x + offset + 96.0;
let y_start = y + grid_height;
let mut slots = Vec::with_capacity(shown.len());
let mut overflow = None;
// Rows fill bottom-up and columns right-to-left, as vanilla draws them.
let mut slot = 0;
for row in 1..=rows {
for column in 1..=4 {
let at = [x_start - column as f32 * 24.0, y_start - row as f32 * 24.0];
if hidden > 0 && row == 1 && column == 1 {
overflow = Some((at, hidden));
} else if let Some(stack) = shown.get(slot) {
slots.push((at, stack.clone()));
slot += 1;
}
}
}
let weight = contents.weight_fraction();
Some(TooltipLayout {
width: 96.0,
height: grid_height + 13.0 + 8.0,
slots,
overflow,
bar: [x + offset, y + grid_height + 4.0],
// `Mth.mulAndTruncate(weight, 94)`, kept within the bar.
fill: (weight * 94.0).trunc().clamp(0.0, 94.0),
full: contents.is_full(),
label: if contents.is_full() {
Some("item.minecraft.bundle.full")
} else {
None
},
empty_description: None,
})
}
#[cfg(test)]
mod tooltip_tests {
use super::*;
/// The prepared resources, when they are on this machine: the tooltip
/// asks the item registry whether a stack is a bundle.
fn items() -> Option<Items> {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client/26.3");
if !root.join("items.json").exists() {
return None;
}
let assets = crate::assets::Assets::load(&root).ok()?;
let facts = crate::blocks::BlockFacts::load(&root, assets.registry).ok()?;
Items::load(&root, assets.registry, &facts).ok()
}
fn bundle_with(counts: &[(&str, u32)]) -> ItemStack {
let mut bundle = ItemStack::new("minecraft:bundle", 1);
bundle.data_mut().bundle_contents = counts
.iter()
.map(|(item, n)| ItemStack::new(item, *n))
.collect();
bundle
}
#[test]
fn a_grid_shows_twelve_stacks_and_counts_the_rest() {
let Some(items) = items() else { return };
let twelve: Vec<(&str, u32)> = (0..12).map(|_| ("minecraft:stone", 1)).collect();
let layout = tooltip_layout(&items, &bundle_with(&twelve), 0.0, 0.0, 96.0).unwrap();
assert_eq!(layout.slots.len(), 12);
assert_eq!(layout.overflow, None);
assert_eq!(layout.height, 3.0 * 24.0 + 13.0 + 8.0);
// Rows fill bottom-up and columns right-to-left: the first item is in
// the bottom-right cell, the twelfth in the top-left.
assert_eq!(layout.slots[0].0, [96.0 - 24.0, 3.0 * 24.0 - 24.0]);
assert_eq!(&*layout.slots[0].1.item, "minecraft:stone");
assert_eq!(layout.slots[11].0, [0.0, 0.0]);
// A wider tooltip centres the 96 pixel column in it.
let centred = tooltip_layout(&items, &bundle_with(&twelve), 0.0, 0.0, 120.0).unwrap();
assert_eq!(centred.slots[0].0[0], 12.0 + 96.0 - 24.0);
// Thirteen stacks: `getNumberOfItemsToShow` leaves the last row room
// for the count, so 8 slots show and `+6` (four stones and two dirt)
// takes the first cell.
let mut counts = twelve;
counts.push(("minecraft:dirt", 2));
let layout = tooltip_layout(&items, &bundle_with(&counts), 0.0, 0.0, 96.0).unwrap();
assert_eq!(layout.slots.len(), 8);
assert_eq!(layout.overflow, Some(([96.0 - 24.0, 48.0], 6)));
}
#[test]
fn the_bar_fills_with_the_weight_and_an_empty_bundle_explains_itself() {
let Some(items) = items() else { return };
let layout = tooltip_layout(&items, &bundle_with(&[]), 4.0, 8.0, 96.0).unwrap();
assert!(layout.slots.is_empty());
assert_eq!(layout.fill, 0.0);
assert_eq!(layout.label, Some("item.minecraft.bundle.empty"));
assert_eq!(layout.empty_description, Some([4.0, 8.0]));
assert_eq!(layout.bar, [4.0, 8.0 + 18.0 + 4.0]);
// A bundle holding one 64 stack is full: the whole bar, the full label.
let layout = tooltip_layout(
&items,
&bundle_with(&[("minecraft:stone", 64)]),
0.0,
0.0,
96.0,
)
.unwrap();
assert!(layout.full);
assert_eq!(layout.fill, 94.0);
assert_eq!(layout.label, Some("item.minecraft.bundle.full"));
// Something that is not a bundle has no component.
let dirt = ItemStack::new("minecraft:dirt", 1);
assert!(tooltip_layout(&items, &dirt, 0.0, 0.0, 96.0).is_none());
}
}
+15 -1
View File
@@ -49,6 +49,17 @@ pub struct Furnace {
/// rather than per item, and a save keeps it as the `RecipesUsed` compound.
pub recipes_used: HashMap<String, u32>,
}
/// The key `recipes_used` keeps a recipe under: its full id, as vanilla's `ResourceKey<Recipe>`
/// writes it in `RecipesUsed`. Horizon's own recipe ids are file names without the namespace, so
/// keeping both forms would write a key twice, and vanilla refuses such a furnace
/// ("Duplicate entry for key").
pub fn recipe_used_key(id: &str) -> String {
if id.contains(':') {
id.to_owned()
} else {
format!("minecraft:{id}")
}
}
/// A hopper's slots: the only plain container with five.
pub const HOPPER_SLOTS: usize = 5;
@@ -638,7 +649,10 @@ impl Furnace {
Some(out) => out.count += recipe.result.count,
None => self.items[2] = Some(recipe.result.clone()),
}
*self.recipes_used.entry(recipe.id.clone()).or_insert(0) += 1;
*self
.recipes_used
.entry(recipe_used_key(&recipe.id))
.or_insert(0) += 1;
if let Some(i) = self.items[0].as_mut() {
i.count -= 1;
if i.count == 0 {
+2
View File
@@ -1612,7 +1612,9 @@ impl Recipes {
}
/// The `experience` of the cooking recipe with this file name, and 0 for one this data
/// pack does not have (a save from another pack can name it).
/// `id` with or without the `minecraft:` namespace (a furnace keeps the full id).
pub fn cooking_experience(&self, id: &str) -> f32 {
let id = id.strip_prefix("minecraft:").unwrap_or(id);
self.cooking
.iter()
.find(|c| c.id == id)
+9 -2
View File
@@ -80,6 +80,7 @@ mod lan_mobs;
mod lan_mount_menu;
mod lan_particles;
mod lan_pvp;
mod lan_quiet;
mod lan_screen;
mod lan_stations;
mod lan_trading;
@@ -147,6 +148,7 @@ mod scoreboard;
mod screens;
mod sculk;
mod sculk_fixture;
mod server_mods;
mod server_packs;
mod server_travel;
mod shader_packs;
@@ -3338,6 +3340,7 @@ impl Game<'_> {
self.pad_rumble(horizon_client::gamepad::Rumble::BlockBroken);
// ServerPlayerGameMode.destroyBlock.
let state = self.world.block(pos[0], pos[1], pos[2]);
let broken = state;
let facts = self.res.facts().get(state).clone();
let state = self.crack_mined_pot(pos, state);
// Block.playerWillDestroy: mining their gold angers all nearby piglins.
@@ -3369,6 +3372,9 @@ impl Game<'_> {
creative,
)
});
if removed {
self.mod_block_event(pos, broken, false);
}
if removed && !creative {
let held = self.held().cloned();
self.mine_block_with_held(&facts.name, facts.hardness);
@@ -3711,6 +3717,7 @@ impl Game<'_> {
return Ok(true);
};
let target = [pos.x, pos.y, pos.z];
self.mod_block_event(target, state, true);
if let Some(entity) = BlockEntity::for_block(&self.res.facts().get(state).name) {
let key = (target[0], target[1], target[2]);
self.world.block_entities.insert(key, entity);
@@ -4244,6 +4251,7 @@ impl Game<'_> {
self.update_totem_ready();
self.tick_command_extras();
self.tick_mods();
self.tick_server_mods();
let camera_eye = self.camera_eye_height();
let stick = self.pad_move();
if self.riding.is_some() && self.player.is_some() {
@@ -9945,8 +9953,7 @@ impl Game<'_> {
} else if self.carried.is_none()
&& let Some(item) = hovered
{
let lines = self.stack_tooltip(&item);
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
self.draw_stack_tooltip(batch, &item, self.cursor.0, self.cursor.1);
}
self.draw_inventory_effects(batch, (ox, oy), Creative::WIDTH as i32);
}
+1 -2
View File
@@ -515,8 +515,7 @@ impl Game<'_> {
if self.carried.is_some() {
self.draw_carried(batch);
} else if let Some(stack) = stack_tip {
let lines = self.stack_tooltip(&stack);
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
self.draw_stack_tooltip(batch, &stack, self.cursor.0, self.cursor.1);
} else if let Some(key) = tooltip {
let text = self.translate(&key, &key);
self.draw_tooltip_lines(
+5 -1
View File
@@ -623,7 +623,10 @@ impl Game<'_> {
return;
}
if let Some(command) = message.strip_prefix('/') {
self.run_command(command);
// A client mod's command first, then a server mod's, as on a server.
if !self.mod_command(command) && !self.local_server_mod_command(command) {
self.run_command(command);
}
} else {
let line = Text::translate(
"chat.type.text",
@@ -643,6 +646,7 @@ impl Game<'_> {
self.mods_chat(&line);
}
self.lan_host_chat(message);
self.mod_player_chat(super::server_mods::Who::Local, message);
}
}
pub(super) fn chat_scroll(&mut self, amount: f32) {
+18 -3
View File
@@ -85,16 +85,16 @@ fn format_double(v: f64) -> String {
impl Game<'_> {
/// Commands.performCommand for a line without its slash.
pub(super) fn run_command(&mut self, command: &str) {
pub(super) fn run_command(&mut self, command: &str) -> bool {
if self.mod_command(command) {
return;
return true;
}
let d = vanilla::game_dispatcher();
let parse = d.parse(command, &self.ui.registries);
let result = match parse.executable() {
Err(e) => {
self.syntax_failure(&e, command);
return;
return false;
}
Ok((ctx, _)) => {
let ctx = ctx.clone();
@@ -103,6 +103,7 @@ impl Game<'_> {
self.run_chain(&root, &ctx)
}
};
let ok = result.is_ok();
if let Err(e) = result {
if e.input.is_some() {
self.syntax_failure(&e, command);
@@ -114,6 +115,20 @@ impl Game<'_> {
if self.player.is_some() {
self.check_inventory_trigger();
}
ok
}
/// `run_command` with its output suppressed
/// (`CommandSourceStack.withSuppressedOutput`): the player's own source,
/// rights and checks, no feedback and no failure in the chat.
pub(super) fn run_command_quietly(&mut self, command: &str) -> bool {
let quiet = execute::Source {
silent: true,
..self.player_source()
};
let outer = self.command_source.replace(quiet);
let ok = self.run_command(command);
self.command_source = outer;
ok
}
fn syntax_failure(&mut self, e: &CommandError, command: &str) {
self.command_failure(e.message.clone());
+3 -1
View File
@@ -222,7 +222,6 @@ impl Game<'_> {
options.report = None;
options.server = None;
options.world = None;
options.dev_mods.clear();
self.join_world_rest()?;
let (res, pack, settings) = (self.res.clone(), self.pack.clone(), self.settings.clone());
let flags = Arc::new(Flags::default());
@@ -292,6 +291,9 @@ impl Game<'_> {
launch.create.as_ref(),
)?)?;
let saved = Box::new(self.level.clone());
// IntegratedServer runs the server mods; the window the client mods.
self.mods.dev = self.options.dev_mods.clone();
self.start_mods();
// Math.max(2, options.renderDistance): past vanilla's 32 when the
// window's render distance is (Horizon's options go to 64).
let view_distance = self.settings.render_distance.max(2);
+14
View File
@@ -71,6 +71,8 @@ pub(super) struct LanHost {
/// Guests' commands waiting for the hub to be back in `self.lan`, where
/// a command can reach every player (game/lan_actions.rs).
pub commands: Vec<super::lan_actions::GuestCommand>,
/// Mods' quiet commands waiting to run a few a tick (game/lan_quiet.rs).
pub quiet: std::collections::VecDeque<super::lan_quiet::QuietBatch>,
/// The entities the guests track, described again every tick
/// (`lan_entities`) over last tick's states.
states: lan::entity::States,
@@ -603,6 +605,7 @@ impl Game<'_> {
waypoint_dead: Default::default(),
border_sent: None,
commands: Vec::new(),
quiet: std::collections::VecDeque::new(),
states: Default::default(),
});
self.audio.capture = Some(Vec::new());
@@ -968,6 +971,9 @@ impl Game<'_> {
event @ (HostEvent::Chat { .. } | HostEvent::Warn(_) | HostEvent::Error(_)) => {
self.lan_log_event(event);
}
HostEvent::PlayerChat { sender, text } => {
self.mod_player_chat(super::server_mods::Who::Uuid(sender), &text);
}
HostEvent::Joined(conn) => {
self.lan_guest_joined(&mut host, conn, state.as_ref(), entities, spawn);
if self.options.dedicated.is_some()
@@ -1037,6 +1043,14 @@ impl Game<'_> {
}
host.states = states;
}
if !host.quiet.is_empty() {
self.lan = Some(host);
self.run_quiet_commands();
host = self
.lan
.take()
.expect("the hub is back after the quiet commands");
}
self.lan_flush_effects(&mut host);
if !paused {
self.tick_guests(&mut host);
+60 -36
View File
@@ -94,11 +94,14 @@ pub(super) struct GuestPlay {
/// A guest's command waiting for the hub (`LanHost::commands`).
pub(super) struct GuestCommand {
conn: u32,
command: String,
permission: u8,
pub(super) conn: u32,
pub(super) command: String,
pub(super) permission: u8,
/// An integrated server's: no level teleports (yet).
integrated: bool,
pub(super) integrated: bool,
/// A mod's quiet command (game/lan_quiet.rs): its output suppressed, as
/// `CommandSourceStack.withSuppressedOutput` does.
pub(super) quiet: bool,
}
/// The game's own state while a guest's is swapped in (`enter_guest`), and
@@ -1210,6 +1213,9 @@ impl Game<'_> {
self.guest_carried_back(host, gi);
}
S::ChatCommand(c) => self.guest_chat_command(host, conn, &c.command),
S::CustomPayload(p) if p.channel == horizon_protocol::quiet::CHANNEL => {
self.guest_quiet_commands(host, conn, &p.data)
}
S::ChatCommandSigned(p) => self.guest_signed_command(host, conn, p),
S::ChangeDifficulty(p) if host.hub.guests[gi].permission >= 2 => {
if !self.level.difficulty_locked && (0..=3).contains(&p.difficulty) {
@@ -1533,6 +1539,10 @@ impl Game<'_> {
);
return;
}
// A server mod's command, for every player whatever their level.
if self.guest_server_mod_command(host, conn, command.trim_start_matches('/')) {
return;
}
// An integrated server runs every player's commands at their own
// permission level (`CommandSourceStack.permissions`); a LAN world
// follows its Allow Commands, and a dedicated server leaves it to
@@ -1559,6 +1569,7 @@ impl Game<'_> {
command: command.trim_start_matches('/').to_owned(),
permission,
integrated,
quiet: false,
});
}
@@ -1573,41 +1584,54 @@ impl Game<'_> {
return;
}
let c = host.commands.remove(0);
let mut host = self.lan.take().expect("checked above");
let Some(swap) = self.enter_guest(&mut host, c.conn) else {
self.lan = Some(host);
continue;
};
self.lan = Some(host);
self.chat_capture = Some(Vec::new());
let level = std::mem::replace(&mut self.ui.registries.permission, c.permission);
self.run_command(&c.command);
self.ui.registries.permission = level;
let lines = self.chat_capture.take().unwrap_or_default();
let mut host = self.lan.take().expect("a command puts the hub back");
self.leave_guest(&mut host, swap);
host.hub.sync_all_effects();
if !c.integrated {
// A teleport into another level happens before its feedback is sent.
self.run_level_teleports(&mut host);
}
// What the command earned is announced before its feedback.
self.announce_guest_advancements(&mut host);
for line in lines {
host.hub.send_to(
c.conn,
&C::SystemChat(play::SystemChat {
content: horizon_client::lan::data::component_nbt(&line.component()),
overlay: false,
}),
);
}
// The other operators hear of it; never the player whose command it was.
self.send_admin_feedback(&mut host, Some(c.conn));
self.lan = Some(host);
self.run_guest_command(c);
}
}
/// One guest's command as that guest, its feedback sent to them; false
/// when it failed (or the guest is gone).
pub(super) fn run_guest_command(&mut self, c: GuestCommand) -> bool {
let Some(mut host) = self.lan.take() else {
return false;
};
let Some(swap) = self.enter_guest(&mut host, c.conn) else {
self.lan = Some(host);
return false;
};
self.lan = Some(host);
self.chat_capture = Some(Vec::new());
let level = std::mem::replace(&mut self.ui.registries.permission, c.permission);
let ok = if c.quiet {
self.run_command_quietly(&c.command)
} else {
self.run_command(&c.command)
};
self.ui.registries.permission = level;
let lines = self.chat_capture.take().unwrap_or_default();
let mut host = self.lan.take().expect("a command puts the hub back");
self.leave_guest(&mut host, swap);
host.hub.sync_all_effects();
if !c.integrated {
// A teleport into another level happens before its feedback is sent.
self.run_level_teleports(&mut host);
}
// What the command earned is announced before its feedback.
self.announce_guest_advancements(&mut host);
for line in lines {
host.hub.send_to(
c.conn,
&C::SystemChat(play::SystemChat {
content: horizon_client::lan::data::component_nbt(&line.component()),
overlay: false,
}),
);
}
// The other operators hear of it; never the player whose command it was.
self.send_admin_feedback(&mut host, Some(c.conn));
self.lan = Some(host);
ok
}
/// The `broadcastToAdmins` lines a command queued (`source`: the guest
/// whose it was; none for the host's or the console's): every other
/// operator gets them, and the console logs them as the server's own
+5 -1
View File
@@ -28,7 +28,11 @@ impl Game<'_> {
/// SignableCommand.of: the command's message arguments, by name, with
/// their text, not past a redirect to the root (`execute ... run`).
fn signable_arguments(&mut self, permission: u8, command: &str) -> Vec<(String, String)> {
pub(super) fn signable_arguments(
&mut self,
permission: u8,
command: &str,
) -> Vec<(String, String)> {
let parse = self.parse_as(permission, command);
let nodes = &vanilla::game_dispatcher().nodes;
let root = parse.context.root;
+165
View File
@@ -0,0 +1,165 @@
//! Quiet commands (`horizon_protocol::quiet`): a Horizon client's mod sends a
//! batch of command lines in one payload, and the server runs each exactly as
//! that player typing it would (`guest_command`'s checks, the player's own
//! permission level, at the time it runs) with its output suppressed, as
//! vanilla's functions run (`CommandSourceStack.withSuppressedOutput`): no
//! feedback and no failure in anyone's chat. A batch waits in a queue and runs
//! [`PER_TICK`] lines a player a tick, so a mod can't flood a server; each
//! finished batch is one line in the server's log.
use super::{Game, lan::LanHost, lan_actions::GuestCommand};
use horizon_protocol::quiet;
use std::collections::{HashMap, VecDeque};
/// Lines a player may have waiting at most; a batch past it loses the rest.
pub(super) const PENDING: usize = 4096;
/// Lines run a player a tick at most.
pub(super) const PER_TICK: usize = 64;
/// A batch waiting to run.
pub(super) struct QuietBatch {
conn: u32,
mod_id: String,
lines: VecDeque<String>,
ran: usize,
failed: usize,
/// Lines past [`PENDING`], never run.
dropped: usize,
}
impl Game<'_> {
/// A `horizon:quiet_commands` payload from `conn`: queued (or logged as
/// refused when it breaks the payload's caps).
pub(super) fn guest_quiet_commands(&mut self, host: &mut LanHost, conn: u32, data: &[u8]) {
let Some(name) = host.hub.guest(conn).map(|g| g.name.clone()) else {
return;
};
let batch = match quiet::decode(data) {
Ok(b) => b,
Err(e) => {
super::dedicated::log(
"WARN",
&format!("{name} sent quiet commands that were refused: {e}"),
);
return;
}
};
let waiting: usize = host
.quiet
.iter()
.filter(|b| b.conn == conn)
.map(|b| b.lines.len())
.sum();
let room = PENDING.saturating_sub(waiting);
let dropped = batch.lines.len().saturating_sub(room);
host.quiet.push_back(QuietBatch {
conn,
mod_id: batch.mod_id,
lines: batch.lines.into_iter().take(room).collect(),
ran: 0,
failed: 0,
dropped,
});
}
/// The waiting batches, [`PER_TICK`] lines a player this tick, in order.
pub(super) fn run_quiet_commands(&mut self) {
let mut left: HashMap<u32, usize> = HashMap::new();
let mut i = 0;
loop {
let Some(host) = self.lan.as_mut() else {
return;
};
let Some(batch) = host.quiet.get_mut(i) else {
return;
};
let conn = batch.conn;
let budget = left.entry(conn).or_insert(PER_TICK);
let gone = host.hub.guest(conn).is_none();
if gone || batch.lines.is_empty() {
let batch = host.quiet.remove(i).expect("got it above");
if !gone {
let name = host
.hub
.guest(conn)
.map_or(String::new(), |g| g.name.clone());
super::dedicated::log("INFO", &summary(&name, &batch));
}
continue;
}
if *budget == 0 {
i += 1;
continue;
}
*budget -= 1;
let line = batch.lines.pop_front().expect("not empty");
let ok = self.run_quiet_line(conn, &line);
if let Some(batch) = self.lan.as_mut().and_then(|h| h.quiet.get_mut(i)) {
batch.ran += 1;
batch.failed += usize::from(!ok);
}
}
}
/// One line as `guest_command` would run it for `conn`, quietly. False
/// when it is refused or fails. A command that carries a chat message
/// (`say`, `msg`...) is refused: it would need the player's signature.
fn run_quiet_line(&mut self, conn: u32, line: &str) -> bool {
let allowed = self.options.dedicated.is_some() || self.allow_commands();
let Some(host) = self.lan.as_ref() else {
return false;
};
let integrated = host.hub.config.integrated;
if !integrated && (!host.settings.guest_commands || !allowed) {
return false;
}
let Some(permission) = host.hub.guest(conn).map(|g| g.permission) else {
return false;
};
let command = line.trim_start_matches('/');
if !self.signable_arguments(permission, command).is_empty() {
return false;
}
self.run_guest_command(GuestCommand {
conn,
command: command.to_owned(),
permission,
integrated,
quiet: true,
})
}
}
/// The batch's line in the server's log.
fn summary(name: &str, b: &QuietBatch) -> String {
let mut line = format!(
"{name} ran {} quiet command(s) from mod {}: {} failed",
b.ran, b.mod_id, b.failed
);
if b.dropped > 0 {
line += &format!(", {} dropped (more than {PENDING} waiting)", b.dropped);
}
line
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_log_line_counts_the_batch() {
let b = QuietBatch {
conn: 1,
mod_id: "orbital".into(),
lines: VecDeque::new(),
ran: 12,
failed: 3,
dropped: 0,
};
assert_eq!(
summary("Alex", &b),
"Alex ran 12 quiet command(s) from mod orbital: 3 failed"
);
let b = QuietBatch { dropped: 5, ..b };
assert!(summary("Alex", &b).ends_with(", 5 dropped (more than 4096 waiting)"));
}
}
+87 -31
View File
@@ -17,6 +17,7 @@ use std::{path::PathBuf, time::Duration};
#[cfg(feature = "mods")]
use {
super::Screen,
super::{execution_role::ExecutionRole, lan::LanHost, server_mods::ModEvent},
horizon_client::{
extras::Corner,
extras_hud,
@@ -28,7 +29,8 @@ use {
ui,
},
horizon_mods::{
Clock, ModKey, Mods, Output, Player, Runs, Snapshot, Status, UiScreen, UiWidget,
Clock, ModKey, Mods, Output, Player, Runs, ServerPlayer, Snapshot, Status, UiScreen,
UiWidget,
},
std::time::Instant,
winit::{event::MouseButton, keyboard::KeyCode},
@@ -52,6 +54,15 @@ pub(super) struct ModsState {
/// The chat's command tree while a running mod owns commands.
#[cfg(feature = "mods")]
tree: Option<Dispatcher>,
/// A server mod runs here: what players do is queued for it.
#[cfg(feature = "mods")]
pub(super) server: bool,
/// The players server mods saw last tick, for joins and leaves.
#[cfg(feature = "mods")]
pub(super) players: Vec<ServerPlayer>,
/// What players did this tick, for server mods at its end.
#[cfg(feature = "mods")]
pub(super) events: Vec<ModEvent>,
/// `command.run` lines for this window's own world, run on the next tick:
/// run at once, their chat lines would reach the mods while their output
/// is still being shown, and a mod answering its own lines would recurse.
@@ -272,7 +283,7 @@ impl Game<'_> {
.collect();
let enabled = &self.settings.mods.enabled;
let on = |id: &str| enabled.contains(id) || dev_ids.iter().any(|d| d == id);
let mods = Mods::load_for(Runs::Client, &paths, on, vanilla_command);
let mods = Mods::load_for(self.mod_runs(), &paths, on, vanilla_command);
self.mods.mods = mods;
let chosen = &self.settings.mods;
self.mods.mods.set_bindings(|id| chosen.keys_of(id));
@@ -282,8 +293,18 @@ impl Game<'_> {
self.sync_mod_commands();
self.show_mod_output();
}
/// Which mods this game runs: a server the server mods, the window
/// client mods, and both when it simulates the world itself (in-frame).
fn mod_runs(&self) -> Runs {
match self.options.execution_role {
ExecutionRole::IntegratedServer | ExecutionRole::DedicatedServer => Runs::Server,
ExecutionRole::Client if self.options.server_thread => Runs::Client,
ExecutionRole::Client => Runs::Both,
}
}
/// The Mods page's rows, from what loaded.
fn list_mods(&mut self) {
self.mods.server = self.mods.mods.runs_server();
let dev = &self.mods.dev;
self.settings.mods.installed = self
.mods
@@ -369,8 +390,18 @@ impl Game<'_> {
self.start_mods();
}
}
/// What mods read this tick (or frame, for mods with a `frame` hook).
/// What mods read this tick (or frame, for mods with a `frame` hook): the
/// server's players as they were at the last tick's end.
fn mod_snapshot(&mut self) -> Snapshot {
let players = if self.mods.server {
self.mods.players.clone()
} else {
Vec::new()
};
self.mod_snapshot_with(players)
}
/// What mods read, with these players on the server.
pub(super) fn mod_snapshot_with(&mut self, players: Vec<ServerPlayer>) -> Snapshot {
let player = self.player.as_ref().map(|p| Player {
x: p.position.x,
y: p.position.y,
@@ -414,7 +445,7 @@ impl Game<'_> {
mappings,
cps,
font_widths: self.mods.font_widths.clone(),
players: Vec::new(),
players,
view_hit: self.mod_view_hit(),
}
}
@@ -490,23 +521,32 @@ impl Game<'_> {
self.mods.mods.tick(self.ticks);
self.show_mod_output();
}
/// Once per frame: the frame hook, and dev mods' rebuilds.
pub(super) fn mods_frame(&mut self, elapsed: Duration) {
if !self.mods.dev.is_empty()
&& self
/// Restarts the dev mods rebuilt since the last check, once a second.
pub(super) fn reload_dev_mods(&mut self) {
if self.mods.dev.is_empty()
|| self
.mods
.checked
.is_none_or(|t| t.elapsed() >= RELOAD_CHECK)
.is_some_and(|t| t.elapsed() < RELOAD_CHECK)
{
self.mods.checked = Some(Instant::now());
if self.mods.mods.reload_changed(vanilla_command) {
let chosen = &self.settings.mods;
self.mods.mods.set_bindings(|id| chosen.keys_of(id));
self.list_mods();
self.sync_mod_commands();
return;
}
self.mods.checked = Some(Instant::now());
if self.mods.mods.reload_changed(vanilla_command) {
let chosen = &self.settings.mods;
self.mods.mods.set_bindings(|id| chosen.keys_of(id));
self.list_mods();
self.sync_mod_commands();
if self.options.execution_role.is_client() {
self.system_message(Text::literal("Mods reloaded").with_color(text::GRAY));
} else {
log::info!("Horizon: mods reloaded");
}
}
}
/// Once per frame: the frame hook, and dev mods' rebuilds.
pub(super) fn mods_frame(&mut self, elapsed: Duration) {
self.reload_dev_mods();
if !self.mods.mods.is_running() {
return;
}
@@ -537,8 +577,13 @@ impl Game<'_> {
self.mods.mods.chat(line);
self.show_mod_output();
}
/// Chat lines, command feedback and stopped mods, into the chat.
fn show_mod_output(&mut self) {
/// What mods showed: client mods' lines into the chat, server mods'
/// to their players.
pub(super) fn show_mod_output(&mut self) {
self.route_mod_output(None);
}
/// [`Game::show_mod_output`], with the hub when it is out of `self.lan`.
pub(super) fn route_mod_output(&mut self, mut host: Option<&mut LanHost>) {
for output in self.mods.mods.drain() {
let line = match output {
Output::Chat { name, text } => {
@@ -566,7 +611,16 @@ impl Game<'_> {
// `mod_ui_view` finds no widgets and the screen closes.
self.list_mods();
self.sync_mod_commands();
Text::literal(format!("Mod {name} stopped: {reason}")).with_color(text::RED)
let line = format!("Mod {name} stopped: {reason}");
if self.options.dedicated.is_some() {
super::dedicated::log("WARN", &line);
}
Text::literal(line).with_color(text::RED)
}
server
@ (Output::Tell { .. } | Output::Broadcast { .. } | Output::Reply { .. }) => {
self.route_server_output(host.as_deref_mut(), server);
continue;
}
Output::OpenScreen { owner } => {
self.open_mod_screen(owner, false);
@@ -582,20 +636,8 @@ impl Game<'_> {
}
continue;
}
// Server mods' lines: this game runs no server mod yet.
Output::Tell { .. } | Output::Broadcast { .. } | Output::Reply { .. } => continue,
};
// Not through system_message: a mod must not hear its own lines.
// Written by this client, so the Chat option doesn't hide it.
let focused = self.screen == Screen::Chat;
self.ui.chat.add(
&self.gui.atlas,
line,
None,
horizon_client::chat::ChatSource::Client,
self.ticks,
focused,
);
self.add_mod_chat_line(line);
}
// A mod may set or clear its settings page in any call, not only
// while loading: its row's Settings button follows.
@@ -604,6 +646,20 @@ impl Game<'_> {
row.has_settings = e.has_ui_settings();
}
}
/// A mod's line in the window's chat; not through system_message: a mod
/// must not hear its own lines.
/// Written by this client, so the Chat option doesn't hide it.
pub(super) fn add_mod_chat_line(&mut self, line: Text) {
let focused = self.screen == Screen::Chat;
self.ui.chat.add(
&self.gui.atlas,
line,
None,
horizon_client::chat::ChatSource::Client,
self.ticks,
focused,
);
}
/// The mods' HUD panels, stacked with the extras in their corners.
pub(super) fn draw_mod_panels(&self, batch: &mut HudBatch, corners: &mut Corners) {
for panel in self.mods.mods.panels() {
+23 -1
View File
@@ -3,7 +3,10 @@
//! window, waits until it stands in the world with the chunks around it,
//! sends a chat message and `/list`, collects the chat it is shown, leaves
//! and writes a JSON report (position, chunks, chat lines, whether the
//! server kept it connected throughout).
//! server kept it connected throughout). With `HORIZON_NET_QUIET` (lines
//! split by `;`) it then sends them as one batch of a mod's quiet commands
//! (`horizon_protocol::quiet`, `tools/quiet_commands_e2e.py`) and waits two
//! seconds for any chat they bring.
use super::Game;
use horizon_client::Result;
use serde_json::json;
@@ -23,6 +26,9 @@ impl Game<'_> {
let mut step_at = Instant::now();
let mut chat_at = 0;
let mut position = None;
let quiet: Vec<String> = std::env::var("HORIZON_NET_QUIET")
.map(|v| v.split(';').map(str::to_owned).collect())
.unwrap_or_default();
let mut chunks = 0;
let mut error = None;
while Instant::now() < deadline {
@@ -71,6 +77,22 @@ impl Game<'_> {
step_at = now;
chat_at = shown;
}
2 if answered && !quiet.is_empty() => {
for data in horizon_protocol::quiet::encode("net_harness", &quiet) {
self.send(horizon_protocol::packets::play::Serverbound::CustomPayload(
horizon_protocol::packets::configuration::CustomPayload {
channel: horizon_protocol::quiet::CHANNEL.into(),
data,
},
));
}
step = 4;
step_at = now;
}
4 if now - step_at > Duration::from_secs(2) => {
step = 3;
break;
}
2 if answered => {
step = 3;
break;
+4 -1
View File
@@ -839,7 +839,10 @@ impl Game<'_> {
remote.brand = brand;
}
}
Event::Reconfigured(registries) => self.set_registries(registries),
Event::Reconfigured(registries) => {
self.boss_overlay.reset();
self.set_registries(registries);
}
// handleTransfer: "Cannot transfer to server from
// singleplayer" (no ServerData), so the world just closes.
Event::Transfer { host, port } => {
@@ -0,0 +1,356 @@
//! Server mods in the game (`docs/mods.md`, "Server mods"): the game that
//! simulates the world (in-frame single player, the server thread, a LAN
//! host, the dedicated server) runs them. At the end of each tick it tells
//! them who joined and left, then what players said, broke and placed since
//! the last one, then ticks them; a player's command reaches them at once.
//! Their lines go to the players they name. With no server mod on, each hook
//! here is one check.
use super::{Game, lan::LanHost};
#[cfg(not(feature = "mods"))]
use horizon_world::registry::BlockStateId;
/// Who did something a server mod hears about, resolved at the tick's end.
#[cfg_attr(not(feature = "mods"), allow(dead_code))]
pub(super) enum Who {
/// The window's own player, in-frame.
Local,
/// A connection's player (the server thread's owner is one).
Conn(u32),
Uuid(u128),
}
/// What players did during a tick, for the server mods at its end.
#[cfg_attr(not(feature = "mods"), allow(dead_code))]
pub(super) enum ModEvent {
Chat(Who, String),
Block {
who: Who,
pos: [i32; 3],
state: String,
placed: bool,
},
}
#[cfg(not(feature = "mods"))]
impl Game<'_> {
pub(super) fn tick_server_mods(&mut self) {}
pub(super) fn mod_block_event(&mut self, _pos: [i32; 3], _state: BlockStateId, _placed: bool) {}
pub(super) fn mod_player_chat(&mut self, _who: Who, _text: &str) {}
pub(super) fn local_server_mod_command(&mut self, _line: &str) -> bool {
false
}
pub(super) fn guest_server_mod_command(
&mut self,
_host: &mut LanHost,
_conn: u32,
_line: &str,
) -> bool {
false
}
}
#[cfg(feature = "mods")]
mod run {
use super::{Game, LanHost, ModEvent, Who};
use horizon_client::{
command::args::GameMode as Mode,
lan::data::component_nbt,
text::{self, Text},
};
use horizon_mods::{BlockPos, GameMode, Output, ServerPlayer};
use horizon_protocol::packets::play::{self, Clientbound as C};
use horizon_world::registry::BlockStateId;
/// `UUID.toString()`.
fn uuid_string(u: u128) -> String {
let h = format!("{u:032x}");
format!(
"{}-{}-{}-{}-{}",
&h[..8],
&h[8..12],
&h[12..16],
&h[16..20],
&h[20..]
)
}
fn mode(id: i32) -> GameMode {
match id {
1 => GameMode::Creative,
2 => GameMode::Adventure,
3 => GameMode::Spectator,
_ => GameMode::Survival,
}
}
impl Game<'_> {
/// The players on this game's server: the window's own player
/// in-frame, then every connection's. `host` is the hub when it is
/// out of `self.lan`.
pub(in crate::game) fn server_players(&self, host: Option<&LanHost>) -> Vec<ServerPlayer> {
let mut out = Vec::new();
if self.options.execution_role.is_client()
&& self.remote.is_none()
&& let Some(p) = &self.player
{
out.push(ServerPlayer {
id: self.player_uuid_string(),
name: crate::game::chat::PLAYER_NAME.to_owned(),
x: p.position.x,
y: p.position.y,
z: p.position.z,
dimension: self.dim.id().to_owned(),
game_mode: match self.mode {
Mode::Survival => GameMode::Survival,
Mode::Creative => GameMode::Creative,
Mode::Adventure => GameMode::Adventure,
Mode::Spectator => GameMode::Spectator,
},
health: p.health.health(),
});
}
let guests = host
.or(self.lan.as_ref())
.into_iter()
.flat_map(|h| &h.hub.guests);
out.extend(guests.filter(|g| g.placed).map(|g| ServerPlayer {
id: uuid_string(g.uuid),
name: g.name.clone(),
x: g.position[0],
y: g.position[1],
z: g.position[2],
dimension: g.dimension.clone(),
game_mode: mode(g.game_mode),
health: g.health,
}));
out
}
/// Whether what players do now reaches server mods: one is running
/// and this game simulates the world.
fn hears_players(&self) -> bool {
self.mods.server && self.remote.is_none()
}
/// The tick's end: joins and leaves, the tick's events, the tick hook.
pub(in crate::game) fn tick_server_mods(&mut self) {
if !self.options.execution_role.is_client() {
// A server has no frames to check its dev mods in.
self.reload_dev_mods();
}
if !self.mods.server {
return;
}
let players = self.server_players(None);
let snapshot = self.mod_snapshot_with(players.clone());
self.mods.mods.set_snapshot(snapshot);
let before = std::mem::take(&mut self.mods.players);
for p in before
.iter()
.filter(|p| !players.iter().any(|q| q.id == p.id))
{
self.mods.mods.player_left(p);
}
for p in players
.iter()
.filter(|p| !before.iter().any(|q| q.id == p.id))
{
self.mods.mods.player_joined(p);
}
for event in std::mem::take(&mut self.mods.events) {
let who = |w: &Who| {
let id = match w {
Who::Local => self.player_uuid_string(),
Who::Uuid(u) => uuid_string(*u),
Who::Conn(c) => {
let guests = self.lan.iter().flat_map(|h| &h.hub.guests);
let g = guests.into_iter().find(|g| g.conn == *c);
g.map_or_else(String::new, |g| uuid_string(g.uuid))
}
};
players.iter().chain(&before).find(|p| p.id == id).cloned()
};
match event {
ModEvent::Chat(w, text) => {
if let Some(p) = who(&w) {
self.mods.mods.player_chat(&p, &text);
}
}
ModEvent::Block {
who: w,
pos,
state,
placed,
} => {
let Some(p) = who(&w) else { continue };
let pos = BlockPos {
x: pos[0],
y: pos[1],
z: pos[2],
};
if placed {
self.mods.mods.block_placed(&p, pos, &state);
} else {
self.mods.mods.block_broken(&p, pos, &state);
}
}
}
}
self.mods.mods.server_tick(self.ticks);
self.mods.players = players;
self.show_mod_output();
}
/// A player broke (or placed) `state` at `pos`: the player acting now.
pub(in crate::game) fn mod_block_event(
&mut self,
pos: [i32; 3],
state: BlockStateId,
placed: bool,
) {
if !self.hears_players() {
return;
}
let who = self.lan_acting.map_or(Who::Local, Who::Conn);
let state = self.state_string(state);
self.mods.events.push(ModEvent::Block {
who,
pos,
state,
placed,
});
}
/// A chat message a player sent.
pub(in crate::game) fn mod_player_chat(&mut self, who: Who, text: &str) {
if self.hears_players() {
self.mods.events.push(ModEvent::Chat(who, text.to_owned()));
}
}
/// `/line` typed by the window's own player in-frame: true when a
/// server mod owns it.
pub(in crate::game) fn local_server_mod_command(&mut self, line: &str) -> bool {
if !self.hears_players() {
return false;
}
let players = self.server_players(None);
let Some(me) = players.first().cloned() else {
return false;
};
let snapshot = self.mod_snapshot_with(players);
self.mods.mods.set_snapshot(snapshot);
let owned = self.mods.mods.server_command(&me, line);
self.show_mod_output();
owned
}
/// `/line` typed by a connection's player: true when a server mod
/// owns it, whatever the player's permission level.
pub(in crate::game) fn guest_server_mod_command(
&mut self,
host: &mut LanHost,
conn: u32,
line: &str,
) -> bool {
if !self.hears_players() {
return false;
}
let Some(g) = host.hub.guest(conn) else {
return false;
};
let id = uuid_string(g.uuid);
let players = self.server_players(Some(host));
let Some(me) = players.iter().find(|p| p.id == id).cloned() else {
return false;
};
let snapshot = self.mod_snapshot_with(players);
self.mods.mods.set_snapshot(snapshot);
if !self.mods.mods.server_command(&me, line) {
return false;
}
self.route_mod_output(Some(host));
true
}
/// Sends a server mod's line to the player with this id: the
/// window's own chat for the local player, a system message for a
/// connection's. `host` is the hub when it is out of `self.lan`.
pub(in crate::game) fn tell_server_player(
&mut self,
host: Option<&mut LanHost>,
id: &str,
line: Text,
) {
let local = self.options.execution_role.is_client()
&& self.remote.is_none()
&& self.player.is_some();
if local && self.player_uuid_string() == id {
self.add_mod_chat_line(line);
return;
}
let Some(host) = host.or(self.lan.as_mut()) else {
return;
};
let to = host
.hub
.guests
.iter()
.find(|g| g.placed && uuid_string(g.uuid) == id);
if let Some(conn) = to.map(|g| g.conn) {
host.hub.send_to(
conn,
&C::SystemChat(play::SystemChat {
content: component_nbt(&line.component()),
overlay: false,
}),
);
}
}
/// Routes a server mod's output: `Tell` and `Reply` to their player,
/// `Broadcast` to everyone and the log.
pub(in crate::game) fn route_server_output(
&mut self,
mut host: Option<&mut LanHost>,
output: Output,
) {
let named = |name: &str, text: String| {
let mut line = Text::literal(format!("[{name}] ")).with_color(text::GRAY);
line.push(Text::literal(text));
line
};
match output {
Output::Tell { name, player, text } => {
self.tell_server_player(host, &player, named(&name, text));
}
Output::Reply {
player,
text,
error,
} => {
let line = Text::literal(text);
let line = if error {
line.with_color(text::RED)
} else {
line
};
self.tell_server_player(host, &player, line);
}
Output::Broadcast { name, text } => {
let plain = format!("[{name}] {text}");
if self.options.dedicated.is_some() {
super::super::dedicated::log("INFO", &plain);
} else {
log::info!("{plain}");
}
for p in self.server_players(host.as_deref()) {
let line = named(&name, text.clone());
self.tell_server_player(host.as_deref_mut(), &p.id, line);
}
}
_ => {}
}
}
}
}
+175 -12
View File
@@ -1142,6 +1142,9 @@ impl Game<'_> {
let local = (self.cursor.0 - ox, self.cursor.1 - oy);
let mut tooltip: Option<Vec<(horizon_client::text::Text, u32)>> = None;
let mut anvil_name = false;
// Keep item tooltips as stacks until drawing: text alone loses the
// bundle contents component (including in the player's inventory).
let mut tooltip_stack: Option<ItemStack> = None;
{
let atlas = &self.gui.atlas;
batch.fill(
@@ -1617,7 +1620,7 @@ impl Game<'_> {
);
self.draw_item(batch, &result, ox + x, oy + y);
if hover {
tooltip = Some(self.stack_tooltip(&result));
tooltip_stack = Some(result);
}
}
}
@@ -1647,13 +1650,16 @@ impl Game<'_> {
);
if self.carried.is_none()
&& tooltip.is_none()
&& tooltip_stack.is_none()
&& let Some(stack) = self.slot_mut(slot).clone()
{
tooltip = Some(self.stack_tooltip(&stack));
tooltip_stack = Some(stack);
}
}
if self.carried.is_some() {
self.draw_carried(batch);
} else if let Some(stack) = tooltip_stack {
self.draw_stack_tooltip(batch, &stack, self.cursor.0, self.cursor.1);
} else if let Some(lines) = tooltip {
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
}
@@ -1948,32 +1954,65 @@ impl Game<'_> {
if lines.is_empty() {
return;
}
let lines: Vec<_> = lines
let lines = Self::resolved(lines);
let atlas = &self.gui.atlas;
let (x, y, w, h) =
Self::tooltip_geometry(atlas, &lines, (x, y), (batch.width, batch.height), 0.0);
Self::tooltip_box(batch, atlas, x, y, w, h);
Self::tooltip_text(batch, atlas, &lines, x, y);
}
/// A tooltip's lines with their legacy codes resolved and their colours.
fn resolved<T: Clone + Into<horizon_client::text::Text>>(
lines: &[(T, u32)],
) -> Vec<(horizon_client::text::Text, u32)> {
lines
.iter()
.map(|(text, color)| {
let text: horizon_client::text::Text = text.clone().into();
(text.resolve_legacy(), *color)
})
.collect();
let atlas = &self.gui.atlas;
.collect()
}
/// The tooltip's text's top-left corner and the box's size: beside the
/// cursor, kept on screen, `extra` pixels taller than the text.
fn tooltip_geometry(
atlas: &horizon_client::hud::HudAtlas,
lines: &[(horizon_client::text::Text, u32)],
(x, y): (f32, f32),
(width, height): (f32, f32),
extra: f32,
) -> (f32, f32, f32, f32) {
let w = lines
.iter()
.map(|(t, _)| atlas.font.width_text(t))
.fold(0.0, f32::max);
let h = if lines.len() == 1 {
.fold(0.0, f32::max)
.max(if extra > 0.0 { 96.0 } else { 0.0 });
let text_h = if lines.len() == 1 {
8.0
} else {
8.0 + 2.0 + (lines.len() - 1) as f32 * 10.0
};
let h = text_h + extra;
let mut x = x + 12.0;
let mut y = y - 12.0;
if x + w > batch.width - 4.0 {
if x + w > width - 4.0 {
x = (x - 28.0 - w).max(4.0);
}
if y + h + 3.0 > batch.height {
y = batch.height - h - 3.0;
if y + h + 3.0 > height {
y = height - h - 3.0;
}
y = y.max(4.0);
(x, y, w, h)
}
/// The box and its frame sprites.
fn tooltip_box(
batch: &mut HudBatch,
atlas: &horizon_client::hud::HudAtlas,
x: f32,
y: f32,
w: f32,
h: f32,
) {
batch.fill(atlas, x - 3.0, y - 4.0, w + 6.0, 1.0, rgba(16, 0, 16, 240));
batch.fill(
atlas,
@@ -2009,12 +2048,137 @@ impl Game<'_> {
h + 4.0,
rgba(60, 0, 190, 80),
);
}
fn tooltip_text(
batch: &mut HudBatch,
atlas: &horizon_client::hud::HudAtlas,
lines: &[(horizon_client::text::Text, u32)],
x: f32,
y: f32,
) {
let mut ty = y;
for (i, (text, color)) in lines.iter().enumerate() {
batch.text_styled(atlas, text, x, ty, *color, true);
ty += if i == 0 { 12.0 } else { 10.0 };
}
}
/// A stack's tooltip: its lines, and under them a bundle's contents
/// (`ClientBundleTooltip`: the 4 wide grid, the `+N` of what it leaves
/// out, and the weight bar).
pub(super) fn draw_stack_tooltip(
&mut self,
batch: &mut HudBatch,
stack: &ItemStack,
x: f32,
y: f32,
) {
let lines = Self::resolved(&self.stack_tooltip(stack));
if lines.is_empty() {
return;
}
// The component's height does not depend on where it is drawn, so a
// probe at the origin gives the box its extra height.
let probe = horizon_client::bundle::tooltip_layout(self.res.items(), stack, 0.0, 0.0, 96.0);
let extra = probe.as_ref().map_or(0.0, |l| l.height + 2.0);
let atlas = &self.gui.atlas;
let (x, y, w, h) =
Self::tooltip_geometry(atlas, &lines, (x, y), (batch.width, batch.height), extra);
Self::tooltip_box(batch, atlas, x, y, w, h);
let text_h = h - extra;
Self::tooltip_text(batch, atlas, &lines, x, y);
let Some(layout) =
horizon_client::bundle::tooltip_layout(self.res.items(), stack, x, y + text_h + 2.0, w)
else {
return;
};
self.draw_bundle_tooltip(batch, &layout);
}
/// `ClientBundleTooltip.extractImage`: the slots, the count past them and
/// the progress bar.
fn draw_bundle_tooltip(
&mut self,
batch: &mut HudBatch,
layout: &horizon_client::bundle::TooltipLayout,
) {
for (at, stack) in &layout.slots {
// Each draw takes the atlas on its own: the item's needs `&mut self`.
horizon_client::ui::nine_slice(
batch,
&self.gui.atlas,
"gui/sprites/container/bundle/slot_background",
at[0],
at[1],
24.0,
24.0,
u32::MAX,
);
let stack = stack.clone();
let [x, y] = *at;
self.draw_item(batch, &stack, x + 4.0, y + 4.0);
}
let atlas = &self.gui.atlas;
if let Some((at, hidden)) = layout.overflow {
let label = horizon_client::text::Text::literal(format!("+{hidden}"));
let w = atlas.font.width_text(&label);
batch.text_styled(
atlas,
&label,
at[0] + 12.0 - (w / 2.0).floor(),
at[1] + 10.0,
u32::MAX,
true,
);
}
if let Some((at, description)) = layout
.empty_description
.zip(Some("item.minecraft.bundle.empty.description"))
{
let text = horizon_client::text::Text::translate(description, &[]);
let mut ty = at[1];
for line in atlas.font.split_lines(&text, layout.width) {
batch.text_styled(atlas, &line.0, at[0], ty, 0xFFAA_AAAA, false);
ty += 9.0;
}
}
let [bx, by] = layout.bar;
let fill_sprite = if layout.full {
"gui/sprites/container/bundle/bundle_progressbar_full"
} else {
"gui/sprites/container/bundle/bundle_progressbar_fill"
};
horizon_client::ui::nine_slice(
batch,
atlas,
fill_sprite,
bx + 1.0,
by,
layout.fill,
13.0,
u32::MAX,
);
horizon_client::ui::nine_slice(
batch,
atlas,
"gui/sprites/container/bundle/bundle_progressbar_border",
bx,
by,
96.0,
13.0,
u32::MAX,
);
if let Some(key) = layout.label {
let label = horizon_client::text::Text::translate(key, &[]);
let w = atlas.font.width_text(&label);
batch.text_styled(
atlas,
&label,
bx + 48.0 - (w / 2.0).floor(),
by + 3.0,
u32::MAX,
true,
);
}
}
/// Hovered-slot tooltip on the plain inventory, crafting and container screens.
pub(super) fn draw_slot_tooltip(&mut self, batch: &mut HudBatch) {
if self.carried.is_some() {
@@ -2025,8 +2189,7 @@ impl Game<'_> {
};
let stack = self.slot_view(slot);
if let Some(stack) = stack {
let lines = self.stack_tooltip(&stack);
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
self.draw_stack_tooltip(batch, &stack, self.cursor.0, self.cursor.1);
} else if let Some(text) = self.crafter_tooltip(slot) {
self.draw_tooltip_lines(
batch,
+1 -2
View File
@@ -803,8 +803,7 @@ impl Game<'_> {
text.split('\n').map(|l| (l.to_owned(), u32::MAX)).collect();
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
} else if let Some(stack) = tooltip {
let lines = self.stack_tooltip(&stack);
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
self.draw_stack_tooltip(batch, &stack, self.cursor.0, self.cursor.1);
}
true
}
+40
View File
@@ -238,6 +238,46 @@ mod tests {
use super::*;
use horizon_protocol::registry::Ids;
/// A bundle's contents cross the wire, so a server's client can draw
/// its tooltip (BundleContents' stream codec: a list of templates).
#[test]
fn a_bundle_keeps_its_contents_across_the_wire() {
let mut components = vec![String::new(); 60];
components[component::BUNDLE_CONTENTS as usize] = "minecraft:bundle_contents".into();
let items = ["minecraft:air", "minecraft:bundle", "minecraft:stone"];
let builtin = Builtin {
registries: [
(
"minecraft:item".to_owned(),
Ids::from_names(items.iter().map(|s| s.to_string()).collect()),
),
(
"minecraft:data_component_type".to_owned(),
Ids::from_names(components),
),
]
.into(),
};
let dynamic = Dynamic {
registries: Default::default(),
};
let mut bundle = ItemStack::new("minecraft:bundle", 1);
bundle.data_mut().bundle_contents = vec![ItemStack::new("minecraft:stone", 32)];
let wire = crate::lan::guest::stack_to_network(
|name| items.iter().position(|i| *i == name).unwrap_or(0) as i32,
|_, _| None,
&Some(bundle),
)
.unwrap();
let back = from_network(&wire, &builtin, &dynamic);
let contents = &back.data().expect("components").bundle_contents;
assert_eq!(contents.len(), 1);
assert_eq!(
(&*contents[0].item, contents[0].count),
("minecraft:stone", 32)
);
}
/// What a creative client sends (`stack_to_network`) comes back whole on
/// the server: damage, both enchantment lists, repair cost, name, trim.
#[test]
+164 -1
View File
@@ -251,6 +251,10 @@ pub struct Items {
loot: HashMap<String, Value>,
/// The `jukebox_song` registry.
pub songs: HashMap<String, Song>,
/// The enchantment registry: loot functions enchant the items they roll
/// (`EnchantWithLevelsFunction`, `EnchantRandomlyFunction`), and the
/// station menus share this copy.
pub enchantments: Arc<crate::enchant::Enchantments>,
}
/// A `JukeboxSong`.
#[derive(Clone, Debug)]
@@ -701,12 +705,15 @@ impl Items {
item_tag_order: load_tag_lists(root, "item")?,
loot,
songs: load_songs(root),
enchantments: Arc::new(crate::enchant::Enchantments::load(root)),
})
}
pub fn get(&self, id: &str) -> Option<&ItemInfo> {
self.items.get(id)
}
/// Only the block and item tags, for tools that need tag membership.
/// Only the block and item tags (and the enchantment registry, which the
/// station rules and loot functions are built from), for tools that need
/// tag membership.
pub fn tags_only(root: &Path) -> Result<Self> {
Ok(Self {
items: HashMap::new(),
@@ -717,6 +724,7 @@ impl Items {
item_tag_order: load_tag_lists(root, "item")?,
loot: HashMap::new(),
songs: HashMap::new(),
enchantments: Arc::new(crate::enchant::Enchantments::load(root)),
})
}
/// An item table with only tags, for unit tests of item rules.
@@ -734,6 +742,7 @@ impl Items {
item_tags,
loot: HashMap::new(),
songs: HashMap::new(),
enchantments: Arc::new(crate::enchant::Enchantments::default()),
}
}
/// Whether `block` is in the block tag `tag` (`minecraft:fire`, no `#`).
@@ -1371,6 +1380,16 @@ impl LootContext<'_> {
self.modifiers(&modifiers, &mut stack, random);
produced.push(stack);
}
/// An enchantment function's `options` (`HolderSet`): a tag, a list or
/// one id; every enchantment when absent (`registryAccess().listElements`).
fn enchant_pool(e: &crate::enchant::Enchantments, options: &Value) -> Vec<Arc<str>> {
match options {
Value::String(s) if s.starts_with('#') => e.tag(s).to_vec(),
Value::String(s) => vec![Arc::from(s.as_str())],
Value::Array(a) => a.iter().filter_map(|x| x.as_str().map(Arc::from)).collect(),
_ => e.list.iter().map(|x| Arc::clone(&x.id)).collect(),
}
}
fn modifiers<R: RandomSource>(&self, m: &Value, stack: &mut ItemStack, random: &mut R) {
let list: Vec<&Value> = match m {
Value::Array(a) => a.iter().collect(),
@@ -1449,6 +1468,54 @@ impl LootContext<'_> {
.with_potion(id);
}
}
// EnchantWithLevelsFunction: EnchantmentHelper.enchantItem on
// the context's random (the End cities' gear).
"minecraft:enchant_with_levels" => {
let cost = Self::int_number(&f["levels"], random);
let e = &self.items.enchantments;
let pool = Self::enchant_pool(e, &f["options"]);
let chosen = e.select(self.items, random, &stack.item, cost, &pool);
// EnchantmentHelper.enchantItem: a book becomes one
// enchanted book (the fresh stack's count).
if &*stack.item == "minecraft:book" {
*stack = ItemStack::new("minecraft:enchanted_book", 1);
}
for (id, level) in chosen {
stack.enchant(&id, level);
}
}
// EnchantRandomlyFunction: one enchantment the item accepts,
// at a level between its min and max.
"minecraft:enchant_randomly" => {
let e = &self.items.enchantments;
let book = &*stack.item == "minecraft:book";
let only_compatible = f["only_compatible"].as_bool().unwrap_or(true);
let options: Vec<Arc<str>> = Self::enchant_pool(e, &f["options"])
.into_iter()
.filter(|id| {
book || !only_compatible || e.can_enchant(self.items, id, &stack.item)
})
.collect();
if options.is_empty() {
continue;
}
let id = options
[random.next_int_bound(options.len() as i32).unwrap_or(0) as usize]
.clone();
let max = e.get(&id).map_or(1, |d| d.max_level).max(1);
// `Mth.nextInt(random, 1, max)`: a single-level
// enchantment (Mending) returns 1 without drawing, so the
// rolls after this one keep vanilla's sequence.
let level = if max <= 1 {
1
} else {
1 + random.next_int_bound(max as i32).unwrap_or(0) as u32
};
if book {
*stack = ItemStack::new("minecraft:enchanted_book", 1);
}
stack.enchant(&id, level);
}
"minecraft:limit_count" => {
let limit = &f["limit"];
if let Some(min) = limit["min"].as_i64() {
@@ -1658,6 +1725,102 @@ mod tests {
assert_eq!(drops[0].potion(), Some("minecraft:fire_resistance"));
}
/// `/loot give` and every other table this dispatcher rolls: the two
/// enchantment functions (`EnchantWithLevelsFunction`,
/// `EnchantRandomlyFunction`) put their enchantments on the stack.
#[test]
fn loot_enchant_functions_enchant_the_rolled_item() {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client/26.3");
if !root.join("items.json").exists() {
return;
}
let assets = crate::assets::Assets::load(&root).unwrap();
let facts = crate::blocks::BlockFacts::load(&root, assets.registry).unwrap();
let items = Items::load(&root, assets.registry, &facts).unwrap();
let props = BTreeMap::new();
let mut random = LegacyRandom::new(11);
// A sword at levels 20..39 comes out enchanted, as in an End city.
let levels = json!({"pools":[{"rolls":1,"entries":[{"type":"minecraft:item",
"name":"minecraft:diamond_sword","modifier":[
{"type":"minecraft:enchant_with_levels","levels":{"type":"minecraft:uniform","min":20.0,"max":39.0}}]}]}]});
let mut enchanted = 0;
for _ in 0..40 {
let drops = ctx(&items, None, &props, "").evaluate(&levels, &mut random);
if drops[0].enchantments().is_empty() {
continue;
}
enchanted += 1;
assert_eq!(&*drops[0].item, "minecraft:diamond_sword");
// Levels stay within the enchantment's range.
for (id, level) in drops[0].enchantments() {
let max = items
.enchantments
.get(id)
.expect("a known enchantment")
.max_level;
assert!((1..=max).contains(level), "{id} at {level}");
}
}
assert!(
enchanted > 30,
"only {enchanted} of 40 rolls were enchanted"
);
// `enchant_randomly` on a book makes one enchanted book, its levels
// stored; the pool is the enchantment tag it names.
let book = json!({"pools":[{"rolls":1,"entries":[{"type":"minecraft:item",
"name":"minecraft:book","modifier":[
{"type":"minecraft:enchant_randomly","options":"#minecraft:on_random_loot"}]}]}]});
let drops = ctx(&items, None, &props, "").evaluate(&book, &mut random);
assert_eq!(&*drops[0].item, "minecraft:enchanted_book");
assert_eq!(drops[0].count, 1);
assert!(drops[0].enchantments().is_empty());
let stored = drops[0].stored_enchantments();
assert_eq!(stored.len(), 1, "{stored:?}");
assert!(
items
.enchantments
.in_tag("minecraft:on_random_loot", &stored[0].0)
);
// An item no enchantment accepts keeps none of them.
let dirt = json!({"pools":[{"rolls":1,"entries":[{"type":"minecraft:item",
"name":"minecraft:dirt","modifier":[
{"type":"minecraft:enchant_with_levels","levels":{"type":"minecraft:constant","value":30.0}}]}]}]});
let drops = ctx(&items, None, &props, "").evaluate(&dirt, &mut random);
assert!(drops[0].enchantments().is_empty());
}
/// `Mth.nextInt(random, 1, max)` returns `1` without drawing when the
/// enchantment has one level (`EnchantRandomlyFunction.enchantItem`), so
/// the rolls after it must not shift. Vanilla with `LegacyRandom(11)`: a
/// Mending book, then `set_count` uniform 1..64, is 46.
#[test]
fn a_single_level_enchantment_draws_no_level() {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client/26.3");
if !root.join("items.json").exists() {
return;
}
let assets = crate::assets::Assets::load(&root).unwrap();
let facts = crate::blocks::BlockFacts::load(&root, assets.registry).unwrap();
let items = Items::load(&root, assets.registry, &facts).unwrap();
let props = BTreeMap::new();
let table = json!({"pools":[{"rolls":1,"entries":[{"type":"minecraft:item",
"name":"minecraft:book","modifier":[
{"type":"minecraft:enchant_randomly","options":"minecraft:mending"},
{"type":"minecraft:set_count","count":{"type":"minecraft:uniform","min":1.0,"max":64.0}}]}]}]});
let drops = ctx(&items, None, &props, "").evaluate(&table, &mut LegacyRandom::new(11));
assert_eq!(drops.len(), 1);
assert_eq!(&*drops[0].item, "minecraft:enchanted_book");
assert_eq!(
drops[0].stored_enchantments(),
[("minecraft:mending".to_owned().into(), 1)],
"the book keeps its single-level enchantment"
);
// 46 is vanilla's count for this seed; an extra level draw gives 28.
assert_eq!(drops[0].count, 46);
}
#[test]
fn always_edible_and_consume_effects_loaded() {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+11
View File
@@ -823,6 +823,17 @@ fn login_and_configure(
_ => {}
}
};
// A Horizon client hears that this server runs its mods' quiet commands
// (horizon_protocol::quiet); a vanilla one is told nothing.
if brand == "horizon" {
send(
c,
cfg::Clientbound::CustomPayload(cfg::CustomPayload {
channel: horizon_protocol::quiet::CHANNEL.into(),
data: Vec::new(),
}),
)?;
}
for packet in sync.registry_packets(known_pack) {
send(c, cfg::Clientbound::RegistryData(packet))?;
}
+12
View File
@@ -601,6 +601,18 @@ fn network_stack(
horizon_protocol::item::Component::Stacks(charged),
));
}
// What a bundle holds, for its tooltip (ClientBundleTooltip).
if !d.bundle_contents.is_empty() {
let contents = d
.bundle_contents
.iter()
.filter_map(|c| network_stack(item_id, synced_id, &Some(c.clone())))
.collect();
stack.added.push((
horizon_protocol::item::component::BUNDLE_CONTENTS,
horizon_protocol::item::Component::Stacks(contents),
));
}
// The books a lectern shows and a guest reads.
if !d.writable_pages.is_empty() {
stack.added.push((
+19 -2
View File
@@ -128,6 +128,11 @@ pub enum HostEvent {
line: String,
secure: bool,
},
/// A chat message a player sent (after it was broadcast), for server mods.
PlayerChat {
sender: u128,
text: String,
},
/// A server log warning (ServerGamePacketListenerImpl's LOGGER.warn).
Warn(String),
/// A server log error (LOGGER.error).
@@ -371,9 +376,21 @@ impl Hub {
id
}
pub fn stack(&mut self, s: &Option<ItemStack>) -> Option<horizon_protocol::item::Stack> {
let id = s.as_ref().map(|s| self.item_id(&s.item))?;
let item = s.as_ref()?.item.clone();
let id = self.item_id(&item);
let sync = self.sync.clone();
stack_to_network(|_| id, |registry, name| sync.id(registry, name), s)
// The stacks inside it (a bundle's contents, a crossbow's projectiles)
// have ids of their own.
let item_id = |name: &str| {
if name == &*item {
return id;
}
sync.builtin
.get("minecraft:item")
.and_then(|i| i.id(name))
.unwrap_or(0)
};
stack_to_network(item_id, |registry, name| sync.id(registry, name), s)
}
pub fn broadcast(&self, packet: &C) {
@@ -219,6 +219,10 @@ impl Hub {
};
let line = format!("<{name}> {}", message.content);
self.broadcast_chat(&message, &bound, line, events);
events.push(HostEvent::PlayerChat {
sender: uuid,
text: message.content,
});
}
/// handleChatSessionUpdate: a new profile key, validated against the
+28 -2
View File
@@ -676,8 +676,10 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain
Tag::Int(n) => *n,
_ => continue,
};
f.recipes_used
.insert(id.to_string_lossy(), count.max(0) as u32);
// Saves from before the key was namespaced hold both forms of an id.
*f.recipes_used
.entry(crate::containers::recipe_used_key(&id.to_string_lossy()))
.or_insert(0) += count.max(0) as u32;
}
}
}
@@ -4382,4 +4384,28 @@ mod tests {
};
assert_eq!(back.recipes_used.get("minecraft:cooked_porkchop"), Some(&3));
}
/// A save written before the key was namespaced holds an id twice, once bare: vanilla
/// refuses such a furnace, so a load merges them under the full id.
#[test]
fn a_furnaces_recipes_used_merges_bare_and_full_ids() {
use crate::containers::BlockEntity;
let Some(BlockEntity::Furnace(mut f)) = BlockEntity::for_block("minecraft:furnace") else {
panic!("a furnace");
};
f.recipes_used
.insert("iron_ingot_from_smelting_iron_ore".to_owned(), 2);
f.recipes_used
.insert("minecraft:iron_ingot_from_smelting_iron_ore".to_owned(), 3);
let tag = encode_block_entity((1, 64, 2), &BlockEntity::Furnace(f), "minecraft:furnace");
let Some((_, BlockEntity::Furnace(back))) = decode_block_entity(&tag) else {
panic!("a furnace back");
};
assert_eq!(back.recipes_used.len(), 1);
assert_eq!(
back.recipes_used
.get("minecraft:iron_ingot_from_smelting_iron_ore"),
Some(&5)
);
}
}
+73
View File
@@ -134,3 +134,76 @@ impl SprintState {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn standing() -> Conditions {
Conditions {
enough_food: true,
on_ground: true,
..Conditions::default()
}
}
fn step(state: &mut SprintState, keys: Keys, sprinting: &mut bool) {
let current = *sprinting;
let mut next = current;
state
.tick(
keys,
Conditions {
sprinting: current,
..standing()
},
7,
|value| {
next = value;
Ok::<(), ()>(())
},
)
.unwrap();
*sprinting = next;
}
/// Vanilla sprint is a state. Releasing the sprint key, including on the
/// jump tick, keeps it while forward is held; releasing forward stops it.
#[test]
fn sprint_survives_releasing_the_key_through_a_jump() {
let mut state = SprintState::default();
let mut sprinting = false;
step(
&mut state,
Keys {
forward: true,
sprint: true,
..Keys::default()
},
&mut sprinting,
);
assert!(sprinting);
step(
&mut state,
Keys {
forward: true,
jump: true,
..Keys::default()
},
&mut sprinting,
);
assert!(
sprinting,
"a jump after the sprint key comes up must stay a sprint"
);
step(
&mut state,
Keys {
jump: true,
..Keys::default()
},
&mut sprinting,
);
assert!(!sprinting);
}
}
+3 -2
View File
@@ -14,7 +14,8 @@ use std::{fs, path::Path, sync::Arc};
/// Everything the workstation menus read, loaded once with the resources.
pub struct StationData {
pub enchantments: Enchantments,
/// The same registry `Items` carries (`Items::enchantments`).
pub enchantments: std::sync::Arc<Enchantments>,
pub recipes: StationRecipes,
pub brewing: crate::brewing::Brewing,
pub trades: crate::merchant::Trades,
@@ -25,7 +26,7 @@ pub struct StationData {
impl StationData {
pub fn load(root: &Path, items: &Items) -> Self {
Self {
enchantments: Enchantments::load(root),
enchantments: std::sync::Arc::clone(&items.enchantments),
recipes: StationRecipes::load(root, items),
brewing: crate::brewing::Brewing::load(root, items),
trades: crate::merchant::Trades::load(root),
+8
View File
@@ -122,6 +122,14 @@ pub struct Project {
pub key: Option<String>,
/// Newest first.
pub versions: Vec<Version>,
/// Its files' downloads from their releases, all versions together:
/// GitHub's counts, added by the registry's publish job (hourly).
#[serde(default, skip_serializing_if = "is_zero")]
pub downloads: u64,
}
fn is_zero(n: &u64) -> bool {
*n == 0
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -231,6 +231,7 @@ pub fn project(entry: &Entry, src: &Sources) -> Result<Project, Vec<String>> {
icon,
key: entry.key.as_ref().map(|k| k.trim().to_owned()),
versions,
downloads: 0,
})
}
+7 -1
View File
@@ -34,8 +34,14 @@ fn reads_the_sample_and_keeps_unknown_kinds() {
[Capability::GameRead, Capability::Hud, Capability::Chat]
);
// What CI writes reads back the same.
let again = Index::parse(&serde_json::to_string(&index).unwrap()).unwrap();
let text = serde_json::to_string(&index).unwrap();
let again = Index::parse(&text).unwrap();
assert_eq!(again, index);
// Download counts: the publish job adds them; none is left out.
assert_eq!(hud.downloads, 0);
assert!(!text.contains("downloads"));
let counted = text.replacen("\"versions\"", "\"downloads\":12345,\"versions\"", 1);
assert_eq!(Index::parse(&counted).unwrap().projects[0].downloads, 12345);
}
#[test]
+17 -1
View File
@@ -35,6 +35,7 @@ pub mod component {
pub const MAP_ID: i32 = 48;
pub const MAP_POST_PROCESSING: i32 = 50;
pub const CHARGED_PROJECTILES: i32 = 51;
pub const BUNDLE_CONTENTS: i32 = 52;
pub const POTION_CONTENTS: i32 = 53;
pub const WRITABLE_BOOK_CONTENT: i32 = 56;
pub const WRITTEN_BOOK_CONTENT: i32 = 57;
@@ -192,7 +193,7 @@ impl Component {
resolved: r.bool()?,
})
}
CHARGED_PROJECTILES => {
CHARGED_PROJECTILES | BUNDLE_CONTENTS => {
let n = r.count(1024)?;
Self::Stacks((0..n).map(|_| Template::read(r)).collect::<Result<_>>()?)
}
@@ -784,6 +785,21 @@ mod tests {
assert_eq!(w.data, bytes);
}
#[test]
fn bundle_contents_are_item_stack_templates() {
// A bundle (id 7) holding 32 of item 9: BundleContents is a list of
// ItemStackTemplate, as ChargedProjectiles is.
let bytes = [1, 7, 1, 0, 52, 1, 9, 32, 0, 0];
let stack = Slot::read(&mut Reader::new(&bytes)).unwrap().unwrap();
assert_eq!(
stack.component(component::BUNDLE_CONTENTS),
Some(&Component::Stacks(vec![Stack::new(9, 32)]))
);
let mut w = Writer::new();
Slot::write(&Some(stack), &mut w);
assert_eq!(w.data, bytes);
}
#[test]
fn filtered_book_pages_are_read_and_dropped() {
// A writable book with one page "hi" and its filtered "**".
+1
View File
@@ -11,6 +11,7 @@ pub mod frame;
pub mod ids;
pub mod item;
pub mod packets;
pub mod quiet;
pub mod registry;
mod resolver;
pub mod rsa;
+166
View File
@@ -0,0 +1,166 @@
//! Quiet commands: a client mod's batch of commands that a Horizon server runs
//! as the player who sent them, at that player's own permission level, with
//! no feedback in the chat (docs/mods.md, `command.run-quiet`).
//!
//! The server announces it understands them with an empty [`CHANNEL`] payload
//! in the configuration phase (a vanilla client ignores it); a client that
//! hears it sends each batch as a serverbound [`CHANNEL`] payload, and falls
//! back to chat commands on any other server. A payload is the mod's id, then
//! the lines without their slash.
use crate::{
Error, Result,
buf::{Reader, Writer},
};
/// The custom payload channel, both ways.
pub const CHANNEL: &str = "horizon:quiet_commands";
/// Lines in one payload at most; a payload with more is refused whole.
pub const MAX_LINES: usize = 256;
/// Characters in a line at most (a chat command's limit).
pub const MAX_LINE: usize = 256;
/// Characters in a mod id at most.
pub const MAX_MOD_ID: usize = 64;
/// Bytes of a serverbound custom payload's data at most
/// (ServerboundCustomPayloadPacket.MAX_PAYLOAD_SIZE).
pub const MAX_PAYLOAD: usize = 32767;
/// A batch as the server reads it.
#[derive(Clone, Debug, PartialEq)]
pub struct Batch {
pub mod_id: String,
pub lines: Vec<String>,
}
/// `lines` as few payloads as fit [`MAX_PAYLOAD`] and [`MAX_LINES`], in
/// order. Lines longer than [`MAX_LINE`] are cut, as a chat command's are.
pub fn encode(mod_id: &str, lines: &[String]) -> Vec<Vec<u8>> {
let mod_id: String = mod_id.chars().take(MAX_MOD_ID).collect();
let mut payloads = Vec::new();
let mut rest = lines
.iter()
.map(|l| -> String { l.chars().take(MAX_LINE).collect() });
let mut next = rest.next();
while next.is_some() {
let mut batch = Vec::new();
// The id, the count (a varint of at most 2 bytes for 256).
let mut size = string_size(&mod_id) + 2;
while let Some(line) = next.take() {
let more = string_size(&line);
if !batch.is_empty() && (batch.len() == MAX_LINES || size + more > MAX_PAYLOAD) {
next = Some(line);
break;
}
size += more;
batch.push(line);
next = rest.next();
}
let mut w = Writer::new();
w.string(&mod_id);
w.varint(batch.len() as i32);
for line in &batch {
w.string(line);
}
payloads.push(w.data);
}
payloads
}
fn string_size(s: &str) -> usize {
crate::buf::varint_size(s.len() as i32) + s.len()
}
/// A payload's batch; an error for one that breaks a cap.
pub fn decode(data: &[u8]) -> Result<Batch> {
if data.len() > MAX_PAYLOAD {
return Err(Error::new("quiet commands: payload too big"));
}
let mut r = Reader::new(data);
let mod_id = r.string(MAX_MOD_ID)?;
let count = r.varint()?;
if !(0..=MAX_LINES as i32).contains(&count) {
return Err(Error::new(format!("quiet commands: {count} lines")));
}
let lines = (0..count)
.map(|_| r.string(MAX_LINE))
.collect::<Result<Vec<_>>>()?;
if r.remaining() > 0 {
return Err(Error::new("quiet commands: trailing bytes"));
}
Ok(Batch { mod_id, lines })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_batch_round_trips() {
let lines = vec!["fill 0 0 0 1 1 1 stone".to_string(), "say hi".to_string()];
let payloads = encode("orbital", &lines);
assert_eq!(payloads.len(), 1);
assert_eq!(
decode(&payloads[0]).unwrap(),
Batch {
mod_id: "orbital".into(),
lines
}
);
}
#[test]
fn big_batches_split_by_lines_and_bytes() {
let lines: Vec<String> = (0..600)
.map(|i| format!("setblock {i} 0 0 stone"))
.collect();
let payloads = encode("m", &lines);
let decoded: Vec<Batch> = payloads.iter().map(|p| decode(p).unwrap()).collect();
assert_eq!(
decoded.iter().map(|b| b.lines.len()).collect::<Vec<_>>(),
[256, 256, 88]
);
assert_eq!(
decoded
.into_iter()
.flat_map(|b| b.lines)
.collect::<Vec<_>>(),
lines
);
let long: Vec<String> = (0..256).map(|_| "x".repeat(300)).collect();
for p in encode("m", &long) {
assert!(p.len() <= MAX_PAYLOAD);
assert!(
decode(&p)
.unwrap()
.lines
.iter()
.all(|l| l.len() == MAX_LINE)
);
}
}
#[test]
fn payloads_over_the_caps_are_refused() {
let mut w = Writer::new();
w.string("m");
w.varint(MAX_LINES as i32 + 1);
for _ in 0..=MAX_LINES {
w.string("say");
}
assert!(decode(&w.data).is_err());
let mut w = Writer::new();
w.string("m");
w.varint(1);
w.string(&"x".repeat(MAX_LINE + 1));
assert!(decode(&w.data).is_err());
let mut w = Writer::new();
w.string("m");
w.varint(-1);
assert!(decode(&w.data).is_err());
assert!(decode(&[0xFF]).is_err());
let mut w = Writer::new();
w.string("m");
w.varint(0);
w.u8(1);
assert!(decode(&w.data).is_err());
}
}
@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M10 1h4v2h-4ZM10 3h4v2h-4ZM8 5h8v2h-8ZM0 7h24v2h-24ZM2 9h20v2h-20ZM4 11h16v2h-16ZM6 13h12v2h-12ZM6 15h12v2h-12ZM4 17h6v2h-6ZM14 17h6v2h-6ZM4 19h4v2h-4ZM16 19h4v2h-4ZM2 21h4v2h-4ZM18 21h4v2h-4Z"/>
</svg>

After

Width:  |  Height:  |  Size: 318 B

+2
View File
@@ -67,6 +67,8 @@ pub mod icons {
"search",
"server",
"sliders",
// Not Pixelarticons': drawn for Horizon's ratings, in the same 2-unit grid.
"star",
"terminal",
"trash",
"user",
+116
View File
@@ -122,3 +122,119 @@ pub fn air_drag<W: LivingMotionWorld>(world: &mut W) -> Result<f32, W::Error> {
};
Ok(modified_friction(drag, world.air_drag_modifier()? as f32))
}
#[cfg(test)]
mod tests {
use super::*;
use horizon_core::geometry::{Vec3, trig};
struct Jumper {
velocity: Vec3,
sprinting: bool,
yaw: f32,
synced: bool,
}
impl LivingMotionWorld for Jumper {
type Error = ();
fn velocity(&self) -> Vec3 {
self.velocity
}
fn set_velocity(&mut self, velocity: Vec3) -> Result<(), ()> {
self.velocity = velocity;
Ok(())
}
fn jump_strength(&mut self) -> Result<f64, ()> {
Ok(0.42)
}
fn block_jump_factor(&mut self) -> Result<f32, ()> {
Ok(1.0)
}
fn has_jump_boost(&mut self) -> Result<bool, ()> {
Ok(false)
}
fn jump_boost_amplifier(&mut self) -> Result<i32, ()> {
Ok(0)
}
fn sprinting(&mut self) -> Result<bool, ()> {
Ok(self.sprinting)
}
fn yaw(&mut self) -> Result<f32, ()> {
Ok(self.yaw)
}
fn mark_needs_sync(&mut self) {
self.synced = true;
}
fn no_gravity(&mut self) -> Result<bool, ()> {
Ok(false)
}
fn gravity_attribute(&mut self) -> Result<f64, ()> {
Ok(0.08)
}
fn has_slow_falling(&mut self) -> Result<bool, ()> {
Ok(false)
}
fn controlling_passenger_is_player(&mut self) -> Result<bool, ()> {
Ok(false)
}
fn speed(&mut self) -> Result<f32, ()> {
Ok(0.1)
}
fn omnidirectional_air_mover(&mut self) -> Result<bool, ()> {
Ok(false)
}
fn air_drag_modifier(&mut self) -> Result<f64, ()> {
Ok(0.0)
}
}
fn impulse(yaw: f32) -> (f64, f64) {
let angle = f64::from(yaw * trig::DEG_TO_RAD);
(
f64::from(-trig::sin(angle)) * 0.2,
f64::from(trig::cos(angle)) * 0.2,
)
}
/// LivingEntity.jumpFromGround: a sprint adds ~0.2 along look; a walk does not.
#[test]
fn sprint_jump_adds_look_direction_impulse() {
for yaw in [0.0, 45.0, 90.0, 180.0, 270.0, 300.0] {
let before = Vec3::new(0.13, -0.08, -0.05);
let mut sprinting = Jumper {
velocity: before,
sprinting: true,
yaw,
synced: false,
};
jump_from_ground(&mut sprinting).unwrap();
let (dx, dz) = impulse(yaw);
let horizontal = ((dx * dx) + (dz * dz)).sqrt();
assert!(
(horizontal - 0.2).abs() < 1.0e-4,
"yaw {yaw}: impulse length {horizontal}"
);
assert!(
(sprinting.velocity.x - (before.x + dx)).abs() < 1.0e-9,
"yaw {yaw}: x {:?} expected {}",
sprinting.velocity,
before.x + dx
);
assert!((sprinting.velocity.z - (before.z + dz)).abs() < 1.0e-9);
// jump_power narrows the 0.42 strength through float, as vanilla does.
let jump_y = f64::from(0.42_f32);
assert!((sprinting.velocity.y - jump_y).abs() < 1.0e-9);
assert!(sprinting.synced);
let mut walking = Jumper {
velocity: before,
sprinting: false,
yaw,
synced: false,
};
jump_from_ground(&mut walking).unwrap();
assert_eq!(walking.velocity.x, before.x);
assert_eq!(walking.velocity.z, before.z);
assert!((walking.velocity.y - jump_y).abs() < 1.0e-9);
}
}
}
+3 -1
View File
@@ -18,7 +18,7 @@ Level: preview ([stability.md](stability.md)). Schema 1.
"projects": [{
"id": "coords_hud", "kind": "mod", "name": "Coordinates HUD", "summary": "One line.",
"description": "Markdown.", "authors": ["Horizon"], "owners": ["ludovic111"],
"license": "MIT", "source": "https://github.com/...", "icon": "https://...png", "key": "RWT...",
"license": "MIT", "source": "https://github.com/...", "icon": "https://...png", "key": "RWT...", "downloads": 1234,
"versions": [{
"version": "0.1.0", "published": "2026-10-24", "changelog": "",
"api": "0.1", "side": "client", "capabilities": ["game-read", "hud", "chat"], "api_level": 0, "game": "26.3",
@@ -41,6 +41,7 @@ Level: preview ([stability.md](stability.md)). Schema 1.
| `icon` | `https://`, optional. |
| `key` | The author's [minisign](https://jedisct1.github.io/minisign/) public key. When set, every version must be signed with it; an update signed with another key is refused. Absent: the project is unsigned and the launcher says so. |
| `versions` | Newest first, at least one. |
| `downloads` | How many times its files were downloaded, every version together: GitHub's count of each release asset, summed by the publish job, which runs every hour. Absent until a file is downloaded. Read-only: never in an entry. |
| `api` | A mod's API line (its manifest's `api`); a modpack's manifest format (`1`). |
| `side`, `capabilities` | A mod's, read from its manifest by CI, never typed by hand. |
| `api_level` | The mod API level a mod's code needs ([stability.md](stability.md#mod-api-levels)): its newest imported function's, read from the file by CI. Absent for content-only mods and in indexes built before levels. Installers take the newest version whose level the running game serves. |
@@ -167,6 +168,7 @@ opens.
## Changelog
- 2026-10-26: `projects[].downloads`, GitHub's download counts of a project's files, refreshed every hour.
- 2026-10-26: the launcher installs `shader` files into `shaderpacks/`; the sample index lists one (`glow`).
- 2026-10-25: `shader` opens, checked by `horizon_shader_api::check`; its files are `.hshader`.
- Schema 1 (2026-10-24): kinds `mod`, `modpack`, `resourcepack`, `shader`; `.hpack` format 1.
+7 -5
View File
@@ -1,7 +1,7 @@
# Mod API
Mods are Rust crates compiled to sandboxed WebAssembly components. They run in the player's game and, once server
mods land, wherever a world is simulated. Design and the runtime: [mods.md](../mods.md).
Mods are Rust crates compiled to sandboxed WebAssembly components. Client mods run in the player's game; server mods
(experimental) run wherever a world is simulated: single player, a LAN host, the dedicated server. Design and the runtime: [mods.md](../mods.md).
## Overview
@@ -87,9 +87,10 @@ release.
What real mods need next, in the order modpacks and servers need it:
- **Server mods in the game** (`api = "0.3"`, [Server mods](../mods.md#server-mods-api-03-experimental)): the
contract, runtime and SDK are here; next the server thread, LAN host and dedicated server start them and call
their hooks, then entity events, game rules and server commands with typed arguments.
- **More for server mods** (`api = "0.3"`, [Server mods](../mods.md#server-mods-api-03-experimental)): they run
on the server thread, a LAN host and the dedicated server today, with joins, chat, commands and players' block
breaking and placing; next entity events, game rules, server commands with typed arguments sent to clients'
command trees.
- **World and blocks**: read blocks, block states and biomes in loaded chunks; change them through the server's block
log, so clients and the parity harnesses see vanilla's updates.
- **Items and inventories**: the player's inventory, held item and open container; item stacks with components.
@@ -105,6 +106,7 @@ What real mods need next, in the order modpacks and servers need it:
## Changelog
- Server mods run in the game: single player (server thread and in-frame), LAN hosts, the dedicated server.
- API 0.3 (server mods, experimental): world `horizon-server-mod`, capability `players`, the `server-events`
hooks; SDK `server::ServerMod`; example `welcome`.
- SDK: `cargo horizon-mod test` and `horizon_mods::testing`, test scripts in TOML; the template has one.
+42 -8
View File
@@ -491,10 +491,40 @@ its component targets the WIT world `horizon-server-mod` instead of
Capabilities that act on a local player (`game-read`, `chat`, `hud`) are for
client mods; `players` is for server mods. In Rust: `impl
horizon_mod_sdk::server::ServerMod` and `export_server_mod!`; the example is
[`welcome`](../crates/horizon-mod-sdk/examples/welcome/src/lib.rs). The
runtime, the registry's `check` and the SDK run them today; the game starts
them once its server code calls these hooks (the next step), and until then a
server mod that is turned on shows as run elsewhere.
[`welcome`](../crates/horizon-mod-sdk/examples/welcome/src/lib.rs).
**Where they run.** The game that simulates the world starts the server mods
that are on, and only that one:
| Mode | Runs server mods | Players they see |
|---|---|---|
| Single player (default) | the server thread | the window's player, a connection like any other |
| Single player `--in-frame` | the window's own game, beside its client mods | the window's player |
| Open to LAN, Play with Friends | the host's server thread (or its window, in-frame) | the host and every guest |
| Dedicated server (`--dedicated`, `horizon-server`) | the server | every connected player |
A window that is a client of a server (single player's window, a LAN guest,
any multiplayer server) never runs them; its Mods page lists a server mod with
the others, and its switch takes effect the next time a world opens. The mods
live in `horizon-mods/` of the game folder, or of the server's folder on a
dedicated server, and are turned on as client mods are: Options > Mods, or
`mod.<id>:true` in `horizon-mods.txt`. `--dev-mod <file>` runs one always
on and reloads it when its file changes, on a server too.
**When hooks run.** At the end of each server tick the game tells the server
mods who joined and who left since the last one, then what players said,
broke and placed, in order, then calls `tick`. A command a player types
reaches its mod at once, whatever the player's permission level, and its
answer goes to that player. `tell` reaches one player, the window's own
chat for the in-frame player and a system message for a connection;
`broadcast` reaches every player and the server's log. With no server mod
on, each of these points costs one branch (measured in the PR that added
them).
**Not yet.** Clients aren't sent server mods' commands with vanilla's
command tree, so a player's chat box doesn't complete or colour them; typing
them works. Block events are a player's own breaking and placing, not
explosions, pistons or other mods.
## Publish your mod
@@ -515,6 +545,10 @@ published. Players find them at [playhorizon.dev/mods](https://playhorizon.dev/m
5. A reviewer merges it: within minutes the file is a release of horizon-mods, and the project is on the site and in
the launcher.
Once it is published, its page and its card in the launcher show its downloads (GitHub's counts of its files,
refreshed every hour) and its rating: players signed in with GitHub on its page give it 1 to 5 stars, one rating per
account, which they can change. Its owners can't rate it, and nobody sees who rated.
An update is the same form with a new version; only the project's `owners` can publish one, signed with its key if it
has one. A published file never changes. Without the form, open the pull request by hand (the repository's README
says how). The formats: [api/mod-index.md](api/mod-index.md).
@@ -561,10 +595,10 @@ so the same rustc and `Cargo.lock` give the same file.
in single player and on any server, vanilla or Horizon. They see only what
the client already knows (the snapshot), like F3 does, and act only on the
local screen and chat. A server cannot see them.
- **Server mods** (`side = "server"`) will run where the world is simulated:
Horizon's integrated server in single player and LAN, and the dedicated
server. Vanilla clients can join if the mod only uses vanilla content
(rules, commands, events).
- **Server mods** (`side = "server"`, API 0.3) run where the world is
simulated: single player's server thread (or the window, in-frame), a LAN
host and the dedicated server ([Server mods](#server-mods-api-03-experimental)).
They use only vanilla messages, so any client, vanilla or Horizon, can join.
- **Both** (`side = "both"`): a server mod with a client half (new blocks,
their textures, a custom screen). On join the Horizon server announces its
mods (id, version, SHA-256) on a `horizon:mods` custom payload channel; a
+11 -2
View File
@@ -28,12 +28,12 @@ The job is `.github/workflows/parity.yml`, a reusable workflow: `checks` calls i
repository, `run-parity.yml` for a fork's pull request a maintainer labels `run-parity`.
Horizon never downloads the game, so harnesses that compare with vanilla run only where the maintainer's own
copy is: the Mac mini and his Linux desktop. Their runners run as the maintainer's account and keep their checkout
copy is: the Mac mini, his Linux desktop and playhorizon (below). Their runners run as the maintainer's account and keep their checkout
between runs (`clean: false`), so the probes build incrementally into `.local/parity-target` and earlier passes
stand.
1. `tools/ci/runner-env.sh` puts the machine's Python 3.13 and the JDK `research-lock.json` pins on the PATH
(Homebrew and `java_home` on the Mac; on NixOS what `linux-runner.sh` pinned, else nixpkgs), and sccache when
(Homebrew and `java_home` on the Mac; on Linux what `linux-runner.sh` pinned, else nixpkgs), and sccache when
the machine has it.
2. `tools/ci/vanilla-data.sh` links `.local/` to the runner's copy of the vanilla data, cloned once from
`~/code/horizon-parity/shared-local` into `~/.actions-runners/horizon/_work/horizon/shared-local`, and
@@ -94,6 +94,15 @@ same. The nightly audit and parity-main stay on the Mac mini's runners: the audi
so it stays on one platform, and a parity-main job slowed down on the desktop because he came back could time out,
and its failures bisect and comment on merges.
**playhorizon's runner.** `playhorizon-horizon` runs on a server a hosting partner lends the project (Ubuntu, 8
AMD EPYC threads, 30 GB, in Detroit; reachable only through the maintainer's tailnet). Nobody sits at it, so the
watcher never pauses it except by hand, and it gets the machine: `RUNNER_CPUS=7 RUNNER_MEMORY=24 RUNNER_JOBS=6`.
Without Nix, `linux-runner.sh` takes the build libraries, the JDK, sccache, Xvfb and Mesa's software Vulkan
(lavapipe; there is no GPU) from apt, and Python 3.13 from uv. The partner can reach the machine, so gh is not
logged in there: the registration token comes from another machine (`RUNNER_TOKEN`), and no job with secrets may
run there (parity has none). It is also a parity host (`playhorizon` in `tools/parity_hosts.json`, 6 jobs). Like
the desktop's, it gets the `horizon-game` label only once a full trial has passed there.
## Merging
Pull requests merge with a merge commit. The orchestrator sessions review a pull request, then turn on
+104 -4
View File
@@ -8,6 +8,7 @@ use super::{
download, installed, java, FileRef, Kind, Project, Query, Source, SourceId, Version, GAME,
};
use horizon_mods::index::{self, Index, Trust};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
@@ -27,6 +28,11 @@ const FRESH: Duration = Duration::from_secs(600);
const MAX_INDEX: u64 = 16 << 20;
/// The last index fetched, kept in the game folder for when the registry can't be reached.
const CACHE: &str = "mod-browser/horizon-index.json";
/// Players' ratings of every project (the registry service, crates/horizon-mod-registry).
const RATINGS_URL: &str = "https://playhorizon.dev/api/mods/ratings";
/// Where a player rates a project: the site's GitHub sign-in, which comes back to its page.
/// The launcher has no GitHub account of its own.
const RATE: &str = "https://playhorizon.dev/api/mods/auth/login?back=/mods/";
/// Where the index comes from: `HORIZON_MOD_INDEX` (a file or an `https://` address, for a
/// test registry), else [`INDEX_URL`].
@@ -110,6 +116,92 @@ fn fetch_index() -> Result<(Index, String), String> {
Ok((index, text))
}
/// A project's ratings: 1 to 5 stars, their mean and how many.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Rating {
pub average: f32,
pub count: u64,
}
/// When the ratings were fetched last, and every rated project's [`Rating`] (None: that failed).
type Ratings = Option<Arc<HashMap<String, Rating>>>;
static RATINGS: Mutex<Option<(Instant, Ratings)>> = Mutex::new(None);
/// A project's rating as fetched last, without asking the network: None when the ratings
/// aren't known (not fetched, or the service didn't answer), `Some(None)` when it has none.
pub fn rating(id: &str) -> Option<Option<Rating>> {
let ratings = RATINGS.lock().unwrap();
let known = ratings.as_ref()?.1.as_ref()?;
Some(known.get(id).copied())
}
/// The page that signs the player in with GitHub on the site and lets them rate `id`.
pub fn rate_url(id: &str) -> String {
format!("{RATE}{id}")
}
/// Fetches the ratings again when the last try is ten minutes old: from `HORIZON_MOD_RATINGS`
/// (a file or an `https://` address, for a test registry), else [`RATINGS_URL`]; a local test
/// registry has none unless given. After a failure the browser shows downloads only.
fn refresh_ratings() {
if RATINGS
.lock()
.unwrap()
.as_ref()
.is_some_and(|(at, _)| at.elapsed() < FRESH)
{
return;
}
let given = std::env::var("HORIZON_MOD_RATINGS")
.ok()
.filter(|v| !v.is_empty());
if given.is_none() && local() {
return;
}
let at = given.unwrap_or_else(|| RATINGS_URL.to_owned());
let text = if at.starts_with("https://") {
download::agent().get(&at).call().ok().and_then(|r| {
use std::io::Read;
let mut text = String::new();
r.into_reader()
.take(MAX_INDEX)
.read_to_string(&mut text)
.ok()
.map(|_| text)
})
} else {
fs::read_to_string(&at).ok()
};
let fetched = text.map(|t| Arc::new(parse_ratings(&t)));
*RATINGS.lock().unwrap() = Some((Instant::now(), fetched));
}
/// `{"projects": {"<id>": {"average", "count"}}}`, keeping only well-formed entries.
fn parse_ratings(text: &str) -> HashMap<String, Rating> {
let Ok(json) = serde_json::from_str::<serde_json::Value>(text) else {
return HashMap::new();
};
let Some(projects) = json["projects"].as_object() else {
return HashMap::new();
};
projects
.iter()
.filter_map(|(id, r)| {
let average = r["average"].as_f64().filter(|a| (1.0..=5.0).contains(a))?;
let count = r["count"].as_u64().filter(|&c| c > 0)?;
index::valid_id(id).then(|| {
(
id.clone(),
Rating {
average: average as f32,
count,
},
)
})
})
.collect()
}
/// The browser's kind for a registry kind; None for one the launcher doesn't install yet
/// (kinds newer than this launcher).
fn kind_of(kind: &index::Kind) -> Option<Kind> {
@@ -158,7 +250,7 @@ fn project_of(p: &index::Project) -> Option<Project> {
title: p.name.clone(),
summary: p.summary.clone(),
author: p.authors.join(", "),
downloads: 0,
downloads: p.downloads,
page: format!("{SITE}/{}", p.id),
icon: p.icon.clone(),
license: p.license.clone(),
@@ -218,14 +310,19 @@ fn matches(p: &index::Project, text: &str) -> bool {
.all(|word| hay.contains(&word.to_lowercase()))
}
/// The projects of the query's kind whose words match, for this game unless `everything`.
/// The projects of the query's kind whose words match, for this game unless `everything`: the
/// most downloaded first.
fn search(index: &Index, query: &Query) -> Vec<Project> {
index
let mut found: Vec<Project> = index
.projects
.iter()
.filter(|p| kind_of(&p.kind) == Some(query.kind) && matches(p, &query.text))
.filter(|p| query.everything || p.versions.iter().any(|v| v.game == GAME))
.filter_map(project_of)
.collect();
found.sort_by_key(|p| std::cmp::Reverse(p.downloads));
found
.into_iter()
.skip(query.offset)
.take(query.limit)
.collect()
@@ -240,7 +337,9 @@ impl Source for Registry {
}
fn search(&self, query: &Query) -> Result<Vec<Project>, String> {
Ok(search(&*index()?, query))
let found = search(&*index()?, query);
refresh_ratings();
Ok(found)
}
fn project(&self, id: &str) -> Result<Project, String> {
@@ -270,6 +369,7 @@ impl Source for Registry {
}
fn details(&self, project: &Project) -> Result<Details, String> {
refresh_ratings();
let index = index()?;
let p = index
.project(&project.id)
+40
View File
@@ -49,6 +49,18 @@ fn searches_by_kind_and_words() {
assert_eq!(found("", Kind::Modpack), ["cozy"]);
assert!(found("skyblock", Kind::ResourcePack).is_empty());
assert_eq!(found("", Kind::Shader), ["glow"]);
// The index's download counts, most downloaded first.
let mut counted = index.clone();
counted.projects.push(index::Project {
id: "zoom".into(),
name: "Zoom".into(),
downloads: 12_345,
..index.project("coords_hud").unwrap().clone()
});
counted.projects[0].downloads = 80;
let first = search(&counted, &Query::new("", Kind::Mod));
let order: Vec<(&str, u64)> = first.iter().map(|p| (p.id.as_str(), p.downloads)).collect();
assert_eq!(order, [("zoom", 12_345), ("coords_hud", 80)]);
let p = hud(&index);
assert_eq!(p.support(), super::super::Support::Works);
assert_eq!(p.page, "https://playhorizon.dev/mods/coords_hud");
@@ -216,3 +228,31 @@ fn versions_for_a_newer_horizon_are_not_installed() {
assert_eq!(v.blocked.as_deref(), Some(NEEDS_NEWER));
assert_eq!(version_of(&index, p, &p.versions[0], Some(1)).blocked, None);
}
#[test]
fn ratings_keep_only_what_is_well_formed() {
let text = r#"{"projects": {
"zoom": {"average": 4.25, "count": 12},
"minimap": {"average": 9, "count": 3},
"keystrokes": {"average": 3, "count": 0},
"Bad Id": {"average": 4, "count": 1},
"fps_overlay": {"average": "5", "count": 1}
}}"#;
let ratings = parse_ratings(text);
assert_eq!(
ratings.into_iter().collect::<Vec<_>>(),
[(
"zoom".to_owned(),
Rating {
average: 4.25,
count: 12
}
)]
);
assert!(parse_ratings("not json").is_empty());
assert!(parse_ratings(r#"{"projects": []}"#).is_empty());
assert_eq!(
rate_url("zoom"),
"https://playhorizon.dev/api/mods/auth/login?back=/mods/zoom"
);
}
+34 -3
View File
@@ -175,6 +175,34 @@ fn count(n: u64) -> String {
}
}
/// A registry project's rating: five pixel stars, the mean's nearest whole number of them lit, the
/// mean and how many; None while the ratings aren't known.
pub(super) fn stars(id: &str, t: &theme::Theme) -> Option<Div> {
let row = div().flex().items_center().gap(px(2.));
Some(match horizon::rating(id)? {
None => row.text_color(t.muted).child("No ratings yet"),
Some(r) => {
let lit = r.average.round() as usize;
row.children((0..5).map(|i| {
blocks::icon(
"star",
12.,
if i < lit {
t.warn
} else {
t.muted.opacity(0.6)
},
)
}))
.child(div().ml(px(4.)).child(format!(
"{:.1} ({})",
r.average,
count(r.count)
)))
}
})
}
/// A checksum as the page shows it: the algorithm and the first and last hex digits.
fn short_sum(checksum: &str) -> String {
let (algo, hex) = checksum.split_once(':').unwrap_or(("", checksum));
@@ -968,9 +996,7 @@ impl Launcher {
if !p.author.is_empty() {
by.push(format!("by {}", p.author));
}
if p.source != SourceId::Horizon {
by.push(format!("{} downloads", count(p.downloads)));
}
by.push(format!("{} downloads", count(p.downloads)));
by.push(format!("from {}", p.source.label()));
if !p.license.is_empty() {
by.push(p.license.clone());
@@ -980,6 +1006,11 @@ impl Launcher {
.flex_col()
.child(div().truncate().child(p.summary.clone()))
.child(by.join(" · "))
.children(
(p.source == SourceId::Horizon)
.then(|| stars(&p.id, &t))
.flatten(),
)
.children(
support
.reason()
+15
View File
@@ -491,6 +491,21 @@ impl Launcher {
.gap(px(24.))
.child(div().flex().child(back))
.child(head);
// Registry projects are rated on the site, signed in with GitHub (one rating per account).
if p.source == SourceId::Horizon {
let url = browser::horizon::rate_url(&p.id);
page = page.child(
div()
.flex()
.items_center()
.gap(px(16.))
.children(super::mods_page::stars(&p.id, &t).map(|s| text(theme::UI).child(s)))
.child(
button("mods-rate", "Sign in with GitHub to rate", Kind::Ghost, &t)
.on_click(move |_, _, cx| cx.open_url(&url)),
),
);
}
if let Some(why) = support.reason() {
page = page.child(
text(theme::UI)
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""Render regression: bundle component tooltips in anvil and brewing screens.
Requires prepared 26.3 resources, a built horizon-client/horizon-ctl and Pillow.
Runs an isolated offscreen game; never opens existing player data. A name-only
bundle tooltip is narrower than the component's 96 GUI-pixel minimum, so its
purple frame cannot pass the image assertion. Screenshots are kept as evidence.
"""
import argparse
import json
from pathlib import Path
import subprocess
import tempfile
import time
from PIL import Image
import lab
ROOT = Path(__file__).resolve().parents[1]
def longest_tooltip_border(image):
"""Longest horizontal purple tooltip-frame run (physical pixels)."""
rgb = image.convert("RGB")
longest = 0
pixels = rgb.load()
for y in range(rgb.height):
run = 0
for x in range(rgb.width):
r, g, b = pixels[x, y]
if g < 25 and r < 100 and b >= r + 15:
run += 1
longest = max(longest, run)
else:
run = 0
return longest
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--game", type=Path, default=ROOT / "target/fast/horizon-client")
parser.add_argument("--ctl", type=Path, default=ROOT / "target/fast/horizon-ctl")
parser.add_argument("--resources", type=Path, default=ROOT / ".local/horizon-client/26.3")
parser.add_argument("--output", type=Path)
parser.add_argument("--in-frame", action="store_true")
args = parser.parse_args()
output = args.output or Path(tempfile.mkdtemp(prefix="bundle-tooltip-"))
output.mkdir(parents=True, exist_ok=True)
output = output.resolve()
homes = {}
for key in ("HORIZON_HOME", "HORIZON_LAUNCHER_HOME", "XDG_DATA_HOME", "XDG_CONFIG_HOME"):
directory = output / key
directory.mkdir(exist_ok=True)
homes[key] = directory
env = lab.game_env(**homes)
socket = output / "ctl.sock"
def ctl(*commands, timeout=45):
result = subprocess.run(
[str(args.ctl.resolve()), "--socket", str(socket), *map(str, commands)],
env=env, cwd=output, capture_output=True, text=True, timeout=timeout,
)
data = json.loads(result.stdout)
if result.returncode or data.get("error"):
raise RuntimeError(f"{commands}: {data}; {result.stderr}")
return data
results = []
try:
ctl("launch", "--game", args.game.resolve(), "--world", output / "world",
"--creative", "--offscreen", "--wait", "--resources", args.resources.resolve(),
*(["--in-frame"] if args.in_frame else []), timeout=120)
state = ctl("state")
px, _, pz = state["player"]["block_pos"]
x, z = (px // 16) * 16 + 8, (pz // 16) * 16 + 8
ctl("command", f"fill {x-3} 99 {z-3} {x+3} 99 {z+3} minecraft:stone")
ctl("command", f"fill {x-3} 100 {z-3} {x+3} 105 {z+3} minecraft:air")
ctl("tp", x + 0.5, 100, z + 0.5)
ctl("command", 'item replace entity @s hotbar.0 with minecraft:bundle['
'minecraft:bundle_contents=[{id:"minecraft:stone",count:32}]]')
for station in ("anvil", "brewing_stand"):
ctl("command", f"setblock {x} 100 {z+2} minecraft:{station}")
ctl("wait", 5)
ctl("look-at-block", x, 100, z+2, "north")
ctl("interact", x, 100, z+2, "north")
time.sleep(0.3)
ui = ctl("ui")
slot = next(w for w in ui["widgets"] if w["id"] == "slot-0")
assert slot["stack"]["item"] == "minecraft:bundle", slot
sx, sy, sw, sh = slot["bounds"]
ctl("scroll-at", sx + sw / 2, sy + sh / 2, 0)
screenshot = output / f"{station}.png"
ctl("screenshot", screenshot)
with Image.open(screenshot) as image:
scale = image.width / ui["gui_size"][0]
longest = longest_tooltip_border(image)
# The component reserves 96 GUI pixels; allow its border/integer rounding.
required = int(90 * scale)
results.append({"station": station, "border_pixels": longest,
"required_pixels": required, "pass": longest >= required,
"screenshot": str(screenshot)})
ctl("close")
finally:
try:
ctl("quit")
except (RuntimeError, subprocess.TimeoutExpired, json.JSONDecodeError):
pass
report = {"mode": "in-frame" if args.in_frame else "server-thread", "results": results}
(output / "results.json").write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps(report, indent=2))
assert len(results) == 2 and all(r["pass"] for r in results), "Missing bundle component tooltip"
if __name__ == "__main__":
main()
+79 -36
View File
@@ -1,7 +1,8 @@
#!/usr/bin/env bash
# A Horizon CI runner (labels self-hosted, Linux, X64, horizon-game and the host's name) on a Linux machine of the
# maintainer's (NixOS: ludodesktop, ludothinkpad), as a systemd user service of the account that holds his
# Minecraft files, like the Mac mini's runners (docs/release-flow.md). Run it on that machine, as that user:
# maintainer's (NixOS: ludodesktop, ludothinkpad; Ubuntu: playhorizon, a partner's server), as a systemd user service
# of the account that holds his Minecraft files, like the Mac mini's runners (docs/release-flow.md). Run it on that
# machine, as that user:
#
# bash tools/ci/linux-runner.sh install # register (gh login), install, start; again to update the scripts
# bash tools/ci/linux-runner.sh status # the services, the runner's state, the pause watcher's last lines
@@ -12,10 +13,16 @@
# never runs as the service). horizon-runner-pause.service (runner_pause.py) starts the runner only while nobody
# uses the machine (screen locked or untouched for 15 min, no game), and stops it otherwise. The runner runs nice,
# in horizon-ci.slice (low CPU and I/O weight, memory capped), on its own virtual screen: vscreen (a headless sway)
# where it is installed, else Xvfb from nixpkgs with Mesa's Vulkan drivers.
# where it is installed, else Xvfb with Mesa's Vulkan drivers (from nixpkgs on NixOS, from the system elsewhere).
# HORIZON_SHARED_SOURCE: the imported vanilla data (default ~/horizon-local/shared-local, else
# ~/code/horizon/.local); RUNNER_JOBS: cargo jobs and harnesses at once (default a third of the threads, at most 8:
# ludodesktop froze under ~7 cold cargo builds on 2026-10-14, and it is the maintainer's own machine).
# RUNNER_CPUS and RUNNER_MEMORY (GB): the slice's CPU quota and memory cap (default half the threads, two thirds of
# the memory), for a machine that does nothing else. RUNNER_TOKEN: the registration (or, for uninstall, removal)
# token, made with gh on another machine, where gh must not be logged in (a machine someone else also runs):
# RUNNER_TOKEN=$(gh api -X POST repos/ludovic111/horizon/actions/runners/registration-token --jq .token)
# Without Nix (Debian, Ubuntu), the packages come from apt (the list in system_packages) and python3.13 from the
# PATH (uv python install 3.13, linked into ~/.local/bin).
set -euo pipefail
repo=ludovic111/horizon
dir=$HOME/.actions-runners/horizon
@@ -27,9 +34,16 @@ here=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
# Nix packages the jobs need, kept alive by GC roots in $dir/nix. nix-build prints the store path; the root's name
# gets the output's suffix (alsa-dev-dev for alsa-lib.dev), so it is not read back from the link.
nix_out() { nix-build '<nixpkgs>' -A "$1" -o "$dir/nix/$2" | tail -1; }
nixos() { [ -d /run/current-system/sw ]; }
system_packages="build-essential pkg-config cmake libasound2-dev libudev-dev sccache mesa-vulkan-drivers libvulkan1 xvfb
libx11-6 libxcursor1 libxrandr2 libxi6 libxinerama1 libxkbcommon0 libxkbcommon-x11-0 libgl1 libegl1 rsync git curl"
# The runner is a .NET program: on NixOS its native libraries (libstdc++, ICU, OpenSSL) come from nix-ld.
export LD_LIBRARY_PATH=/run/current-system/sw/share/nix-ld/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
if nixos; then export LD_LIBRARY_PATH=/run/current-system/sw/share/nix-ld/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}; fi
token() {
if [ -n "${RUNNER_TOKEN:-}" ]; then echo "$RUNNER_TOKEN"; else gh api -X POST "repos/$repo/actions/runners/$1" --jq .token; fi
}
# NixOS has no /bin/bash: the runner's scripts (again after each of its self-updates) get a portable one.
fix_shebangs() { sed -i '1s|^#!/bin/bash|#!/usr/bin/env bash|' "$dir"/*.sh "$dir"/bin/*.sh; }
@@ -77,32 +91,59 @@ install() {
fi
tar xzf "$cache" -C "$dir"
fix_shebangs
gh api -X POST "repos/$repo/actions/runners/registration-token" --jq .token |
token registration-token |
(cd "$dir" && bash ./config.sh --unattended --replace --url "https://github.com/$repo" --token "$(cat)" \
--name "$name" --labels "${RUNNER_LABELS:-horizon-game,$(hostname)}" --work _work > /dev/null)
fi
# Libraries for building (pkg-config) and running (dlopen) the game, the JDK pinned by research-lock.json, sccache.
local alsa udev java
alsa=$(nix_out alsa-lib.dev alsa-dev)
udev=$(nix_out systemd.dev systemd-dev)
java=$(nix_out "jdk$(sed -n 's/.*"java_major": *\([0-9]*\).*/\1/p' "$here/../../research-lock.json" | head -1)_headless" jdk)/lib/openjdk
nix_out sccache sccache > /dev/null # on the PATH below: runner-env.sh hands it to cargo
local libs=/run/opengl-driver/lib:/run/current-system/sw/share/nix-ld/lib
if ! command -v vscreen > /dev/null; then
local mesa x
mesa=$(nix_out mesa mesa)
x=$(nix_out xvfb-run xvfb-run)
for lib in libx11 libxcursor libxrandr libxi libxext libxinerama libxrender libxxf86vm libxcb libxkbcommon \
vulkan-loader libGL; do
libs=$libs:$(nix_out "$lib" "$lib")/lib
done
libs=$mesa/lib:$libs
echo "VK_DRIVER_FILES=$mesa/share/vulkan/icd.d/intel_icd.x86_64.json:$mesa/share/vulkan/icd.d/lvp_icd.x86_64.json" \
> "$dir/.env.display"
echo "$x/bin" > "$dir/.path.display"
local major java platform_env path
major=$(sed -n 's/.*"java_major": *\([0-9]*\).*/\1/p' "$here/../../research-lock.json" | head -1)
if nixos; then
local alsa udev libs=/run/opengl-driver/lib:/run/current-system/sw/share/nix-ld/lib display_path=""
alsa=$(nix_out alsa-lib.dev alsa-dev)
udev=$(nix_out systemd.dev systemd-dev)
java=$(nix_out "jdk${major}_headless" jdk)/lib/openjdk
nix_out sccache sccache > /dev/null # on the PATH below: runner-env.sh hands it to cargo
platform_env="PKG_CONFIG_PATH=$alsa/lib/pkgconfig:$udev/lib/pkgconfig
C_INCLUDE_PATH=$udev/include
NIX_LD=/run/current-system/sw/share/nix-ld/lib/ld.so
NIX_LD_LIBRARY_PATH=/run/current-system/sw/share/nix-ld/lib"
if ! command -v vscreen > /dev/null; then
local mesa x
mesa=$(nix_out mesa mesa)
x=$(nix_out xvfb-run xvfb-run)
for lib in libx11 libxcursor libxrandr libxi libxext libxinerama libxrender libxxf86vm libxcb libxkbcommon \
vulkan-loader libGL; do
libs=$libs:$(nix_out "$lib" "$lib")/lib
done
libs=$mesa/lib:$libs
platform_env="$platform_env
VK_DRIVER_FILES=$mesa/share/vulkan/icd.d/intel_icd.x86_64.json:$mesa/share/vulkan/icd.d/lvp_icd.x86_64.json"
display_path=$x/bin:
fi
platform_env="$platform_env
LD_LIBRARY_PATH=$libs"
path="$dir/cargo/bin:$display_path$dir/nix/sccache/bin:$java/bin:$HOME/.local/bin:/run/wrappers/bin:/etc/profiles/per-user/$USER/bin:/run/current-system/sw/bin"
else
# apt's packages (installed here when sudo needs no password), its JDK, and Mesa's software Vulkan (lavapipe):
# a server has no GPU.
local missing
missing=$(dpkg-query -W -f='${Package} ${Status}\n' $system_packages "openjdk-$major-jdk-headless" 2>&1 |
awk '/^dpkg-query: no packages found matching/ {print $NF; next} !/ installed$/ {print $1}' | tr '\n' ' ')
if [ -n "${missing// /}" ]; then
sudo -n env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq $missing > /dev/null ||
{ echo "Install first: sudo apt-get install $missing"; exit 1; }
fi
command -v python3.13 > /dev/null || [ -x "$HOME/.local/bin/python3.13" ] ||
{ echo "No python3.13: uv python install 3.13, then link it into ~/.local/bin"; exit 1; }
java=$(ls -d /usr/lib/jvm/java-"$major"-openjdk-* | head -1)
platform_env=""
command -v vscreen > /dev/null || platform_env="VK_DRIVER_FILES=$(ls /usr/share/vulkan/icd.d/lvp_icd*.json | head -1)"
path="$dir/cargo/bin:$java/bin:$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin"
fi
cat > "$dir/.env" <<EOF
{
cat <<EOF
LANG=C.UTF-8
RUSTUP_HOME=$dir/rustup
CARGO_HOME=$dir/cargo
@@ -115,25 +156,26 @@ HORIZON_NO_AUDIO=1
HORIZON_NO_HEARTBEAT=1
HORIZON_TELEMETRY_URL=off
HORIZON_LAUNCHER_NO_SELF_UPDATE=1
PKG_CONFIG_PATH=$alsa/lib/pkgconfig:$udev/lib/pkgconfig
C_INCLUDE_PATH=$udev/include
LD_LIBRARY_PATH=$libs
NIX_LD=/run/current-system/sw/share/nix-ld/lib/ld.so
NIX_LD_LIBRARY_PATH=/run/current-system/sw/share/nix-ld/lib
EOF
if [ -f "$dir/.env.display" ]; then cat "$dir/.env.display" >> "$dir/.env"; else echo "VSCREEN=ci-horizon" >> "$dir/.env"; fi
echo "$dir/cargo/bin:$(cat "$dir/.path.display" 2>/dev/null || true)${dir}/nix/sccache/bin:$java/bin:$HOME/.local/bin:/run/wrappers/bin:/etc/profiles/per-user/$USER/bin:/run/current-system/sw/bin" \
| sed 's/::/:/g' > "$dir/.path"
[ -n "$platform_env" ] && echo "$platform_env"
command -v vscreen > /dev/null && echo "VSCREEN=ci-horizon"
true
} > "$dir/.env"
echo "$path" > "$dir/.path"
rm -f "$dir/.env.display" "$dir/.path.display" # written by older versions of this script
local memory cpus
memory=${RUNNER_MEMORY:-$(( $(awk '/MemTotal/ {print int($2 / 1048576)}' /proc/meminfo) * 2 / 3 ))}
cpus=${RUNNER_CPUS:-$(( threads / 2 > 1 ? threads / 2 : 1 ))}
cat > "$units/horizon-ci.slice" <<EOF
[Unit]
Description=Horizon CI: the runner's jobs and parity workers sent from other machines
[Slice]
CPUWeight=20
IOWeight=20
CPUQuota=$(( threads * 50 ))%
MemoryHigh=$(( $(awk '/MemTotal/ {print int($2 / 1048576)}' /proc/meminfo) / 2 ))G
MemoryMax=$(( $(awk '/MemTotal/ {print int($2 / 1048576)}' /proc/meminfo) * 2 / 3 ))G
CPUQuota=$(( cpus * 100 ))%
MemoryHigh=$(( memory * 3 / 4 ))G
MemoryMax=${memory}G
EOF
cat > "$units/horizon-runner.service" <<EOF
[Unit]
@@ -156,6 +198,7 @@ EOF
Description=Runs the Horizon CI runner only while nobody uses the machine or plays on it
[Service]
ExecStart=$(command -v python3) $dir/runner_pause.py
Environment=NORMAL_CPUS=$cpus
Restart=always
RestartSec=10
[Install]
@@ -201,7 +244,7 @@ status() {
uninstall() {
systemctl --user disable --now horizon-runner-pause.service horizon-runner.service 2>/dev/null || true
gh api -X POST "repos/$repo/actions/runners/remove-token" --jq .token |
token remove-token |
(cd "$dir" && bash ./config.sh remove --token "$(cat)")
rm -f "$units/horizon-runner.service" "$units/horizon-runner-pause.service" "$units/horizon-ci.slice"
systemctl --user daemon-reload
+1 -1
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
# The tools the vanilla harnesses need, on a self-hosted runner (label horizon-game): the Mac mini's, whose service
# starts with a bare PATH, and the Linux ones (tools/ci/linux-runner.sh, NixOS). Python 3.13 and the JDK pinned by
# starts with a bare PATH, and the Linux ones (tools/ci/linux-runner.sh: NixOS, Ubuntu). Python 3.13 and the JDK pinned by
# research-lock.json come from the machine, never from a download. Writes them to $GITHUB_PATH and $GITHUB_ENV for
# the next steps.
set -euo pipefail
+10
View File
@@ -20,6 +20,16 @@
"nice": 19,
"note": "ludodesktop, the maintainer's own machine: only while nobody uses it (tools/ci/runner_pause.py: screen locked or untouched for 15 min, no game; a paused desktop refuses workers and stops the running ones, whose harnesses then run here); 8 jobs at most, in the CI runner's environment and slice"
},
"playhorizon": {
"ssh": "ludovic@playhorizon",
"root": ".actions-runners/horizon/parity-host",
"shell": "systemd-run --user --scope --quiet --slice=horizon-ci.slice --unit=horizon-parity-worker-$$ bash -c",
"setup": "test ! -e ~/.actions-runners/horizon/paused && set -a && . ~/.actions-runners/horizon/.env && set +a && export PATH=$(cat ~/.actions-runners/horizon/.path) && unset WAYLAND_DISPLAY && export DISPLAY=:$(cat ~/.actions-runners/horizon/display)",
"python": "python3.13",
"jobs": 6,
"nice": 10,
"note": "a partner's server (Ubuntu, 8 EPYC threads, 30 GB, Detroit; tailnet only), used by nothing else: 6 jobs, in the CI runner's environment, slice and Xvfb screen (tools/ci/linux-runner.sh); the light Linux checks that used to go to the ThinkPad go here"
},
"thinkpad": {
"ssh": "thinkpad",
"root": "code/horizon-parity",
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""Mods' quiet commands on Horizon's dedicated server, end to end (horizon_protocol::quiet).
Horizon's dedicated server (a flat world) and Horizon's headless client (`HORIZON_NET_REPORT`, the net
harness), which joins, then sends a batch of quiet commands as a mod would (`HORIZON_NET_QUIET`):
- as a player who isn't an operator: `setblock` is refused (the block stays air), as it would be typed;
- as an operator: `setblock` runs, a `fill` that changes nothing fails, and `say` is refused (a chat
message needs the player's signature);
- either way the player's chat gets nothing of them, and the server logs one line per batch: the player,
the mod, how many ran and how many failed.
python3 tools/quiet_commands_e2e.py --bin-dir target/fast
The client runs with fresh HORIZON_HOME, launcher and XDG folders and without audio; the logs go to --out.
"""
import argparse
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import lab # noqa: E402
from integration_env import run_game # noqa: E402
from test_dedicated_server_parity import Server # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
PLAYER = 'Tester'
PROPERTIES = {
'online-mode': 'false',
'white-list': 'false',
'level-type': 'minecraft\\:flat',
'generate-structures': 'false',
'spawn-protection': '0',
'view-distance': '3',
'simulation-distance': '3',
'pause-when-empty-seconds': '-1',
}
BLOCK = '2 -55 2'
# What a player would see of these commands, were they typed.
FEEDBACK = ['Changed the block', 'No blocks were filled', 'Unknown or incomplete command', 'hi from a mod',
'Could not set the block']
def join(binary, port, out, label, lines):
"""The headless client joins, sends `lines` as one quiet batch and leaves: its report."""
home = Path(tempfile.mkdtemp(prefix=f'quiet-{label}-'))
report = out / f'{label}-report.json'
# run_game gives the game fresh home, launcher and XDG folders.
env = dict(HORIZON_NET_REPORT=str(report), HORIZON_NET_QUIET=';'.join(lines))
with (out / f'{label}-client.log').open('w') as log:
run_game([str(binary), '--resources', str(lab.RESOURCES), '--render-distance', '2',
'--server', f'127.0.0.1:{port}', '--name', PLAYER],
cwd=home, env=dict(os.environ, **env), stdout=log, stderr=subprocess.STDOUT, timeout=300,
check=True)
shutil.rmtree(home, ignore_errors=True)
return json.loads(report.read_text())
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--bin-dir', help='a prebuilt horizon-client (default: build it with the fast profile)')
parser.add_argument('--out', default=str(ROOT / '.local/quiet-commands-e2e'), help='logs go here')
args = parser.parse_args()
out = Path(args.out)
shutil.rmtree(out, ignore_errors=True)
out.mkdir(parents=True)
if args.bin_dir:
binary = Path(args.bin_dir) / 'horizon-client'
else:
subprocess.run(['cargo', 'build', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client'],
cwd=ROOT, check=True)
binary = Path(lab.cargo_target()) / 'fast' / 'horizon-client'
port = lab.free_port()
directory = out / 'server'
directory.mkdir()
props = dict(PROPERTIES, **{'server-port': str(port)})
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()),
encoding='iso-8859-1')
(directory / 'eula.txt').write_text('eula=true\n')
server = Server([binary, '--resources', lab.RESOURCES, '--dedicated', '--nogui'], directory, 'server')
failures = []
def check(what, ok, detail=''):
print(('PASS ' if ok else 'FAIL ') + what + ('' if ok else f': {detail}'))
if not ok:
failures.append(what)
def test_block(want):
"""The console's `execute if block`: 'Test passed' when the block is `want`."""
before = len(server.lines)
server.console(f'execute if block {BLOCK} {want}')
deadline = time.time() + 30
while time.time() < deadline:
answer = [l for l in server.lines[before:] if 'Test passed' in l or 'Test failed' in l]
if answer:
return 'Test passed' in answer[0]
time.sleep(0.2)
raise AssertionError('the console never answered execute if block')
try:
server.wait_for(r'Done \(')
# Not an operator: the setblock is refused, as typed.
got = join(binary, port, out, 'not-op', [f'setblock {BLOCK} minecraft:gold_block'])
server.wait_for(rf'{PLAYER} ran 1 quiet command\(s\) from mod net_harness: 1 failed', timeout=30)
check('not an operator: connected throughout', got['error'] is None, got['error'])
check("not an operator: a quiet setblock is refused", not test_block('minecraft:gold_block'))
heard = [c for c in got['chat'] if any(f in c for f in FEEDBACK)]
check('not an operator: nothing in the chat', not heard, heard)
server.wait_for(rf'{PLAYER} left the game', timeout=60)
# An operator: it runs, quietly.
server.console(f'op {PLAYER}')
server.wait_for(rf'Made {PLAYER} a server operator', timeout=30)
got = join(binary, port, out, 'op', [f'setblock {BLOCK} minecraft:gold_block',
f'fill {BLOCK} {BLOCK} minecraft:gold_block', 'say hi from a mod'])
server.wait_for(rf'{PLAYER} ran 3 quiet command\(s\) from mod net_harness: 2 failed', timeout=30)
check('operator: connected throughout', got['error'] is None, got['error'])
check('operator: the quiet setblock ran', test_block('minecraft:gold_block'))
heard = [c for c in got['chat'] if any(f in c for f in FEEDBACK)]
check('operator: nothing in the chat (no feedback, no failure, no say)', not heard, heard)
said = [l for l in server.lines if 'hi from a mod' in l]
check('operator: say is refused', not said, said)
finally:
server.stop()
print(f'logs: {out}')
sys.exit(1 if failures else 0)
if __name__ == '__main__':
main()
+3 -2
View File
@@ -18,7 +18,7 @@ import { CPUS, GPUS, singleThread } from "./src/hardware.js";
import { isGame, isLauncher, launcherVersion, newestFirst } from "./src/versions.js";
import { contributorsFrom, contributorsHtml } from "./src/contributors.js";
import { areaFilterHtml, boardFilterHtml, boardFrom, boardHtml, creditFrom, creditHtml, helpWantedHtml, journalFrom, journalHtml, journalJson, overviewHtml, roadmapHtml, slimIssue, suggestItemsHtml } from "./src/hub.js";
import { INDEX_URL, KINDS, SUBMIT, listHtml, projectHtml, readIndex, submitHtml } from "./src/mods.js";
import { INDEX_URL, KINDS, SORTS, SUBMIT, listHtml, projectHtml, readIndex, sorted, submitHtml } from "./src/mods.js";
const site = dirname(fileURLToPath(import.meta.url));
const dist = join(site, "dist");
@@ -484,10 +484,11 @@ const modsList = ` <p class="kicker"><span>Mods</span>Made for Horizon, r
<button type="button" class="button secondary small" data-kind-filter="all" aria-pressed="true">All</button>
${KINDS.map(([k, label]) => ` <button type="button" class="button secondary small" data-kind-filter="${k}" aria-pressed="false">${label}</button>`).join("\n")}
</div>
<select class="mod-search mod-sort" id="mod-sort" aria-label="Order">${SORTS.map(([k, label]) => `<option value="${k}">${label}</option>`).join("")}</select>
</div>
<p class="meta release-count" data-mod-count>${modProjects.length} of ${modProjects.length}</p>
<div class="mod-list" id="mod-list" aria-live="polite">
${listHtml(modProjects)}
${listHtml(sorted(modProjects, "downloads"))}
</div>`;
const modPages = [
{ file: "mods.html", path: "/mods", title: "Mods", description: "Mods, modpacks and resource packs made for Horizon, reviewed, each with what it may do and how to install it.", main: modsList },
+89 -9
View File
@@ -1,32 +1,47 @@
// /mods and /mods/<id>: the registry's list (kind filter, search) and a project's page. The pages are baked from
// the index at build time; this fetches the published index again so a project merged since shows at once.
import { INDEX_URL, KINDS, listHtml, matches, projectHtml, readIndex } from "./mods.js";
// /mods and /mods/<id>: the registry's list (kind filter, search, order) and a project's page. The pages are baked
// from the index at build time; this fetches the published index again so a project merged since shows at once,
// the ratings (crates/horizon-mod-registry), and on a project's page the signed-in player's own rating to change.
import { API, INDEX_URL, KINDS, RATINGS, SORTS, listHtml, matches, projectHtml, rateHtml, ratingOf, readIndex, sorted, starsHtml } from "./mods.js";
import { cached, setUpMenu, setUpTheme } from "./chrome.js";
import { escape } from "./markdown.js";
const root = document.getElementById("mods");
const baked = readIndex(JSON.parse(document.getElementById("mods-index").textContent || "null")) || [];
let projects = baked;
// Every project's ratings, once the service answered.
let ratings = null;
let kind = "all";
let text = "";
let order = "downloads";
// On a project's page: the signed-in account ({login, csrf}) or null, and its own rating of the project.
let me;
let mine = null;
const id = (location.pathname.match(/^\/mods\/([a-z0-9_]+)\/?$/) || [])[1];
function showList() {
const list = root.querySelector("#mod-list");
if (!list) return;
const shown = projects.filter((p) => matches(p, kind, text));
list.innerHTML = listHtml(shown);
const shown = sorted(projects.filter((p) => matches(p, kind, text)), order, ratings);
list.innerHTML = listHtml(shown, ratings);
root.querySelector("[data-mod-count]").textContent = `${shown.length} of ${projects.length}`;
root.querySelectorAll("[data-kind-filter]").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.kindFilter === kind)));
}
function showRate(p, message = "") {
const rate = root.querySelector("#mod-rate");
if (!rate || me === undefined) return;
rate.innerHTML = rateHtml(p, me, mine) + (message ? `<p class="mod-error">${escape(message)}</p>` : "");
}
function showProject() {
const p = projects.find((x) => x.id === id);
const page = root.querySelector(".mod-page, .mod-missing");
if (!page) return;
if (p) {
page.outerHTML = projectHtml(p);
page.outerHTML = projectHtml(p, ratings ? ratingOf(ratings, p.id) : undefined);
document.title = `${p.name} · Horizon`;
showRate(p);
} else {
page.outerHTML = `<div class="mod-missing"><h1 class="display page-title">Not in the registry</h1><p class="lede">No project is called ${id} here. It may not be published yet, or it was taken down.</p><a class="button secondary" href="/mods">Every mod</a></div>`;
}
@@ -37,7 +52,56 @@ function render() {
else showList();
}
if (!id) {
// The signed-in account and its own rating, for the page's rating control.
async function signIn() {
try {
const r = await fetch(`${API}/me`, { credentials: "same-origin" });
me = r.ok ? await r.json() : null;
if (me) {
const own = await fetch(`${API}/${id}/rating`, { credentials: "same-origin" });
mine = own.ok ? (await own.json()).stars : null;
}
} catch {
me = null;
}
const p = projects.find((x) => x.id === id);
if (p) showRate(p);
}
async function rate(stars) {
const p = projects.find((x) => x.id === id);
if (!p || !me) return;
root.querySelectorAll(".mod-star").forEach((b) => (b.disabled = true));
let message = "";
try {
const r = await fetch(`${API}/${id}/rating`, {
method: "POST",
credentials: "same-origin",
headers: { "Content-Type": "application/json", "X-CSRF-Token": me.csrf },
body: JSON.stringify({ stars }),
});
const json = await r.json().catch(() => ({}));
if (r.ok) {
mine = json.stars;
ratings = { ...ratings, [id]: { average: json.average, count: json.count } };
const line = root.querySelector("[data-mod-rating]");
if (line) line.innerHTML = `${starsHtml(ratingOf(ratings, id))} · `;
} else {
message = json.error || `The service answered ${r.status}.`;
}
} catch {
message = "The service didn't answer. Try again in a minute.";
}
showRate(p, message);
}
if (id) {
root.addEventListener("click", (e) => {
const star = e.target.closest?.("[data-stars]");
if (star) rate(Number(star.dataset.stars));
});
signIn();
} else {
root.querySelectorAll("[data-kind-filter]").forEach((b) =>
b.addEventListener("click", () => {
kind = b.dataset.kindFilter;
@@ -48,8 +112,15 @@ if (!id) {
text = e.target.value;
showList();
});
const wanted = new URLSearchParams(location.search).get("kind");
if (KINDS.some(([k]) => k === wanted)) kind = wanted;
root.querySelector("#mod-sort")?.addEventListener("change", (e) => {
order = e.target.value;
showList();
});
const query = new URLSearchParams(location.search);
if (KINDS.some(([k]) => k === query.get("kind"))) kind = query.get("kind");
if (SORTS.some(([k]) => k === query.get("sort"))) order = query.get("sort");
const select = root.querySelector("#mod-sort");
if (select) select.value = order;
}
setUpTheme();
@@ -64,3 +135,12 @@ cached("horizon:mod-index", () => fetch(INDEX_URL).then((r) => (r.ok ? r.json()
}
})
.catch(() => {});
fetch(RATINGS)
.then((r) => (r.ok ? r.json() : Promise.reject(new Error(`${r.status}`))))
.then((json) => {
if (json && typeof json.projects === "object") {
ratings = json.projects;
render();
}
})
.catch(() => {});
+66 -6
View File
@@ -8,6 +8,8 @@ const REGISTRY = "https://github.com/ludovic111/horizon-mods";
export const SUBMIT = "/mods/submit";
// The submission form's service (crates/horizon-mod-registry), behind the site's own address.
export const API = "/api/mods";
// Every project's ratings: {projects: {<id>: {average, count}}}.
export const RATINGS = `${API}/ratings`;
export const SCHEMA = 1;
// The kinds the site shows, in the filter's order. Kinds a newer index adds are left out until the site knows them.
@@ -43,21 +45,66 @@ const initial = (p) => escape((p.name || p.id).trim().charAt(0).toUpperCase());
const icon = (p) =>
https(p.icon) ? `<img class="mod-icon" src="${escape(p.icon)}" alt="" width="48" height="48" loading="lazy">` : `<span class="mod-icon" aria-hidden="true">${initial(p)}</span>`;
// A count as the launcher writes it: 999, 12.3k, 4.1M.
export function count(n) {
if (n < 1000) return String(n);
if (n < 1e6) return `${(n / 1e3).toFixed(1)}k`;
return `${(n / 1e6).toFixed(1)}M`;
}
const downloads = (p) => {
const n = Number.isSafeInteger(p.downloads) && p.downloads > 0 ? p.downloads : 0;
return `${count(n)} download${n === 1 ? "" : "s"}`;
};
// A project's ratings from the service's answer, or null when it has none.
export function ratingOf(ratings, id) {
const r = ratings?.[id];
return r && Number.isFinite(r.average) && Number.isSafeInteger(r.count) && r.count > 0 ? r : null;
}
// Five stars, the mean's nearest whole number of them filled, and the mean and count beside.
export function starsHtml(r) {
if (!r) return `<span class="mod-stars-none">No ratings yet</span>`;
const on = Math.min(5, Math.max(0, Math.round(r.average)));
const mean = r.average.toFixed(1);
return `<span class="mod-rating-line" title="${mean} out of 5 from ${r.count} rating${r.count === 1 ? "" : "s"}"><span class="mod-stars" aria-hidden="true"><span class="on">${"★".repeat(on)}</span>${"★".repeat(5 - on)}</span><span class="sr-only">Rated ${mean} out of 5</span> ${mean} (${count(r.count)})</span>`;
}
// The list's orders: the most downloaded first (the default), the best rated, or by name.
export const SORTS = [
["downloads", "Most downloaded"],
["rating", "Best rated"],
["name", "Name"],
];
export function sorted(projects, by, ratings) {
const avg = (p) => ratingOf(ratings, p.id)?.average || 0;
const votes = (p) => ratingOf(ratings, p.id)?.count || 0;
const name = (a, b) => a.name.localeCompare(b.name);
const order = {
downloads: (a, b) => (b.downloads || 0) - (a.downloads || 0) || name(a, b),
rating: (a, b) => avg(b) - avg(a) || votes(b) - votes(a) || name(a, b),
name,
}[by] || (() => 0);
return [...projects].sort(order);
}
export function matches(p, kind, text) {
if (kind !== "all" && p.kind !== kind) return false;
const hay = `${p.id} ${p.name} ${p.summary} ${(p.authors || []).join(" ")}`.toLowerCase();
return text.toLowerCase().split(/\s+/).filter(Boolean).every((w) => hay.includes(w));
}
// The list: a row per project, newest version and kind on the right.
export function listHtml(projects) {
// The list: a row per project; its kind, ratings (once `ratings` is known), downloads and newest version on the right.
export function listHtml(projects, ratings = null) {
if (!projects.length) return `<p class="lede mod-empty">Nothing here yet. <a href="${SUBMIT}">Submit yours</a>.</p>`;
return projects
.map(
(p) => `<a class="mod-row" href="/mods/${p.id}" data-kind="${escape(p.kind)}" data-search="${escape(`${p.id} ${p.name} ${p.summary} ${(p.authors || []).join(" ")}`.toLowerCase())}">
${icon(p)}
<span class="mod-text"><span class="mod-name">${escape(p.name)}</span><span class="mod-summary">${escape(p.summary || "")}</span></span>
<span class="mod-side"><span class="badge">${escape(KIND_NAMES[p.kind] || p.kind)}</span><span class="mod-version">${escape(p.versions[0].version)} · ${escape((p.authors || []).join(", "))}</span></span>
<span class="mod-side"><span class="badge">${escape(KIND_NAMES[p.kind] || p.kind)}</span><span class="mod-stats">${ratings ? `${starsHtml(ratingOf(ratings, p.id))} · ` : ""}${downloads(p)}</span><span class="mod-version">${escape(p.versions[0].version)} · ${escape((p.authors || []).join(", "))}</span></span>
</a>`,
)
.join("\n");
@@ -92,8 +139,19 @@ export function ownersHtml(p) {
return `<p class="meta mod-owners">Published by ${links}</p>`;
}
// One project's page.
export function projectHtml(p) {
// The rating control under a project's ratings: five stars to press when signed in (`mine`, the account's own
// rating, pressed), a sign-in link when not, a note for the project's owners.
export function rateHtml(p, me, mine) {
if (!me) return `<a class="button secondary small" href="${API}/auth/login?back=/mods/${escape(p.id)}">Sign in with GitHub to rate</a>`;
if ((p.owners || []).some((o) => o.toLowerCase() === String(me.login).toLowerCase())) return `<p class="meta">You publish it: players rate it.</p>`;
const stars = [1, 2, 3, 4, 5]
.map((n) => `<button type="button" class="mod-star${n <= (mine || 0) ? " lit" : ""}" data-stars="${n}" aria-pressed="${mine === n}" aria-label="${n} star${n === 1 ? "" : "s"}">★</button>`)
.join("");
return `<span class="mod-rate-label">${mine ? "Your rating" : "Rate it"}</span><span class="mod-rate-stars" role="group" aria-label="Your rating">${stars}</span>`;
}
// One project's page; `rating` is its ratings (null: none yet), left out when they aren't known.
export function projectHtml(p, rating) {
const v = p.versions[0];
const caps = v.capabilities || [];
const capsHtml = caps.length
@@ -108,7 +166,9 @@ export function projectHtml(p) {
return `<article class="mod-page" data-id="${escape(p.id)}">
<header class="mod-head">${icon(p)}<div><p class="kicker"><span>${escape(KIND_NAMES[p.kind] || p.kind)}</span>${escape((p.authors || []).join(", "))}</p>${ownersHtml(p)}
<h1 class="display page-title">${escape(p.name)}</h1><p class="lede">${escape(p.summary || "")}</p>
<p class="mod-badges">${trust(p)} <span class="badge">${escape(p.license)}</span> <span class="badge">${escape(v.version)}</span>${v.side ? ` <span class="badge">${escape(v.side)}</span>` : ""}</p></div></header>
<p class="mod-badges">${trust(p)} <span class="badge">${escape(p.license)}</span> <span class="badge">${escape(v.version)}</span>${v.side ? ` <span class="badge">${escape(v.side)}</span>` : ""}</p>
<p class="mod-stats mod-page-stats"><span data-mod-rating>${rating === undefined ? "" : `${starsHtml(rating)} · `}</span>${downloads(p)}</p>
<div class="mod-rate" id="mod-rate" aria-live="polite"></div></div></header>
${p.description ? `<div class="prose">${markdown(p.description)}</div>` : ""}
${p.kind === "mod" ? `<h2 class="heading">What it may do</h2>${capsHtml}<p class="meta">Mods run in a sandbox with no file, network or clock access. The game refuses a mod whose code uses more than this list.</p>` : ""}
${requires}
+48 -1
View File
@@ -1,6 +1,6 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { CAPABILITIES, entryFrom, listHtml, matches, projectHtml, readIndex, submitHtml } from "./mods.js";
import { CAPABILITIES, count, entryFrom, listHtml, matches, projectHtml, rateHtml, ratingOf, readIndex, sorted, starsHtml, submitHtml } from "./mods.js";
const project = (over = {}) => ({
id: "coords_hud", kind: "mod", name: "Coordinates HUD", summary: "Where you are.", authors: ["Horizon"],
@@ -61,3 +61,50 @@ test("a project's page links its owners' GitHub profiles, and only valid logins"
for (const bad of ["bad login", "github.com/-x", "a--b", "<script>"]) assert.ok(!html.includes(bad), bad);
assert.ok(!projectHtml(project()).includes("Published by"));
});
test("downloads read short, as in the launcher, and a missing count is 0", () => {
assert.equal(count(999), "999");
assert.equal(count(12_345), "12.3k");
assert.equal(count(51_404_735), "51.4M");
assert.ok(listHtml([project({ downloads: 12_345 })]).includes("12.3k downloads"));
assert.ok(listHtml([project({ downloads: 1 })]).includes("1 download<"));
assert.ok(projectHtml(project({ downloads: "9999<script>" })).includes("0 downloads"));
});
test("ratings show their mean and count, and nothing a broken answer holds", () => {
const ratings = { coords_hud: { average: 4.26, count: 12 }, zoom: { average: "<b>", count: 3 } };
assert.deepEqual(ratingOf(ratings, "coords_hud"), { average: 4.26, count: 12 });
assert.equal(ratingOf(ratings, "zoom"), null);
assert.equal(ratingOf(ratings, "__proto__"), null);
const stars = starsHtml(ratingOf(ratings, "coords_hud"));
assert.ok(stars.includes(`<span class="on">★★★★</span>★`), stars);
assert.ok(stars.includes("4.3 (12)"));
assert.ok(starsHtml(null).includes("No ratings yet"));
assert.ok(listHtml([project()], ratings).includes("4.3 (12)"));
// Before the service answers (or without it), no stars at all.
assert.ok(!listHtml([project()]).includes("No ratings yet"));
assert.ok(!projectHtml(project()).includes("No ratings yet"));
assert.ok(projectHtml(project(), null).includes("No ratings yet"));
});
test("the list orders by downloads, by rating or by name", () => {
const a = project({ id: "a", name: "Alpha", downloads: 5 });
const b = project({ id: "b", name: "Beta", downloads: 50 });
const c = project({ id: "c", name: "Gamma" });
const ratings = { a: { average: 4.5, count: 2 }, c: { average: 4.5, count: 9 } };
const ids = (by) => sorted([a, b, c], by, ratings).map((p) => p.id);
assert.deepEqual(ids("downloads"), ["b", "a", "c"]);
assert.deepEqual(ids("rating"), ["c", "a", "b"]);
assert.deepEqual(ids("name"), ["a", "b", "c"]);
});
test("rating: a sign-in link signed out, stars signed in, none for the project's owners", () => {
const p = project({ owners: ["Alice"] });
assert.ok(rateHtml(p, null, null).includes('href="/api/mods/auth/login?back=/mods/coords_hud">Sign in with GitHub to rate'));
assert.ok(rateHtml(p, { login: "alice" }, null).includes("You publish it"));
const mine = rateHtml(p, { login: "bob" }, 3);
assert.equal((mine.match(/data-stars=/g) || []).length, 5);
assert.equal((mine.match(/mod-star lit/g) || []).length, 3);
assert.ok(mine.includes('data-stars="3" aria-pressed="true"'));
assert.ok(rateHtml(p, { login: "bob" }, null).includes("Rate it"));
});
+19
View File
@@ -881,6 +881,25 @@ code { border-radius: 0; background: var(--well); box-shadow: 0 0 0 1px var(--ou
.mod-side .badge { margin-right: 0; }
.mod-version { font: var(--text-micro) / 1.4 var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); }
.mod-empty a { color: var(--accent); }
.mod-sort { width: auto; }
.mod-stats { font-size: var(--text-ui); color: var(--muted); white-space: nowrap; }
.mod-stars { color: color-mix(in srgb, var(--muted) 45%, transparent); letter-spacing: 0.08em; }
.mod-stars .on { color: var(--warn); }
.mod-page-stats { margin: 12px 0 0; }
.mod-rate { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin-top: 12px; }
.mod-rate:empty { display: none; }
.mod-rate .meta, .mod-rate .mod-error { margin: 0; flex-basis: 100%; }
.mod-rate-label { font-size: var(--text-ui); color: var(--muted); }
.mod-rate-stars { display: inline-flex; }
.mod-star {
padding: 0 3px; border: 0; background: none; cursor: pointer; font-size: 26px; line-height: 1;
color: color-mix(in srgb, var(--muted) 45%, transparent);
transition: color var(--quick) var(--ease-quick);
}
/* The rating's stars are lit; hovering lights a star and those before it. */
.mod-star.lit, .mod-rate-stars:hover .mod-star { color: var(--warn); }
.mod-rate-stars .mod-star:hover ~ .mod-star { color: color-mix(in srgb, var(--muted) 45%, transparent); }
.mod-star:disabled { cursor: progress; }
.badge-signed { background: color-mix(in srgb, var(--success) 22%, var(--panel)); color: var(--ink); }
.badge-unsigned { background: color-mix(in srgb, var(--warn) 24%, var(--panel)); color: var(--ink); }
.mod-page { display: grid; gap: 16px; max-width: calc(var(--measure) + 240px); }