From d422564ab3f292d0c5be6a24073f540069417406 Mon Sep 17 00:00:00 2001 From: Eshayat Al-Wasiu Date: Mon, 26 Oct 2026 13:16:45 +0600 Subject: [PATCH 01/51] Respect tool restrictions on Creative block destruction Check the tool component before server destruction, local mining and remote prediction. Cover vanilla item defaults, overrides and mode-switch cancellation. Co-Authored-By: OpenAI GPT-6.1 Sol --- .../examples/probe/creative_mining_probe.rs | 48 ++++++++++++++ crates/horizon-client/examples/probe/main.rs | 2 + crates/horizon-client/src/game.rs | 14 +++- crates/horizon-client/src/game/remote.rs | 9 +++ crates/horizon-client/src/items.rs | 26 ++++++++ .../parity/VanillaCreativeMiningOracle.java | 64 +++++++++++++++++++ tests/test_remote_mining.py | 28 ++++++-- tools/lan_e2e.py | 38 +++++++++++ tools/test_creative_mining_parity.py | 35 ++++++++++ 9 files changed, 259 insertions(+), 5 deletions(-) create mode 100644 crates/horizon-client/examples/probe/creative_mining_probe.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCreativeMiningOracle.java create mode 100644 tools/test_creative_mining_parity.py diff --git a/crates/horizon-client/examples/probe/creative_mining_probe.rs b/crates/horizon-client/examples/probe/creative_mining_probe.rs new file mode 100644 index 000000000..897e4bf81 --- /dev/null +++ b/crates/horizon-client/examples/probe/creative_mining_probe.rs @@ -0,0 +1,48 @@ +use horizon_client::{ + Result, + item_data::StackData, + items::{ItemStack, Items}, +}; +use horizon_world::nbt::Tag; +use serde_json::Value; +use std::{ + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, + path::Path, +}; + +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().collect(); + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + let items = Items::catalog(&root)?; + let mut out = BufWriter::new(File::create(&args[2])?); + for line in BufReader::new(File::open(&args[1])?).lines() { + let row: Value = serde_json::from_str(&line?)?; + let mut stack = ItemStack::new( + row["item"].as_str().unwrap(), + row["count"].as_u64().unwrap() as u32, + ); + match row["tool"].as_str().unwrap() { + "default" => {} + mode => { + let mut data = StackData::default(); + let tool = if mode == "implicit" { + Tag::compound([] as [(&str, Tag); 0]) + } else { + Tag::compound([( + "can_destroy_blocks_in_creative", + Tag::Byte(i8::from(mode == "allow")), + )]) + }; + data.set_other("minecraft:tool", Some(tool)); + stack.extra = Some(Box::new(data)); + } + } + writeln!( + out, + "{}", + items.can_destroy_block(Some(&stack), row["creative"].as_bool().unwrap()) + )?; + } + Ok(()) +} diff --git a/crates/horizon-client/examples/probe/main.rs b/crates/horizon-client/examples/probe/main.rs index e80088fd0..c803dcf2f 100644 --- a/crates/horizon-client/examples/probe/main.rs +++ b/crates/horizon-client/examples/probe/main.rs @@ -27,6 +27,7 @@ mod chat_screen_fixture; mod cloud_fixture; mod command_parse_fixture; mod container_screen_probe; +mod creative_mining_probe; mod creative_search_fixture; mod emitter_particles_probe; mod enchanting_fixture; @@ -107,6 +108,7 @@ probes! { block_transform_fixture, breaking_fixture, camera_probe, + creative_mining_probe, cauldron_fixture, chat_screen_fixture, cloud_fixture, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f7dffb734..1073b7308 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3318,6 +3318,13 @@ impl Game<'_> { self.with_player_actor(|game| game.break_block_as_player(pos)) } fn break_block_as_player(&mut self, pos: [i32; 3]) -> Result<()> { + if !self + .res + .items() + .can_destroy_block(self.held(), self.creative) + { + return Ok(()); + } self.pad_rumble(horizon_client::gamepad::Rumble::BlockBroken); // ServerPlayerGameMode.destroyBlock. let state = self.world.block(pos[0], pos[1], pos[2]); @@ -3936,7 +3943,12 @@ impl Game<'_> { return Ok(()); }; // GameType.isBlockPlacingRestricted: adventure and spectator. - if !self.may_build() { + if !self.may_build() + || !self + .res + .items() + .can_destroy_block(self.held(), self.creative) + { self.mining = None; return Ok(()); } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3a2dd1d69..e18e49949 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3779,6 +3779,15 @@ impl Game<'_> { /// MultiPlayerGameMode.startDestroyBlock / continueDestroyBlock. fn remote_mining(&mut self, start: bool) { + if !self + .res + .items() + .can_destroy_block(self.held(), self.creative) + { + self.stop_remote_mining(); + self.mining = None; + return; + } let Some(r) = self.remote.as_mut() else { return; }; diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 8ac450bcb..b35bcdc29 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -71,6 +71,8 @@ pub struct ItemInfo { /// The `tool` component's `damage_per_block`, when the item has the /// component (a mace or trident has one without rules). pub tool_damage_per_block: Option, + /// `tool.can_destroy_blocks_in_creative` (defaults to true). + pub can_destroy_blocks_in_creative: bool, pub food: Option<(u32, f32)>, pub can_always_eat: bool, /// `consumable`: its timing, sound, particles and `on_consume_effects`. @@ -552,6 +554,10 @@ impl Items { tool_damage_per_block: c .get("minecraft:tool") .map(|t| t["damage_per_block"].as_u64().unwrap_or(1) as u32), + can_destroy_blocks_in_creative: + c["minecraft:tool"]["can_destroy_blocks_in_creative"] + .as_bool() + .unwrap_or(true), food, can_always_eat, // Consumable.CODEC's defaults. @@ -746,6 +752,26 @@ impl Items { None => spec == block, } } + /// `Item.canDestroyBlock`: a tool may forbid block destruction with instabuild. + pub fn can_destroy_block(&self, held: Option<&ItemStack>, creative: bool) -> bool { + if !creative { + return true; + } + let Some(held) = held.filter(|s| s.count > 0 && &*s.item != "minecraft:air") else { + return true; + }; + if let Some(tool) = held.data().and_then(|d| d.other("minecraft:tool")) { + return tool + .get("can_destroy_blocks_in_creative") + .and_then(|v| match v { + horizon_world::nbt::Tag::Byte(v) => Some(*v), + _ => None, + }) + .is_none_or(|v| v != 0); + } + self.get(&held.item) + .is_none_or(|info| info.can_destroy_blocks_in_creative) + } /// `Tool.getMiningSpeed` for the held item (1.0 without a tool component). pub fn mining_speed(&self, held: Option<&ItemStack>, block: &str) -> f32 { let Some(info) = held.and_then(|s| self.get(&s.item)) else { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCreativeMiningOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCreativeMiningOracle.java new file mode 100644 index 000000000..7d1d5f6e3 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCreativeMiningOracle.java @@ -0,0 +1,64 @@ +package dev.horizonlab.parity; + +import com.google.gson.JsonParser; +import java.io.PrintWriter; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import net.minecraft.core.component.DataComponents; +import net.minecraft.core.component.DataComponentMap; +import com.mojang.serialization.JsonOps; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Abilities; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.Tool; + +/** Calls the actual item predicate; its unused block and level arguments are null. */ +public final class VanillaCreativeMiningOracle { + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + var defaults = JsonParser.parseString(Files.readString(Path.of(args[0]).getParent() + .getParent().resolve("horizon-client/26.3/items.json"))).getAsJsonObject(); + for (var entry : defaults.entrySet()) { + var item = BuiltInRegistries.ITEM.getValue(Identifier.parse(entry.getKey())); + var components = DataComponentMap.builder(); + var tool = entry.getValue().getAsJsonObject().getAsJsonObject("minecraft:tool"); + if (tool != null) { + // Only the restriction is queried here; mining-rule tag resolution is separate. + tool = tool.deepCopy(); + tool.add("rules", new com.google.gson.JsonArray()); + components.set(DataComponents.TOOL, Tool.CODEC.parse(JsonOps.INSTANCE, tool).getOrThrow()); + } + item.builtInRegistryHolder().bindComponents(components.build()); + } + var unsafeClass = Class.forName("sun.misc.Unsafe"); + var unsafeField = unsafeClass.getDeclaredField("theUnsafe"); + unsafeField.setAccessible(true); + var unsafe = unsafeField.get(null); + var player = (ServerPlayer) unsafeClass.getMethod("allocateInstance", Class.class) + .invoke(unsafe, ServerPlayer.class); + var abilities = new Abilities(); + var field = Player.class.getDeclaredField("abilities"); + field.setAccessible(true); + field.set(player, abilities); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]))); + var lines = Files.lines(Path.of(args[0]))) { + for (var line : (Iterable) lines::iterator) { + var row = JsonParser.parseString(line).getAsJsonObject(); + var item = BuiltInRegistries.ITEM.getValue(Identifier.parse(row.get("item").getAsString())); + var stack = new ItemStack(item, row.get("count").getAsInt()); + var mode = row.get("tool").getAsString(); + if (!mode.equals("default")) { + stack.set(DataComponents.TOOL, new Tool(List.of(), 1.0f, 1, !mode.equals("deny"))); + } + abilities.instabuild = row.get("creative").getAsBoolean(); + // Use the base Item implementation: special debug-stick interactions are separate. + out.println(net.minecraft.world.item.Items.STICK.canDestroyBlock(stack, null, null, null, player)); + } + } + } +} diff --git a/tests/test_remote_mining.py b/tests/test_remote_mining.py index 1a35b3865..9feb255fa 100644 --- a/tests/test_remote_mining.py +++ b/tests/test_remote_mining.py @@ -18,7 +18,7 @@ ROOT = Path(__file__).resolve().parents[1] class RemoteMiningTests(unittest.TestCase): def test_break_timing_and_packets(self): source = (ROOT / "crates/horizon-client/src/game/remote.rs").read_text() - start = source.index(" fn remote_mining(") + start = source.index(" pub(super) fn stop_remote_mining(") end = source.index(" /// MultiPlayerGameMode.destroyBlock", start) fixture = r''' #![allow(dead_code)] @@ -33,8 +33,11 @@ struct Player { ground: Ground } struct Sounds { hit: String, volume: f32, pitch: f32 } #[derive(Clone)] struct Facts { hardness: f32, name: String, requires_tool: bool, sounds: Sounds } -struct Resources { facts: Facts, speed: f32 } +struct Resources { facts: Facts, speed: f32, tool_allows_creative: bool } impl Resources { + fn can_destroy_block(&self, _: Option<&()>, creative: bool) -> bool { + !creative || self.tool_allows_creative + } fn facts(&self) -> &Self { self } fn items(&self) -> &Self { self } fn get(&self, _: u32) -> &Facts { &self.facts } @@ -72,7 +75,7 @@ impl Game { remote: Some(Remote::default()), mining: None, creative, world: World::default(), res: Resources { facts: Facts { hardness, name: "block".into(), - requires_tool: false, sounds: Sounds { hit: "hit".into(), volume: 1.0, pitch: 1.0 } }, speed }, + requires_tool: false, sounds: Sounds { hit: "hit".into(), volume: 1.0, pitch: 1.0 } }, speed, tool_allows_creative: true }, player: Some(Player { ground: Ground { on_ground: true } }), audio: Audio, hit: Hit { pos: [0, 64, 0], face: 1 }, sequence: 0, packets: vec![], } @@ -138,8 +141,25 @@ fn main() { game.remote_mining(false); assert_eq!(game.world.broken.len(), 2); assert_eq!(game.remote.as_ref().unwrap().destroy_delay, 5); + // A restricted tool must neither predict a break nor send START in Creative. + let mut game = Game::new(1.0, 1.0, true); + game.res.tool_allows_creative = false; + game.remote_mining(true); + game.remote_mining(false); + assert!(game.world.broken.is_empty()); + assert!(game.packets.is_empty()); + // Survival still mines with the same tool. Switching to Creative aborts the crack. + game.creative = false; + game.remote_mining(true); + assert_eq!(game.packets[0].action, 0); + game.creative = true; + game.remote_mining(false); + assert_eq!(game.packets.iter().map(|p| p.action).collect::>(), [0, 2]); + assert!(game.remote.as_ref().unwrap().destroying.is_none()); + assert!(game.mining.is_none()); + assert!(game.world.broken.is_empty()); } -'''.replace("METHOD", source[start:end]) +'''.replace("METHOD", source[start:end].replace("pub(super) fn", "fn")) with tempfile.TemporaryDirectory(prefix="remote-mining-") as directory: path = Path(directory) (path / "main.rs").write_text(fixture) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 804add98a..8592c3e35 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -6591,5 +6591,43 @@ CHECKS += ['replant'] CHECK_FNS['replant'] = check_replant +def check_creative_tools(host, guest, out): + """#2035: switching Survival -> Creative cannot mine with a restricted tool. + Verify both the player's prediction and the host's authoritative block; + an ordinary tool must still break the same block. + """ + seen = {} + for label, player in (('host', host), ('guest', guest)): + x, y, z = (int(v // 1) for v in pos_of(player)) + cell = (x, y + 1, z + 2) + host('command', command=f'fill {x - 1} {y} {z + 1} {x + 1} {y + 3} {z + 3} minecraft:air') + player('command', command='gamemode survival') + player('command', command='item replace entity @s weapon.mainhand with minecraft:netherite_sword') + player('command', command='gamemode creative') + host('command', command=f'setblock {cell[0]} {cell[1]} {cell[2]} minecraft:stone') + player.wait(10) + player.raw('look-at', x + 0.5, y + 1.5, z + 2.5) + player.raw('mouse', 'left', 'down') + try: + player.wait(15) + finally: + player.raw('mouse', 'left', 'up') + seen[label] = {'client': player.raw('block', *cell).get('block'), + 'server': host.raw('block', *cell).get('block')} + player.shot(out, 'creative-sword') + assert seen[label]['client'] == seen[label]['server'] == 'minecraft:stone', seen + player('command', command='item replace entity @s weapon.mainhand with minecraft:diamond_pickaxe') + player.wait(6) + player.raw('mouse', 'left', 'click') + player.wait(10) + seen[label]['ordinary_tool'] = host.raw('block', *cell).get('block') + assert seen[label]['ordinary_tool'] == 'minecraft:air', seen + return seen + + +CHECKS += ['creative_tools'] +CHECK_FNS['creative_tools'] = check_creative_tools + + if __name__ == '__main__': main() diff --git a/tools/test_creative_mining_parity.py b/tools/test_creative_mining_parity.py new file mode 100644 index 000000000..3e6bfed1a --- /dev/null +++ b/tools/test_creative_mining_parity.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +"""Compare Creative mining eligibility for every item and tool overrides.""" +import json + +try: + from . import lab, oracle_harness as harness +except ImportError: + import lab, oracle_harness as harness + + +def make_input(build): + resources = lab.LOCAL / 'horizon-client' / '26.3' + items = json.loads((resources / 'items.json').read_text()) + rows = [dict(item=item, creative=creative, count=count, tool=tool) + for item in sorted(items) + for creative in (False, True) + for count in (0, 1) + for tool in ('default', 'allow', 'deny', 'implicit')] + path = build / 'inputs.jsonl' + path.write_text(''.join(json.dumps(row) + '\n' for row in rows)) + return path, len(rows) + + +def main(): + harness.differential( + 'rust-creative-mining-parity', 'VanillaCreativeMiningOracle', + 'creative_mining_probe', make_input, + 'Item.canDestroyBlock with each vanilla item, empty stacks, Survival/Creative ' + 'abilities, and explicit/implicit tool overrides. Block destruction and network ' + 'prediction call this predicate; end-to-end packet handling is not covered here.', + sources=[lab.ROOT / 'crates/horizon-client/src/items.rs']) + + +if __name__ == '__main__': + main() From 606efe5af0a642b4ec08b6d64078da12366ab336 Mon Sep 17 00:00:00 2001 From: Eshayat Al-Wasiu Date: Mon, 26 Oct 2026 13:16:54 +0600 Subject: [PATCH 02/51] Animate remote squid bodies and tentacles from server velocity Run the client branch of Squid.aiStep, preserve authoritative movement and synchronize tentacle-cycle resets with entity event 19. Co-Authored-By: OpenAI GPT-6.1 Sol --- crates/horizon-client/examples/probe/main.rs | 2 + .../examples/probe/squid_client_probe.rs | 51 +++++++++++++ crates/horizon-client/src/game/creatures.rs | 1 + crates/horizon-client/src/game/remote.rs | 7 ++ crates/horizon-client/src/mobs.rs | 5 ++ crates/horizon-client/src/mobs/aquatic.rs | 61 +++++++++++++--- .../parity/VanillaSquidClientOracle.java | 73 +++++++++++++++++++ tools/test_squid_client_parity.py | 47 ++++++++++++ 8 files changed, 236 insertions(+), 11 deletions(-) create mode 100644 crates/horizon-client/examples/probe/squid_client_probe.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSquidClientOracle.java create mode 100644 tools/test_squid_client_parity.py diff --git a/crates/horizon-client/examples/probe/main.rs b/crates/horizon-client/examples/probe/main.rs index e80088fd0..e4cc68b9a 100644 --- a/crates/horizon-client/examples/probe/main.rs +++ b/crates/horizon-client/examples/probe/main.rs @@ -83,6 +83,7 @@ mod sound_engine_fixture; mod sound_event_fixture; mod spawn_rules_fixture; mod sprint_probe; +mod squid_client_probe; mod subtitle_fixture; mod tab_list_fixture; mod team_rules_fixture; @@ -107,6 +108,7 @@ probes! { block_transform_fixture, breaking_fixture, camera_probe, + squid_client_probe, cauldron_fixture, chat_screen_fixture, cloud_fixture, diff --git a/crates/horizon-client/examples/probe/squid_client_probe.rs b/crates/horizon-client/examples/probe/squid_client_probe.rs new file mode 100644 index 000000000..f9f9c9b2c --- /dev/null +++ b/crates/horizon-client/examples/probe/squid_client_probe.rs @@ -0,0 +1,51 @@ +use horizon_client::{ + Result, + mobs::{Mob, MobTypes, aquatic}, +}; +use horizon_core::geometry::Vec3; +use serde_json::Value; +use std::{ + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, + path::Path, + sync::Arc, +}; + +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().collect(); + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + let types = MobTypes::load(&root)?; + let mut out = BufWriter::new(File::create(&args[2])?); + for line in BufReader::new(File::open(&args[1])?).lines() { + let row: Value = serde_json::from_str(&line?)?; + let kind = Arc::new( + types.types[&format!("minecraft:{}", row["species"].as_str().unwrap())].clone(), + ); + let mut mob = Mob::new(1, kind, Vec3::ZERO, 0.0); + mob.fluids.in_water = row["water"].as_bool().unwrap(); + mob.velocity = Vec3::new( + row["x"].as_f64().unwrap(), + row["y"].as_f64().unwrap(), + row["z"].as_f64().unwrap(), + ); + mob.body_yaw = row["body"].as_f64().unwrap() as f32; + for (i, value) in row["v"].as_array().unwrap().iter().enumerate() { + mob.anim.v[i] = value.as_f64().unwrap() as f32; + } + if row["reset"].as_bool().unwrap() { + aquatic::squid_cycle_event(&mut mob); + } + let velocity = mob.velocity; + aquatic::squid_client_step(&mut mob); + assert_eq!( + velocity, mob.velocity, + "a remote animation must preserve packet velocity" + ); + write!(out, "{:08x}", mob.body_yaw.to_bits())?; + for value in &mob.anim.v[..6] { + write!(out, " {:08x}", value.to_bits())?; + } + writeln!(out)?; + } + Ok(()) +} diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index be7923037..cc45faf78 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -810,6 +810,7 @@ impl Game<'_> { pub(super) fn handle_mob_events(&mut self, events: Vec) -> Result<()> { for e in events { match e { + MobEvent::SquidCycle { mob, at } => self.lan_entity_event(mob as i32, 19, at), MobEvent::RabbitHop { mob, at } => self.lan_entity_event(mob as i32, 1, at), MobEvent::Sound(name, at, volume, pitch) | MobEvent::LocalSound(name, at, volume, pitch) => { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3a2dd1d69..547099cfe 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2174,6 +2174,11 @@ impl Game<'_> { { horizon_client::mobs::rabbit::hop_event(m); } + if p.event == 19 + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) + { + horizon_client::mobs::aquatic::squid_cycle_event(m); + } // EntityEvent.DEATH: start the death animation. if p.event == 3 && let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) @@ -3581,6 +3586,8 @@ impl Game<'_> { } else if m.alive() { m.body_rotation_tick(); } + // Squid.aiStep follows LivingEntity's interpolation and head turn. + horizon_client::mobs::aquatic::squid_client_step(m); // WalkAnimationState.update from the horizontal distance moved. let (dx, dz) = (m.position.x - m.previous.x, m.position.z - m.previous.z); let target = (((dx * dx + dz * dz).sqrt() * 4.0) as f32).min(1.0); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 1b5dddbe7..393ced4d1 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -868,6 +868,11 @@ pub struct Mob { /// Events a mob tick asks the game to act on. #[derive(Clone, Debug)] pub enum MobEvent { + /// Squid.handleEntityEvent(19), resetting the remote tentacle cycle. + SquidCycle { + mob: u32, + at: [f64; 3], + }, /// Rabbit entity event 1, sent only when a ground jump actually happens. RabbitHop { mob: u32, diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index dc80c6ea4..3f86d8edc 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -234,12 +234,40 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } /// Squid.aiStep: tentacle cycle, propulsion and body rotation. fn squid_ai_step(m: &mut Mob) { + squid_step(m, false); +} + +/// Squid.aiStep also runs on remote entities: animate from packet velocity, +/// without running goals or replacing that velocity with the server's movement vector. +pub fn squid_client_step(m: &mut Mob) { + if matches!(m.species(), Species::Squid | Species::GlowSquid) { + m.anim.vo = m.anim.v; + squid_step(m, true); + } +} + +/// Squid.handleEntityEvent(19): begin the next server-synchronised tentacle cycle. +pub fn squid_cycle_event(m: &mut Mob) { + if matches!(m.species(), Species::Squid | Species::GlowSquid) { + m.anim.v[TENTACLE_MOVEMENT] = 0.0; + } +} + +fn squid_step(m: &mut Mob, client: bool) { let v = &mut m.anim.v; v[TENTACLE_MOVEMENT] += v[TENTACLE_SPEED]; - if v[TENTACLE_MOVEMENT] > PI * 2.0 { - v[TENTACLE_MOVEMENT] -= PI * 2.0; - if m.random.next_int_bound(10).unwrap_or(1) == 0 { - m.anim.v[TENTACLE_SPEED] = 1.0 / (m.random.next_float() + 1.0) * 0.2; + if f64::from(v[TENTACLE_MOVEMENT]) > std::f64::consts::TAU { + if client { + v[TENTACLE_MOVEMENT] = PI * 2.0; + } else { + v[TENTACLE_MOVEMENT] -= PI * 2.0; + if m.random.next_int_bound(10).unwrap_or(1) == 0 { + m.anim.v[TENTACLE_SPEED] = 1.0 / (m.random.next_float() + 1.0) * 0.2; + } + m.outbox.push(MobEvent::SquidCycle { + mob: m.id, + at: [m.position.x, m.position.y, m.position.z], + }); } } let v = &mut m.anim.v; @@ -248,28 +276,39 @@ fn squid_ai_step(m: &mut Mob) { let scale = v[TENTACLE_MOVEMENT] / PI; v[TENTACLE_ANGLE] = (scale * scale * PI).msin() * PI * 0.25; if scale > 0.75 { - let mv = m.extra.vector; - m.velocity = Vec3::new(mv[0], mv[1], mv[2]); + if !client { + let mv = m.extra.vector; + m.velocity = Vec3::new(mv[0], mv[1], mv[2]); + } m.anim.v[ROTATE_SPEED] = 1.0; } else { m.anim.v[ROTATE_SPEED] *= 0.8; } } else { v[TENTACLE_ANGLE] = 0.0; - m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9); + if !client { + m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9); + } m.anim.v[ROTATE_SPEED] *= 0.99; } let mv = m.velocity; let horizontal = (mv.x * mv.x + mv.z * mv.z).sqrt(); - m.body_yaw += (-(mv.x.atan2(mv.z) as f32).to_degrees() - m.body_yaw) * 0.1; + m.body_yaw += (-(horizon_core::geometry::trig::atan2(mv.x, mv.z) as f32) * 57.295776 + - m.body_yaw) + * 0.1; m.yaw = m.body_yaw; let v = &mut m.anim.v; v[Z_BODY_ROT] += PI * v[ROTATE_SPEED] * 1.5; - v[X_BODY_ROT] += (-(horizontal.atan2(mv.y) as f32).to_degrees() - v[X_BODY_ROT]) * 0.1; + v[X_BODY_ROT] += (-(horizon_core::geometry::trig::atan2(horizontal, mv.y) as f32) + * 57.295776 + - v[X_BODY_ROT]) + * 0.1; } else { v[TENTACLE_ANGLE] = v[TENTACLE_MOVEMENT].msin().abs() * PI * 0.25; - let yd = m.velocity.y - m.kind.gravity; - m.velocity = Vec3::new(0.0, yd * 0.98, 0.0); + if !client { + let yd = m.velocity.y - m.kind.gravity; + m.velocity = Vec3::new(0.0, yd * 0.98, 0.0); + } let v = &mut m.anim.v; v[X_BODY_ROT] += (-90.0 - v[X_BODY_ROT]) * 0.02; } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSquidClientOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSquidClientOracle.java new file mode 100644 index 000000000..66b833c54 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSquidClientOracle.java @@ -0,0 +1,73 @@ +package dev.horizonlab.parity; + +import com.google.gson.JsonParser; +import java.io.PrintWriter; +import java.lang.reflect.Field; +import java.lang.reflect.Proxy; +import java.nio.file.Files; +import java.nio.file.Path; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.core.Holder; +import net.minecraft.world.effect.MobEffect; +import net.minecraft.world.entity.*; +import net.minecraft.world.entity.animal.squid.Squid; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; + +/** Runs the real Squid.aiStep, with unrelated movement/world services controlled. */ +public final class VanillaSquidClientOracle { + static Field field(Class owner, String name) throws Exception { + var f = owner.getDeclaredField(name); f.setAccessible(true); return f; + } + static final class Shell extends Squid { + Level world; boolean water; + Shell() { super(EntityTypes.SQUID, null); } + @Override public Level level() { return world; } + @Override public boolean isAgeLocked() { return true; } + @Override public boolean isInWater() { return water; } + @Override protected boolean isImmobile() { return true; } + @Override protected void applyInput() {} + @Override public boolean isEffectiveAi() { return false; } + @Override public boolean isFallFlying() { return false; } + @Override public boolean hasEffect(Holder effect) { return false; } + @Override public LivingEntity getControllingPassenger() { return null; } + @Override public void calculateEntityAnimation(boolean flying) {} + @Override protected void pushEntities() {} + } + static String bits(float value) { return String.format("%08x", Float.floatToIntBits(value)); } + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + var u = Class.forName("sun.misc.Unsafe"); + var uf = field(u, "theUnsafe"); var unsafe = uf.get(null); + var allocate = u.getMethod("allocateInstance", Class.class); + var world = (ClientLevel) allocate.invoke(unsafe, ClientLevel.class); + field(Level.class, "isClientSide").setBoolean(world, true); + String[] names = {"tentacleMovement", "tentacleAngle", "xBodyRot", "zBodyRot", "tentacleSpeed", "rotateSpeed"}; + Field[] values = new Field[names.length]; + for (int i = 0; i < names.length; i++) values[i] = field(Squid.class, names[i]); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]))); + var lines = Files.lines(Path.of(args[0]))) { + for (var line : (Iterable) lines::iterator) { + var row = JsonParser.parseString(line).getAsJsonObject(); + var m = (Shell) allocate.invoke(unsafe, Shell.class); + m.world = world; field(Entity.class, "level").set(m, world); m.water = row.get("water").getAsBoolean(); + field(Entity.class, "type").set(m, EntityTypes.SQUID); + field(LivingEntity.class, "equipment").set(m, new EntityEquipment()); + field(Entity.class, "interpolationHandler").set(m, Proxy.newProxyInstance( + InterpolationHandler.class.getClassLoader(), new Class[]{InterpolationHandler.class}, + (proxy, method, arguments) -> method.getName().equals("hasActiveInterpolation") ? true : null)); + m.setBoundingBox(new AABB(0, 0, 0, 1, 1, 1)); + m.setDeltaMovement(new Vec3(row.get("x").getAsDouble(), row.get("y").getAsDouble(), row.get("z").getAsDouble())); + m.yBodyRot = row.get("body").getAsFloat(); + for (int i = 0; i < names.length; i++) values[i].setFloat(m, row.getAsJsonArray("v").get(i).getAsFloat()); + if (row.get("reset").getAsBoolean()) m.handleEntityEvent((byte)19); + m.aiStep(); + out.print(bits(m.yBodyRot)); + for (var f : values) out.print(" " + bits(f.getFloat(m))); + out.println(); + } + } + } +} diff --git a/tools/test_squid_client_parity.py b/tools/test_squid_client_parity.py new file mode 100644 index 000000000..9ded209aa --- /dev/null +++ b/tools/test_squid_client_parity.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +"""Compare the real Squid.aiStep client branch and cycle event with Rust.""" +import json +import random + +try: + from . import lab, oracle_harness as harness +except ImportError: + import lab, oracle_harness as harness + + +def make_input(build): + rng = random.Random(1684) + rows = [] + for species in ('squid', 'glow_squid'): + for water in (False, True): + for reset in (False, True): + for velocity in ((0, 0, 0), (.1, 0, 0), (0, .1, 0), + (0, -.1, 0), (0, 0, -.1), (.1, .2, -.3)): + for movement in (0, 1, 2.4, 3.14, 4, 6.2, 6.4): + rows.append(dict(species=species, water=water, reset=reset, + x=velocity[0], y=velocity[1], z=velocity[2], + body=rng.uniform(-180, 180), + v=[movement, .2, -45, 33, .15, .8])) + for _ in range(1000): + rows.append(dict(species=rng.choice(('squid', 'glow_squid')), water=True, + reset=False, x=rng.uniform(.01, .2), y=rng.uniform(.01, .2), + z=rng.uniform(.01, .2), body=rng.uniform(-180, 180), + v=[rng.uniform(0, 7), 0, rng.uniform(-90, 90), + rng.uniform(0, 180), rng.uniform(.1, .2), rng.random()])) + path = build / 'inputs.jsonl' + path.write_text(''.join(json.dumps(row) + '\n' for row in rows)) + return path, len(rows) + + +def main(): + harness.differential( + 'rust-squid-client-parity', 'VanillaSquidClientOracle', 'squid_client_probe', + make_input, + 'Actual Squid.aiStep on a client with controlled inherited movement/world services. ' + 'Checks water/air body rotation and tentacle state, cycle clamping and event 19. ' + 'Glow squid uses the same inherited method; packet dispatch and rendering are separate.', + sources=[lab.ROOT / 'crates/horizon-client/src/mobs/aquatic.rs']) + + +if __name__ == '__main__': + main() From 66f32a7a3aab0c00faec4c2c487c3047890c337b Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:45:35 +0000 Subject: [PATCH 03/51] Persist forced chunks across world restarts Co-Authored-By: Codex GPT-6.1 Sol --- crates/horizon-client/src/game.rs | 2 + crates/horizon-client/src/game/saving.rs | 1 + .../horizon-client/src/game/world_loading.rs | 1 + crates/horizon-client/src/save.rs | 105 ++++++++++++++++- tools/singleplayer_forced_chunks_audit.py | 110 ++++++++++++++++++ 5 files changed, 218 insertions(+), 1 deletion(-) create mode 100644 tools/singleplayer_forced_chunks_audit.py diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 8f9c1957d..977bcaeca 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -7968,6 +7968,7 @@ impl Game<'_> { /// (scaled coordinates, or the End portal's fixed destination). pub(super) fn switch_level(&mut self, target: Dim, from: Vec3) -> Result { // Save the departing dimension's changed chunks. + self.save.save_forced_chunks(&self.streaming.forced)?; self.streaming.save(&mut self.world, true); let keys: Vec<_> = self.world.modified.drain().collect(); let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k))); @@ -10082,6 +10083,7 @@ impl Game<'_> { } /// Save the level in place: its changed chunks, its entities and its raids. fn save_level(&mut self, wait: bool) -> Result<()> { + self.save.save_forced_chunks(&self.streaming.forced)?; self.streaming.save(&mut self.world, wait); let keys: Vec<_> = self.world.modified.drain().collect(); let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k))); diff --git a/crates/horizon-client/src/game/saving.rs b/crates/horizon-client/src/game/saving.rs index 378ffe9ce..1c6632562 100644 --- a/crates/horizon-client/src/game/saving.rs +++ b/crates/horizon-client/src/game/saving.rs @@ -179,6 +179,7 @@ impl Game<'_> { if keys.is_empty() { self.prune_entity_memory(); self.save_raids(); + self.save.save_forced_chunks(&self.streaming.forced)?; self.save_game_metadata()?; save.stage = Stage::Writes; } diff --git a/crates/horizon-client/src/game/world_loading.rs b/crates/horizon-client/src/game/world_loading.rs index 0cea31fd0..ef47cc9c0 100644 --- a/crates/horizon-client/src/game/world_loading.rs +++ b/crates/horizon-client/src/game/world_loading.rs @@ -261,6 +261,7 @@ pub(super) fn make_streaming( res.threads(), ) }; + streaming.forced = save.load_forced_chunks(); streaming.radius = settings.render_distance; streaming.biome_blend = settings.biome_blend; streaming.smooth_lighting = settings.smooth_lighting; diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 0c353bb38..e93d6019b 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -36,7 +36,7 @@ use horizon_world::{ worldgen::terrain::TerrainBlockStates, }; use std::{ - collections::{BTreeMap, HashMap}, + collections::{BTreeMap, HashMap, HashSet}, fs, path::{Path, PathBuf}, sync::{ @@ -1613,6 +1613,9 @@ pub struct SaveDir { /// False in dimensions without skylight (no SkyLight layers are written). pub sky_light: bool, } +fn is_forced_ticket(ticket: &Tag) -> bool { + matches!(ticket.get("type"), Some(Tag::String(t)) if *t == JavaString::from("minecraft:forced")) +} impl SaveDir { pub fn new(root: PathBuf) -> Self { let sky_light = !root.ends_with("the_nether") && !root.ends_with("DIM-1"); @@ -1628,6 +1631,50 @@ impl SaveDir { sky_light, } } + /// 26.3's TicketStorage: persistent tickets live in each dimension's + /// data/minecraft/chunk_tickets.dat, with ChunkPos.CODEC's [x, z] int array. + pub fn load_forced_chunks(&self) -> HashSet<(i32, i32)> { + let Some(data) = read_saved_data(&self.root, "chunk_tickets") else { + return HashSet::new(); + }; + let Some(Tag::List(tickets)) = data.get("tickets") else { + return HashSet::new(); + }; + tickets + .iter() + .filter(|t| is_forced_ticket(t)) + .filter_map(|t| match t.get("chunk_pos")? { + Tag::IntArray(pos) if pos.len() == 2 => Some((pos[0], pos[1])), + _ => None, + }) + .collect() + } + pub fn save_forced_chunks(&self, forced: &HashSet<(i32, i32)>) -> Result<()> { + if forced.is_empty() && !saved_data_path(&self.root, "chunk_tickets").exists() { + return Ok(()); + } + let mut data = compound_or_empty(read_saved_data(&self.root, "chunk_tickets")); + // Preserve persistent tickets Horizon does not simulate. + let mut tickets = match data.get("tickets") { + Some(Tag::List(tickets)) => tickets + .iter() + .filter(|t| !is_forced_ticket(t)) + .cloned() + .collect::>(), + _ => Vec::new(), + }; + let mut chunks: Vec<_> = forced.iter().copied().collect(); + chunks.sort_unstable(); + tickets.extend(chunks.into_iter().map(|(x, z)| { + Tag::compound([ + ("type", Tag::String("minecraft:forced".into())), + ("level", Tag::Int(31)), // ChunkMap.FORCED_TICKET_LEVEL: ENTITY_TICKING. + ("chunk_pos", Tag::IntArray(vec![x, z])), + ]) + })); + put(&mut data, "tickets", Tag::List(tickets)); + write_saved_data(&self.root, "chunk_tickets", data) + } fn region_path(&self, folder: &str, rx: i32, rz: i32) -> PathBuf { region_path(&self.root, folder, rx, rz) } @@ -3436,6 +3483,62 @@ impl ChunkGenerator for Persistent { #[cfg(test)] mod tests { + #[test] + fn forced_chunks_survive_dimension_restarts_and_removals() { + let root = std::env::temp_dir().join(format!("horizon-forced-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + let dimensions = [ + "minecraft:overworld", + "minecraft:the_nether", + "minecraft:the_end", + ]; + for (i, dim) in dimensions.iter().enumerate() { + let save = SaveDir::new(dimension_dir(&root, dim)); + assert!(save.load_forced_chunks().is_empty()); + let forced = HashSet::from([(i as i32, -17), (-23, i as i32), (-1, -1)]); + save.save_forced_chunks(&forced).unwrap(); + } + for (i, dim) in dimensions.iter().enumerate() { + let path = dimension_dir(&root, dim); + let save = SaveDir::new(path.clone()); + let mut forced = save.load_forced_chunks(); + assert_eq!( + forced, + HashSet::from([(i as i32, -17), (-23, i as i32), (-1, -1)]) + ); + let mut data = read_saved_data(&path, "chunk_tickets").unwrap(); + let other = Tag::compound([ + ("type", Tag::String("minecraft:portal".into())), + ("level", Tag::Int(30)), + ("chunk_pos", Tag::IntArray(vec![7, -8])), + ("ticks_left", Tag::Long(42)), + ]); + if let Some(Tag::List(tickets)) = data.get_mut("tickets") { + assert!( + tickets + .iter() + .all(|t| t.get("level") == Some(&Tag::Int(31))) + ); + tickets.push(other.clone()); + } + write_saved_data(&path, "chunk_tickets", data).unwrap(); + forced.remove(&(-1, -1)); + save.save_forced_chunks(&forced).unwrap(); + drop(save); + let reopened = SaveDir::new(path.clone()); + assert_eq!(reopened.load_forced_chunks(), forced); + reopened.save_forced_chunks(&HashSet::new()).unwrap(); + assert!(SaveDir::new(path.clone()).load_forced_chunks().is_empty()); + assert_eq!( + read_saved_data(&path, "chunk_tickets") + .unwrap() + .get("tickets"), + Some(&Tag::List(vec![other])) + ); + } + fs::remove_dir_all(root).unwrap(); + } + #[test] fn saved_far_surface_reads_builds_and_water_without_gameplay_chunks() { let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES") else { diff --git a/tools/singleplayer_forced_chunks_audit.py b/tools/singleplayer_forced_chunks_audit.py new file mode 100644 index 000000000..89fdd572b --- /dev/null +++ b/tools/singleplayer_forced_chunks_audit.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Check #1527: per-dimension /forceload add/remove across normal restarts. + +Build horizon-client and horizon-ctl with the fast profile first, then run: + python3 tools/singleplayer_forced_chunks_audit.py --case force-save +Runs both default server-thread and in-frame singleplayer, using scratch homes. +""" +import argparse +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import time + +from agent_control_e2e import Cli +import lab + + +DIMENSIONS = ('the_nether', 'the_end', 'overworld') + + +def query(cli, dimension, expected): + since = cli('events')['last'] + cli('command', command='forceload query') + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + reply = cli('events', since=since) + for event in reply['events']: + text = event.get('text', '') + if event.get('event') != 'chat' or f'minecraft:{dimension}' not in text: + continue + if expected: + if all(f'[{x}, {z}]' in text for x, z in expected): + return + elif 'No force loaded chunks' in text: + return + time.sleep(0.1) + raise AssertionError(f'{dimension}: expected {expected}, got {reply}') + + +def run(bin_dir, resources, in_frame): + with tempfile.TemporaryDirectory(prefix='hz-force-save-') as scratch: + work = Path(scratch) + previous = None + for stage in range(3): + # Every process gets fresh homes; copy only this fixture's saved world. + env = lab.game_env({k: v for k, v in os.environ.items() if k not in ( + 'HORIZON_HOME', 'HORIZON_LAUNCHER_HOME', 'XDG_DATA_HOME', 'XDG_CONFIG_HOME')}) + home = Path(env['HORIZON_HOME']) + if previous is not None: + shutil.copytree(previous, home / 'saves') + socket = work / f'{stage}.sock' + cli = Cli(bin_dir / 'horizon-ctl', socket, home, env) + args = [str(bin_dir / 'horizon-client'), '--resources', str(resources), + '--world', 'forced', '--creative', '--seed', '4242', '--offscreen', + '--render-distance', '4', '--control', '--control-socket', str(socket)] + if in_frame: + args.append('--in-frame') + with (work / f'{stage}.log').open('w') as log: + process = subprocess.Popen(args, cwd=home, env=env, stdout=log, stderr=log) + try: + deadline = time.monotonic() + 120 + while not socket.exists(): + if process.poll() is not None or time.monotonic() > deadline: + raise RuntimeError('game did not open its control socket') + time.sleep(0.1) + cli('wait_ready', seconds=240) + for i, dim in enumerate(DIMENSIONS): + cli('command', command=f'execute in minecraft:{dim} run tp @s 0 100 0') + for _ in range(30): + cli('wait', ticks=20) + if cli('state').get('dimension') == f'minecraft:{dim}': + break + else: + raise AssertionError(f'did not enter {dim}') + cli('wait_ready', seconds=240) + expected = [(i - 1, -1)] if stage == 1 else [] + query(cli, dim, expected) + if stage == 0: + cli('command', command=f'forceload add {(i - 1) * 16} -1') + query(cli, dim, [(i - 1, -1)]) + elif stage == 1: + cli('command', command=f'forceload remove {(i - 1) * 16} -1') + query(cli, dim, []) + cli('quit') + assert process.wait(timeout=120) == 0 + except Exception: + log.flush() + print((work / f'{stage}.log').read_text(errors='replace')[-6000:]) + raise + finally: + if process.poll() is None: + process.terminate() + process.wait(timeout=30) + previous = home / 'saves' + print(f'PASS force-save: {"in-frame" if in_frame else "server-thread"}, three dimensions, add/remove/restart') + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--case', choices=['force-save'], default='force-save') + parser.add_argument('--bin-dir', type=Path, default=Path(__file__).resolve().parents[1] / 'target/fast') + args = parser.parse_args() + for in_frame in (False, True): + run(args.bin_dir.resolve(), lab.RESOURCES.resolve(), in_frame) + + +if __name__ == '__main__': + main() From ad50996f7c087500de2d52dc366e268a9d400e99 Mon Sep 17 00:00:00 2001 From: FusselTV Date: Mon, 26 Oct 2026 00:09:45 +0100 Subject: [PATCH 04/51] Structures: save the remaining legacy pieces as vanilla does Desert and jungle temples, swamp huts, buried treasure, ocean monuments, mineshafts, fortresses and strongholds save the tag their StructurePiece subclass writes, with the state placement leaves: the height a scattered feature settled on, the buried treasure chest, placed chests, traps and spawners, and the swamp hut's witch and cat. With these every StructurePieceType is saved. test_structure_start_nbt_parity gets one site of each of these kinds, and a badlands mineshaft. Co-Authored-By: Claude Opus 5.5 --- .../src/worldgen/structure/fortress.rs | 23 +++++++++ .../src/worldgen/structure/mineshaft.rs | 51 +++++++++++++++++++ .../src/worldgen/structure/monument.rs | 10 ++++ .../src/worldgen/structure/simple.rs | 38 ++++++++++++++ .../src/worldgen/structure/start.rs | 1 + .../src/worldgen/structure/stronghold.rs | 42 +++++++++++++++ .../src/worldgen/structure/temple.rs | 26 ++++++++++ tools/test_structure_start_nbt_parity.py | 7 ++- 8 files changed, 196 insertions(+), 2 deletions(-) diff --git a/crates/horizon-world/src/worldgen/structure/fortress.rs b/crates/horizon-world/src/worldgen/structure/fortress.rs index 4d3704413..521dac872 100644 --- a/crates/horizon-world/src/worldgen/structure/fortress.rs +++ b/crates/horizon-world/src/worldgen/structure/fortress.rs @@ -871,6 +871,29 @@ impl LegacyPiece for FortressPiece { fn bounding_box(&self) -> BoundingBox { self.frame.bounding_box } + fn save(&self) -> Option { + use crate::nbt::Tag; + let mut tag = super::legacy::piece_tag( + self.type_name(), + self.frame.bounding_box, + self.frame.orientation, + self.depth, + ); + let flag = Tag::Byte(i8::from(*self.flag.lock().unwrap())); + match self.kind { + Kind::BridgeEndFiller => { + tag.insert("Seed".into(), Tag::Int(self.seed)); + } + Kind::SmallCorridorLeftTurn | Kind::SmallCorridorRightTurn => { + tag.insert("Chest".into(), flag); + } + Kind::MonsterThrone => { + tag.insert("Mob".into(), flag); + } + _ => {} + } + Some(tag) + } fn type_name(&self) -> &'static str { match self.kind { // StartPiece is built through the BridgeCrossing constructor. diff --git a/crates/horizon-world/src/worldgen/structure/mineshaft.rs b/crates/horizon-world/src/worldgen/structure/mineshaft.rs index 1173c03bf..0c2d32c08 100644 --- a/crates/horizon-world/src/worldgen/structure/mineshaft.rs +++ b/crates/horizon-world/src/worldgen/structure/mineshaft.rs @@ -732,6 +732,57 @@ impl LegacyPiece for MineshaftPiece { fn bounding_box(&self) -> BoundingBox { self.frame.bounding_box } + fn save(&self) -> Option { + use crate::nbt::Tag; + let flag = |b: bool| Tag::Byte(i8::from(b)); + let mut tag = super::legacy::piece_tag( + self.type_name(), + self.frame.bounding_box, + self.frame.orientation, + self.depth, + ); + // MineshaftStructure.Type's ordinal: NORMAL, MESA. + let mesa = self.wood.log == MESA.log; + let mut entries = vec![("MST", Tag::Int(i32::from(mesa)))]; + match &self.kind { + Kind::Room(entrances) => entries.push(( + "Entrances", + Tag::List( + entrances + .iter() + .map(|b| { + Tag::IntArray(vec![ + b.min[0], b.min[1], b.min[2], b.max[0], b.max[1], b.max[2], + ]) + }) + .collect(), + ), + )), + Kind::Corridor { + rails, + spider, + sections, + placed_spider, + } => entries.extend([ + ("hr", flag(*rails)), + ("sc", flag(*spider)), + ("hps", flag(*placed_spider.lock().unwrap())), + ("Num", Tag::Int(*sections)), + ]), + Kind::Crossing { + direction, + two_floored, + } => { + let d = crate::level::data_2d(*direction) as i8; + entries.extend([("tf", flag(*two_floored)), ("D", Tag::Byte(d))]); + } + Kind::Stairs => {} + } + for (key, value) in entries { + tag.insert(key.into(), value); + } + Some(tag) + } fn type_name(&self) -> &'static str { match self.kind { Kind::Room(_) => "minecraft:msroom", diff --git a/crates/horizon-world/src/worldgen/structure/monument.rs b/crates/horizon-world/src/worldgen/structure/monument.rs index 39959557e..ababac969 100644 --- a/crates/horizon-world/src/worldgen/structure/monument.rs +++ b/crates/horizon-world/src/worldgen/structure/monument.rs @@ -463,6 +463,16 @@ impl LegacyPiece for MonumentBuilding { fn type_name(&self) -> &'static str { "minecraft:omb" } + /// `MonumentBuilding`: the base fields only; vanilla builds its rooms + /// again after loading (`OceanMonumentStructure.regeneratePiecesAfterLoad`). + fn save(&self) -> Option { + Some(super::legacy::piece_tag( + "minecraft:omb", + self.frame.bounding_box, + self.frame.orientation, + 0, + )) + } fn post_process(&self, c: &mut PieceContext<'_>) -> Result<()> { let sea = c.world.sea_level()?; let water = c.state("water"); diff --git a/crates/horizon-world/src/worldgen/structure/simple.rs b/crates/horizon-world/src/worldgen/structure/simple.rs index d69314c13..d05aab20f 100644 --- a/crates/horizon-world/src/worldgen/structure/simple.rs +++ b/crates/horizon-world/src/worldgen/structure/simple.rs @@ -18,11 +18,22 @@ fn empty_processors() -> Arc { #[derive(Debug)] pub struct BuriedTreasurePiece { pub position: [i32; 3], + /// Where the chest went: the box vanilla saves once placed. + pub found: Mutex>, } impl LegacyPiece for BuriedTreasurePiece { fn bounding_box(&self) -> BoundingBox { BoundingBox::new(self.position, self.position) } + fn save(&self) -> Option { + let at = self.found.lock().unwrap().unwrap_or(self.position); + Some(super::legacy::piece_tag( + "minecraft:btp", + BoundingBox::new(at, at), + None, + 0, + )) + } fn type_name(&self) -> &'static str { "minecraft:btp" } @@ -58,6 +69,7 @@ impl LegacyPiece for BuriedTreasurePiece { } } } + *self.found.lock().unwrap() = Some(pos); create_chest(c, pos, "minecraft:chests/buried_treasure", None)?; return Ok(()); } @@ -441,6 +453,21 @@ impl Scattered { pub fn frame(&self) -> PieceFrame { *self.frame.lock().unwrap() } + /// `ScatteredFeaturePiece`'s tag: the box and the height it settled on. + pub fn saved(&self, id: &str) -> crate::nbt::Compound { + use crate::nbt::Tag; + let f = self.frame(); + let mut tag = super::legacy::piece_tag(id, f.bounding_box, f.orientation, 0); + for (key, value) in [ + ("Width", self.width), + ("Height", self.height), + ("Depth", self.depth), + ("HPos", *self.height_position.lock().unwrap()), + ] { + tag.insert(key.into(), Tag::Int(value)); + } + tag + } /// updateAverageGroundHeight over the part of the box inside the chunk. pub fn average_ground(&self, c: &mut PieceContext<'_>, offset: i32) -> Result { if *self.height_position.lock().unwrap() >= 0 { @@ -498,12 +525,15 @@ impl Scattered { #[derive(Debug)] pub struct SwampHutPiece { pub base: Scattered, + /// spawnedWitch and spawnedCat: both spawn in the same chunk. + spawned: Mutex, } impl SwampHutPiece { pub fn new(random: &mut impl RandomSource, west: i32, north: i32) -> Self { let direction = random_horizontal(random); Self { base: Scattered::new(west, 64, north, 7, 7, 9, direction), + spawned: Mutex::new(false), } } } @@ -511,6 +541,13 @@ impl LegacyPiece for SwampHutPiece { fn bounding_box(&self) -> BoundingBox { self.base.frame().bounding_box } + fn save(&self) -> Option { + let mut tag = self.base.saved("minecraft:tesh"); + let spawned = crate::nbt::Tag::Byte(i8::from(*self.spawned.lock().unwrap())); + tag.insert("Witch".into(), spawned.clone()); + tag.insert("Cat".into(), spawned); + Some(tag) + } fn type_name(&self) -> &'static str { "minecraft:tesh" } @@ -579,6 +616,7 @@ impl LegacyPiece for SwampHutPiece { c.world .entity(super::legacy::spawn_nbt(id, pos, true, true))?; } + *self.spawned.lock().unwrap() = true; } Ok(()) } diff --git a/crates/horizon-world/src/worldgen/structure/start.rs b/crates/horizon-world/src/worldgen/structure/start.rs index 862423de7..810332c61 100644 --- a/crates/horizon-world/src/worldgen/structure/start.rs +++ b/crates/horizon-world/src/worldgen/structure/start.rs @@ -962,6 +962,7 @@ fn try_generate( let stub = top_of_chunk_center(context, chunk, HeightmapType::OceanFloorWg)?; let piece = super::simple::BuriedTreasurePiece { position: [chunk.x * 16 + 9, 90, chunk.z * 16 + 9], + found: std::sync::Mutex::new(None), }; (stub, legacy(vec![piece])) } diff --git a/crates/horizon-world/src/worldgen/structure/stronghold.rs b/crates/horizon-world/src/worldgen/structure/stronghold.rs index 94042ba6f..29f7cd149 100644 --- a/crates/horizon-world/src/worldgen/structure/stronghold.rs +++ b/crates/horizon-world/src/worldgen/structure/stronghold.rs @@ -1075,6 +1075,48 @@ impl LegacyPiece for StrongholdPiece { fn bounding_box(&self) -> BoundingBox { self.frame.bounding_box } + fn save(&self) -> Option { + use crate::nbt::Tag; + let flag = |b: bool| Tag::Byte(i8::from(b)); + let mut tag = super::legacy::piece_tag( + self.type_name(), + self.frame.bounding_box, + self.frame.orientation, + self.depth, + ); + // SmallDoorType.LEGACY_CODEC: the enum name. + let door = match self.door { + Door::Opening => "OPENING", + Door::Wood => "WOOD_DOOR", + Door::Grates => "GRATES", + Door::Iron => "IRON_DOOR", + }; + let placed = *self.placed.lock().unwrap(); + let [a, b, c, d] = self.flags; + let mut entries = vec![("EntryDoor", Tag::String(door.into()))]; + match self.kind { + Kind::ChestCorridor => entries.push(("Chest", flag(placed))), + Kind::Filler => entries.push(("Steps", Tag::Int(self.value))), + Kind::FiveCrossing => entries.extend([ + ("leftLow", flag(a)), + ("leftHigh", flag(b)), + ("rightLow", flag(c)), + ("rightHigh", flag(d)), + ]), + Kind::Library => entries.push(("Tall", flag(a))), + Kind::PortalRoom => entries.push(("Mob", flag(placed))), + Kind::RoomCrossing => entries.push(("Type", Tag::Int(self.value))), + // StartPiece is a StairsDown that is the source. + Kind::StairsDown => entries.push(("Source", flag(false))), + Kind::Start => entries.push(("Source", flag(true))), + Kind::Straight => entries.extend([("Left", flag(a)), ("Right", flag(b))]), + _ => {} + } + for (key, value) in entries { + tag.insert(key.into(), value); + } + Some(tag) + } fn type_name(&self) -> &'static str { match self.kind { Kind::Straight => "minecraft:shs", diff --git a/crates/horizon-world/src/worldgen/structure/temple.rs b/crates/horizon-world/src/worldgen/structure/temple.rs index 195f37791..c328f0f55 100644 --- a/crates/horizon-world/src/worldgen/structure/temple.rs +++ b/crates/horizon-world/src/worldgen/structure/temple.rs @@ -82,6 +82,16 @@ impl LegacyPiece for DesertPyramidPiece { fn bounding_box(&self) -> BoundingBox { self.base.frame().bounding_box } + fn save(&self) -> Option { + let mut tag = self.base.saved("minecraft:tedp"); + for (i, placed) in self.placed_chest.lock().unwrap().iter().enumerate() { + tag.insert( + format!("hasPlacedChest{i}").as_str().into(), + crate::nbt::Tag::Byte(i8::from(*placed)), + ); + } + Some(tag) + } fn type_name(&self) -> &'static str { "minecraft:tedp" } @@ -448,6 +458,22 @@ impl LegacyPiece for JungleTemplePiece { fn bounding_box(&self) -> BoundingBox { self.base.frame().bounding_box } + fn save(&self) -> Option { + let mut tag = self.base.saved("minecraft:tejp"); + let placed = *self.placed.lock().unwrap(); + for (key, value) in [ + "placedMainChest", + "placedHiddenChest", + "placedTrap1", + "placedTrap2", + ] + .into_iter() + .zip(placed) + { + tag.insert(key.into(), crate::nbt::Tag::Byte(i8::from(value))); + } + Some(tag) + } fn type_name(&self) -> &'static str { "minecraft:tejp" } diff --git a/tools/test_structure_start_nbt_parity.py b/tools/test_structure_start_nbt_parity.py index c222ad127..00ff7f9d5 100755 --- a/tools/test_structure_start_nbt_parity.py +++ b/tools/test_structure_start_nbt_parity.py @@ -4,8 +4,8 @@ The oracle (VanillaStructureStartOracle with HORIZON_START_NBT) generates the start of each case's chunk with the pinned server's own classes and prints its tag; the probe (world_probe structure_start_nbt) prints the tag Horizon saves for the same chunk. Both print sorted keys and typed numbers, and the lines must be identical. -The cases are the start chunks of one site of every structure kind built from jigsaw pools or templates (seed -12345). +The cases are the start chunks of one site of every structure kind (seed 12345, and a badlands mineshaft of seed +-7777), which between them use every StructurePieceType. """ import argparse import collections @@ -31,6 +31,9 @@ CASES = [ (12345, 'overworld', 114, -133), (12345, 'overworld', -16, 5), (12345, 'overworld', -109, 91), (12345, 'overworld', 0, -18), (12345, 'overworld', -150, 51), (12345, 'overworld', 61, 49), (12345, 'the_nether', 0, -18), (12345, 'the_nether', -22, 6), (12345, 'the_end', -15, -76), + (12345, 'overworld', 38, -115), (12345, 'overworld', -238, -313), (12345, 'overworld', -95, 2), + (12345, 'overworld', -126, -106), (12345, 'overworld', 47, 25), (12345, 'overworld', 110, 23), + (12345, 'overworld', 4, -1), (12345, 'the_nether', -13, -37), (-7777, 'overworld', 75, 84), ] From fc0b73954f28fe022b0f9ac4ace3392118469108 Mon Sep 17 00:00:00 2001 From: FusselTV Date: Sun, 25 Oct 2026 20:28:49 +0100 Subject: [PATCH 05/51] x A container whose items no longer match its roll is saved without the table, also when it was loaded with one, so a chest emptied after a load does not fill again on the next one. A zero LootTableSeed is left out, as trySaveLootTable does. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/fishing.rs | 2 +- crates/horizon-client/src/game/minecarts.rs | 10 ++ crates/horizon-client/src/game/persist.rs | 27 +++- crates/horizon-client/src/save.rs | 147 ++++++++++++++++- crates/horizon-client/src/structure_blocks.rs | 149 ++++++++++-------- crates/horizon-client/src/vanillagen.rs | 11 +- 6 files changed, 274 insertions(+), 72 deletions(-) diff --git a/crates/horizon-client/src/game/fishing.rs b/crates/horizon-client/src/game/fishing.rs index d454df406..22cb3774b 100644 --- a/crates/horizon-client/src/game/fishing.rs +++ b/crates/horizon-client/src/game/fishing.rs @@ -231,7 +231,7 @@ impl Game<'_> { } damage } - fn biome_name_at(&self, p: Vec3) -> Option { + pub(super) fn biome_name_at(&self, p: Vec3) -> Option { let (x, y, z) = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); let c = self.world.chunks.get(&(x >> 4, z >> 4))?; Some( diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 8d4920b48..3ab6ae304 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -87,6 +87,9 @@ pub(super) struct Minecart { pub fuse: i32, /// Hopper minecarts: an unpowered activator rail enables them. pub enabled: bool, + /// Chest minecarts: the loot table rolled into `items` on load, saved + /// again while the items are still that roll. + pub loot: Option, } const WIDTH: f64 = 0.98; const HEIGHT: f64 = 0.7; @@ -182,6 +185,7 @@ impl Minecart { push: [0.0; 2], fuse: -1, enabled: true, + loot: None, } } pub fn bounds(&self) -> Aabb { @@ -1514,6 +1518,12 @@ impl Minecart { } CartKind::Rideable => {} } + // A loaded loot table goes back while the items are still its roll; + // otherwise the items replace it, as vanilla's unpackLootTable does. + if !self.loot.as_ref().is_some_and(|l| l.restore(map)) { + map.remove(&JavaString::from("LootTable")); + map.remove(&JavaString::from("LootTableSeed")); + } } tag } diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 45ef8801f..24fd9a5aa 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -279,7 +279,8 @@ impl Game<'_> { k if super::minecarts::CartKind::from_id(k).is_some() => { let kind = super::minecarts::CartKind::from_id(k).unwrap(); let id = self.next_entity + 1; - if let Some(c) = super::minecarts::Minecart::from_nbt(&tag, id, kind) { + if let Some(mut c) = super::minecarts::Minecart::from_nbt(&tag, id, kind) { + self.roll_cart_loot(&mut c, &tag); self.next_entity = id; self.remember(id, uuid, tag); self.carts.push(c); @@ -527,6 +528,30 @@ impl Game<'_> { pub(super) fn persist_raw(&self, id: u32) -> Option<&Tag> { self.persist.raw.get(&id) } + /// A loaded chest minecart with a loot table and no items: the table + /// rolled now, as generated containers are (Horizon does not unpack on + /// first open), and kept to save it again while unchanged. + fn roll_cart_loot(&self, cart: &mut super::minecarts::Minecart, tag: &Tag) { + let Some(table) = horizon_client::save::text(tag.get("LootTable")) else { + return; + }; + if cart.items.is_empty() || cart.items.iter().any(Option::is_some) { + return; + } + let loot = horizon_client::structure_blocks::loot_data(&self.options.resources); + let p = cart.position; + let pos = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); + let biome = self.biome_name_at(p).unwrap_or_default(); + let seed = horizon_client::structure_blocks::loot_seed(tag); + cart.loot = Some(horizon_client::structure_blocks::roll_container( + &mut cart.items, + loot.as_deref(), + table, + seed, + pos, + &biome, + )); + } fn remember(&mut self, id: u32, uuid: Option<[i32; 4]>, tag: Tag) { self.restore_portal_cooldown(id, &tag); if let Some(u) = uuid { diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 0c353bb38..783aa506d 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -297,6 +297,35 @@ impl SaveTables { } } +/// A container's loot table and what Horizon rolled from it. Vanilla keeps +/// `LootTable` and `LootTableSeed` until the container is first opened; +/// Horizon rolls when it generates or loads the chunk, and saves the table +/// again while the container still holds exactly the rolled items. +#[derive(Clone, Debug, PartialEq)] +pub struct RolledLoot { + pub pos: (i32, i32, i32), + pub table: String, + /// The saved `LootTableSeed`, written back unless 0 (trySaveLootTable). + pub seed: Option, + /// The rolled `Items`. + pub items: Tag, +} +impl RolledLoot { + /// Puts the loot table back in place of `Items` while they are still the + /// roll; false once the container holds anything else. + pub fn restore(&self, map: &mut Compound) -> bool { + if map.get(&"Items".into()) != Some(&self.items) { + return false; + } + map.remove(&"Items".into()); + map.insert("LootTable".into(), string(&self.table)); + if let Some(seed) = self.seed.filter(|s| *s != 0) { + map.insert("LootTableSeed".into(), Tag::Long(seed)); + } + true + } +} + /// Save data loaded with a chunk that Horizon keeps but does not simulate. #[derive(Clone, Debug, Default)] pub struct ChunkExtras { @@ -318,6 +347,8 @@ pub struct ChunkExtras { pub fluid_ticks: Vec, /// Game time written as `LastUpdate`. pub last_update: i64, + /// Containers still holding their loot table's roll. + pub rolled_loot: Vec, } fn tick_list(ticks: &[SavedTick], name: impl Fn(u32) -> Option) -> Tag { @@ -594,6 +625,34 @@ pub fn decode_banner(tag: &Tag) -> crate::containers::Banner { }, } } +/// A loaded container with a loot table and no items yet, rolled as +/// generation rolls it (Horizon does not unpack on first open). +fn roll_loaded_loot( + chunk: &Chunk, + biomes: &Biomes, + tag: &Tag, + be: &mut ((i32, i32, i32), crate::containers::BlockEntity), +) -> Option { + let crate::containers::BlockEntity::Chest(slots) = &mut be.1 else { + return None; + }; + let table = text(tag.get("LootTable"))?; + if slots.iter().any(Option::is_some) { + return None; + } + let loot = crate::structure_blocks::loaded_loot_data()?; + let (x, y, z) = be.0; + let biome = &biomes.get(chunk.biome(x & 15, y, z & 15)).name; + let seed = crate::structure_blocks::loot_seed(tag); + Some(crate::structure_blocks::roll_container( + slots, + Some(&loot), + table, + seed, + be.0, + biome, + )) +} pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers::BlockEntity)> { use crate::containers::BlockEntity; let int = |k: &str| number(tag.get(k)).map(|v| v as i32); @@ -959,7 +1018,16 @@ pub fn encode_with( } None => current, }; - crate::block_entity_nbt::canonical(&merged).unwrap_or(merged) + let mut saved = crate::block_entity_nbt::canonical(&merged).unwrap_or(merged); + if let Some(r) = extras.and_then(|x| x.rolled_loot.iter().find(|r| r.pos == *p)) + && let Tag::Compound(map) = &mut saved + && !r.restore(map) + { + // A loaded source still carries the table; kept, it rolls again on load. + map.remove(&"LootTable".into()); + map.remove(&"LootTableSeed".into()); + } + saved }) .collect(); if let Some(extras) = extras { @@ -1189,10 +1257,13 @@ fn decode_column( extras.block_entity_order.push((x, y, z)); } match decode_block_entity(e) { - Some(be) => { + Some(mut be) => { if let Some(name) = text(e.get("CustomName")) { chunk.block_names.push((be.0, name)); } + if let Some(rolled) = roll_loaded_loot(&chunk, biomes, e, &mut be) { + extras.rolled_loot.push(rolled); + } extras.block_entity_sources.push((be.0, e.clone())); chunk.block_entities.push(be); } @@ -3436,6 +3507,78 @@ impl ChunkGenerator for Persistent { #[cfg(test)] mod tests { + #[test] + fn unopened_rolled_containers_save_their_loot_table() { + let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES") else { + return; + }; + let root = PathBuf::from(root); + let assets = crate::assets::Assets::load(&root).expect("assets"); + let biomes = Biomes::load(&root).expect("biomes"); + let tables = SaveTables::new(&assets); + let chest = assets.registry.default_state("minecraft:chest").unwrap(); + let mut slots = vec![None; 27]; + slots[3] = Some(crate::items::ItemStack::new("minecraft:bone", 2)); + let mut chunk = Chunk::empty(0, 0); + chunk.set(1, 64, 2, chest.0); + chunk.block_entities.push(( + (1, 64, 2), + crate::containers::BlockEntity::Chest(slots.clone()), + )); + let rolled = RolledLoot { + pos: (1, 64, 2), + table: "minecraft:chests/simple_dungeon".into(), + seed: Some(42), + items: encode_items(&slots), + }; + chunk.saved = Some(Arc::new(ChunkExtras { + rolled_loot: vec![rolled], + ..ChunkExtras::default() + })); + let saved_chest = |chunk: &Chunk| -> Tag { + let saved = encode_with(chunk, assets.registry, &biomes, Some(&tables), true); + let Some(Tag::List(list)) = saved.tag.get("block_entities") else { + panic!("no block entities"); + }; + list[0].clone() + }; + let unopened = saved_chest(&chunk); + assert_eq!( + text(unopened.get("LootTable")).as_deref(), + Some("minecraft:chests/simple_dungeon") + ); + assert_eq!(number(unopened.get("LootTableSeed")), Some(42)); + assert!(unopened.get("Items").is_none()); + // Taking an item makes the items the container's own. + if let crate::containers::BlockEntity::Chest(s) = &mut chunk.block_entities[0].1 { + s[3] = None; + s[4] = Some(crate::items::ItemStack::new("minecraft:bone", 1)); + } + let opened = saved_chest(&chunk); + assert!(opened.get("LootTable").is_none()); + assert!(opened.get("Items").is_some()); + // Loaded with its table, rolled, then emptied: no table, or it refills on load. + let mut extras = ChunkExtras::clone(chunk.saved.as_ref().unwrap()); + extras.block_entity_sources = vec![( + (1, 64, 2), + Tag::compound([ + ("id", string("minecraft:chest")), + ("x", Tag::Int(1)), + ("y", Tag::Int(64)), + ("z", Tag::Int(2)), + ("LootTable", string("minecraft:chests/simple_dungeon")), + ("LootTableSeed", Tag::Long(42)), + ]), + )]; + chunk.saved = Some(Arc::new(extras)); + if let crate::containers::BlockEntity::Chest(s) = &mut chunk.block_entities[0].1 { + s.fill(None); + } + let emptied = saved_chest(&chunk); + assert!(emptied.get("LootTable").is_none()); + assert!(emptied.get("LootTableSeed").is_none()); + } + #[test] fn saved_far_surface_reads_builds_and_water_without_gameplay_chunks() { let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES") else { diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index 9503294e0..f77696277 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -108,9 +108,10 @@ pub fn has_pending_map(item: &ItemStack) -> bool { }) } +static LOOT: OnceLock>> = OnceLock::new(); + /// Loot data of the resource root, loaded once per process. pub fn loot_data(root: &Path) -> Option> { - static LOOT: OnceLock>> = OnceLock::new(); LOOT.get_or_init(|| match LootData::load(root) { Ok(data) => Some(Arc::new(data)), Err(e) => { @@ -121,6 +122,54 @@ pub fn loot_data(root: &Path) -> Option> { .clone() } +/// The loot data `loot_data` loaded, if it ran. +pub fn loaded_loot_data() -> Option> { + LOOT.get().cloned().flatten() +} + +/// `RandomizableContainer.unpackLootTable` of a container at `pos`: `table` +/// rolled into `slots`. A missing or zero seed is the level's random in +/// vanilla; Horizon derives one from the position. Without loot data the +/// container stays empty and still saves its table. +pub fn roll_container( + slots: &mut [Option], + loot: Option<&LootData>, + table: String, + saved_seed: Option, + pos: (i32, i32, i32), + biome: &str, +) -> crate::save::RolledLoot { + let seed = saved_seed.filter(|s| *s != 0).unwrap_or_else(|| { + horizon_core::random::position_seed(horizon_core::position::BlockPos::new( + pos.0, pos.1, pos.2, + )) + }); + if let Some(loot) = loot { + // LootTable.fill spreads the items over the container's own size. + let rolled = loot.fill(&table, seed, slots.len(), Some(biome)); + for (slot, stack) in slots.iter_mut().zip(rolled) { + // With what the rolls put on them: enchantments + // (enchant_with_levels in End city chests), potions and an + // ominous bottle's level. + *slot = stack.map(|s| loot_item_with_components(&s)); + } + } + crate::save::RolledLoot { + pos, + table, + seed: saved_seed, + items: crate::save::encode_items(slots), + } +} + +/// A saved `LootTableSeed`, if any. +pub fn loot_seed(nbt: &Tag) -> Option { + match nbt.get("LootTableSeed") { + Some(Tag::Long(seed)) => Some(*seed), + _ => None, + } +} + fn text(nbt: &Compound, key: &str) -> Option { match nbt.get(&JavaString::from(key)) { Some(Tag::String(s)) => Some(s.to_string_lossy()), @@ -149,81 +198,37 @@ fn generated_block_entity(block: &str, nbt: &Compound) -> Option { Some(entity) } -/// Client block entities for the generated block entities of a chunk. +/// Client block entities for the generated block entities of a chunk, and the +/// loot rolled into its containers. pub fn block_entities( chunk: &ProtoChunk, loot: Option<&LootData>, -) -> Vec<((i32, i32, i32), BlockEntity)> { +) -> ( + Vec<((i32, i32, i32), BlockEntity)>, + Vec, +) { let mut out = Vec::new(); + let mut rolled = Vec::new(); for (pos, nbt) in &chunk.block_entities { let [x, y, z] = *pos; let block = chunk.block_name(x, y, z); let Some(mut entity) = generated_block_entity(block, nbt) else { continue; }; - if let (BlockEntity::Chest(slots), Some(table), Some(loot)) = - (&mut entity, text(nbt, "LootTable"), loot) - { - let seed = match nbt.get(&JavaString::from("LootTableSeed")) { - Some(Tag::Long(seed)) => *seed, - // Seed 0 means "the level's random": derive one from the position. - _ => horizon_core::random::position_seed(horizon_core::position::BlockPos::new( - x, y, z, - )), - }; - let biome = chunk.biome_at(x, y, z); - for (slot, stack) in slots - .iter_mut() - .zip(loot.fill(&table, seed, 27, Some(biome))) - { - // With what the rolls put on them: enchantments - // (enchant_with_levels in End city chests), potions and an - // ominous bottle's level. - *slot = stack.map(|s| loot_item_with_components(&s)); - } + if let (BlockEntity::Chest(slots), Some(table)) = (&mut entity, text(nbt, "LootTable")) { + let seed = loot_seed(&Tag::Compound(nbt.clone())); + rolled.push(roll_container( + slots, + loot, + table, + seed, + (x, y, z), + chunk.biome_at(x, y, z), + )); } out.push(((x, y, z), entity)); } - out -} - -/// Chest minecarts placed with a loot table (mineshafts): the table rolled -/// into `Items` as `unpackLootTable` would on first open. -pub fn unpack_entity_loot( - chunk: &ProtoChunk, - mut nbt: horizon_world::nbt::Compound, - loot: Option<&LootData>, -) -> horizon_world::nbt::Compound { - let (Some(table), Some(loot)) = ( - match nbt.get(&JavaString::from("LootTable")) { - Some(Tag::String(s)) => Some(s.to_string_lossy()), - _ => None, - }, - loot, - ) else { - return nbt; - }; - let seed = match nbt.get(&JavaString::from("LootTableSeed")) { - Some(Tag::Long(seed)) => *seed, - _ => 0, - }; - let pos = match nbt.get(&JavaString::from("Pos")) { - Some(Tag::List(p)) => std::array::from_fn(|i| match p.get(i) { - Some(Tag::Double(b)) => f64::from_bits(*b).floor() as i32, - _ => 0, - }), - _ => [0; 3], - }; - let biome = chunk.biome_at(pos[0], pos[1], pos[2]); - let slots: Vec> = loot - .fill(&table, seed, 27, Some(biome)) - .into_iter() - .map(|s| s.map(|s| loot_item_with_components(&s))) - .collect(); - nbt.remove(&JavaString::from("LootTable")); - nbt.remove(&JavaString::from("LootTableSeed")); - nbt.insert("Items".into(), crate::save::encode_items(&slots)); - nbt + (out, rolled) } #[cfg(test)] @@ -270,6 +275,24 @@ mod tests { assert_eq!(arrow.potion(), Some("minecraft:slowness")); } + #[test] + fn a_container_rolled_without_loot_data_saves_its_table() { + let mut slots = vec![None; 27]; + let rolled = roll_container( + &mut slots, + None, + "minecraft:chests/simple_dungeon".into(), + Some(7), + (1, 2, 3), + "minecraft:plains", + ); + let mut saved = horizon_world::nbt::Compound::new(); + saved.insert("Items".into(), crate::save::encode_items(&slots)); + assert!(rolled.restore(&mut saved)); + assert!(!saved.contains_key(&"Items".into())); + assert_eq!(saved.get(&"LootTableSeed".into()), Some(&Tag::Long(7))); + } + #[test] fn exploration_maps_wait_in_custom_data_until_searched() { let mut stack = LootStack { diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index c890213c5..441375b23 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -531,7 +531,9 @@ impl ChunkGenerator for VanillaTerrain { VanillaProto::Failed(x, z) => return Chunk::empty(x, z), }; let mut out = self.column(&chunk); - out.block_entities = crate::structure_blocks::block_entities(&chunk, self.loot.as_deref()); + let (block_entities, rolled_loot) = + crate::structure_blocks::block_entities(&chunk, self.loot.as_deref()); + out.block_entities = block_entities; // The block entities Horizon does not model (decorated pots with their // sherds and loot table, brushable blocks) stay as placed, like a // loaded chunk's. @@ -555,13 +557,14 @@ impl ChunkGenerator for VanillaTerrain { Some(Tag::Compound(nbt)) }) .collect(); - if !unmodelled.is_empty() { + if !unmodelled.is_empty() || !rolled_loot.is_empty() { let mut extras = out .saved .take() .map(Arc::unwrap_or_clone) .unwrap_or_default(); extras.block_entities = unmodelled; + extras.rolled_loot = rolled_loot; out.saved = Some(Arc::new(extras)); } out.structure_refs = chunk @@ -570,11 +573,9 @@ impl ChunkGenerator for VanillaTerrain { .map(|(id, start, _, _)| (Arc::from(id), (start.x, start.z))) .collect(); let entities = std::mem::take(&mut chunk.entities); + // Chest minecarts keep their loot table; the game rolls it on load. out.entities = entities .into_iter() - .map(|nbt| { - crate::structure_blocks::unpack_entity_loot(&chunk, nbt, self.loot.as_deref()) - }) .map(horizon_world::nbt::Tag::Compound) .collect(); for s in &mut out.sections { From c67a963da7f60410fe7bf72abceb9293a5b484e3 Mon Sep 17 00:00:00 2001 From: FusselTV Date: Sun, 25 Oct 2026 22:33:35 +0100 Subject: [PATCH 06/51] Saves: write the structure starts a chunk holds A generated chunk keeps the starts it holds and its save writes them into structures.starts with their current state, as vanilla saves the StructureStart objects its chunks share. Proto chunks get their references and starts too, so vanilla and Paper find the structures of the chunks they finish at the edge of a generated area. A start with a piece that cannot be saved is left out, with a warning. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/chunk.rs | 4 ++++ crates/horizon-client/src/save.rs | 19 +++++++++++++++++++ crates/horizon-client/src/vanillagen.rs | 11 ++++++----- .../horizon-world/src/worldgen/generator.rs | 9 +++++++++ 4 files changed, 38 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs index 41330df5f..e158b6ca6 100644 --- a/crates/horizon-client/src/chunk.rs +++ b/crates/horizon-client/src/chunk.rs @@ -147,6 +147,9 @@ pub struct Chunk { /// Structure starts reaching into this chunk (`structures.References`): /// structure id and the start's chunk. pub structure_refs: Vec<(Arc, (i32, i32))>, + /// The starts generation made in this chunk (`structures.starts`), saved + /// with the state their placement has reached by then. + pub structure_starts: Vec>, } impl Chunk { pub fn empty(x: i32, z: i32) -> Self { @@ -164,6 +167,7 @@ impl Chunk { block_entities: Vec::new(), block_names: Vec::new(), structure_refs: Vec::new(), + structure_starts: Vec::new(), postprocess: Vec::new(), saved: None, entities: Vec::new(), diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 0c353bb38..3bf39bad4 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -1017,6 +1017,25 @@ pub fn encode_with( .collect(); s.insert("References".into(), Tag::Compound(refs)); } + let starts: Compound = chunk + .structure_starts + .iter() + .filter_map(|start| match start.save() { + Some(tag) => Some((start.name.as_str().into(), tag)), + None => { + log::warn!( + "Horizon: structure start {} not saved: one of its pieces cannot be", + start.name + ); + None + } + }) + .collect(); + if !starts.is_empty() + && let Some(Tag::Compound(s)) = map.get_mut(&"structures".into()) + { + s.insert("starts".into(), Tag::Compound(starts)); + } map.entry("PostProcessing".into()) .or_insert_with(|| Tag::List(vec![Tag::List(Vec::new()); SECTIONS])); } diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index c890213c5..1e13f8fa3 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -158,6 +158,12 @@ impl VanillaTerrain { chunk.terrain.min_y().max(MIN_Y), (chunk.terrain.min_y() + chunk.terrain.height()).min(MIN_Y + HEIGHT), ); + out.structure_refs = chunk + .structures() + .into_iter() + .map(|(id, start, _, _)| (Arc::from(id), (start.x, start.z))) + .collect(); + out.structure_starts = chunk.own_starts(); let mut values = Box::new([0u32; 4096]); for si in 0..SECTIONS as i32 { let base = MIN_Y + si * 16; @@ -564,11 +570,6 @@ impl ChunkGenerator for VanillaTerrain { extras.block_entities = unmodelled; out.saved = Some(Arc::new(extras)); } - out.structure_refs = chunk - .structures() - .into_iter() - .map(|(id, start, _, _)| (Arc::from(id), (start.x, start.z))) - .collect(); let entities = std::mem::take(&mut chunk.entities); out.entities = entities .into_iter() diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 316bd837c..1672e31e9 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -594,6 +594,15 @@ impl ProtoChunk { pub fn is_decorated(&self) -> bool { self.decorated } + /// The structure starts this chunk holds itself (`structures.starts`). + pub fn own_starts(&self) -> Vec> { + let pos = self.position(); + self.structure_starts + .iter() + .filter(|s| s.chunk == pos) + .cloned() + .collect() + } /// Also restores a saved proto chunk that was decorated before it was saved. pub fn set_decorated(&mut self) { self.decorated = true; From 2143c26a2e6205af93ef55729f9db45866c2bc84 Mon Sep 17 00:00:00 2001 From: FusselTV Date: Sun, 25 Oct 2026 23:00:07 +0100 Subject: [PATCH 07/51] Saves: write points of interest Horizon finds villager POIs from the blocks and kept no poi folder, so a world it made had none. Vanilla rebuilds a missing section on load, but until a chunk is loaded nothing knows its beds, job sites, bells, nests, portals or lodestones. Saving a chunk now writes its POI records the way PoiManager saves its sections: each section with POI blocks, valid, one record per block of PoiTypes with its max tickets, free_tickets left out at 0. A chunk that lost its last POI and had a record gets an empty one, since vanilla trusts a valid section. The records are built on the region writer thread, which reads the saved record there, so unloading chunks reads no files on the tick thread. A straw bed is no home (PoiTypes.BEDS is the sixteen colours); /locate poi uses the same table. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/commands.rs | 33 +- crates/horizon-client/src/save.rs | 419 +++++++++++++++++++-- 2 files changed, 388 insertions(+), 64 deletions(-) diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 76e10cb57..7ed8f9658 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -2572,38 +2572,7 @@ impl Game<'_> { /// `PoiTypes`: the point of interest type of a block state. fn poi_type(&self, state: horizon_world::registry::BlockStateId) -> Option<&'static str> { let s = self.pack.assets.registry.state(state)?; - let name = s.name.strip_prefix("minecraft:")?; - Some(match name { - "blast_furnace" => "minecraft:armorer", - "smoker" => "minecraft:butcher", - "cartography_table" => "minecraft:cartographer", - "brewing_stand" => "minecraft:cleric", - "composter" => "minecraft:farmer", - "barrel" => "minecraft:fisherman", - "fletching_table" => "minecraft:fletcher", - "cauldron" | "lava_cauldron" | "water_cauldron" | "powder_snow_cauldron" => { - "minecraft:leatherworker" - } - "lectern" => "minecraft:librarian", - "stonecutter" => "minecraft:mason", - "loom" => "minecraft:shepherd", - "smithing_table" => "minecraft:toolsmith", - "grindstone" => "minecraft:weaponsmith", - "bell" => "minecraft:meeting", - "beehive" => "minecraft:beehive", - "bee_nest" => "minecraft:bee_nest", - "nether_portal" => "minecraft:nether_portal", - "lodestone" => "minecraft:lodestone", - "test_instance_block" => "minecraft:test_instance", - n if n.ends_with("_bed") => { - if s.properties.get("part").map(String::as_str) != Some("head") { - return None; - } - "minecraft:home" - } - n if n.ends_with("lightning_rod") => "minecraft:lightning_rod", - _ => return None, - }) + horizon_client::save::poi_type(s).map(|(kind, _)| kind) } /// `LocateCommand.locatePoi`: `PoiManager.findClosestWithType` within /// 256 blocks of the source, over the loaded chunks. diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 0c353bb38..246bacbac 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -247,6 +247,44 @@ pub struct SaveTables { block_entity: Vec, heightmaps: crate::assets::Properties, air: u32, + /// The POI type and its max tickets of each state (`PoiTypes`). + poi: Vec>, +} +/// `PoiTypes.register`: the POI type of a block state and its max tickets. +pub fn poi_type(state: &horizon_world::chunk::BlockState) -> Option<(&'static str, i32)> { + let name = state.name.strip_prefix("minecraft:")?; + Some(match name { + "blast_furnace" => ("minecraft:armorer", 1), + "smoker" => ("minecraft:butcher", 1), + "cartography_table" => ("minecraft:cartographer", 1), + "brewing_stand" => ("minecraft:cleric", 1), + "composter" => ("minecraft:farmer", 1), + "barrel" => ("minecraft:fisherman", 1), + "fletching_table" => ("minecraft:fletcher", 1), + "cauldron" | "lava_cauldron" | "water_cauldron" | "powder_snow_cauldron" => { + ("minecraft:leatherworker", 1) + } + "lectern" => ("minecraft:librarian", 1), + "stonecutter" => ("minecraft:mason", 1), + "loom" => ("minecraft:shepherd", 1), + "smithing_table" => ("minecraft:toolsmith", 1), + "grindstone" => ("minecraft:weaponsmith", 1), + "bell" => ("minecraft:meeting", 32), + "beehive" => ("minecraft:beehive", 0), + "bee_nest" => ("minecraft:bee_nest", 0), + "nether_portal" => ("minecraft:nether_portal", 0), + "lodestone" => ("minecraft:lodestone", 0), + "test_instance_block" => ("minecraft:test_instance", 0), + // PoiTypes.BEDS is the sixteen colours: no straw bed. + bed if bed.ends_with("_bed") && bed != "straw_bed" => { + if state.properties.get("part").map(String::as_str) != Some("head") { + return None; + } + ("minecraft:home", 1) + } + rod if rod.ends_with("lightning_rod") => ("minecraft:lightning_rod", 0), + _ => return None, + }) } impl SaveTables { pub fn new(assets: &crate::assets::Assets) -> Self { @@ -275,6 +313,9 @@ impl SaveTables { block_entity: Vec::new(), heightmaps: assets.properties.clone(), air: registry.default_state("minecraft:air").map_or(0, |s| s.0), + poi: (0..registry.len()) + .map(|id| registry.state(BlockStateId(id as u32)).and_then(poi_type)) + .collect(), } } /// Tables with only the heightmaps' state facts, for tests. @@ -287,6 +328,7 @@ impl SaveTables { block_entity: Vec::new(), heightmaps, air: 0, + poi: Vec::new(), } } /// Which states carry a block entity (`BlockFacts`), to drop entries for @@ -734,6 +776,103 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain Some((pos, entity)) } +/// The chunk's points of interest as `PoiManager` saves them: each section +/// with POI blocks, valid, with a record per block at its max tickets (a +/// freshly made world). None when the chunk has none. +pub fn encode_poi(chunk: &Chunk, tables: &SaveTables) -> Option { + let kind = |v: u32| tables.poi.get(v as usize).copied().flatten(); + let mut sections = Compound::new(); + let mut states = [0u32; 4096]; + for (si, section) in chunk.sections.iter().enumerate() { + if !section.blocks.maybe_has(|v| kind(v).is_some()) { + continue; + } + section.unpack(&mut states); + let y = (MIN_Y >> 4) + si as i32; + let records: Vec = states + .iter() + .enumerate() + .filter_map(|(i, &v)| { + let (id, tickets) = kind(v)?; + let i = i as i32; + let pos = [ + chunk.x * 16 + (i & 15), + y * 16 + (i >> 8), + chunk.z * 16 + ((i >> 4) & 15), + ]; + let mut record = vec![("pos", Tag::IntArray(pos.to_vec())), ("type", string(id))]; + // PoiRecord.CODEC: free_tickets defaults to 0 and is then left out. + if tickets != 0 { + record.push(("free_tickets", Tag::Int(tickets))); + } + Some(Tag::compound(record)) + }) + .collect(); + if !records.is_empty() { + sections.insert( + y.to_string().as_str().into(), + Tag::compound([("Valid", Tag::Byte(1)), ("Records", Tag::List(records))]), + ); + } + } + (!sections.is_empty()).then(|| poi_root(sections)) +} +/// A record's `free_tickets` from the POI file the chunk had, while the same +/// POI is still there: a bed or job site a villager claimed stays claimed. +fn keep_claims(saved: &mut NamedTag, old: &NamedTag) { + let key = |r: &Tag| match (r.get("pos"), text(r.get("type"))) { + (Some(Tag::IntArray(pos)), Some(kind)) => Some((pos.clone(), kind)), + _ => None, + }; + let mut claims = HashMap::new(); + if let Some(Tag::Compound(sections)) = old.tag.get("Sections") { + for section in sections.values() { + if let Some(Tag::List(records)) = section.get("Records") { + for r in records { + if let Some(k) = key(r) { + claims.insert(k, number(r.get("free_tickets")).unwrap_or(0) as i32); + } + } + } + } + } + let Tag::Compound(root) = &mut saved.tag else { + return; + }; + let Some(Tag::Compound(sections)) = root.get_mut(&"Sections".into()) else { + return; + }; + for section in sections.values_mut() { + let Tag::Compound(section) = section else { + continue; + }; + let Some(Tag::List(records)) = section.get_mut(&"Records".into()) else { + continue; + }; + for r in records { + let Some(&tickets) = key(r).and_then(|k| claims.get(&k)) else { + continue; + }; + if let Tag::Compound(r) = r { + if tickets == 0 { + r.remove(&"free_tickets".into()); + } else { + r.insert("free_tickets".into(), Tag::Int(tickets)); + } + } + } + } +} +fn poi_root(sections: Compound) -> NamedTag { + NamedTag { + name: "".into(), + tag: Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("Sections", Tag::Compound(sections)), + ]), + } +} + /// A column's sections as `Heightmap.primeHeightmaps` reads them. struct HeightmapView<'a> { sections: &'a [Arc
], @@ -1555,6 +1694,9 @@ enum Record { Tag(Arc), /// A chunk to encode on the writer thread. Chunk(Arc, Arc), + /// A chunk's points of interest, made on the writer thread against the + /// saved ones (`resolve_poi`). + Poi(Arc, Arc), Delete, } /// What encoding a chunk needs, captured when it is queued. @@ -1575,14 +1717,86 @@ impl Record { e.tables.as_deref(), e.sky_light, ))), + Record::Poi(c, t) => encode_poi(c, t).map(Arc::new), Record::Delete => None, } } } +/// A queued POI record as it is written: claims kept from the saved one, and +/// a chunk that lost its last POI gets an empty one, as vanilla trusts a +/// saved section. None when the chunk never had any. +fn resolve_poi( + root: &Path, + cache: &RegionCache, + (x, z): (i32, i32), + record: &Record, +) -> Option { + let Record::Poi(chunk, tables) = record else { + return Some(record.clone()); + }; + let old = read_region_record(root, cache, "poi", x, z).unwrap_or_else(|e| { + log::warn!("Horizon: could not read the poi record of chunk {x} {z}: {e}"); + None + }); + let tag = match (encode_poi(chunk, tables), old) { + (Some(mut tag), Some(old)) => { + keep_claims(&mut tag, &old); + tag + } + (Some(tag), None) => tag, + (None, Some(_)) => poi_root(Compound::new()), + (None, None) => return None, + }; + Some(Record::Tag(Arc::new(tag))) +} +fn read_region_record( + root: &Path, + cache: &RegionCache, + folder: &str, + x: i32, + z: i32, +) -> Result> { + let key = (x >> 5, z >> 5); + let path = region_path(root, folder, key.0, key.1); + let Some(region) = cached_region(cache, key, &path, false)? else { + return Ok(None); + }; + let record = region + .lock() + .map_err(|_| "region file poisoned")? + .read(ChunkPos::new(x, z))?; + Ok(match record { + Some(r) => Some(r.nbt(Limits::default())?), + None => None, + }) +} /// Chunk and entity records waiting for the writer thread, by (entities?, /// x, z): reads see them before the region files do. -type PendingWrites = Mutex>; -type WriteBatch = (bool, Vec<((i32, i32), Record, u64)>); +type PendingWrites = Mutex>; +type WriteBatch = (Folder, Vec<((i32, i32), Record, u64)>); +/// The region folders of a dimension. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +enum Folder { + Region, + Entities, + Poi, +} +impl Folder { + fn of(name: &str) -> Self { + match name { + "entities" => Self::Entities, + "poi" => Self::Poi, + _ => Self::Region, + } + } + fn name(self) -> &'static str { + match self { + Self::Region => "region", + Self::Entities => "entities", + Self::Poi => "poi", + } + } +} /// The background thread that encodes chunks and writes them into the region files, in /// submission order. @@ -1604,6 +1818,7 @@ pub struct SaveDir { pub root: PathBuf, regions: Arc, entity_regions: Arc, + poi_regions: Arc, pending: Arc, sequence: AtomicU64, writer: Mutex>, @@ -1620,6 +1835,7 @@ impl SaveDir { root, regions: Default::default(), entity_regions: Default::default(), + poi_regions: Default::default(), pending: Default::default(), sequence: AtomicU64::new(0), writer: Mutex::new(None), @@ -1636,21 +1852,17 @@ impl SaveDir { .pending .lock() .ok()? - .get(&(folder != "region", x, z)) + .get(&(Folder::of(folder), x, z)) .map(|(_, r)| r.clone()); if let Some(record) = pending { return record.tag().map(|t| (*t).clone()); } - let key = (x >> 5, z >> 5); - let cache = if folder == "region" { - &self.regions - } else { - &self.entity_regions + let cache = match Folder::of(folder) { + Folder::Region => &self.regions, + Folder::Entities => &self.entity_regions, + Folder::Poi => &self.poi_regions, }; - let path = self.region_path(folder, key.0, key.1); - let region = cached_region(cache, key, &path, false).ok()??; - let record = region.lock().ok()?.read(ChunkPos::new(x, z)).ok()??; - record.nbt(Limits::default()).ok() + read_region_record(&self.root, cache, folder, x, z).ok()? } pub fn load(&self, x: i32, z: i32, registry: &BlockRegistry, biomes: &Biomes) -> Option { let root = self.read_record("region", x, z)?; @@ -1710,16 +1922,16 @@ impl SaveDir { .into_iter() .map(|(k, t)| (k, t.map_or(Record::Delete, |t| Record::Tag(Arc::new(t))))) .collect(); - self.queue(folder != "region", records, wait) + self.queue(Folder::of(folder), records, wait) } - fn queue(&self, entities: bool, records: Vec<((i32, i32), Record)>, wait: bool) -> Result<()> { + fn queue(&self, folder: Folder, records: Vec<((i32, i32), Record)>, wait: bool) -> Result<()> { if !records.is_empty() { let mut batch = Vec::with_capacity(records.len()); { let mut pending = self.pending.lock().map_err(|_| "pending writes poisoned")?; for (key, record) in records { let seq = self.sequence.fetch_add(1, Ordering::Relaxed); - pending.insert((entities, key.0, key.1), (seq, record.clone())); + pending.insert((folder, key.0, key.1), (seq, record.clone())); batch.push((key, record, seq)); } } @@ -1730,7 +1942,7 @@ impl SaveDir { .map_err(|_| "writer poisoned")? += 1; let mut writer = self.writer.lock().map_err(|_| "writer poisoned")?; let writer = writer.get_or_insert_with(|| self.start_writer()); - if writer.send.send((entities, batch)).is_err() { + if writer.send.send((folder, batch)).is_err() { *self .outstanding .error @@ -1753,30 +1965,36 @@ impl SaveDir { fn start_writer(&self) -> Writer { let (send, receive) = mpsc::channel::(); let root = self.root.clone(); - let (regions, entity_regions) = (self.regions.clone(), self.entity_regions.clone()); + let (regions, entity_regions, poi_regions) = ( + self.regions.clone(), + self.entity_regions.clone(), + self.poi_regions.clone(), + ); let pending = self.pending.clone(); let outstanding = self.outstanding.clone(); let thread = std::thread::Builder::new() .name("horizon-region-writer".into()) .spawn(move || { - for (entities, batch) in receive { - let (folder, cache) = if entities { - ("entities", &entity_regions) - } else { - ("region", ®ions) + for (kind, batch) in receive { + let cache = match kind { + Folder::Region => ®ions, + Folder::Entities => &entity_regions, + Folder::Poi => &poi_regions, }; + let folder = kind.name(); // IOWorker.pendingWrites: a chunk queued again since is // written once, by its newest batch. let newest = |k: &(i32, i32), seq: u64| { pending.lock().map_or(true, |p| { - p.get(&(entities, k.0, k.1)).is_none_or(|p| p.0 <= seq) + p.get(&(kind, k.0, k.1)).is_none_or(|p| p.0 <= seq) }) }; - let records: Vec<_> = batch + let resolved: Vec<_> = batch .iter() .filter(|(k, _, seq)| newest(k, *seq)) - .map(|(k, r, _)| (*k, r)) + .filter_map(|(k, r, _)| Some((*k, resolve_poi(&root, cache, *k, r)?))) .collect(); + let records: Vec<_> = resolved.iter().map(|(k, r)| (*k, r)).collect(); let result = write_region_records(&root, cache, folder, &records); if let Err(e) = &result { let message = format!("failed to write {folder} files: {e}"); @@ -1788,11 +2006,8 @@ impl SaveDir { && let Ok(mut pending) = pending.lock() { for (k, _, seq) in &batch { - if pending - .get(&(entities, k.0, k.1)) - .is_some_and(|p| p.0 == *seq) - { - pending.remove(&(entities, k.0, k.1)); + if pending.get(&(kind, k.0, k.1)).is_some_and(|p| p.0 == *seq) { + pending.remove(&(kind, k.0, k.1)); } } } @@ -1861,8 +2076,19 @@ impl SaveDir { }) .collect(); self.write_records("region", records, true)?; + self.save_poi(chunks, true)?; Ok(chunks.len()) } + fn save_poi(&self, chunks: &[Arc], wait: bool) -> Result<()> { + let Some(tables) = self.tables.get() else { + return Ok(()); + }; + let records = chunks + .iter() + .map(|c| ((c.x, c.z), Record::Poi(c.clone(), tables.clone()))) + .collect(); + self.queue(Folder::Poi, records, wait) + } /// `save` on the writer thread: returns before the files are written; /// loads see the chunks meanwhile. pub fn save_later( @@ -1881,7 +2107,8 @@ impl SaveDir { .iter() .map(|c| ((c.x, c.z), Record::Chunk(c.clone(), encoding.clone()))) .collect(); - self.queue(false, records, false)?; + self.queue(Folder::Region, records, false)?; + self.save_poi(chunks, false)?; Ok(chunks.len()) } /// Write the entity chunks (`EntityStorage`): an empty list deletes it. @@ -3326,7 +3553,7 @@ impl SaveDir { .pending .lock() .ok()? - .get(&(false, x, z)) + .get(&(Folder::Region, x, z)) .map(|(_, record)| record.clone()); let root = if let Some(record) = pending { record.tag().map(|tag| (*tag).clone())? @@ -3436,6 +3663,134 @@ impl ChunkGenerator for Persistent { #[cfg(test)] mod tests { + #[test] + fn points_of_interest_save_as_poi_sections() { + let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES") else { + return; + }; + let assets = crate::assets::Assets::load(&PathBuf::from(root)).expect("assets"); + let tables = SaveTables::new(&assets); + let state = |name: &str, props: &[(&str, &str)]| { + let mut s = assets + .registry + .state(assets.registry.default_state(name).unwrap()) + .unwrap() + .clone(); + for (k, v) in props { + s.properties.insert((*k).into(), (*v).into()); + } + assets.registry.id(&s).unwrap().0 + }; + let mut chunk = Chunk::empty(2, -1); + chunk.set(1, 70, 1, state("minecraft:red_bed", &[("part", "head")])); + chunk.set(1, 70, 2, state("minecraft:red_bed", &[("part", "foot")])); + chunk.set(5, 71, 5, state("minecraft:bell", &[])); + chunk.set(6, 71, 5, state("minecraft:stone", &[])); + chunk.set(9, 70, 9, state("minecraft:straw_bed", &[("part", "head")])); + assert!(encode_poi(&Chunk::empty(0, 0), &tables).is_none()); + let saved = encode_poi(&chunk, &tables).expect("records"); + let Some(Tag::Compound(sections)) = saved.tag.get("Sections") else { + panic!("no sections"); + }; + assert_eq!(sections.len(), 1); + let section = §ions[&"4".into()]; + assert_eq!(section.get("Valid"), Some(&Tag::Byte(1))); + let Some(Tag::List(records)) = section.get("Records") else { + panic!("no records"); + }; + let records: Vec<_> = records + .iter() + .map(|r| { + ( + text(r.get("type")).unwrap(), + r.get("pos").cloned(), + number(r.get("free_tickets")), + ) + }) + .collect(); + assert_eq!( + records, + [ + ( + "minecraft:home".into(), + Some(Tag::IntArray(vec![33, 70, -15])), + Some(1) + ), + ( + "minecraft:meeting".into(), + Some(Tag::IntArray(vec![37, 71, -11])), + Some(32) + ), + ] + ); + } + + #[test] + fn a_chunk_that_loses_its_last_poi_saves_empty_sections() { + let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES") else { + return; + }; + let root = PathBuf::from(root); + let assets = crate::assets::Assets::load(&root).expect("assets"); + let biomes = Arc::new(Biomes::load(&root).expect("biomes")); + let bell = assets.registry.default_state("minecraft:bell").unwrap().0; + let dir = std::env::temp_dir().join(format!("horizon-poi-save-{}", std::process::id())); + fs::create_dir_all(&dir).unwrap(); + let save = SaveDir::new(dir.clone()); + let _ = save.tables.set(Arc::new(SaveTables::new(&assets))); + let mut chunk = Chunk::empty(0, 0); + chunk.set(5, 71, 5, bell); + let sections = |save: &SaveDir| match save.read_record("poi", 0, 0)?.tag.get("Sections") { + Some(Tag::Compound(s)) => Some(s.len()), + _ => None, + }; + save.save_later(&[Arc::new(chunk.clone())], assets.registry, &biomes) + .unwrap(); + save.flush().unwrap(); + assert_eq!(sections(&save), Some(1)); + chunk.set(5, 71, 5, 0); + save.save_later(&[Arc::new(chunk)], assets.registry, &biomes) + .unwrap(); + save.flush().unwrap(); + assert_eq!(sections(&SaveDir::new(dir.clone())), Some(0)); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn saved_poi_records_keep_their_claims() { + let record = |pos: [i32; 3], kind: &str, tickets: Option| { + let mut r = vec![("pos", Tag::IntArray(pos.to_vec())), ("type", string(kind))]; + if let Some(t) = tickets { + r.push(("free_tickets", Tag::Int(t))); + } + Tag::compound(r) + }; + let poi = |records: Vec| { + let mut sections = Compound::new(); + sections.insert( + "4".into(), + Tag::compound([("Valid", Tag::Byte(1)), ("Records", Tag::List(records))]), + ); + poi_root(sections) + }; + let old = poi(vec![ + record([1, 70, 1], "minecraft:home", None), + record([5, 71, 5], "minecraft:meeting", Some(30)), + ]); + let mut saved = poi(vec![ + record([1, 70, 1], "minecraft:home", Some(1)), + record([5, 71, 5], "minecraft:meeting", Some(32)), + record([9, 71, 9], "minecraft:home", Some(1)), + ]); + keep_claims(&mut saved, &old); + let expected = poi(vec![ + record([1, 70, 1], "minecraft:home", None), + record([5, 71, 5], "minecraft:meeting", Some(30)), + record([9, 71, 9], "minecraft:home", Some(1)), + ]); + assert_eq!(saved.tag, expected.tag); + } + #[test] fn saved_far_surface_reads_builds_and_water_without_gameplay_chunks() { let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES") else { From fb9b26a06cf72d8d9f61fb260d9db76937623713 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 08:35:02 +0100 Subject: [PATCH 08/51] Work out the creative grid's stacks once per tab or search, not every frame With the creative inventory open, every frame cloned all the tabs with their stacks (twice), and items() cloned the selected tab's stacks again on each of its three or four calls a frame; on the search tab each call ran the whole search again, building every stack's localised name. That took the frame rate from about 1,900 to 980 with the inventory open and 340 while searching (#1953). Vanilla fills ItemPickerMenu.items when the tab or the search changes (selectTab, refreshSearchResults): the grid's stacks are now kept until the tab, the search text or the language changes, and the screen draws the tabs without copying their stacks. --- crates/horizon-client/src/creative.rs | 75 +++++++++++++++++++++++---- crates/horizon-client/src/game.rs | 5 +- 2 files changed, 68 insertions(+), 12 deletions(-) diff --git a/crates/horizon-client/src/creative.rs b/crates/horizon-client/src/creative.rs index 249e40b11..95d32ac90 100644 --- a/crates/horizon-client/src/creative.rs +++ b/crates/horizon-client/src/creative.rs @@ -3,7 +3,12 @@ //! (`creative-inventory.json`), a 9x5 scrolling grid and the search tab. use crate::{Result, items::ItemStack}; use serde_json::Value; -use std::{collections::HashMap, fs, path::Path}; +use std::{ + collections::HashMap, + fs, + path::Path, + sync::{Arc, Mutex}, +}; #[derive(Clone, Debug)] pub struct Tab { @@ -42,6 +47,17 @@ pub struct Creative { /// The search tab's stacks, in its display order. search_items: Vec, search_index: Vec, + /// ItemPickerMenu.items: what the grid shows, filled when the tab or the + /// search changes (selectTab, refreshSearchResults), not on every frame. + shown: Mutex>, +} +/// The grid's stacks for one tab, search text and language. +struct Shown { + tab: usize, + search: String, + /// A display name, so a language change refills the search results. + language: String, + items: Arc<[ItemStack]>, } /// Display names from the pinned en_us language file. #[derive(Default)] @@ -288,6 +304,7 @@ impl Creative { search_focused: std::time::Instant::now(), search_items, search_index, + shown: Mutex::new(None), } } /// Where a stack comes in the creative tabs (the search tab lists them @@ -300,6 +317,22 @@ impl Creative { .position(|s| s.same_item_same_components(stack)) .or_else(|| items.iter().position(|s| s.item == stack.item)) } + /// The tabs without their stacks: what the screen draws of them each frame. + pub fn tab_headers(&self) -> Vec { + self.tabs + .iter() + .map(|t| Tab { + id: t.id.clone(), + title: t.title.clone(), + icon: t.icon.clone(), + items: Vec::new(), + top: t.top, + column: t.column, + search: t.search, + inventory: t.inventory, + }) + .collect() + } pub fn tab(&self) -> &Tab { &self.tabs[self.selected.min(self.tabs.len() - 1)] } @@ -380,17 +413,39 @@ impl Creative { }) .collect() } - /// Items shown by the selected tab (the search tab filters by `search`). - pub fn items(&self, names: &Names) -> Vec { - let tab = self.tab(); - if tab.search { - return self - .search_results(&self.search, names) + /// Items shown by the selected tab (the search tab filters by `search`), + /// worked out again only when the tab, the search or the language changed. + pub fn items(&self, names: &Names) -> Arc<[ItemStack]> { + let tab = self.selected.min(self.tabs.len() - 1); + let search = if self.tab().search { + self.search.as_str() + } else { + "" + }; + let language = names.display_get("itemGroup.search").unwrap_or_default(); + let mut shown = self.shown.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(s) = shown.as_ref() + && s.tab == tab + && s.search == search + && s.language == language + { + return s.items.clone(); + } + let items: Arc<[ItemStack]> = if self.tab().search { + self.search_results(search, names) .into_iter() .map(|i| self.search_items[i].clone()) - .collect(); - } - tab.items.clone() + .collect() + } else { + self.tab().items.as_slice().into() + }; + *shown = Some(Shown { + tab, + search: search.to_owned(), + language, + items: items.clone(), + }); + items } pub fn rows(&self, names: &Names) -> usize { self.items(names).len().div_ceil(9) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 8591c721f..4defa03ef 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9721,8 +9721,9 @@ impl Game<'_> { fn draw_creative(&mut self, batch: &mut HudBatch) { let (ox, oy) = Self::creative_origin(batch); let selected = self.creative_screen.selected; - let tabs = self.creative_screen.tabs.clone(); - let tab = self.creative_screen.tab().clone(); + // Only what is drawn of the tabs: their stacks stay where they are. + let tabs = self.creative_screen.tab_headers(); + let tab = tabs[selected.min(tabs.len() - 1)].clone(); let tab_sprite = |t: &horizon_client::creative::Tab, on: bool| { format!( "gui/sprites/container/creative_inventory/tab_{}_{}_{}", From 515c0bdb7d4361d702eb583b6c8f627991705834 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 09:36:10 +0100 Subject: [PATCH 09/51] Work out the level item models read once a frame draw_item_model built the client level state (dimension, game time, sun angle, moon phase, respawn) for every stack it drew, sampling the sky each time: about seventy times a frame with the creative inventory open, a fifth of the time spent on its items. Within a frame the level is the same for all of them, so it is kept for the frame (keyed by the frame, game time, day time and dimension). --- crates/horizon-client/src/game.rs | 8 ++++++++ crates/horizon-client/src/game/item_draw.rs | 20 +++++++++++++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 4defa03ef..c8de9e7e1 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1266,6 +1266,13 @@ struct Game<'a> { /// Controllers (Horizon's own). pad: pad::Pads, frames: u64, + /// `item_level` for one frame, game time, day time and dimension. + item_level_cache: std::cell::RefCell< + Option<( + (u64, i64, i64, &'static str), + horizon_assets::item_model::LevelState, + )>, + >, /// Frames drawn with the player in the world, for `--world-frames`. world_frames: u64, fps: f32, @@ -12157,6 +12164,7 @@ impl<'a> Game<'a> { last_input: now, pad: Default::default(), frames: 0, + item_level_cache: Default::default(), world_frames: 0, fps: 0.0, fps_frames: 0, diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index 1d79f077d..b6b7e2fb7 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -196,13 +196,31 @@ impl Game<'_> { skins: &self.skin_downloads, } } - /// The client level as item models read it. + /// The client level as item models read it: worked out once a frame (a + /// screen of items read the same level, its sky sampled once). pub(super) fn item_level(&self) -> LevelState { let dimension = match self.dim { Dim::Overworld => "minecraft:overworld", Dim::Nether => "minecraft:the_nether", Dim::End => "minecraft:the_end", }; + let key = ( + self.frames, + self.world.game_time, + self.world.day_time, + dimension, + ); + let mut cached = self.item_level_cache.borrow_mut(); + if let Some((at, level)) = cached.as_ref() + && *at == key + { + return level.clone(); + } + let level = self.level_state_now(dimension); + *cached = Some((key, level.clone())); + level + } + fn level_state_now(&self, dimension: &'static str) -> LevelState { let sky = self .dim_environment() .sample(self.world.day_time, None, None); From 0f6569070d13ba42d43db11711d62c572bf2b50d Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 10:00:56 +0100 Subject: [PATCH 10/51] Draw a GUI item's vertices once while it stays in place Two costs a frame were repeated for every item a screen draws. ItemModels::components cloned the item's whole default component map (a JSON map of every default component) on every resolve, though most stacks carry no patch; it now borrows the defaults and copies only to apply a patch. And gui::draw submitted, culled, sorted and clipped every quad of a static item again each frame (hundreds of edge quads for a generated item, all facing sideways in the GUI), though the result for the same layers at the same position is the same; the HUD vertices of a static item are now kept per GUI position, keyed by its baked models, tints, transforms, the atlas and the exact position, and appended as they were. Items with a glint or a special model renderer are drawn as before. With the creative inventory open the HUD's share of a frame went from 0.66 ms to 0.23 ms. --- crates/horizon-assets/src/item_model.rs | 17 ++-- crates/horizon-client/src/item_render.rs | 4 + crates/horizon-client/src/item_render/gui.rs | 91 +++++++++++++++++++- 3 files changed, 104 insertions(+), 8 deletions(-) diff --git a/crates/horizon-assets/src/item_model.rs b/crates/horizon-assets/src/item_model.rs index 5999805eb..d567bc6ac 100644 --- a/crates/horizon-assets/src/item_model.rs +++ b/crates/horizon-assets/src/item_model.rs @@ -1031,19 +1031,22 @@ pub struct ItemModels { } impl ItemModels { - pub fn components(&self, stack: &StackView) -> Components { - let mut out = self - .prototypes - .get(&stack.item) - .cloned() - .unwrap_or_default(); + /// The stack's components: its item's defaults with the stack's patch on top. A stack + /// with no patch (most stacks a screen draws) borrows the defaults instead of copying them. + pub fn components(&self, stack: &StackView) -> std::borrow::Cow<'_, Components> { + static NONE: Components = BTreeMap::new(); + let prototype = self.prototypes.get(&stack.item).unwrap_or(&NONE); + if stack.patch.is_empty() { + return std::borrow::Cow::Borrowed(prototype); + } + let mut out = prototype.clone(); for (key, value) in &stack.patch { match value { Some(v) => out.insert(key.clone(), v.clone()), None => out.remove(key), }; } - out + std::borrow::Cow::Owned(out) } /// `ItemModelResolver.updateForTopItem`. pub fn resolve(&self, stack: &StackView, ctx: &Context, env: &dyn ItemEnv) -> ResolvedItem { diff --git a/crates/horizon-client/src/item_render.rs b/crates/horizon-client/src/item_render.rs index c2f5c8400..4f981b874 100644 --- a/crates/horizon-client/src/item_render.rs +++ b/crates/horizon-client/src/item_render.rs @@ -363,6 +363,9 @@ pub struct ItemRenderer { sprites: FileSprites, baked: Mutex>>, extents: Mutex>>>, + /// GUI items already drawn: the HUD vertices of a static item at a GUI position + /// (`gui::draw`), which are the same every frame it stays there. + pub(crate) gui_drawn: Mutex>>, /// Entity model layers of the special renderers. parts: HashMap, /// `colormap/grass.png` as ARGB. @@ -452,6 +455,7 @@ impl ItemRenderer { }, baked: Mutex::default(), extents: Mutex::default(), + gui_drawn: Mutex::default(), parts, grass, }) diff --git a/crates/horizon-client/src/item_render/gui.rs b/crates/horizon-client/src/item_render/gui.rs index e3d7cc876..ff25fff1d 100644 --- a/crates/horizon-client/src/item_render/gui.rs +++ b/crates/horizon-client/src/item_render/gui.rs @@ -8,7 +8,7 @@ use super::{Foil, ItemQuad, ItemRenderState, ItemRenderer, SpecialHost}; use crate::hud::{HudBatch, Rect}; use glam::{EulerRot, Mat4, Vec2, Vec3}; -use std::{collections::HashMap, f32::consts::PI}; +use std::{collections::HashMap, f32::consts::PI, sync::Arc}; mod depth; @@ -148,6 +148,95 @@ pub fn draw( if state.is_empty() { return; } + // A static item drawn where it was drawn before gives the same vertices: + // take them instead of submitting, sorting and clipping its quads again. + let key = DrawnKey::of(state, renderer, sprites, x, y); + if let Some(key) = &key + && let Some(drawn) = renderer + .gui_drawn + .lock() + .ok() + .and_then(|d| d.get(key).cloned()) + { + batch.vertices.extend_from_slice(&drawn); + return; + } + let start = batch.vertices.len(); + draw_now(state, renderer, sprites, host, batch, x, y, time); + if let Some(key) = key + && let Ok(mut drawn) = renderer.gui_drawn.lock() + { + // GUI positions and items are few; a long scroll through every tab stays bounded. + if drawn.len() >= DRAWN_LIMIT { + drawn.clear(); + } + drawn.insert(key, batch.vertices[start..].into()); + } +} + +/// Entries of `ItemRenderer::gui_drawn` before it starts over. +const DRAWN_LIMIT: usize = 8192; + +/// What a GUI item's vertices depend on: its layers' baked models (kept for the +/// renderer's life, so their addresses name them), tints and transforms, the +/// atlas, and the exact position. None for items whose drawing changes with time +/// or the host: a glint, or a special model renderer. +#[derive(Clone, PartialEq, Eq, Hash)] +pub(crate) struct DrawnKey { + renderer: usize, + sprites: (usize, usize), + at: [u32; 2], + oversized: bool, + layers: Vec<(usize, Vec, [u32; 16], bool)>, +} +impl DrawnKey { + fn of( + state: &ItemRenderState, + renderer: &ItemRenderer, + sprites: &HashMap, + x: f32, + y: f32, + ) -> Option { + if state.animated { + return None; + } + let layers = state + .layers + .iter() + .map(|layer| match &layer.geometry { + super::LayerGeometry::Quads(baked) if layer.foil == super::FoilType::None => { + Some(( + Arc::as_ptr(baked) as usize, + layer.tints.clone(), + layer.matrix.to_cols_array().map(f32::to_bits), + layer.uses_block_light, + )) + } + _ => None, + }) + .collect::>>()?; + Some(Self { + renderer: std::ptr::from_ref(renderer) as usize, + sprites: (std::ptr::from_ref(sprites) as usize, sprites.len()), + at: [x.to_bits(), y.to_bits()], + oversized: state.oversized_in_gui, + layers, + }) + } +} + +/// [`draw`] without the cache. +#[allow(clippy::too_many_arguments)] +fn draw_now( + state: &ItemRenderState, + renderer: &ItemRenderer, + sprites: &HashMap, + host: &dyn SpecialHost, + batch: &mut HudBatch, + x: f32, + y: f32, + time: f32, +) { let pose = Mat4::from_translation(Vec3::new(x + 8.0, y + 8.0, 0.0)) * Mat4::from_scale(Vec3::new(16.0, -16.0, 16.0)); let mut quads: Vec = Vec::new(); From 5389f72b9a7479d791f66977a25b6bfd1bc5d9cb Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 11:24:41 +0100 Subject: [PATCH 11/51] Creative: work out the shown items again after a resource or language reload A resource pack can rename items without changing the Search label the cache was keyed on, so a search kept its old results until the query or tab changed. --- crates/horizon-client/src/creative.rs | 5 +++++ crates/horizon-client/src/game/options.rs | 1 + crates/horizon-client/src/game/packs.rs | 2 ++ 3 files changed, 8 insertions(+) diff --git a/crates/horizon-client/src/creative.rs b/crates/horizon-client/src/creative.rs index 95d32ac90..bcc16a3dd 100644 --- a/crates/horizon-client/src/creative.rs +++ b/crates/horizon-client/src/creative.rs @@ -447,6 +447,11 @@ impl Creative { }); items } + /// Drop the shown items, so the next `items` works them out again: a + /// reload can rename items without changing the Search label. + pub fn forget_items(&self) { + *self.shown.lock().unwrap_or_else(|e| e.into_inner()) = None; + } pub fn rows(&self, names: &Names) -> usize { self.items(names).len().div_ceil(9) } diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index 243eced5c..81510004d 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -257,6 +257,7 @@ impl Game<'_> { lang::set(lang::Language::load(&[&root], code)); self.refresh_remote_language(); self.ui.chat.rescale(&self.gui.atlas); + self.creative_screen.forget_items(); } /// Settings that Horizon applies beyond render distance, volume and GUI scale. pub(super) fn apply_ui_settings(&mut self) { diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index ee57e9f2b..0d9658e06 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -221,6 +221,8 @@ impl Game<'_> { self.apply_ui_settings(); } self.ui.chat.rescale(&self.gui.atlas); + // The creative screen survives the reload; item names may not. + self.creative_screen.forget_items(); Ok(()) } } From 0a2de159fd6f84dde1405d59a35fc3d1e6f9349e Mon Sep 17 00:00:00 2001 From: socksprox Date: Mon, 26 Oct 2026 11:39:08 +0100 Subject: [PATCH 12/51] Fire: ambient smoke particles and no mob-break crumbs BaseFireBlock.animateTick adds large smoke above a fire (three puffs in its top half), or two puffs at each burnable neighbour's face when the fire sits on nothing burnable or sturdy. SoulFireBlock.canBurn is always true, so soul fire always takes the top-half branch. The burnable table mirrors FireBlock.canBurn (fire.igniteOdds above zero) from block-behaviours.json. Mobs breaking blocks (MobEvent::BreakBlock) map to Level.destroyBlock, whose Block.spawnDestroyParticles BaseFireBlock overrides to nothing: a wither or another mob destroying fire no longer emits break particles. Player breaks already route through player_destroy (1009); the client-side predict_break particles are PR #2082's. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/horizon-client/src/animate_tick.rs | 76 ++++++++++++++++++++- crates/horizon-client/src/game/creatures.rs | 5 +- 2 files changed, 77 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index 48e8f16f4..945de2300 100644 --- a/crates/horizon-client/src/animate_tick.rs +++ b/crates/horizon-client/src/animate_tick.rs @@ -58,7 +58,10 @@ enum Animate { BubbleColumn { drag: bool, }, - Fire, + /// `BaseFireBlock` (`SoulFireBlock.canBurn` is always true). + Fire { + soul: bool, + }, /// An active sculk sensor. SculkSensor, /// Potent sulfur that is not dry. @@ -140,7 +143,8 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { "bubble_column" => Animate::BubbleColumn { drag: prop("drag").as_deref() == Some("true"), }, - "fire" | "soul_fire" => Animate::Fire, + "fire" => Animate::Fire { soul: false }, + "soul_fire" => Animate::Fire { soul: true }, "dried_ghast" => Animate::DriedGhast { waterlogged: prop("waterlogged").as_deref() == Some("true"), }, @@ -190,6 +194,8 @@ pub struct AnimateTables { power_transmitter: Vec, /// `#triggers_ambient_dried_ghast_block_sounds` (soul sand, soul soil). dried_ghast_sounds: Vec, + /// `FireBlock.canBurn`: states of blocks with ignite odds above zero. + burnable: Vec, /// Biome id -> ambient particles and probabilities (`minecraft:visual/ambient_particles`). ambient: Vec>, } @@ -220,6 +226,20 @@ impl AnimateTables { }) .collect() }; + let behaviour: serde_json::Value = + serde_json::from_slice(&std::fs::read(root.join("block-behaviours.json"))?)?; + let ignite_odds = behaviour["fire"]["igniteOdds"].as_object(); + let burnable = (0..registry.len() as u32) + .map(|id| { + registry.state(BlockStateId(id)).is_some_and(|s| { + ignite_odds + .and_then(|m| m.get(s.name.as_str())) + .and_then(serde_json::Value::as_i64) + .unwrap_or(0) + > 0 + }) + }) + .collect(); let mut ambient = vec![Vec::new(); biomes.list.len()]; for (name, &id) in &biomes.index { let path = root.join(format!( @@ -248,6 +268,7 @@ impl AnimateTables { power_provider: by_state("minecraft:enchantment_power_provider"), power_transmitter: by_state("minecraft:enchantment_power_transmitter"), dried_ghast_sounds: by_state("minecraft:triggers_ambient_dried_ghast_block_sounds"), + burnable, ambient, }) } @@ -1103,7 +1124,7 @@ fn block_animate_tick( } } } - Animate::Fire => { + Animate::Fire { soul } => { let r = engine.random(); if next_int(r, 24) == 0 { let (volume, pitch) = (1.0 + r.next_float(), r.next_float() * 0.7 + 0.3); @@ -1115,6 +1136,55 @@ fn block_animate_tick( pitch, ); } + // BaseFireBlock.animateTick: three large smoke above the fire, or + // two at each burnable neighbour's face when nothing burnable or + // sturdy supports it (SoulFireBlock.canBurn is always true). + let can_burn = |p: [i32; 3]| { + soul || tables + .burnable + .get(ctx.state(p).0 as usize) + .copied() + .unwrap_or(false) + }; + let below = [pos[0], pos[1] - 1, pos[2]]; + let sturdy = ctx.facts.get(ctx.state(below)).sturdy_full & (1 << 1) != 0; + if !can_burn(below) && !sturdy { + // (neighbour, coordinate axis, face at the axis' high end): the + // west, east, north, south and above faces, in vanilla order. + for (at, axis, high) in [ + ([pos[0] - 1, pos[1], pos[2]], 0usize, false), + ([pos[0] + 1, pos[1], pos[2]], 0, true), + ([pos[0], pos[1], pos[2] - 1], 2, false), + ([pos[0], pos[1], pos[2] + 1], 2, true), + ([pos[0], pos[1] + 1, pos[2]], 1, true), + ] { + if !can_burn(at) { + continue; + } + for _ in 0..2 { + let r = engine.random(); + let d = [r.next_double(), r.next_double(), r.next_double()]; + let mut p = [fx + d[0], fy + d[1], fz + d[2]]; + // The face coordinate hugs the edge: `* 0.1F` (float). + p[axis] = if high { + f64::from(pos[axis]) + 1.0 - d[axis] * f64::from(0.1f32) + } else { + f64::from(pos[axis]) + d[axis] * f64::from(0.1f32) + }; + add(engine, T::LargeSmoke, p, [0.0; 3]); + } + } + } else { + for _ in 0..3 { + let r = engine.random(); + let p = [ + fx + r.next_double(), + fy + r.next_double() * 0.5 + 0.5, + fz + r.next_double(), + ]; + add(engine, T::LargeSmoke, p, [0.0; 3]); + } + } } } } diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index be7923037..6897e9713 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1035,7 +1035,10 @@ impl Game<'_> { } MobEvent::BreakBlock { pos, drop } => { let old = self.world.block(pos[0], pos[1], pos[2]); - self.destroy_particles(pos, old); + // Block.spawnDestroyParticles: fire breaks leave nothing. + if !self.res.facts().get(old).has_class("BaseFireBlock") { + self.destroy_particles(pos, old); + } if drop { let drops = self.res.items().block_drops_in( self.pack.assets.registry, From 1e6884c591e704a9190e896dbf02d291058a3e2f Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 11:43:37 +0100 Subject: [PATCH 13/51] Show the poem and credits on a player's first End exit in server-thread mode --- crates/horizon-client/src/game/lan_actions.rs | 11 ++++++++ .../horizon-client/src/game/server_travel.rs | 28 +++++++++++++++++++ crates/horizon-client/src/lan/guest.rs | 3 ++ crates/horizon-client/src/lan/playerdata.rs | 2 ++ 4 files changed, 44 insertions(+) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index e19b0f3fc..0919447a1 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -77,6 +77,10 @@ pub(super) struct GuestPlay { last_inventory: u64, /// `Entity.portalProcess` and `portalCooldown` (game/server_travel.rs). pub(super) portal: horizon_client::nether_portal::PortalState, + /// `ServerPlayer.wonGame`: the End poem is showing, the player waits for + /// its client's PERFORM_RESPAWN (`respawn_requested`). + pub(super) won_game: bool, + pub(super) respawn_requested: bool, /// `Player.takeXpDelay`: ticks until the next orb can be taken. xp_delay: u32, /// What last killed the guest outright (`/kill`): the death message's key. @@ -1308,6 +1312,13 @@ impl Game<'_> { self.guest_suggestions(host, conn, &payload); } S::PlaceRecipe(p) => self.lan_place_recipe(host, conn, &p), + // handleClientCommand: PERFORM_RESPAWN after the poem leaves the End + // (the next server tick sends the player on). + S::ClientCommand(c) + if c.action == 0 && host.play.get(&conn).is_some_and(|p| p.won_game) => + { + host.play.entry(conn).or_default().respawn_requested = true; + } S::ClientCommand(c) if c.action == 0 => self.guest_respawn(host, conn), // ServerStatsCounter.sendStats. S::ClientCommand(c) if c.action == 1 => { diff --git a/crates/horizon-client/src/game/server_travel.rs b/crates/horizon-client/src/game/server_travel.rs index 158b2301e..bcaf37a76 100644 --- a/crates/horizon-client/src/game/server_travel.rs +++ b/crates/horizon-client/src/game/server_travel.rs @@ -13,6 +13,7 @@ use super::respawn_anchor::RespawnConfig; use super::{Dim, Game, lan::LanHost}; use horizon_client::{lan::hub::TickCtx, text::Text}; use horizon_core::{geometry::Vec3, position::BlockPos}; +use horizon_protocol::packets::play::{self, Clientbound as C}; /// A trip under way: the player is in the destination's level, whose /// chunks are loading around `target`. @@ -103,8 +104,35 @@ impl Game<'_> { if let Some(pos) = self.nether_portal_inside(at) { self.portals.player.set_inside(pos, PLAYER_DELAY); } + // `ServerPlayer.showEndCredits`: the player stays out of the world while the + // poem rolls, then PERFORM_RESPAWN takes it to its respawn point. + let play = host.play.entry(conn).or_default(); + if play.won_game { + if std::mem::take(&mut play.respawn_requested) { + play.won_game = false; + self.start_server_trip(host, conn, Dim::Overworld, None); + self.portals.player.cooldown = 10; + } + return; + } let (end_portal, gateway) = self.inside_end_portals(at, WIDTH, HEIGHT); if end_portal { + // EndPortalBlock.entityInside: the first exit from the End shows the credits. + if self.dim == Dim::End && !host.hub.guest(conn).is_some_and(|g| g.seen_credits) { + if let Some(g) = host.hub.guests.iter_mut().find(|g| g.conn == conn) { + g.seen_credits = true; + } + host.play.entry(conn).or_default().won_game = true; + // ClientboundGameEventPacket.WIN_GAME. + host.hub.send_to( + conn, + &C::GameEvent(play::GameEvent { + event: 4, + param: 0.0, + }), + ); + return; + } if self.portals.player.cooldown == 0 { let target = if self.dim == Dim::End { Dim::Overworld diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index aa1994257..6dffa3e9f 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -237,6 +237,8 @@ pub struct Guest { pub drag: Option<(u8, Vec)>, /// The compound this player was loaded from, for fields Horizon does not model. pub saved: Option, + /// `ServerPlayer.seenCredits`: the end poem has been shown. + pub seen_credits: bool, /// `ServerPlayer.recipeBook`. pub recipe_book: crate::recipe_book::Settings, /// `PlayerAdvancements`: the criteria obtained, whether they came from @@ -358,6 +360,7 @@ impl Guest { next_window: 0, drag: None, saved: None, + seen_credits: false, recipe_book: Default::default(), advancements: Default::default(), advancements_loaded: false, diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index 90fe0bcfe..f5eb935c9 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -85,6 +85,7 @@ pub fn apply(guest: &mut Guest, level: &Level) { .map(|s| [s[0] + 0.5, s[1], s[2] + 0.5]); guest.respawn_elsewhere = level.respawn_elsewhere.clone(); guest.saved = level.player_extra.clone(); + guest.seen_credits = level.seen_credits; let extra = level.player_extra.as_ref(); let short = |key: &str, default: i64| { extra @@ -166,6 +167,7 @@ pub fn store(guest: &Guest, level: &mut Level) { level.spawn = guest.spawn.map(|s| [s[0] - 0.5, s[1], s[2] - 0.5]); level.respawn_elsewhere = guest.respawn_elsewhere.clone(); level.on_ground = guest.on_ground; + level.seen_credits = guest.seen_credits; level.player_extra = guest.saved.clone(); // The live body's fire, air and fall distance (Entity.saveWithoutId), // or what the file had while the player has no body yet. From 49b167ce22c9c40bde3a122a84ff84f1b7cd4bb8 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 11:45:56 +0100 Subject: [PATCH 14/51] Item frames: shade the frame model by face and light glow frames from 5 --- crates/horizon-client/src/game/frames.rs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/frames.rs b/crates/horizon-client/src/game/frames.rs index 7f5e6c26a..d08c5f283 100644 --- a/crates/horizon-client/src/game/frames.rs +++ b/crates/horizon-client/src/game/frames.rs @@ -355,12 +355,23 @@ impl Game<'_> { * glam::DMat4::from_rotation_y(y_rot.to_radians()); let light = self.world.light(f.pos[0], f.pos[1], f.pos[2]); let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); + // ItemFrameRenderer.getBlockLightLevel: a glow frame's model is at least 5 bright. + let frame_light = if f.glow { + (light & 0xF0) | (light & 15).max(5) + } else { + light + }; + let frame_packed = + (u32::from(frame_light >> 4) * 16) | ((u32::from(frame_light & 15) * 16) << 8); let mut quad = |m: &glam::DMat4, corners: [[f64; 3]; 4], uv: [[f32; 2]; 4], light: u32| { - for (c, uv) in corners.iter().zip(uv) { - let p = m.transform_point3(glam::DVec3::from_array(*c)); + // The frame model is drawn with the entity shader, lit by its face normal. + let at = corners.map(|c| m.transform_point3(glam::DVec3::from_array(c))); + let n = (at[1] - at[0]).cross(at[2] - at[0]).normalize_or_zero(); + let normal = [0, 1, 2].map(|k| (n[k].clamp(-1.0, 1.0) * 127.0) as i8); + for (p, uv) in at.into_iter().zip(uv) { out.push(Vertex { - normal: [0; 4], + normal: [normal[0], normal[1], normal[2], -127], pos: p.as_vec3().to_array(), uv, layer: 0, @@ -393,7 +404,7 @@ impl Game<'_> { ] }), map_uv(r, *uv), - packed, + frame_packed, ); } } From 990786901ad732f66460618fcd8eec4d448ee5f8 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 11:46:16 +0100 Subject: [PATCH 15/51] Let empty boats and minecarts enter Nether portals --- crates/horizon-client/src/game/boats.rs | 2 +- crates/horizon-client/src/game/minecarts.rs | 4 +- .../horizon-client/src/game/nether_portal.rs | 79 ++++++++++++++++++- 3 files changed, 79 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index df7158d9a..575c68553 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -55,7 +55,7 @@ pub(super) struct Boat { /// `ChestBoat.CONTAINER_SIZE`. pub(super) const CHEST_SLOTS: usize = 27; pub(super) const WIDTH: f64 = 1.375; -const HEIGHT: f64 = 0.5625; +pub(super) const HEIGHT: f64 = 0.5625; impl Boat { pub fn new(id: u32, wood: Arc, position: Vec3, yaw: f32) -> Self { Self { diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index a19b6df73..369c3f358 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -88,8 +88,8 @@ pub(super) struct Minecart { /// Hopper minecarts: an unpowered activator rail enables them. pub enabled: bool, } -const WIDTH: f64 = 0.98; -const HEIGHT: f64 = 0.7; +pub(super) const WIDTH: f64 = 0.98; +pub(super) const HEIGHT: f64 = 0.7; /// AbstractMinecart.getDefaultDisplayOffset, in sixteenths of a block. fn display_offset(kind: CartKind) -> f64 { if kind == CartKind::Hopper { 1.0 } else { 6.0 } diff --git a/crates/horizon-client/src/game/nether_portal.rs b/crates/horizon-client/src/game/nether_portal.rs index 353ad216c..87ba81c93 100644 --- a/crates/horizon-client/src/game/nether_portal.rs +++ b/crates/horizon-client/src/game/nether_portal.rs @@ -454,11 +454,24 @@ impl Game<'_> { for m in &self.mobs { self.portals.before.insert(m.id, m.position); } + for b in &self.boats { + self.portals.before.insert(b.id, b.position); + } + for c in &self.carts { + self.portals.before.insert(c.id, c.position); + } let ids: Vec<(u32, bool)> = self .dropped .iter() .map(|e| (e.id, true)) .chain(self.mobs.iter().map(|m| (m.id, self.mob_can_use_portal(m)))) + .chain( + self.boats + .iter() + .map(|b| b.id) + .chain(self.carts.iter().map(|c| c.id)) + .map(|id| (id, !self.vehicle_occupied(id))), + ) .collect(); let present: std::collections::HashSet = ids.iter().map(|(id, _)| *id).collect(); self.portals.entities.retain(|id, _| present.contains(id)); @@ -501,8 +514,15 @@ impl Game<'_> { && self.riding != Some(m.id) && m.species() != Species::Wither } - /// `NetherPortalBlock.entityInside` for the items and mobs that moved this - /// tick: the portal blocks their box swept through. + /// Whether the player, a server player or a mob rides vehicle `id`. + fn vehicle_occupied(&self, id: u32) -> bool { + self.riding == Some(id) + || self.ridden_by_guest(id) + || self.mobs.iter().any(|m| m.extra.mount == Some(id)) + } + /// `NetherPortalBlock.entityInside` for the items, mobs and empty boats + /// and minecarts that moved this tick: the portal blocks their box swept + /// through. pub(super) fn find_entity_portals(&mut self) { if self.remote.is_some() { return; @@ -519,8 +539,23 @@ impl Game<'_> { .filter(|m| self.mob_can_use_portal(m)) .map(|m| (m.id, m.position, m.width(), m.height())) .collect(); + let vehicles: Vec<(u32, Vec3, f32, f32)> = self + .boats + .iter() + .map(|b| (b.id, b.position, super::boats::WIDTH, super::boats::HEIGHT)) + .chain(self.carts.iter().map(|c| { + ( + c.id, + c.position, + super::minecarts::WIDTH, + super::minecarts::HEIGHT, + ) + })) + .filter(|(id, ..)| !self.vehicle_occupied(*id)) + .map(|(id, at, w, h)| (id, at, w as f32, h as f32)) + .collect(); let mut portal_sections = std::mem::take(&mut self.portals.sections); - for (id, to, width, height) in items.into_iter().chain(mobs) { + for (id, to, width, height) in items.into_iter().chain(mobs).chain(vehicles) { let from = self.portals.before.get(&id).copied().unwrap_or(to); if let Some(pos) = self.swept_portal(from, to, width, height, &mut portal_sections) { inside.push((id, pos)); @@ -678,6 +713,44 @@ impl Game<'_> { } self.portals.arrivals.push(Arrival { plan, tag }); self.portals.dirty = true; + } else if let Some(i) = self.boats.iter().position(|b| b.id == id) { + let b = &self.boats[i]; + let (width, height) = (super::boats::WIDTH as f32, super::boats::HEIGHT as f32); + let plan = self.portal_plan(entry, b.position, width, height, false); + if !self.may_enter(plan.dim) { + return; + } + let uuid = self.uuid_for(id); + let b = &self.boats[i]; + let tag = horizon_client::entity_nbt::boat_to_nbt( + &b.entity_type(), + b.position, + b.velocity, + b.yaw, + uuid, + self.persist_raw(id), + b.chest.then_some(&b.items[..]), + ); + self.boats.remove(i); + self.forget_entity(id); + self.portals.arrivals.push(Arrival { plan, tag }); + self.portals.dirty = true; + } else if let Some(i) = self.carts.iter().position(|c| c.id == id) { + let c = &self.carts[i]; + let (width, height) = ( + super::minecarts::WIDTH as f32, + super::minecarts::HEIGHT as f32, + ); + let plan = self.portal_plan(entry, c.position, width, height, false); + if !self.may_enter(plan.dim) { + return; + } + let uuid = self.uuid_for(id); + let tag = self.carts[i].to_nbt(uuid, self.persist_raw(id)); + self.carts.remove(i); + self.forget_entity(id); + self.portals.arrivals.push(Arrival { plan, tag }); + self.portals.dirty = true; } } /// Entities waiting for the loaded dimension whose exit area is loaded: From 858eeba1b850716e5779e1bea6c47d7908e713ad Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 11:59:33 +0100 Subject: [PATCH 16/51] Resource packs: hand the window surface to the reloaded renderer instead of creating a new one Applying packs dropped the window surface and created a new one for the renderer built on the same device. On Wayland with Mesa (RADV) the new surface came back lost (ERROR_SURFACE_LOST_KHR), the new renderer failed, and restoring the old one failed too, which crashed the game. --- crates/horizon-client/src/game/packs.rs | 2 +- crates/horizon-client/src/gfx.rs | 39 +++++++++++++++++++++---- 2 files changed, 34 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index ee57e9f2b..50cd4dd5a 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -163,7 +163,7 @@ impl Game<'_> { self.pack.context.biomes.clone(), self.pack.context.light.clone(), )?; - // Keep the working GPU resources, but release its exclusive window surface. + // Keep the working GPU resources, and hand its window surface over. if let Some(renderer) = &mut self.renderer { renderer.release_surface(); } diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 78f73bc8b..3e6428287 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -331,6 +331,10 @@ pub struct Renderer { adapter: wgpu::Adapter, /// The window's swapchain; `None` when rendering offscreen (`--offscreen`). surface: Option>, + /// The surface `release_surface` set aside for the renderer that replaces + /// this one on the same device: reused, not created again, as a new + /// surface for the window can come back lost (Wayland on Mesa). + spare_surface: std::sync::Mutex>>, /// The offscreen colour target, sized like `config`. offscreen: Option, /// Offscreen submissions still on the GPU: at most two frames run ahead. @@ -1026,7 +1030,15 @@ impl Renderer { surface: if offscreen { None } else { - Some(renderer.instance.create_surface(window.clone())?) + let spare = renderer + .spare_surface + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take(); + Some(match spare { + Some(surface) => surface, + None => renderer.instance.create_surface(window.clone())?, + }) }, instance: renderer.instance.clone(), adapter: renderer.adapter.clone(), @@ -2296,6 +2308,7 @@ impl Renderer { instance, adapter, surface, + spare_surface: std::sync::Mutex::new(None), offscreen, in_flight: std::collections::VecDeque::new(), first_frame: if previous.is_none() { @@ -2472,18 +2485,32 @@ impl Renderer { view_formats: &config.view_formats, }) } - /// Release the window surface before another renderer uses the same window. + /// Hand the window surface over to the renderer that replaces this one on + /// the same device (it takes `spare_surface`). pub fn release_surface(&mut self) { - self.surface = None; + *self + .spare_surface + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner) = self.surface.take(); } /// Reattach a window after surface loss or a failed renderer replacement. pub fn recreate_surface(&mut self) -> Result<()> { if self.offscreen.is_some() { return Ok(()); } - // Wayland allows only one tearing-control object per window surface. - self.release_surface(); - let surface = self.instance.create_surface(self.window.clone())?; + // The surface set aside for a replacement that failed, else a new one + // (Wayland allows only one tearing-control object per window surface, + // so the old one goes first). + let spare = self + .spare_surface + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take(); + self.surface = None; + let surface = match spare { + Some(surface) => surface, + None => self.instance.create_surface(self.window.clone())?, + }; surface.configure(&self.device, &self.config); self.surface = Some(surface); Ok(()) From 9ef7a6fa256a5e9ba56d823552a211ae5b8ec2ed Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 12:05:16 +0100 Subject: [PATCH 17/51] Server players see the dragon's breath clouds The breath clouds are kept as a list, not entities, so the server thread drew their particles into its own copy and players never saw them. Each cloud is now tracked as an area_effect_cloud (radius, waiting, particle), and a server's client draws it as AreaEffectCloud.clientTick does. --- crates/horizon-client/src/game/dragon.rs | 10 +- .../horizon-client/src/game/lan_entities.rs | 24 +++++ .../horizon-client/src/game/lan_particles.rs | 6 +- crates/horizon-client/src/game/potions.rs | 2 + .../src/game/remote_projectiles.rs | 101 +++++++++++++++++- 5 files changed, 138 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index 8c316deeb..468d6fbb1 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -1558,6 +1558,7 @@ impl Game<'_> { y -= 1.0; } self.breath_clouds.push(Breath { + id: 0, at: [x, y.floor() + 1.0, z], radius: 5.0, age: 0, @@ -2083,6 +2084,7 @@ impl Game<'_> { }); if hit_block || hit_player || b.age > 600 { self.breath_clouds.push(Breath { + id: 0, at: [next.x, next.y, next.z], radius: 3.0, age: 0, @@ -2208,9 +2210,11 @@ pub(super) struct DragonFireball { age: i32, } pub(super) struct Breath { - at: [f64; 3], - radius: f32, - age: i32, + /// Its entity id once a server's players track it (0 until then). + pub(super) id: u32, + pub(super) at: [f64; 3], + pub(super) radius: f32, + pub(super) age: i32, duration: i32, from_dragon: bool, } diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index cd4ba2fb8..2ef862200 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -279,6 +279,7 @@ impl Game<'_> { self.bolts.iter_mut().for_each(|b| give(&mut b.id)); self.potions.thrown_ids().for_each(&mut give); self.end.eye_ids().for_each(&mut give); + self.breath_clouds.iter_mut().for_each(|b| give(&mut b.id)); } /// Primed TNT, falling blocks, projectiles, tridents, firework rockets and @@ -435,6 +436,29 @@ impl Game<'_> { } out.push(e); } + // The dragon's breath clouds (AreaEffectCloud's DATA_RADIUS, + // DATA_WAITING for its 20-tick wait, and DATA_PARTICLE): the + // client draws them from these (`tick_remote_clouds`). + let breath = self.network_particle( + &horizon_client::particles::ParticleOptions::simple( + horizon_client::particles::ParticleType::DragonBreath, + ), + None, + ); + for b in self.breath_clouds.iter().filter(|b| b.id != 0) { + let mut e = state(b.id, "minecraft:area_effect_cloud", b.at, 0.0, false); + e.meta.push((8, serializer::FLOAT, Value::Float(b.radius))); + if b.age < 20 { + e.meta.push((9, serializer::BOOLEAN, Value::Bool(true))); + } + if let Some(p) = &breath { + e.meta + .push((10, serializer::PARTICLE, Value::Particle(p.clone()))); + } + e.defaults + .push((9, serializer::BOOLEAN, Value::Bool(false))); + out.push(e); + } out.extend(self.lan_dragon_state()); } } diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs index 0e35392bf..8162be3ec 100644 --- a/crates/horizon-client/src/game/lan_particles.rs +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -68,7 +68,11 @@ impl Game<'_> { /// The options a server's particle stands for (None for a type or data /// this client doesn't draw). - fn received_particle(&mut self, p: &Particle, at: [f64; 3]) -> Option { + pub(super) fn received_particle( + &mut self, + p: &Particle, + at: [f64; 3], + ) -> Option { let name = self .remote .as_ref()? diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index b28c2fb4d..74c4ccd0c 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -71,6 +71,8 @@ pub(super) struct BodyPotions { pub(super) struct PotionState { pub(super) effects: PlayerEffects, thrown: Vec, + /// The area effect clouds a server tracks (game/remote_projectiles.rs). + pub(super) clouds: Vec, applied: Vec<(&'static str, &'static str, f64, &'static str)>, /// Armor the protection table was computed for. protection_for: Option>>, diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index a117b1b7c..fa1a5b35c 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -3,11 +3,26 @@ //! and `handleSetEntityData`): the server simulates them, the client draws //! them where it says and interpolates their moves. use super::{FallStep, FallingBlock, Game, fireworks::fireworks_of, view_vector}; +use horizon_client::particles::{ParticleOptions, ParticleType}; use horizon_client::projectiles::{Projectile, ProjectileKind}; -use horizon_core::{geometry::Vec3, position::BlockPos}; +use horizon_core::{geometry::Vec3, position::BlockPos, random::RandomSource}; use horizon_protocol::entity_data::Value; use horizon_world::registry::BlockStateId; +/// An `AreaEffectCloud` a server tracks: what its client tick reads. +pub(super) struct RemoteCloud { + id: u32, + at: [f64; 3], + radius: f32, + waiting: bool, + particle: ParticleOptions, +} + +/// `AreaEffectCloud.DEFAULT_PARTICLE`: a white entity effect. +fn default_cloud_particle() -> ParticleOptions { + ParticleOptions::colored(ParticleType::EntityEffect, [1.0; 4]) +} + /// The projectile a type id names, as Horizon models it. fn projectile_kind(kind: &str) -> Option { Some(match kind { @@ -92,6 +107,13 @@ impl Game<'_> { | "minecraft:experience_bottle" => { self.potions.add_remote_thrown(id, kind, at, velocity); } + "minecraft:area_effect_cloud" => self.potions.clouds.push(RemoteCloud { + id, + at: position, + radius: 3.0, + waiting: false, + particle: default_cloud_particle(), + }), "minecraft:eye_of_ender" => { self.end .add_remote_eye(id, position, [velocity.x, velocity.y, velocity.z]) @@ -125,6 +147,31 @@ impl Game<'_> { pub(super) fn remote_projectile_data(&mut self, id: i32, values: &[(u8, i32, Value)]) { let id = id as u32; self.remote_hook_data(id, values); + if let Some(at) = self + .potions + .clouds + .iter() + .find(|c| c.id == id) + .map(|c| c.at) + { + // AreaEffectCloud.DATA_RADIUS, DATA_WAITING and DATA_PARTICLE. + for (index, _, value) in values { + let particle = match (index, value) { + (10, Value::Particle(p)) => self.received_particle(p, at), + _ => None, + }; + let Some(c) = self.potions.clouds.iter_mut().find(|c| c.id == id) else { + return; + }; + match (index, value) { + (8, Value::Float(r)) => c.radius = *r, + (9, Value::Bool(w)) => c.waiting = *w, + (10, _) => c.particle = particle.unwrap_or_else(default_cloud_particle), + _ => {} + } + } + return; + } if self.rockets.iter().any(|r| r.id == id) { for (index, _, value) in values { match (index, value) { @@ -308,6 +355,56 @@ impl Game<'_> { let at = step(id, Vec3::new(at[0], at[1], at[2])); [at.x, at.y, at.z] }); + self.tick_remote_clouds(); + } + + /// `AreaEffectCloud.clientTick`: while waiting, now and then two + /// particles near the middle; then about one per square block of the + /// disc, drifting (an entity effect stays still). + fn tick_remote_clouds(&mut self) { + for c in &self.potions.clouds { + let r = self.particles.random(); + if c.waiting && r.next_boolean() { + continue; + } + let (count, spread) = if c.waiting { + (2, 0.2) + } else { + ( + (std::f32::consts::PI * c.radius * c.radius).ceil() as i32, + c.radius, + ) + }; + for _ in 0..count { + let r = self.particles.random(); + let angle = r.next_float() * std::f32::consts::TAU; + let distance = r.next_float().sqrt() * spread; + let at = [ + c.at[0] + f64::from(angle.cos() * distance), + c.at[1], + c.at[2] + f64::from(angle.sin() * distance), + ]; + let (options, velocity) = if c.particle.ty == ParticleType::EntityEffect { + let default = c.waiting && r.next_boolean(); + let options = if default { + default_cloud_particle() + } else { + c.particle.clone() + }; + (options, [0.0; 3]) + } else if c.waiting { + (c.particle.clone(), [0.0; 3]) + } else { + let v = [ + (0.5 - r.next_double()) * 0.15, + f64::from(0.01f32), + (0.5 - r.next_double()) * 0.15, + ]; + (c.particle.clone(), v) + }; + self.particles.add(&options, at, velocity); + } + } } pub(super) fn remove_remote_projectile(&mut self, id: u32) { @@ -318,6 +415,7 @@ impl Game<'_> { self.rockets.retain(|r| r.id != id); self.crystals.retain(|c| c.id != id); self.potions.remove_remote_thrown(id); + self.potions.clouds.retain(|c| c.id != id); self.end.remove_remote_eye(id); self.remove_remote_hook(id); } @@ -331,6 +429,7 @@ impl Game<'_> { self.rockets.clear(); self.crystals.clear(); self.potions.clear_thrown(); + self.potions.clouds.clear(); self.end.clear_remote_eyes(); self.clear_remote_hooks(); } From f5ef003bada695889f9d788d6a97ede2fa404299 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 12:09:05 +0100 Subject: [PATCH 18/51] Server players see the dragon's fireballs in flight Dragon fireballs were a server-side list like the breath clouds, so a server's players never saw them. Each is now tracked as a minecraft:dragon_fireball; the client keeps it in the same list, flies it on as AbstractHurtingProjectile.tick does, snaps it to the server's moves and draws it with its dragon_breath trail. --- crates/horizon-client/src/game/dragon.rs | 41 +++++++++++++++++-- .../horizon-client/src/game/lan_entities.rs | 9 ++++ crates/horizon-client/src/game/remote.rs | 10 +++++ .../src/game/remote_projectiles.rs | 24 +++++++++++ 4 files changed, 81 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index 468d6fbb1..e1880f9aa 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -2038,6 +2038,7 @@ impl Game<'_> { // assignDirectionalMovement: the direction times the acceleration power 0.1. let velocity = Vec3::new(v.x * 0.1, v.y * 0.1, v.z * 0.1); self.dragon_fireballs.push(DragonFireball { + id: 0, position: at, previous: at, velocity, @@ -2204,11 +2205,45 @@ impl Game<'_> { } } pub(super) struct DragonFireball { - position: Vec3, - previous: Vec3, - velocity: Vec3, + /// Its entity id once a server's players track it (0 until then). + pub(super) id: u32, + pub(super) position: Vec3, + pub(super) previous: Vec3, + pub(super) velocity: Vec3, age: i32, } +impl DragonFireball { + /// One a server sent (`handleAddEntity`). + pub(super) fn remote(id: u32, at: Vec3, velocity: Vec3) -> Self { + Self { + id, + position: at, + previous: at, + velocity, + age: 0, + } + } + /// `AbstractHurtingProjectile.tick` on a server's client: accelerate + /// along the motion (power 0.1, inertia 0.95 or 0.8 in water) and move; + /// only the server decides what it hits. + pub(super) fn remote_step(&mut self, water: bool) { + self.previous = self.position; + self.age += 1; + let v = self.velocity; + self.position = Vec3::new( + self.position.x + v.x, + self.position.y + v.y, + self.position.z + v.z, + ); + let l = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt().max(1.0e-9); + let inertia = if water { 0.8 } else { 0.95 }; + self.velocity = Vec3::new( + (v.x + v.x / l * 0.1) * inertia, + (v.y + v.y / l * 0.1) * inertia, + (v.z + v.z / l * 0.1) * inertia, + ); + } +} pub(super) struct Breath { /// Its entity id once a server's players track it (0 until then). pub(super) id: u32, diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 2ef862200..574f5303e 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -280,6 +280,9 @@ impl Game<'_> { self.potions.thrown_ids().for_each(&mut give); self.end.eye_ids().for_each(&mut give); self.breath_clouds.iter_mut().for_each(|b| give(&mut b.id)); + self.dragon_fireballs + .iter_mut() + .for_each(|b| give(&mut b.id)); } /// Primed TNT, falling blocks, projectiles, tridents, firework rockets and @@ -445,6 +448,12 @@ impl Game<'_> { ), None, ); + for b in self.dragon_fireballs.iter().filter(|b| b.id != 0) { + let p = b.position; + let mut e = state(b.id, "minecraft:dragon_fireball", at(p), 0.0, false); + e.velocity = [b.velocity.x, b.velocity.y, b.velocity.z]; + out.push(e); + } for b in self.breath_clouds.iter().filter(|b| b.id != 0) { let mut e = state(b.id, "minecraft:area_effect_cloud", b.at, 0.0, false); e.meta.push((8, serializer::FLOAT, Value::Float(b.radius))); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5651647b7..7bde124b0 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1377,6 +1377,14 @@ impl Game<'_> { } return; } + // A dragon fireball keeps Entity's NO_OP InterpolationHandler too: + // the server's position replaces its own at once. + if let Some(b) = self.dragon_fireballs.iter_mut().find(|b| b.id == id as u32) { + if path.is_some() { + b.position = Vec3::new(position[0], position[1], position[2]); + } + return; + } if let Some(p) = r.pending_items.get_mut(&id) { p.0 = position; } @@ -2949,6 +2957,8 @@ impl Game<'_> { .find(|p| p.id == id as u32) { p.velocity = v; + } else if let Some(b) = self.dragon_fireballs.iter_mut().find(|b| b.id == id as u32) { + b.velocity = v; } else if let Some(p) = self .remote .as_mut() diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index fa1a5b35c..bbb7b7cde 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -107,6 +107,9 @@ impl Game<'_> { | "minecraft:experience_bottle" => { self.potions.add_remote_thrown(id, kind, at, velocity); } + "minecraft:dragon_fireball" => self + .dragon_fireballs + .push(super::dragon::DragonFireball::remote(id, at, velocity)), "minecraft:area_effect_cloud" => self.potions.clouds.push(RemoteCloud { id, at: position, @@ -356,6 +359,25 @@ impl Game<'_> { [at.x, at.y, at.z] }); self.tick_remote_clouds(); + // The dragon's fireballs fly on between the tracker's updates, with + // their dragon_breath trail (`AbstractHurtingProjectile.getTrailParticle`). + let trail = ParticleOptions::simple(ParticleType::DragonBreath); + for b in &mut self.dragon_fireballs { + let at = b.position; + let water = self + .res + .facts() + .get(self.world.block( + at.x.floor() as i32, + at.y.floor() as i32, + at.z.floor() as i32, + )) + .fluid + == horizon_client::blocks::Fluid::Water; + b.remote_step(water); + let p = b.position; + self.particles.add(&trail, [p.x, p.y + 0.5, p.z], [0.0; 3]); + } } /// `AreaEffectCloud.clientTick`: while waiting, now and then two @@ -416,6 +438,7 @@ impl Game<'_> { self.crystals.retain(|c| c.id != id); self.potions.remove_remote_thrown(id); self.potions.clouds.retain(|c| c.id != id); + self.dragon_fireballs.retain(|b| b.id != id); self.end.remove_remote_eye(id); self.remove_remote_hook(id); } @@ -430,6 +453,7 @@ impl Game<'_> { self.crystals.clear(); self.potions.clear_thrown(); self.potions.clouds.clear(); + self.dragon_fireballs.clear(); self.end.clear_remote_eyes(); self.clear_remote_hooks(); } From b0d378fe99acfdd2ac721976f93d82c7394a3288 Mon Sep 17 00:00:00 2001 From: Eshayat Al-Wasiu Date: Mon, 26 Oct 2026 17:16:07 +0600 Subject: [PATCH 19/51] Apply multiplayer motion packets to mobs for squid animation Co-Authored-By: Codex --- crates/horizon-client/src/game/remote.rs | 5 +- tests/test_remote_motion.py | 58 ++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 tests/test_remote_motion.py diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 547099cfe..d245524a1 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3050,7 +3050,10 @@ impl Game<'_> { /// blocks and primed TNT. fn remote_motion(&mut self, id: i32, velocity: [f64; 3]) { let v = Vec3::new(velocity[0], velocity[1], velocity[2]); - if let Some(d) = self.dropped.iter_mut().find(|d| d.id == id as u32) { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) { + // Squid.aiStep derives its body pitch and roll from network motion. + m.velocity = v; + } else if let Some(d) = self.dropped.iter_mut().find(|d| d.id == id as u32) { d.velocity = v; } else if let Some(f) = self.falling.iter_mut().find(|f| f.id == id as u32) { f.velocity = v; diff --git a/tests/test_remote_motion.py b/tests/test_remote_motion.py new file mode 100644 index 000000000..da059c60b --- /dev/null +++ b/tests/test_remote_motion.py @@ -0,0 +1,58 @@ +"""Exercise Entity motion delivery through the live multiplayer handler.""" +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] + + +@unittest.skipUnless(shutil.which("rustc"), "requires Rust") +class RemoteMotionTests(unittest.TestCase): + def test_mob_velocity_reaches_squid_animation(self): + source = (ROOT / "crates/horizon-client/src/game/remote.rs").read_text() + start = source.index(" fn remote_motion(") + end = source.index(" fn apply_remote_health(", start) + fixture = r''' +#![allow(dead_code)] +use std::collections::HashMap; +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Vec3(f64, f64, f64); +impl Vec3 { fn new(x: f64, y: f64, z: f64) -> Self { Self(x,y,z) } } +#[derive(Default)] +struct Entity { id: u32, velocity: Vec3 } +#[derive(Default)] +struct Remote { pending_items: HashMap } +#[derive(Default)] +struct Creatures { projectiles: Vec } +#[derive(Default)] +struct Game { + mobs: Vec, dropped: Vec, falling: Vec, tnts: Vec, + creatures: Creatures, remote: Option, +} +impl Game { +METHOD +} +fn main() { + let mut game = Game::default(); + game.mobs.push(Entity { id: 42, ..Entity::default() }); + game.dropped.push(Entity { id: 43, ..Entity::default() }); + // AddEntity initial motion and subsequent SetEntityMotion share this handler. + for motion in [[0.12, -0.04, 0.08], [-0.05, 0.03, 0.2], [0.0; 3]] { + game.remote_motion(42, motion); + assert_eq!(game.mobs[0].velocity, Vec3::new(motion[0], motion[1], motion[2])); + assert_eq!(game.dropped[0].velocity, Vec3::default()); + } + game.remote_motion(43, [0.1, 0.2, 0.3]); + assert_eq!(game.dropped[0].velocity, Vec3::new(0.1, 0.2, 0.3)); + game.remote_motion(999, [1.0; 3]); // Untracked entity is harmless. +} +'''.replace("METHOD", source[start:end]) + with tempfile.TemporaryDirectory(prefix="remote-motion-") as directory: + path = Path(directory) + (path / "main.rs").write_text(fixture) + subprocess.run(["rustc", "--edition=2024", str(path / "main.rs"), "-o", str(path / "probe")], + check=True, capture_output=True, text=True) + result = subprocess.run([str(path / "probe")], capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) From e2e591858eadc0b3423389412f9d1e41a65968c3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:11:49 +0100 Subject: [PATCH 20/51] Fire smoke: a waterlogged neighbour doesn't burn FireBlock.getIgniteOdds returns 0 for a waterlogged state, so canBurn is false there and the smoke takes the other branch. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/animate_tick.rs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index 945de2300..b3a587114 100644 --- a/crates/horizon-client/src/animate_tick.rs +++ b/crates/horizon-client/src/animate_tick.rs @@ -194,7 +194,7 @@ pub struct AnimateTables { power_transmitter: Vec, /// `#triggers_ambient_dried_ghast_block_sounds` (soul sand, soul soil). dried_ghast_sounds: Vec, - /// `FireBlock.canBurn`: states of blocks with ignite odds above zero. + /// `FireBlock.canBurn`: states with ignite odds above zero (none waterlogged). burnable: Vec, /// Biome id -> ambient particles and probabilities (`minecraft:visual/ambient_particles`). ambient: Vec>, @@ -231,12 +231,13 @@ impl AnimateTables { let ignite_odds = behaviour["fire"]["igniteOdds"].as_object(); let burnable = (0..registry.len() as u32) .map(|id| { + // FireBlock.getIgniteOdds: a waterlogged state never burns. registry.state(BlockStateId(id)).is_some_and(|s| { - ignite_odds - .and_then(|m| m.get(s.name.as_str())) - .and_then(serde_json::Value::as_i64) - .unwrap_or(0) - > 0 + s.properties.get("waterlogged").map(String::as_str) != Some("true") + && ignite_odds + .and_then(|m| m.get(s.name.as_str())) + .and_then(serde_json::Value::as_i64) + .is_some_and(|odds| odds > 0) }) }) .collect(); From e0fea857ce23200d76cdd1db1e707a79384428b5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:15:16 +0100 Subject: [PATCH 21/51] Remote dragon fireball: apply inertia before the move AbstractHurtingProjectile.tick calls applyInertia first and then moves by the new delta movement; Vec3.normalize leaves a near-zero vector at zero. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/dragon.rs | 27 +++++++++++++++--------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index e1880f9aa..89be88e61 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -2223,25 +2223,32 @@ impl DragonFireball { age: 0, } } - /// `AbstractHurtingProjectile.tick` on a server's client: accelerate - /// along the motion (power 0.1, inertia 0.95 or 0.8 in water) and move; - /// only the server decides what it hits. + /// `AbstractHurtingProjectile.tick` on a server's client: `applyInertia` + /// first (power 0.1, inertia 0.95 or 0.8 in water), then the move; only + /// the server decides what it hits. pub(super) fn remote_step(&mut self, water: bool) { self.previous = self.position; self.age += 1; let v = self.velocity; + // Vec3.normalize: a vector shorter than 1e-5 stays zero. + let l = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt(); + let n = if l < 1.0e-5 { + Vec3::new(0.0, 0.0, 0.0) + } else { + Vec3::new(v.x / l, v.y / l, v.z / l) + }; + let inertia = f64::from(if water { 0.8f32 } else { 0.95f32 }); + let v = Vec3::new( + (v.x + n.x * 0.1) * inertia, + (v.y + n.y * 0.1) * inertia, + (v.z + n.z * 0.1) * inertia, + ); + self.velocity = v; self.position = Vec3::new( self.position.x + v.x, self.position.y + v.y, self.position.z + v.z, ); - let l = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt().max(1.0e-9); - let inertia = if water { 0.8 } else { 0.95 }; - self.velocity = Vec3::new( - (v.x + v.x / l * 0.1) * inertia, - (v.y + v.y / l * 0.1) * inertia, - (v.z + v.z / l * 0.1) * inertia, - ); } } pub(super) struct Breath { From aec3b7e2624ea88f8d5ccd2019a9b13e03700e04 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 13:43:51 +0100 Subject: [PATCH 22/51] Scale mob damage to players with the difficulty Damage types marked when_caused_by_living_non_player now scale when a mob (or the owner of its projectile, or an exploding mob) caused the hit. --- crates/horizon-client/src/game/creatures.rs | 6 ++++- crates/horizon-client/src/game/explosion.rs | 4 +++- crates/horizon-client/src/health.rs | 26 +++++++++++++++++++-- crates/horizon-client/src/hunger.rs | 1 + 4 files changed, 33 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 3a8562ee1..e27e6b175 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1509,15 +1509,19 @@ impl Game<'_> { if let Some(a) = attacker.or(owner) { self.note_attacker(damage_type, a); } + // DamageSource.scalesWithDifficulty: a mob (or its projectile's + // owner) caused the hit, not a player. + let living_cause = attacker.or(owner).is_some(); let mut outcome = horizon_client::health::BlockOutcome::default(); if let Some(player) = self.player.as_mut() && let Some(id) = self.motion.health.damage.id(damage_type) - && let Ok(o) = player.hurt_blocking( + && let Ok(o) = player.hurt_caused_by( &self.motion.health, self.world.health_rules, id, amount, blocking, + living_cause, ) && { outcome = o; diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 6ecba3a54..8800e29d8 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -296,12 +296,14 @@ impl Game<'_> { if !creative && !spectator && hurtable - && let Ok(o) = p.hurt_blocking( + && let Ok(o) = p.hurt_caused_by( &self.motion.health, self.world.health_rules, id, amount, blocking, + // The exploding mob is the causing entity. + exploding.is_some(), ) { outcome = o; diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index 25c719bfb..4f7824b25 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -295,6 +295,20 @@ impl PlayerMotion { source: DamageTypeId, amount: f32, blocking: Option, + ) -> Result { + self.hurt_caused_by(resources, rules, source, amount, blocking, false) + } + /// `hurt_blocking` from a source whose causing entity is a living + /// non-player (`living_cause`), which the `when_caused_by_living_non_player` + /// damage types scale with the difficulty. + pub fn hurt_caused_by( + &mut self, + resources: &HealthResources, + rules: HealthRules, + source: DamageTypeId, + amount: f32, + blocking: Option, + living_cause: bool, ) -> Result { if self.client_side { return Ok(BlockOutcome::default()); @@ -315,6 +329,7 @@ impl PlayerMotion { invulnerable, rules, source, + living_cause, events: &mut self.events, dead: &mut h.dead, sync_velocity: &mut h.sync_velocity, @@ -390,6 +405,8 @@ pub(crate) struct Environment<'a> { pub(crate) invulnerable: bool, pub(crate) rules: HealthRules, pub(crate) source: DamageSource<'a, ()>, + /// The causing entity is a living non-player (a mob, or its projectile's owner). + pub(crate) living_cause: bool, pub(crate) events: &'a mut Vec, pub(crate) dead: &'a mut bool, pub(crate) sync_velocity: &'a mut bool, @@ -773,8 +790,13 @@ impl PlayerHurtWorld for Environment<'_> { Ok(()) } fn scales_with_difficulty(&mut self, _: &mut State) -> io::Result { - Ok(self.source.definition().scaling == Scaling::Always) - } // no causing entity + // DamageSource.scalesWithDifficulty. + Ok(match self.source.definition().scaling { + Scaling::Never => false, + Scaling::Always => true, + Scaling::LivingNonPlayer => self.living_cause, + }) + } fn difficulty(&mut self, _: &mut State) -> io::Result { Ok(self.rules.difficulty) } diff --git a/crates/horizon-client/src/hunger.rs b/crates/horizon-client/src/hunger.rs index 15eac144f..34f414d50 100644 --- a/crates/horizon-client/src/hunger.rs +++ b/crates/horizon-client/src/hunger.rs @@ -151,6 +151,7 @@ impl FoodWorld for TickWorld<'_> { .damage .source::<()>(id, None, None, None) .expect("validated starvation source"), + living_cause: false, events: self.events, dead: self.dead, sync_velocity: self.sync_velocity, From 5b0ae25ff8ac27d0454ab59c3b80c0f42a08d33e Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 13:49:39 +0100 Subject: [PATCH 23/51] Make thorns hurt the entity that hit the player Thorns picked the nearest living mob in the world. They now hurt the mob that caused the hit (or its projectile's owner), or the attacking player in a player-versus-player hit. --- crates/horizon-client/src/game/creatures.rs | 5 +- .../src/game/enchant_effects.rs | 48 +++++++++---------- crates/horizon-client/src/game/lan_pvp.rs | 28 ++++++++--- 3 files changed, 48 insertions(+), 33 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 3a8562ee1..9a685066a 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1536,7 +1536,10 @@ impl Game<'_> { } } self.hurt_armor(amount); - self.thorns(from); + // The thorns hurt the entity that caused the hit, if there is one. + if let Some(a) = attacker.or(owner) { + self.thorns(a); + } } if raised { self.after_block(outcome, amount, attacker, projectile); diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index aa9f75e06..7cdb3e526 100644 --- a/crates/horizon-client/src/game/enchant_effects.rs +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -255,23 +255,26 @@ impl Game<'_> { let _ = self.wind_burst(feet, radius, knockback, false, false); } } - /// Thorns on worn armor when a mob at `from` hits the player. - pub(super) fn thorns(&mut self, from: [f64; 3]) { - let attacker = self - .mobs - .iter() - .enumerate() - .filter(|(_, m)| m.alive()) - .min_by(|a, b| { - let d = |m: &horizon_client::mobs::Mob| { - (m.position.x - from[0]).powi(2) - + (m.position.y - from[1]).powi(2) - + (m.position.z - from[2]).powi(2) - }; - d(a.1).total_cmp(&d(b.1)) - }) - .map(|(i, _)| i); - let Some(attacker) = attacker else { return }; + /// Thorns on worn armor when the mob `attacker` hits the player: the + /// `affected: attacker` effect of `Enchantment.doPostAttack` hurts the + /// entity that caused the hit. + pub(super) fn thorns(&mut self, attacker: u32) { + let Some(index) = self.mobs.iter().position(|m| m.id == attacker && m.alive()) else { + return; + }; + for damage in self.thorns_damage() { + let m = &mut self.mobs[index]; + m.hurt(damage, None, &mut self.world.random); + let center = [m.position.x, m.position.y, m.position.z]; + self.audio + .play("minecraft:enchant.thorns.hit", Some(center), 1.0, 1.0); + } + } + /// The victim's side of thorns: for each worn piece whose chance comes up, + /// the damage to deal the attacker (`DamageEntity` min 1, max 5) and the + /// piece's wear (`ChangeItemDamage` 2). + pub(super) fn thorns_damage(&mut self) -> Vec { + let mut hits = Vec::new(); for slot in 0..4 { let Some(stack) = self.armor[slot].clone() else { continue; @@ -299,15 +302,7 @@ impl Game<'_> { if !ok { continue; } - // DamageEntity(min 1, max 5) and ChangeItemDamage(2). - let damage = 1.0 + self.world.random.next_float() * 4.0; - let center = { - let m = &mut self.mobs[attacker]; - m.hurt(damage, None, &mut self.world.random); - [m.position.x, m.position.y, m.position.z] - }; - self.audio - .play("minecraft:enchant.thorns.hit", Some(center), 1.0, 1.0); + hits.push(1.0 + self.world.random.next_float() * 4.0); if let Some(s) = self.armor[slot].as_mut() { s.damage += 2; if self @@ -320,6 +315,7 @@ impl Game<'_> { } } } + hits } /// `ExperienceOrb.repairPlayerItems`: returns the experience left over. pub(super) fn mending(&mut self, amount: u32) -> u32 { diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index 467c4537c..518470dbb 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -37,6 +37,8 @@ pub(super) struct Strike { crit: bool, from: [f64; 3], sweep: Option<[f64; 3]>, + /// The attacking player: a guest's connection, or the host. + attacker: Option, /// `causeExtraKnockback`: its strength and direction (the attacker's /// yaw), and whether the hit is a sprinting knockback attack. knockback: (f32, f64, f64), @@ -124,6 +126,7 @@ impl Game<'_> { crit, from, sweep, + attacker: self.lan_acting, knockback: (strength, xd, zd), knockback_attack, team: self.player_team().cloned(), @@ -242,14 +245,27 @@ impl Game<'_> { if hurt && strength > 0.0 { g.knock_back_player(f64::from(strength), xd, zd); } - hurt + // The victim's thorns, dealt to the attacker below. + let thorns = if hurt { g.thorns_damage() } else { Vec::new() }; + (hurt, thorns) }; - let hurt = self.ui.rules.bool("pvp") - && harm - && match victim { + let (hurt, thorns) = if self.ui.rules.bool("pvp") && harm { + match victim { Victim::Host => land(self), - Victim::Guest(conn) => self.guest_struck_by(host, conn, land).unwrap_or(false), - }; + Victim::Guest(conn) => self.guest_struck_by(host, conn, land).unwrap_or_default(), + } + } else { + Default::default() + }; + // `Enchantment.doPostAttack`: thorns hurt the attacking player. + for damage in thorns { + match s.attacker { + None => self.hurt_player_by("minecraft:thorns", damage), + Some(conn) => { + self.guest_hit_by(host, conn, |g| g.hurt_player_by("minecraft:thorns", damage)); + } + } + } let sound = match (hurt, s.crit, s.scale > 0.9) { (false, ..) => "minecraft:entity.player.attack.nodamage", (true, true, _) => "minecraft:entity.player.attack.crit", From 7c16e83fdf200aa6eedb26e1dc6c0625712e7428 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:13:03 +0100 Subject: [PATCH 24/51] Key binds: a key bound to several mappings drives all of them --- crates/horizon-client/src/game.rs | 45 +++++++++-------- crates/horizon-client/src/keybinds.rs | 69 +++++++++++++++++++-------- 2 files changed, 76 insertions(+), 38 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5760ffbe7..3d8392357 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -11509,16 +11509,17 @@ impl ApplicationHandler for Game<'_> { } self.extras_mouse(button, pressed); self.mod_mouse_key(button, pressed); - match self.settings.keys.translate_mouse(button) { - Some(Err(b)) => self.play_mouse(b, pressed)?, - Some(Ok(k)) if pressed => { - self.keys.insert(k); - self.key_pressed(k)?; + for mapped in self.settings.keys.translate_mouse_all(button) { + match mapped { + Err(b) => self.play_mouse(b, pressed)?, + Ok(k) if pressed => { + self.keys.insert(k); + self.key_pressed(k)?; + } + Ok(k) => { + self.keys.remove(&k); + } } - Some(Ok(k)) => { - self.keys.remove(&k); - } - None => {} } } Screen::Inventory | Screen::Creative @@ -11754,18 +11755,24 @@ impl ApplicationHandler for Game<'_> { { self.smooth_camera = !self.smooth_camera; } - // Key binds: act as the default key of the bound mapping. - let key = match self.settings.keys.translate(key) { - Some(Ok(k)) => k, - Some(Err(button)) => { - if self.screen == Screen::Playing && !event.repeat { - self.play_mouse(button, event.state == ElementState::Pressed)?; + // Key binds: act as the default key of every mapping bound + // to it (KeyMapping.set drives them all). + for mapped in self.settings.keys.translate_all(key) { + match mapped { + Ok(k) => { + self.mapped_key( + k, + event.state == ElementState::Pressed, + event.repeat, + )?; + } + Err(button) => { + if self.screen == Screen::Playing && !event.repeat { + self.play_mouse(button, event.state == ElementState::Pressed)?; + } } - return Ok(()); } - None => return Ok(()), - }; - self.mapped_key(key, event.state == ElementState::Pressed, event.repeat)?; + } } WindowEvent::RedrawRequested => { self.observe_fullscreen(); diff --git a/crates/horizon-client/src/keybinds.rs b/crates/horizon-client/src/keybinds.rs index a59aa627c..99eb5a15a 100644 --- a/crates/horizon-client/src/keybinds.rs +++ b/crates/horizon-client/src/keybinds.rs @@ -320,49 +320,80 @@ impl KeyBinds { } /// The mapping a physical input triggers (first in list order). pub fn mapping_for(&self, key: &str) -> Option<&'static str> { - MAPPINGS.iter().map(|m| m.0).find(|n| self.get(n) == key) + self.mappings_for(key).next() + } + /// Every mapping a physical input triggers, in list order: like + /// `KeyMapping.set`/`click`, one key drives all the mappings bound to it. + pub fn mappings_for<'a>(&'a self, key: &'a str) -> impl Iterator + 'a { + MAPPINGS + .iter() + .map(|m| m.0) + .filter(move |n| self.get(n) == key) } /// Translate a physical key into the default key of the mapping it is /// bound to, so game code written against vanilla defaults follows the /// player's bindings. `None` means the key now does nothing; mouse - /// mappings bound to keys come back as `Err(button)`. + /// mappings bound to keys come back as `Err(button)`. The first of + /// [`KeyBinds::translate_all`]. pub fn translate(&self, key: KeyCode) -> Option> { + self.translate_all(key).into_iter().next() + } + /// The default keys of every mapping `key` is bound to (empty when it + /// now does nothing), so a key bound to two mappings (forward and + /// sprint) drives both, as `KeyMapping.set` does. + pub fn translate_all(&self, key: KeyCode) -> Vec> { let Some(name) = key_name(key) else { - return Some(Ok(key)); + return vec![Ok(key)]; }; - if let Some(mapping) = self.mapping_for(name) { - let default = Self::default_of(mapping); - if let Some(code) = key_code(default) { - return Some(Ok(code)); - } - return mouse_button(default).map(Err); + let bound: Vec<_> = self + .mappings_for(name) + .filter_map(|mapping| { + let default = Self::default_of(mapping); + match key_code(default) { + Some(code) => Some(Ok(code)), + None => mouse_button(default).map(Err), + } + }) + .collect(); + if !bound.is_empty() { + return bound; } // An unbound key whose default meaning was moved elsewhere is inert. if MAPPINGS .iter() .any(|(n, d, _)| *d == name && !self.is_default(n)) { - return None; + return Vec::new(); } - Some(Ok(key)) + vec![Ok(key)] } /// Translate a mouse button the same way (keys bound to mouse buttons). pub fn translate_mouse(&self, button: MouseButton) -> Option> { + self.translate_mouse_all(button).into_iter().next() + } + /// [`KeyBinds::translate_all`] for a mouse button. + pub fn translate_mouse_all(&self, button: MouseButton) -> Vec> { let name = mouse_name(button); - if let Some(mapping) = self.mapping_for(&name) { - let default = Self::default_of(mapping); - if let Some(b) = mouse_button(default) { - return Some(Err(b)); - } - return key_code(default).map(Ok); + let bound: Vec<_> = self + .mappings_for(&name) + .filter_map(|mapping| { + let default = Self::default_of(mapping); + match mouse_button(default) { + Some(b) => Some(Err(b)), + None => key_code(default).map(Ok), + } + }) + .collect(); + if !bound.is_empty() { + return bound; } if MAPPINGS .iter() .any(|(n, d, _)| *d == name && !self.is_default(n)) { - return None; + return Vec::new(); } - Some(Err(button)) + vec![Err(button)] } /// `AbstractContainerScreen.checkHotbarMouseClicked`: off hand, then hotbar. pub fn container_mouse_key(&self, button: MouseButton, creative: bool) -> Option { From 3caf8f70145953860b5a4d8d66f689aff13cc50e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:24:09 +0100 Subject: [PATCH 25/51] lan_e2e portals: close the credits on the host's first End exit The first exit from the End now rolls the poem and credits, and the host goes home once they close (PERFORM_RESPAWN); the check asserts they show. Co-Authored-By: Claude Opus 5.5 --- tools/lan_e2e.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 804add98a..f251e68ca 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -653,6 +653,16 @@ def portals(host, guest, out, x, y, z, hx, hy, hz): guest('command', command=f'tp @s {arrived[0] + 0.5} {arrived[1]} {arrived[2] - 2.5}') guest.wait(30) guest('command', command=f'tp @s {arrived[0] + 0.5} {arrived[1]} {arrived[2] + 0.5}') + # ServerPlayer.showEndCredits: the host's first exit from the End rolls the poem and credits; + # closing them (WinScreen.onClose sends PERFORM_RESPAWN) takes it home. + credits = False + for _ in range(60): + host.wait(5) + if host('screen').get('screen') == 'win': + credits = True + host.raw('key', 'esc', 'tap') + break + assert credits, 'the host left the End without the credits' home = wait_dimension(host, 'minecraft:overworld', 600) back = wait_dimension(guest, 'minecraft:overworld', 600) guest.wait(40) @@ -660,7 +670,7 @@ def portals(host, guest, out, x, y, z, hx, hy, hz): guest.shot(out, 'portals-back') assert home.get('dimension') == 'minecraft:overworld', f'the host stayed in {home.get("dimension")}' assert back.get('dimension') == 'minecraft:overworld', f'the guest stayed in {back.get("dimension")}' - return {'guest_nether': arrived, 'host_end': [ex, ey, ez], 'back': pos_of(guest)} + return {'guest_nether': arrived, 'host_end': [ex, ey, ez], 'credits': credits, 'back': pos_of(guest)} NETHER, END, OVERWORLD = 'minecraft:the_nether', 'minecraft:the_end', 'minecraft:overworld' From 23d546c6d50051ce1ef6e0832cbb452ae9a60ad3 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:24:20 +0100 Subject: [PATCH 26/51] Sleep: creative skips the monster check, bed reach and obstruction match vanilla, morning follows the time and weather rules --- crates/horizon-client/src/game.rs | 75 +++++++++++++++++++++---------- 1 file changed, 51 insertions(+), 24 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5760ffbe7..3e2c861d7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9594,8 +9594,9 @@ impl Game<'_> { rain.extend(snow_vertices); rain } - /// Player.startSleepInBed: night or thunder, no monsters within 8 blocks; - /// the bed becomes the respawn point either way. + /// ServerPlayer.startSleepInBed: in reach, not obstructed, night or thunder, + /// and (outside creative) no monsters within 8 blocks; the bed becomes the + /// respawn point either way. fn try_sleep(&mut self, pos: [i32; 3]) { let Some(p) = self.player.as_ref() else { return; @@ -9610,22 +9611,40 @@ impl Game<'_> { .state(state) .map(|s| s.properties.clone()) .unwrap_or_default(); - let head = if props.get("part").map(String::as_str) == Some("foot") { - let d = facing_offset(props.get("facing").map_or("north", String::as_str)); - [pos[0] + d[0], pos[1], pos[2] + d[2]] + // The head and the foot: the block faces from the foot to the head. + let d = facing_offset(props.get("facing").map_or("north", String::as_str)); + let (head, foot) = if props.get("part").map(String::as_str) == Some("foot") { + ([pos[0] + d[0], pos[1], pos[2] + d[2]], pos) } else { - pos + (pos, [pos[0] - d[0], pos[1], pos[2] - d[2]]) }; - let dist = ((p.position.x - f64::from(head[0]) - 0.5).powi(2) - + (p.position.z - f64::from(head[2]) - 0.5).powi(2)) - .sqrt(); - if dist > 3.0 { + // ServerPlayer.bedInRange / isReachableBedBlock: within 3 blocks + // sideways and 2 vertically of the head or the foot. + let reachable = |bed: [i32; 3]| { + (p.position.x - f64::from(bed[0]) - 0.5).abs() <= 3.0 + && (p.position.y - f64::from(bed[1])).abs() <= 2.0 + && (p.position.z - f64::from(bed[2]) - 0.5).abs() <= 3.0 + }; + if !reachable(head) && !reachable(foot) { self.message = Some(( "You may not rest now; the bed is too far away".into(), Instant::now(), )); return; } + // ServerPlayer.bedBlocked: Player.freeAt (not suffocating) for the + // blocks above the head and the foot, as `in_wall` reads suffocating. + let blocked = [head, foot].iter().any(|bed| { + let f = self + .res + .facts() + .get(self.world.block(bed[0], bed[1] + 1, bed[2])); + f.full_collision && f.solid_render + }); + if blocked { + self.message = Some(("This bed is obstructed".into(), Instant::now())); + return; + } // In reach (bedInRange), day or night: setRespawnPosition( // RespawnConfig(the head, the player's yaw), not forced). It replaces // an anchor or a spawnpoint; respawning checks the bed is still there @@ -9655,13 +9674,15 @@ impl Game<'_> { )); return; } - let monsters = self.mobs.iter().any(|m| { - m.hostile() - && m.alive() - && (m.position.x - p.position.x).abs() < 8.0 - && (m.position.y - p.position.y).abs() < 5.0 - && (m.position.z - p.position.z).abs() < 8.0 - }); + // Creative players skip the monster check (`!this.isCreative()`). + let monsters = !self.creative + && self.mobs.iter().any(|m| { + m.hostile() + && m.alive() + && (m.position.x - p.position.x).abs() < 8.0 + && (m.position.y - p.position.y).abs() < 5.0 + && (m.position.z - p.position.z).abs() < 8.0 + }); if monsters { self.message = Some(( "You may not rest now; there are monsters nearby".into(), @@ -9711,14 +9732,20 @@ impl Game<'_> { } } // ServerLevel.tick: once enough of the players have slept 100 ticks, - // skip to morning, clear the weather and wake everyone. + // skip to morning if `advance_time` is on, wake everyone, and + // resetWeatherCycle if `advance_weather` is on and it is raining. if self.enough_slept() { - let t = self.world.day_time; - self.world.day_time = t + 24000 - t.rem_euclid(24000); - self.world.weather.raining = false; - self.world.weather.thundering = false; - self.world.weather.rain_time = 0; - self.world.weather.thunder_time = 0; + if self.ui.rules.bool("advance_time") { + let t = self.world.day_time; + self.world.day_time = t + 24000 - t.rem_euclid(24000); + } + // Level.isRaining: the rain level is above 0.2. + if self.ui.rules.bool("advance_weather") && self.world.weather.levels(1.0).0 > 0.2 { + self.world.weather.raining = false; + self.world.weather.thundering = false; + self.world.weather.rain_time = 0; + self.world.weather.thunder_time = 0; + } if self.sleeping.is_some() { self.wake_up(); } From 19c7a4a008e9d5bd01405adb9511b47a7fa9a51d Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:25:37 +0100 Subject: [PATCH 27/51] Slime block slows a walking player (SlimeBlock.stepOn) While standing on slime with a vertical speed under 0.1 and not sneaking, the horizontal speed is scaled by 0.4 + |vertical speed| * 0.2 every tick. --- crates/horizon-client/src/motion.rs | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 0bce8927c..fcdd32cbd 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -1083,7 +1083,7 @@ impl MotionWorld<'_, '_, '_> { /// `Entity.applyEffectsFromBlocks` for the blocks Horizon's player reacts /// to inside its movement path: powder snow (`PowderSnowBlock.entityInside` /// and the FREEZE / EXTINGUISH effects), cobwebs, sweet berry bushes, - /// cactus and lit campfires, and the magma block it stands on + /// cactus and lit campfires, and the magma and slime blocks it stands on /// (`stepOn`). Pressure plates, tripwires and rails are the world tick's /// scan. pub fn apply_effects_from_blocks(&mut self) -> Result<()> { @@ -1141,14 +1141,22 @@ impl MotionWorld<'_, '_, '_> { // MagmaBlock's hot floor hurts unless it steps carefully (sneaks). if self.player.ground.on_ground { let on = self.legacy_on_position()?; - let magma = self - .assets - .registry - .state(self.block(on)) - .is_some_and(|s| s.name == "minecraft:magma_block"); + let under = self.assets.registry.state(self.block(on)); + let magma = under.is_some_and(|s| s.name == "minecraft:magma_block"); + let slime = under.is_some_and(|s| s.name == "minecraft:slime_block"); if magma && !self.player.shift_key_down { self.environment_hurt("minecraft:hot_floor", 1.0)?; } + // SlimeBlock.stepOn: a slow walk on slime drags the horizontal + // speed (the client moves its own player, so not the server's copy). + if slime && !damage_only && !self.player.shift_key_down { + let abs_delta_y = self.player.velocity.y.abs(); + if abs_delta_y < 0.1 { + let scale = 0.4 + abs_delta_y * 0.2; + self.player.velocity.x *= scale; + self.player.velocity.z *= scale; + } + } } let mut visited = std::collections::HashSet::new(); let mut entered = Vec::new(); From 71981a95a28738df145e1affadc60d069f906436 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:26:34 +0100 Subject: [PATCH 28/51] Weather: the rain and thunder fade runs even with the weather cycle off --- crates/horizon-client/src/game.rs | 3 ++- crates/horizon-client/src/world.rs | 8 +++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5760ffbe7..1e6bd7e4b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4227,8 +4227,9 @@ impl Game<'_> { if running { self.world.game_time += 1; if self.ui.rules.bool("advance_weather") { - self.world.weather.tick(&mut self.world.random); + self.world.weather.tick_timers(&mut self.world.random); } + self.world.weather.tick_levels(); self.tick_weather_effects(); } if self.ticks.is_multiple_of(6000) { diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index d73956d85..83083eba2 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -109,7 +109,9 @@ pub struct Weather { pub thunder_level: (f32, f32), } impl Weather { - pub fn tick(&mut self, random: &mut horizon_core::random::LegacyRandom) { + /// The timers of `advanceWeatherCycle`, which run only while + /// `advance_weather` is on. + pub fn tick_timers(&mut self, random: &mut horizon_core::random::LegacyRandom) { use horizon_core::random::RandomSource; let mut uniform = |min: i32, max: i32| min + random.next_int_bound(max - min + 1).unwrap_or(0); @@ -141,6 +143,10 @@ impl Weather { self.rain_time = uniform(12000, 180000); } } + } + /// The rain and thunder level fade at the end of `advanceWeatherCycle`, + /// which runs whatever `advance_weather` says, so `/weather` still shows. + pub fn tick_levels(&mut self) { self.thunder_level.0 = self.thunder_level.1; self.thunder_level.1 = (self.thunder_level.1 + if self.thundering { 0.01 } else { -0.01 }).clamp(0.0, 1.0); From d8fcebdf71076f0475ceb1ceb9349c652fa2ddcd Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:30:31 +0100 Subject: [PATCH 29/51] Match vanilla difficulty and survival rules for lightning fire --- crates/horizon-client/src/game/lightning.rs | 30 +++++++++------------ 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 916bd2a0a..297f372c5 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -162,11 +162,9 @@ impl Game<'_> { converted: Vec::new(), }); } - /// `spawnFire`: fire at the strike point and `extra` random neighbours. + /// `spawnFire`: fire at the strike point and `extra` random neighbours, + /// wherever `BaseFireBlock.getState` fire can survive. fn bolt_fire(&mut self, at: [f64; 3], extra: i32) { - if self.ui.difficulty < 2 { - return; - } let base = [ at[0].floor() as i32, at[1].floor() as i32, @@ -183,18 +181,13 @@ impl Game<'_> { if !self.res.facts().is_air(state) { continue; } - // BaseFireBlock.getState: soul fire on soul soil and sand. - let below = self.res.facts().get(self.world.block(p[0], p[1] - 1, p[2])); - let name = if matches!(&*below.name, "minecraft:soul_soil" | "minecraft:soul_sand") { - "minecraft:soul_fire" - } else { - "minecraft:fire" - }; - // FireBlock.canSurvive: a sturdy floor (flammable neighbours aside). - if below.sturdy_full >> 1 & 1 == 0 { - continue; - } - if let Some(fire) = self.pack.assets.registry.default_state(name) { + // BaseFireBlock.getState and FireBlock/SoulFireBlock.canSurvive. + let at = BlockPos::new(p[0], p[1], p[2]); + let fire = self.with_level(|b, level, ticks| { + let fire = b.fire_state_for(level, ticks, at); + b.can_survive(level, ticks, at, fire).then_some(fire) + }); + if let Some(fire) = fire { let _ = self.level_set(p, fire); } } @@ -219,7 +212,10 @@ impl Game<'_> { pitch, ); if !b.visual_only { - self.bolt_fire(b.at, 4); + // Only Normal and Hard start fires with the strike itself. + if self.ui.difficulty >= 2 { + self.bolt_fire(b.at, 4); + } self.strike_rod(b.at); } } From 7abb092089d5e2008234673454a50f393e26bbc6 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:30:34 +0100 Subject: [PATCH 30/51] Wire fire burnout, difficulty and spread radius into the fire tick --- crates/horizon-client/src/biome.rs | 6 ++++ crates/horizon-client/src/game.rs | 48 ++++++++++++++++++++++++++ crates/horizon-client/src/game/chat.rs | 1 + crates/horizon-world/src/level/mod.rs | 8 +++++ crates/horizon-world/src/level/tick.rs | 5 ++- 5 files changed, 65 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/biome.rs b/crates/horizon-client/src/biome.rs index 63ad004d4..c8c15e44e 100644 --- a/crates/horizon-client/src/biome.rs +++ b/crates/horizon-client/src/biome.rs @@ -28,6 +28,9 @@ pub struct BiomeInfo { pub spawn_costs: HashMap, /// The `gameplay/creature_world_gen_spawn_probability` attribute. pub creature_probability: f32, + /// The `gameplay/increased_fire_burnout` attribute (jungles, swamps, peaks, + /// mushroom fields). + pub increased_fire_burnout: bool, pub name: String, pub temperature: f32, pub downfall: f32, @@ -128,6 +131,9 @@ impl Biomes { attributes["minecraft:gameplay/creature_world_gen_spawn_probability"] .as_f64() .unwrap_or(0.1) as f32, + increased_fire_burnout: attributes["minecraft:gameplay/increased_fire_burnout"] + .as_bool() + .unwrap_or(false), temperature, downfall, precipitation: v["has_precipitation"].as_bool().unwrap_or(true), diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5760ffbe7..b3e379e02 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -552,6 +552,11 @@ struct GameLevel<'w> { loot: Option>, registry: &'static horizon_world::registry::BlockRegistry, rules: horizon_world::level::GameRules, + /// `Difficulty.getId()` (peaceful 0 .. hard 3). + difficulty: i32, + /// The feet of the players who keep fire spreading around them: the local + /// player and the LAN guests in this level, spectators aside. + fire_players: Vec<[f64; 3]>, /// Block loot random sequences (`ServerLevel.getRandomSequence`). rand_sequences: &'w mut horizon_client::random_sequences::RandomSequences, pending: &'w mut spill::Pending, @@ -715,6 +720,34 @@ impl LevelAccess for GameLevel<'_> { fn game_rules(&self) -> horizon_world::level::GameRules { self.rules } + fn difficulty(&self) -> i32 { + self.difficulty + } + /// `ServerLevel.canSpreadFireAround`: a player (not a spectator) closer + /// than the `fire_spread_radius_around_player` rule to the block's corner + /// (`ChunkMap.anyPlayerCloseEnoughTo`); -1 spreads everywhere. + fn can_spread_fire_around(&self, pos: BlockPos) -> bool { + let radius = self.rules.fire_spread_radius_around_player; + radius == -1 + || self.fire_players.iter().any(|p| { + let d = [ + p[0] - f64::from(pos.x), + p[1] - f64::from(pos.y), + p[2] - f64::from(pos.z), + ]; + d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < f64::from(radius) * f64::from(radius) + }) + } + fn increased_fire_burnout(&self, pos: BlockPos) -> bool { + self.world + .chunks + .get(&(pos.x >> 4, pos.z >> 4)) + .is_some_and(|chunk| { + self.biomes + .get(chunk.biome(pos.x, pos.y, pos.z)) + .increased_fire_burnout + }) + } fn block_state(&self, pos: BlockPos) -> BlockStateId { self.world.block(pos.x, pos.y, pos.z) } @@ -2454,6 +2487,19 @@ impl Game<'_> { Dim::End => LevelDimension::End, }; let rules = self.level_rules(); + let fire_players: Vec<[f64; 3]> = self + .player + .iter() + .filter(|_| !spectator) + .map(|p| [p.position.x, p.position.y, p.position.z]) + .chain(self.lan.iter().flat_map(|h| { + h.hub + .guests + .iter() + .filter(|g| h.hub.here(g) && !g.spectator()) + .map(|g| g.position) + })) + .collect(); let blockers = Blockers { mobs: &self.mobs, armor_stands: &self.armor_stands, @@ -2484,6 +2530,8 @@ impl Game<'_> { loot: horizon_client::structure_blocks::loot_data(&self.options.resources), registry: self.pack.assets.registry, rules, + difficulty: i32::from(self.ui.difficulty), + fire_players, rand_sequences: &mut self.rand_sequences, pending: &mut self.pending, spill: &mut self.spill, diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index de5bbf116..fa108c723 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -778,6 +778,7 @@ impl Game<'_> { max_snow_accumulation_height: r.int("max_snow_accumulation_height"), spawn_mobs: r.bool("spawn_mobs"), spawn_monsters: r.bool("spawn_monsters"), + fire_spread_radius_around_player: r.int("fire_spread_radius_around_player"), } } /// Apply rules mirrored in other state (natural regeneration, difficulty). diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 3831efbd6..bdc1562f9 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -180,6 +180,8 @@ pub struct GameRules { pub max_snow_accumulation_height: i32, pub spawn_mobs: bool, pub spawn_monsters: bool, + /// `fire_spread_radius_around_player`: -1 spreads everywhere. + pub fire_spread_radius_around_player: i32, } impl Default for GameRules { fn default() -> Self { @@ -192,6 +194,7 @@ impl Default for GameRules { max_snow_accumulation_height: 1, spawn_mobs: true, spawn_monsters: true, + fire_spread_radius_around_player: 128, } } } @@ -342,6 +345,11 @@ pub trait LevelAccess { fn can_spread_fire_around(&self, _pos: BlockPos) -> bool { true } + /// The `INCREASED_FIRE_BURNOUT` environment attribute at `pos` (a biome + /// attribute). + fn increased_fire_burnout(&self, _pos: BlockPos) -> bool { + false + } /// `Level.isUnobstructed(state, pos, context)`: whether the state's /// collision shape at `pos` would intersect an entity. fn is_unobstructed(&self, _pos: BlockPos, _state: BlockStateId) -> bool { diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs index 29f53e053..25e2a19d3 100644 --- a/crates/horizon-world/src/level/tick.rs +++ b/crates/horizon-world/src/level/tick.rs @@ -565,9 +565,8 @@ impl Sim<'_, L> { return; } } - // FireBlock.tick reads the INCREASED_FIRE_BURNOUT environment attribute - // (jungles, swamps, peaks, mushroom fields); Horizon doesn't yet. - let burnout = false; + // FireBlock.tick: the INCREASED_FIRE_BURNOUT environment attribute. + let burnout = self.level.increased_fire_burnout(pos); let extra = if burnout { -50 } else { 0 }; for (direction, chance) in [ (Direction::East, 300), From 199178907cf702a2949fb9494c40cf1e3c16c3f6 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:30:49 +0100 Subject: [PATCH 31/51] Shovels put out a lit campfire --- crates/horizon-client/src/animate_tick.rs | 23 ++++++-- crates/horizon-client/src/game.rs | 5 ++ .../horizon-client/src/game/campfire_douse.rs | 53 +++++++++++++++++++ 3 files changed, 78 insertions(+), 3 deletions(-) create mode 100644 crates/horizon-client/src/game/campfire_douse.rs diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index 48e8f16f4..7cf96d9df 100644 --- a/crates/horizon-client/src/animate_tick.rs +++ b/crates/horizon-client/src/animate_tick.rs @@ -1157,13 +1157,19 @@ pub fn campfire_particles<'a>( if r.next_float() < 0.11 { let count = next_int(r, 2) + 2; for _ in 0..count { - make_campfire_smoke(engine, pos, signal); + make_campfire_smoke(engine, pos, signal, false); } } } } -/// `CampfireBlock.makeParticles` (always visible, overriding the limiter). -pub fn make_campfire_smoke(engine: &mut ParticleEngine, pos: [i32; 3], signal: bool) { +/// `CampfireBlock.makeParticles` (always visible, overriding the limiter); +/// `smoking` adds the plain smoke puff at the logs. +pub fn make_campfire_smoke( + engine: &mut ParticleEngine, + pos: [i32; 3], + signal: bool, + smoking: bool, +) { let r = engine.random(); let sign = |r: &mut LegacyRandom| if r.next_boolean() { 1.0 } else { -1.0 }; let dx = r.next_double() / 3.0; @@ -1177,6 +1183,17 @@ pub fn make_campfire_smoke(engine: &mut ParticleEngine, pos: [i32; 3], signal: b T::CampfireCosySmoke }; engine.create(&ParticleOptions::simple(ty), [x, y, z], [0.0, 0.07, 0.0]); + if smoking { + let r = engine.random(); + let dx = r.next_double() / 4.0 * sign(r); + let dz = r.next_double() / 4.0 * sign(r); + let at = [ + f64::from(pos[0]) + 0.5 + dx, + f64::from(pos[1]) + 0.4, + f64::from(pos[2]) + 0.5 + dz, + ]; + engine.create(&ParticleOptions::simple(T::Smoke), at, [0.0, 0.005, 0.0]); + } } #[cfg(test)] diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5760ffbe7..7f5f77020 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -18,6 +18,7 @@ mod boats; mod books; mod bossbars; mod breezes; +mod campfire_douse; mod cartography; mod chat; mod client_ambient; @@ -3538,6 +3539,10 @@ impl Game<'_> { self.swing_arm(); return Ok(true); } + if self.use_campfire_douse(hit.pos, held.as_ref())? { + self.swing_arm(); + return Ok(true); + } match self.use_respawn_anchor(hit.pos, held.as_ref())? { respawn_anchor::AnchorUse::Charged => { self.swing_arm(); diff --git a/crates/horizon-client/src/game/campfire_douse.rs b/crates/horizon-client/src/game/campfire_douse.rs new file mode 100644 index 000000000..04accb2d3 --- /dev/null +++ b/crates/horizon-client/src/game/campfire_douse.rs @@ -0,0 +1,53 @@ +//! `CampfireBlock.useItemOn`: an item in `#minecraft:douses_campfires` (the +//! shovels) put on a lit campfire puts it out. +use super::Game; +use horizon_client::{Result, animate_tick::make_campfire_smoke, items::ItemStack}; + +impl Game<'_> { + /// `CampfireBlock.useItemOn` with `held` in the hand that acts, the block + /// at `pos` clicked: true when it doused a lit campfire (SUCCESS). + pub(super) fn use_campfire_douse( + &mut self, + pos: [i32; 3], + held: Option<&ItemStack>, + ) -> Result { + let Some(tool) = held.filter(|s| { + self.res + .items() + .item_tags + .get("minecraft:douses_campfires") + .is_some_and(|members| members.contains(&*s.item)) + }) else { + return Ok(false); + }; + let registry = self.pack.assets.registry; + let Some(mut state) = registry + .state(self.world.block(pos[0], pos[1], pos[2])) + .filter(|s| matches!(&*s.name, "minecraft:campfire" | "minecraft:soul_campfire")) + .filter(|s| s.properties.get("lit").map(String::as_str) == Some("true")) + .cloned() + else { + return Ok(false); + }; + // Level event 1009 (SOUND_EXTINGUISH_FIRE) goes to every player. + self.level_event_at(1009, pos, 0); + // CampfireBlock.douse: the acting client's own smoke (twenty puffs), + // then the block change game event from the player. + if self.lan_acting.is_none() { + let signal = state.properties.get("signal_fire").map(String::as_str) == Some("true"); + for _ in 0..20 { + make_campfire_smoke(&mut self.particles, pos, signal, true); + } + } + self.post_block_game_event("minecraft:block_change", pos, self.sculk_actor(), None); + state.properties.insert("lit".into(), "false".into()); + if let Ok(unlit) = registry.resolve(&state) { + self.level_set(pos, unlit)?; + } + let used = tool.clone(); + self.damage_held(1); + // ServerPlayerGameMode.useItemOn: the action was consumed. + self.trigger_block("minecraft:item_used_on_block", pos, &used); + Ok(true) + } +} From b1136ac287648375239b1813a1fc42303c235afc Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:30:54 +0000 Subject: [PATCH 32/51] Keep forced server levels ticking without players Fixes #1525. Respect forced tickets when scheduling levels and bound playerless integrated-server ticks to their ticket sources. Co-Authored-By: Codex (GPT-6.1 Sol) --- crates/horizon-client/src/game.rs | 17 ++++---- crates/horizon-client/src/game/levels.rs | 22 +++++++--- tools/lan_e2e.py | 53 ++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 14 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5760ffbe7..2cc892d8d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2551,14 +2551,15 @@ impl Game<'_> { (p.position.z.floor() as i32) >> 4, )); } - let sources = (self.options.dedicated.is_some() || !players.is_empty()).then(|| { - horizon_client::ticket_levels::Sources { - players, - forced: self.streaming.forced.iter().copied().collect(), - view_distance: self.settings.render_distance.clamp(2, 32), - simulation_distance: self.settings.simulation_distance.max(2), - } - }); + let sources = + (!self.options.execution_role.is_client() || !players.is_empty()).then(|| { + horizon_client::ticket_levels::Sources { + players, + forced: self.streaming.forced.iter().copied().collect(), + view_distance: self.settings.render_distance.clamp(2, 32), + simulation_distance: self.settings.simulation_distance.max(2), + } + }); self.tickets.update(sources); } /// `ServerLevel.startTickingChunk`: a loaded chunk's saved ticks are diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index bfc739cee..f68c52d87 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -3,8 +3,8 @@ //! The game's tick code reads one level: the one in place, held in `Game`'s //! own fields (the world, its streaming and save, block ticks, entities). //! A server (the dedicated server and single player's server thread) keeps -//! the other dimensions' levels here and ticks each one that has players by -//! swapping it into place (`enter_level`), the way `as_guest` swaps a player +//! the other dimensions' levels here and ticks each one with players or forced +//! chunks by swapping it into place (`enter_level`), the way `as_guest` swaps a player //! in, so the tick code runs unchanged, one level at a time. The in-frame //! game holds one level, which follows its player (`enter_dimension`). //! @@ -290,8 +290,8 @@ impl Game<'_> { } /// One server tick (`MinecraftServer.tickServer`): each level with - /// players in turn (`tickChildren`), its chunks streamed and loaded and - /// its world ticked. The first pass reads the network and runs the + /// players or forced chunks in turn (`tickChildren`), its chunks streamed + /// and loaded and its world ticked. The first pass reads the network and runs the /// tick's shared parts (the clock, the weather, functions, the autosave); /// the next ones only their level. While `paused`, only the connections /// run. @@ -393,7 +393,7 @@ impl Game<'_> { /// The levels this server tick runs, in `MinecraftServer.levels` order /// (the Overworld, the Nether, the End): every level with a player in - /// it or a `/pregen` task, or the Overworld while nobody is online. + /// it, forced chunks or a `/pregen` task, or the Overworld while idle. pub(super) fn levels_to_tick(&self) -> Vec { let guests = self .lan @@ -402,7 +402,17 @@ impl Game<'_> { let mut dims: Vec = [Dim::Overworld, Dim::Nether, Dim::End] .into_iter() .filter(|d| { - guests.iter().any(|g| g.dimension == d.id()) || self.pregen_level() == Some(*d) + let forced = if *d == self.dim { + !self.streaming.forced.is_empty() + } else { + self.levels + .parked + .get(d) + .is_some_and(|p| !p.streaming.forced.is_empty()) + }; + guests.iter().any(|g| g.dimension == d.id()) + || forced + || self.pregen_level() == Some(*d) }) .collect(); if dims.is_empty() { diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 6dabe6dd7..958950ee5 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -6955,5 +6955,58 @@ CHECKS += ['sonic'] CHECK_FNS['sonic'] = check_sonic +def check_forced_levels(host, guest, out): + """#1525: forced block/entity ticks outlive the last player and the 300-tick idle timeout. + + Also keep a resident, unforced furnace outside the forced ticket's neighbour ring: scheduling + a playerless integrated-server level must not enable the fixtures' tick-everywhere fallback. + """ + if not SERVER_THREAD: + return 'skipped (needs --server-thread)' + start = pos_of(guest) + results = {} + guest('command', command='gamemode creative') + try: + for dimension in (NETHER, END): + into_level(guest, dimension, 8, 100, 8) + host('command', command='tick freeze') + furnace = ('minecraft:furnace{Items:[{Slot:0b,id:"minecraft:raw_iron",count:1},' + '{Slot:1b,id:"minecraft:coal",count:1}],cooking_total_time:200,' + 'cooking_time_spent:0}') + for x in (8, 56): + guest('command', command=f'setblock {x} 100 8 {furnace}') + server_reply(guest, f'execute if data block {x} 100 8 ' + 'Items[{Slot:0b,id:"minecraft:raw_iron"}] ' + 'run say forced-input-ready', 'forced-input-ready') + guest('command', command='forceload add 8 8') + guest('command', command='summon minecraft:armor_stand 8.5 104 8.5 {Tags:["forced_tick"]}') + guest('command', command=f'execute in {OVERWORLD} run tp @s {start[0]} {start[1]} {start[2]}') + wait_dimension(guest, OVERWORLD, 400) + host('command', command='tick step 450') + host.wait(500) + prefix = f'execute in {dimension} ' + results[dimension] = server_reply( + host, prefix + 'if data block 8 100 8 Items[{Slot:2b,id:"minecraft:iron_ingot"}] ' + 'if data block 56 100 8 {cooking_time_spent:0} ' + 'if data block 56 100 8 Items[{Slot:0b,id:"minecraft:raw_iron"}] ' + 'if data entity @e[tag=forced_tick,limit=1] {Pos:[8.5d,101.0d,8.5d]} run say forced-level-pass', + 'forced-level-pass') + assert dims(host, guest) == (OVERWORLD, OVERWORLD), dims(host, guest) + host('command', command=prefix + 'run forceload remove 8 8') + host('command', command=prefix + 'run kill @e[tag=forced_tick]') + host('command', command='tick unfreeze') + finally: + host('command', command='tick unfreeze') + for dimension in (NETHER, END): + host('command', command=f'execute in {dimension} run forceload remove 8 8') + guest('command', command=f'execute in {OVERWORLD} run tp @s {start[0]} {start[1]} {start[2]}') + guest('command', command='gamemode survival') + return results + + +CHECKS += ['forced-levels'] +CHECK_FNS['forced-levels'] = check_forced_levels + + if __name__ == '__main__': main() From 8bfa7a5b7ba893b6faa899d5d9a5b72f2ae7c060 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:31:03 +0100 Subject: [PATCH 33/51] Loot: suspicious stew keeps the effect set_stew_effect rolled The function drew an effect and a duration but dropped them. The stack now carries the effect and it is stored in suspicious_stew_effects. --- .../probe/entity_death_loot_fixture.rs | 1 + crates/horizon-client/src/game/creatures.rs | 1 + crates/horizon-client/src/mobs/drops.rs | 1 + crates/horizon-client/src/structure_blocks.rs | 8 ++++++++ crates/horizon-world/src/loot.rs | 20 ++++++++++++++++++- 5 files changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs b/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs index 86ef275d9..3f47ba787 100644 --- a/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs +++ b/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs @@ -23,6 +23,7 @@ fn stack(spec: &str) -> LootStack { map: false, exploration: None, ominous_amplifier: None, + stew_effects: Vec::new(), }; for e in parts { let (name, level) = e.rsplit_once(':').unwrap_or((e, "1")); diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 194256040..6abd646fd 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -3297,6 +3297,7 @@ fn to_loot(stack: &ItemStack) -> horizon_world::loot::LootStack { map: false, exploration: None, ominous_amplifier: None, + stew_effects: Vec::new(), } } /// A generated loot stack as a Horizon item stack. diff --git a/crates/horizon-client/src/mobs/drops.rs b/crates/horizon-client/src/mobs/drops.rs index e5ccfd283..c7b1c77e1 100644 --- a/crates/horizon-client/src/mobs/drops.rs +++ b/crates/horizon-client/src/mobs/drops.rs @@ -304,6 +304,7 @@ fn loot_stack(item: &str, count: i32) -> LootStack { map: false, exploration: None, ominous_amplifier: None, + stew_effects: Vec::new(), } } /// `Mob.dropChances.byEquipment(slot)`: the recorded chance, or the one the diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index 9503294e0..0ff675572 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -63,6 +63,12 @@ pub fn loot_item_with_components(s: &horizon_world::loot::LootStack) -> ItemStac if let Some(level) = s.ominous_amplifier.filter(|l| *l > 0) { item.data_mut().ominous_amplifier = Some(level.clamp(0, 4) as u8); } + // set_stew_effect's `suspicious_stew_effects`. + for (effect, duration) in &s.stew_effects { + item.data_mut() + .stew_effects + .push((Arc::from(effect.as_str()), *duration)); + } item } @@ -243,6 +249,7 @@ mod tests { map: false, exploration: None, ominous_amplifier: None, + stew_effects: Vec::new(), }; // An End city chest's enchant_with_levels roll. let boots = loot_item_with_components(&stack( @@ -286,6 +293,7 @@ mod tests { "zoom": 1 })))), ominous_amplifier: None, + stew_effects: Vec::new(), }; let mut item = loot_item(&stack); assert!(has_pending_map(&item)); diff --git a/crates/horizon-world/src/loot.rs b/crates/horizon-world/src/loot.rs index 96ca5bdee..f98afa21f 100644 --- a/crates/horizon-world/src/loot.rs +++ b/crates/horizon-world/src/loot.rs @@ -31,6 +31,9 @@ pub struct LootStack { pub exploration: Option>, /// Set by set_ominous_bottle_amplifier. pub ominous_amplifier: Option, + /// Added by set_stew_effect (the `suspicious_stew_effects` component): + /// (effect id, duration in ticks). + pub stew_effects: Vec<(String, i32)>, } /// `ExplorationMapFunction`'s settings. #[derive(Clone, Debug, PartialEq, Eq)] @@ -74,6 +77,7 @@ impl LootStack { map: false, exploration: None, ominous_amplifier: None, + stew_effects: Vec::new(), } } pub fn is_empty(&self) -> bool { @@ -678,6 +682,13 @@ impl LootData { } } +/// `MobEffect.isInstantaneous`. +fn is_instantaneous(effect: &str) -> bool { + matches!( + effect, + "minecraft:saturation" | "minecraft:instant_health" | "minecraft:instant_damage" + ) +} /// The level of one enchantment on a stack (its `enchantments` component). fn item_level(stack: &LootStack, enchantment: &str) -> i32 { stack @@ -1134,7 +1145,14 @@ impl Context<'_, R> { .random .next_int_bound(effects.len() as i32) .unwrap_or(0) as usize; - self.int(&effects[pick]["duration"]); + let effect = effects[pick]["type"].as_str().unwrap_or(""); + let mut duration = self.int(&effects[pick]["duration"]); + // Seconds, unless the effect is instantaneous. + if !is_instantaneous(effect) { + duration *= 20; + } + // SuspiciousStewEffects.withEffectAdded + stack.stew_effects.push((effect.to_owned(), duration)); } } "minecraft:set_ominous_bottle_amplifier" => { From fd1d857f1ba2485b468b8bfcdf45e79ce7517d50 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:32:02 +0100 Subject: [PATCH 34/51] Hoglins keep away from warped fungus, portals and respawn anchors Hoglins now sense the nearest block from the hoglin repellents tag within 8 blocks sideways and 4 up or down. While one is near they become passive for 200 ticks (the attack target is dropped and no new one is picked), walk away from it, and avoid picking random walk spots within 8 blocks of it. Being hit ends the passive state. --- crates/horizon-client/src/mobs.rs | 3 + crates/horizon-client/src/mobs/ai.rs | 14 ++++ crates/horizon-client/src/mobs/piglin.rs | 86 +++++++++++++++++++++++- crates/horizon-client/src/mobs/world.rs | 29 ++++++++ 4 files changed, 129 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 1b5dddbe7..bf42bc587 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -709,6 +709,9 @@ pub struct Extra { /// A copper golem's `openedChestPos`. pub opened_chest: Option<[i32; 3]>, pub point: Option<[f64; 3]>, + /// `NEAREST_REPELLENT`: the nearest repelling block a hoglin or piglin + /// sensed, looked up every 20 ticks. + pub repellent: Option<[i32; 3]>, pub vector: [f64; 3], /// Active status effects: (effect id, ticks left, amplifier). pub effects: Vec<(&'static str, i32, i32)>, diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 8335cb745..2676c3a37 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -1242,6 +1242,20 @@ pub fn walk_target_value(m: &Mob, w: &MobWorld, p: [i32; 3]) -> f32 { if m.species() == Species::Strider { return super::strider::walk_target_value(m, w, p); } + // Hoglin.getWalkTargetValue: nowhere near a repellent, crimson nylium best. + if m.species() == Species::Hoglin { + let near = m.extra.repellent.is_some_and(|r| { + let d = |i: usize| i64::from(r[i] - p[i]); + d(0) * d(0) + d(1) * d(1) + d(2) * d(2) < 64 + }); + return if near { + -1.0 + } else if w.block_name(p[0], p[1] - 1, p[2]) == "minecraft:crimson_nylium" { + 10.0 + } else { + 0.0 + }; + } // Bee.getWalkTargetValue: any air block. if m.species() == Species::Bee { return if w.facts.is_air(w.world.block(p[0], p[1], p[2])) { diff --git a/crates/horizon-client/src/mobs/piglin.rs b/crates/horizon-client/src/mobs/piglin.rs index 410364097..155d53d2f 100644 --- a/crates/horizon-client/src/mobs/piglin.rs +++ b/crates/horizon-client/src/mobs/piglin.rs @@ -9,7 +9,7 @@ use super::{ NearestTarget, Prey, RandomLookAround, Stroll, goal_clone, }, }; -use horizon_core::geometry::trig::Mth; +use horizon_core::geometry::{Vec3, trig::Mth}; use horizon_core::random::RandomSource; use std::f32::consts::PI; @@ -83,12 +83,16 @@ pub fn register_hoglin(m: &mut Mob) { g.add(1, BabyPanic(super::goals::Panic::new(1.25))); g.add(2, MeleeAttack::new(1.0, true)); g.add(3, super::goals::Breed::new(1.0)); + g.add(3, HoglinAvoidRepellent); g.add(4, super::goals::FollowParent::new(1.1)); g.add(5, Stroll::avoiding_water(0.4)); g.add(6, LookAtPlayer::new(8.0)); m.ai.targets.add(1, HurtByTarget::new().alert()); - m.ai.targets - .add(2, NearestTarget::player(true).when(|m, _| !m.is_baby())); + // `HoglinAi.findNearestValidAttackTarget`: nothing while pacified. + m.ai.targets.add( + 2, + NearestTarget::player(true).when(|m, _| !m.is_baby() && m.extra.ints[0] <= 0), + ); } pub fn register_zoglin(m: &mut Mob) { let g = &mut m.ai.goals; @@ -108,6 +112,49 @@ pub fn register_zoglin(m: &mut Mob) { .interval(10), ); } +/// `SetWalkTargetAwayFrom.pos(NEAREST_REPELLENT, 1.0, 8, true)` of the hoglin's +/// idle activity: closer than 8 blocks to a repellent, walk away from it. +#[derive(Clone, Debug)] +struct HoglinAvoidRepellent; +impl Goal for HoglinAvoidRepellent { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some(r) = m.extra.repellent else { + return false; + }; + // Vec3.atBottomCenterOf. + let avoid = [ + f64::from(r[0]) + 0.5, + f64::from(r[1]), + f64::from(r[2]) + 0.5, + ]; + if m.distance_sqr(Vec3::new(avoid[0], avoid[1], avoid[2])) >= 64.0 { + return false; + } + for _ in 0..10 { + if let Some(p) = m.land_random_pos_away(cx.w, 16, 7, avoid) { + let at = [ + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32, + ]; + m.ai.pending_path = m.create_path_to(cx.w, at, 0); + return m.ai.pending_path.is_some(); + } + } + false + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + !m.ai.nav.is_done() + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + let path = m.ai.pending_path.take(); + m.nav_move_to_path(path, 1.0); + } +} /// Baby hoglins flee what hurts them; adults stand their ground. #[derive(Clone, Debug)] struct BabyPanic(super::goals::Panic); @@ -165,12 +212,45 @@ impl Goal for GoToWantedItem { m.extra.point = None; } } +/// `HoglinSpecificSensor.findNearestRepellent`: the nearest `#hoglin_repellents` +/// block within 8 blocks sideways and 4 up or down. +fn find_repellent(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> { + let tag = w.block_tags.get("minecraft:hoglin_repellents")?; + let at = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + w.nearest_block(at, 8, 4, |_, name| tag.contains(name)) +} +/// The hoglin's repellent memories: the sensor (every 20 ticks), the end of +/// `PACIFIED` (`ints[0]`), a hit ending it (`HoglinAi.wasHurtBy`, `ints[1]` +/// remembers the hit seen) and `BecomePassiveIfMemoryPresent(NEAREST_REPELLENT, 200)`. +fn hoglin_repellent(m: &mut Mob, w: &MobWorld) { + if m.extra.ints[0] > 0 { + m.extra.ints[0] -= 1; + } + if m.ai.last_hurt_by.is_some() && m.ai.last_hurt_by_time != m.extra.ints[1] { + m.extra.ints[1] = m.ai.last_hurt_by_time; + m.extra.ints[0] = 0; + } + if m.age.wrapping_add(m.id) % 20 == 0 { + m.extra.repellent = find_repellent(m, w); + } + if m.extra.ints[0] <= 0 && m.extra.repellent.is_some() { + m.extra.ints[0] = 200; + m.ai.target = None; + } +} /// Per-tick piglin and hoglin state: admiring, anger, zombification and the /// hoglin attack animation. Returns a conversion when it happens. pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { if m.extra.anim_ticks > 0 { m.extra.anim_ticks -= 1; } + if m.species() == Species::Hoglin && m.alive() { + hoglin_repellent(m, w); + } if m.extra.anger > 0 { m.extra.anger -= 1; if m.extra.anger == 0 && m.ai.target == Some(Who::Player) && !hostile_to_player(m, w) { diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs index 7836a49ef..aa665decc 100644 --- a/crates/horizon-client/src/mobs/world.rs +++ b/crates/horizon-client/src/mobs/world.rs @@ -65,6 +65,35 @@ impl MobWorld<'_> { pub fn has_tag(&self, tag: &str, block: &str) -> bool { self.block_tags.get(tag).is_some_and(|s| s.contains(block)) } + /// `findBlocksInBoxByManhattanDistance(at, range_xz, range_y).filterState(..).findFirst()`: + /// the first block `matches` accepts (given its position and name), going + /// out from `at` by Manhattan distance as `BlockPos.withinBoxByManhattanDistance` does. + pub fn nearest_block( + &self, + at: [i32; 3], + range_xz: i32, + range_y: i32, + matches: impl Fn([i32; 3], &str) -> bool, + ) -> Option<[i32; 3]> { + // Visiting order: distance, then x, then y, then +z before -z. + let mut best: Option<((i32, i32, i32, bool), [i32; 3])> = None; + for dx in -range_xz..=range_xz { + for dy in -range_y..=range_y { + for dz in -range_xz..=range_xz { + let key = (dx.abs() + dy.abs() + dz.abs(), dx, dy, dz < 0); + if best.is_some_and(|(k, _)| k <= key) { + continue; + } + let p = [at[0] + dx, at[1] + dy, at[2] + dz]; + let state = self.world.block(p[0], p[1], p[2]); + if !self.facts.is_air(state) && matches(p, &self.facts.get(state).name) { + best = Some((key, p)); + } + } + } + } + best.map(|(_, p)| p) + } /// Level.clip with COLLIDER shapes (optionally stopping at any fluid): true on a miss. pub fn clear_between(&self, from: Vec3, to: Vec3, fluids_block: bool) -> bool { let mut scene = SceneCollisions { From 091a98656ea98e1869b66ab9192075bdbadc4a29 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 14:32:46 +0100 Subject: [PATCH 35/51] Dragon: find healing crystals in its grown box and cap healing at max The search now uses the dragon's 16 by 8 box grown by 32 blocks like EnderDragon.checkCrystals, and healing no longer goes above max health. --- crates/horizon-client/src/game/dragon.rs | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index f28049fd5..4bb7993d3 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -1685,21 +1685,31 @@ impl Game<'_> { .play("minecraft:entity.ender_dragon.growl", Some(at), 2.5, pitch); } } - // checkCrystals: heal 1 every 10 ticks from the nearest crystal within 32. + // checkCrystals: heal 1 every 10 ticks from the nearest crystal, found + // among those touching the dragon's box grown by 32. let d = self.dragon.as_mut().expect("dragon"); if d.nearest_crystal.is_some() && d.ticks % 10 == 0 && d.health < MAX_HEALTH { - d.health += 1.0; + // LivingEntity.setHealth clamps to the maximum. + d.health = (d.health + 1.0).min(MAX_HEALTH); } if d.random.next_int_bound(10).unwrap_or(1) == 0 { let p = d.position; + // The dragon's 16 by 8 box. + let reach = Aabb::new( + Vec3::new(p.x - 8.0, p.y, p.z - 8.0), + Vec3::new(p.x + 8.0, p.y + 8.0, p.z + 8.0), + ) + .inflate(Vec3::new(32.0, 32.0, 32.0)); d.nearest_crystal = self .crystals .iter() .enumerate() .filter(|(_, c)| { - (c.position.x - p.x).abs() <= 32.0 - && (c.position.y - p.y).abs() <= 32.0 - && (c.position.z - p.z).abs() <= 32.0 + // An end crystal's 2 by 2 box. + reach.intersects(Aabb::new( + Vec3::new(c.position.x - 1.0, c.position.y, c.position.z - 1.0), + Vec3::new(c.position.x + 1.0, c.position.y + 2.0, c.position.z + 1.0), + )) }) .min_by(|a, b| { let da = (a.1.position.x - p.x).powi(2) From 6e0a49029fb4b28465bf8256bed71e44448643e3 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:39:51 +0000 Subject: [PATCH 36/51] Keep block-breaking cracks aligned between stages Restore integer atlas origins and sample local texel centers before nearest filtering. Cover the packed stage origins with a GPU sampling regression. Fixes #1882. Co-Authored-By: Codex GPT-6.1 Sol --- crates/horizon-client/src/entity.wgsl | 13 +- crates/horizon-client/src/gfx.rs | 2 + .../horizon-client/src/gfx/crumbling_tests.rs | 191 ++++++++++++++++++ 3 files changed, 205 insertions(+), 1 deletion(-) create mode 100644 crates/horizon-client/src/gfx/crumbling_tests.rs diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index 2e865dfb1..79e11719f 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -166,12 +166,23 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { if d >= end { return 1.0; } return (d - start) / (end - start); } +// CRUMBLING_UV_BEGIN +fn crumbling_uv(uv: vec2, packed_origin: vec2, sprite_size: vec2, dimensions: vec2) -> vec2 { + let size = vec2(dimensions); + // Undo stage_light's 16-bit quantization before adding local texels. Otherwise + // different stages can fall on opposite sides of a nearest-sampling boundary. + let origin = round(packed_origin * size); + let extent = max(round(sprite_size * size), vec2(1.0)); + let local = min(floor(fract(uv) * extent), extent - vec2(1.0)); + return (origin + local + vec2(0.5)) / size; +} +// CRUMBLING_UV_END @fragment fn fs_entity(in: Out, @builtin(front_facing) front: bool) -> @location(0) vec4 { var uv = in.uv; if in.overlay == 6u { uv.y = in.wrap.x + fract(in.uv.y) * in.wrap.y; } if in.overlay == 11u || in.overlay == 12u { // Each crack's stage sprite origin comes in its light bytes (breaking::stage_light). - uv = in.wrap + fract(in.uv) * globals.crumbling_sprite.zw; + uv = crumbling_uv(in.uv, in.wrap, globals.crumbling_sprite.zw, textureDimensions(atlas)); } var color = textureSample(atlas, atlas_sampler, uv) * select(in.back_color, in.color, front); if in.overlay == 9u || in.overlay == 10u { diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index ca308060b..660bfb2ad 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -32,6 +32,8 @@ fn entity_shader() -> String { crate::overlay::wgsl_constants() + include_str!("entity.wgsl") } +#[cfg(test)] +mod crumbling_tests; mod entity_batch; mod weather; use entity_batch::EntityBatch; diff --git a/crates/horizon-client/src/gfx/crumbling_tests.rs b/crates/horizon-client/src/gfx/crumbling_tests.rs new file mode 100644 index 000000000..620a57cf9 --- /dev/null +++ b/crates/horizon-client/src/gfx/crumbling_tests.rs @@ -0,0 +1,191 @@ +use wgpu::util::DeviceExt; + +/// Sample the production WGSL with the production nearest/no-mipmap atlas sampler. +#[test] +#[ignore = "requires a Vulkan/Metal/DX12 adapter"] +fn crack_samples_stay_aligned_between_stages() { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let adapter = + pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) + .unwrap(); + eprintln!("crack sampling adapter: {:?}", adapter.get_info()); + let (device, queue) = + pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).unwrap(); + #[repr(C)] + #[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] + struct Case { + uv: [f32; 2], + stage: u32, + extent: u32, + } + let mut cases = Vec::new(); + let mut expected = Vec::<[u32; 2]>::new(); + // Include exact texel boundaries, their neighbours, negative projected UVs, + // wrapping and the far sprite edge. Origins straddle the packing error's sign change. + for extent in [16, 32] { + for x in [32, 2080, 4064] { + for y in [0, 32] { + for i in -32..=32 { + for delta in [-0.0001, 0.0, 0.0001] { + let uv = [i as f32 / 16.0 + delta, 0.5 - delta]; + cases.push(Case { + uv, + stage: crate::breaking::stage_light([ + x as f32 / 4096.0, + y as f32 / 64.0, + ]), + extent, + }); + expected.push(uv.map(|v| { + (((v - v.floor()) * extent as f32).floor() as u32).min(extent - 1) + })); + } + } + } + } + } + let math = include_str!("../entity.wgsl") + .split("// CRUMBLING_UV_BEGIN") + .nth(1) + .unwrap() + .split("// CRUMBLING_UV_END") + .next() + .unwrap(); + let source = format!( + "{math}\n{}", + r#" +struct Case { uv: vec2, stage: u32, extent: u32 } +@group(0) @binding(0) var cases: array; +@group(0) @binding(1) var results: array>; +@group(0) @binding(2) var atlas: texture_2d; +@group(0) @binding(3) var atlas_sampler: sampler; +@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3) { + if id.x >= arrayLength(&cases) { return; } + let c = cases[id.x]; + let origin = vec2(f32(c.stage & 65535u), f32(c.stage >> 16u)) / 65535.0; + let dimensions = textureDimensions(atlas); + let uv = crumbling_uv(c.uv, origin, vec2(f32(c.extent)) / vec2(dimensions), dimensions); + // Keep the old addressing as a control: the fixture must reproduce its stage jitter. + let old_uv = origin + fract(c.uv) * vec2(f32(c.extent)) / vec2(dimensions); + results[id.x] = vec4( + vec2(round(textureSampleLevel(atlas, atlas_sampler, uv, 0.0).rg * 255.0)), + vec2(round(textureSampleLevel(atlas, atlas_sampler, old_uv, 0.0).rg * 255.0))); +}"# + ); + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Crack sampling regression"), + source: wgpu::ShaderSource::Wgsl(source.into()), + }); + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: None, + module: &shader, + entry_point: Some("main"), + compilation_options: Default::default(), + cache: None, + }); + // Every sprite repeats the same coordinate pattern, so moving a stage's + // atlas origin must leave every sampled local texel unchanged. + let pixels: Vec = (0..64) + .flat_map(|y| (0..4096).flat_map(move |x| [(x % 32) as u8, (y % 32) as u8, 0, 255])) + .collect(); + let atlas = device.create_texture_with_data( + &queue, + &wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { + width: 4096, + height: 64, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }, + wgpu::util::TextureDataOrder::LayerMajor, + &pixels, + ); + let view = atlas.create_view(&Default::default()); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor::default()); + let input = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: None, + contents: bytemuck::cast_slice(&cases), + usage: wgpu::BufferUsages::STORAGE, + }); + let size = (expected.len() * 16) as u64; + let output = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, + mapped_at_creation: false, + }); + let readback = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &pipeline.get_bind_group_layout(0), + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: input.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: output.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::TextureView(&view), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: wgpu::BindingResource::Sampler(&sampler), + }, + ], + }); + let mut encoder = device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &group, &[]); + pass.dispatch_workgroups((cases.len() as u32).div_ceil(64), 1, 1); + } + encoder.copy_buffer_to_buffer(&output, 0, &readback, 0, size); + queue.submit([encoder.finish()]); + let (tx, rx) = std::sync::mpsc::channel(); + readback.map_async(wgpu::MapMode::Read, .., move |r| tx.send(r).unwrap()); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + rx.recv().unwrap().unwrap(); + let mapped = readback.get_mapped_range(..).unwrap(); + let actual: &[[u32; 4]] = bytemuck::cast_slice(&mapped); + for (i, (actual, expected)) in actual.iter().zip(&expected).enumerate() { + assert_eq!( + &actual[..2], + expected, + "case {i}, uv={:?}, stage={}, extent={}", + cases[i].uv, + cases[i].stage, + cases[i].extent + ); + } + let old_mismatches = actual + .iter() + .zip(&expected) + .filter(|(a, e)| &a[2..] != e.as_slice()) + .count(); + assert!( + old_mismatches > 0, + "fixture must detect the original sampling bug" + ); + eprintln!( + "{} crack texture samples matched; old addressing mismatched {old_mismatches}", + cases.len() + ); +} From f0d2a2ae741f0319ff66e7e04cfb5dfdb13c2f54 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:02:43 +0100 Subject: [PATCH 37/51] Satisfy clippy --- crates/horizon-client/src/mobs/piglin.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/horizon-client/src/mobs/piglin.rs b/crates/horizon-client/src/mobs/piglin.rs index 155d53d2f..6bf0aa096 100644 --- a/crates/horizon-client/src/mobs/piglin.rs +++ b/crates/horizon-client/src/mobs/piglin.rs @@ -234,7 +234,7 @@ fn hoglin_repellent(m: &mut Mob, w: &MobWorld) { m.extra.ints[1] = m.ai.last_hurt_by_time; m.extra.ints[0] = 0; } - if m.age.wrapping_add(m.id) % 20 == 0 { + if m.age.wrapping_add(m.id).is_multiple_of(20) { m.extra.repellent = find_repellent(m, w); } if m.extra.ints[0] <= 0 && m.extra.repellent.is_some() { From 48811b12f1fc3146e74b7b45f01e6e92ae3a5ab2 Mon Sep 17 00:00:00 2001 From: socksprox Date: Mon, 26 Oct 2026 14:54:31 +0100 Subject: [PATCH 38/51] Pistons animate their moves on the clients, as Java's do A remote client (single player's window on its server thread, a LAN guest, a dedicated server's client) never ran the client side of a piston's move: the block event reached block_entity_event, which has no piston ticker, so moving_piston blocks arrived with no moving block entity and pushed blocks teleported (#1704). Vanilla's runBlockEvents broadcasts a handled event to the clients, whose own level re-runs triggerEvent (PistonBaseBlock.moveBlocks) to build the PistonMovingBlockEntity it then ticks and renders interpolated. Do the same: - run_block_events emits a BlockEntityEvent for a handled event; the LAN and integrated hubs send it as ClientboundBlockEventPacket, before the tick's block changes, as vanilla's broadcast precedes ChunkHolder.broadcastChanges. - The remote client re-runs triggerEvent for pistons, note blocks and bells on its own level (dropResources stays server-side, as popResource checks !isClientSide), and ticks the resulting moving pistons each client tick so they animate and collide between the server's states. Block events a client-side move queues run right away, as ClientLevel.blockEvent does. Note blocks and bell rings reach the guests through the same packet, which they did not get before. Co-Authored-By: Devin --- crates/horizon-client/src/game.rs | 14 +- crates/horizon-client/src/game/lan.rs | 41 ++++-- crates/horizon-client/src/game/remote.rs | 41 ++++-- crates/horizon-world/src/level/mod.rs | 5 + crates/horizon-world/src/level/pistons.rs | 150 +++++++++++++++++++--- crates/horizon-world/src/level/tests.rs | 62 +++++++++ 6 files changed, 274 insertions(+), 39 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a29b497ce..834bcfbe1 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -563,6 +563,9 @@ struct GameLevel<'w> { random_tick_sections: &'w mut horizon_client::random_tick_sections::RandomTickSections, /// Players with each chest open (a trapped chest's signal). lid_openers: &'w HashMap<(i32, i32, i32), i32>, + /// `Level.isClientSide`: a client's copy of the level (a guest of a LAN + /// world, a window on its server thread, a dedicated server's client). + client_side: bool, } struct PlayerCollision { y: f64, @@ -652,6 +655,9 @@ impl GameLevel<'_> { } } impl LevelAccess for GameLevel<'_> { + fn is_client_side(&self) -> bool { + self.client_side + } fn world_surface(&self, x: i32, z: i32) -> i32 { self.world.world_surface(x, z, |s| self.facts.is_air(s)) } @@ -855,7 +861,12 @@ impl LevelAccess for GameLevel<'_> { fn emit(&mut self, event: LevelEvent) { match event { // Block.dropResources draws its loot and spots right away. - LevelEvent::DropResources { pos, state } => self.drop_resources_now(pos, state), + // `popResource` only drops server-side (`!level.isClientSide`): + // a client's moveBlocks (a piston's block event) skips it. + LevelEvent::DropResources { pos, state } if !self.client_side => { + self.drop_resources_now(pos, state) + } + LevelEvent::DropResources { .. } => {} // Block.popResource of the block's own item (tall flowers, flower beds). LevelEvent::BlockEvent { pos, @@ -2492,6 +2503,7 @@ impl Game<'_> { tickets: self.tickets.levels(), random_tick_sections: &mut self.random_tick_sections, lid_openers: &self.lid_openers, + client_side: self.remote.is_some(), }; let result = f(self.res.behaviours(), &mut level, &mut self.block_ticks); self.flush_spill(); diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 9f468db9f..c65a2bd8e 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -923,6 +923,13 @@ impl Game<'_> { for m in &mut self.mobs { m.needs_sync = false; } + // `runBlockEvents`' broadcast precedes the tick's block changes + // (`ChunkHolder.broadcastChanges` in `tick_level` below): the + // guest re-runs a piston's `triggerEvent` while its level still + // has the blocks as they were before the move. + for (pos, b0, b1, state) in std::mem::take(&mut self.lan_block_events) { + host.hub.block_event(pos, b0, b1, state); + } let entities = states.as_slice(); let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]); let events = { @@ -1156,17 +1163,29 @@ impl Game<'_> { return; } for e in events { - if let horizon_world::level::LevelEvent::LevelEvent { id, pos, data } = e { - // The acting guest does not predict the egg's teleport - // particles, bone meal's growth, or anvil result sounds - // (these levelEvent calls name no excluded player). - let except = if matches!(*id, 2015 | 1505 | 1029 | 1030) { - None - } else { - self.lan_acting - }; - self.lan_events - .push((*id, [pos.x, pos.y, pos.z], *data, except)); + match e { + horizon_world::level::LevelEvent::LevelEvent { id, pos, data } => { + // The acting guest does not predict the egg's teleport + // particles, bone meal's growth, or anvil result sounds + // (these levelEvent calls name no excluded player). + let except = if matches!(*id, 2015 | 1505 | 1029 | 1030) { + None + } else { + self.lan_acting + }; + self.lan_events + .push((*id, [pos.x, pos.y, pos.z], *data, except)); + } + // `ServerLevel.runBlockEvents` broadcasts a handled block + // event (`ClientboundBlockEventPacket`): the guest re-runs + // the block's `triggerEvent` — a piston's `moveBlocks` is + // what animates the move there. `state` is the block the + // event named, read before it ran (the packet's `block`). + horizon_world::level::LevelEvent::BlockEntityEvent { pos, state, a, b } => { + self.lan_block_events + .push(([pos.x, pos.y, pos.z], *a, *b, state.0)); + } + _ => {} } } } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 857f955da..637e0c542 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1664,19 +1664,30 @@ impl Game<'_> { } } C::BlockChangedAck(p) => self.end_predictions(p.sequence), - // ClientLevel.blockEvent: BlockEntity.triggerEvent (chest lids, - // shulker boxes, bells) when the block is still the one it names. + // Level.blockEvent on the client level: the block's triggerEvent + // runs on the client's copy of whatever is at pos (a piston's + // moveBlocks builds the moving block entities it animates, a note + // block plays); what it doesn't handle reaches the client copy of + // the block entity (chest lids, shulker boxes). C::BlockEvent(p) => { - let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]); - let block = &self.res.facts().get(state).name; - let named = self.remote.as_ref().and_then(|r| { - r.builtin - .get("minecraft:block")? - .name(p.block) - .map(str::to_owned) + let pos = horizon_core::position::BlockPos::new(p.pos[0], p.pos[1], p.pos[2]); + let triggered = self.with_level(|b, level, ticks| { + b.client_block_event(level, ticks, pos, i32::from(p.b0), i32::from(p.b1)) }); - if named.as_deref() == Some(&**block) { - self.block_entity_event(p.pos, i32::from(p.b0), i32::from(p.b1)); + self.sync_moving_pistons(); + self.process_level_events()?; + if !triggered { + let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]); + let block = &self.res.facts().get(state).name; + let named = self.remote.as_ref().and_then(|r| { + r.builtin + .get("minecraft:block")? + .name(p.block) + .map(str::to_owned) + }); + if named.as_deref() == Some(&**block) { + self.block_entity_event(p.pos, i32::from(p.b0), i32::from(p.b1)); + } } } // ClientLevel.levelEvent: LevelEventHandler, as this client's own @@ -3108,8 +3119,14 @@ impl Game<'_> { self.border.tick(); self.player_border(); self.tick_remote_entities(running); - // ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells. + // ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells, + // and the moving pistons a block event's client-side moveBlocks made + // (their progress advances between the server's block updates). self.tick_block_entity_anims(); + self.with_level(|b, level, ticks| { + b.client_tick_block_entities(level, ticks); + }); + self.sync_moving_pistons(); self.tick_hand(); self.tick_particles(); self.tick_client_ambient(); diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 3831efbd6..d4af6fb9e 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -287,6 +287,11 @@ pub enum LevelEvent { /// The world as seen by block behaviour. Implemented by the game and tests. pub trait LevelAccess { + /// `Level.isClientSide`: this level is a client's copy (false on a + /// server, a host or the test harness). + fn is_client_side(&self) -> bool { + false + } /// `getBlockState`. Unloaded or out-of-bounds positions read as air. fn block_state(&self, pos: BlockPos) -> BlockStateId; /// Storage write (`LevelChunkSection.setBlockState`). Returns the previous diff --git a/crates/horizon-world/src/level/pistons.rs b/crates/horizon-world/src/level/pistons.rs index 648d6d543..5a34433e1 100644 --- a/crates/horizon-world/src/level/pistons.rs +++ b/crates/horizon-world/src/level/pistons.rs @@ -27,6 +27,9 @@ pub struct MovingPiston { pub progress: f32, pub progress_o: f32, pub last_ticked: i64, + /// `PistonMovingBlockEntity.deathTicks`: on a client the entity waits + /// five ticks past progress 1.0 before placing the block itself. + pub death_ticks: i32, /// Identity of this block entity (a replaced entity is a new ticker). pub id: u64, } @@ -126,11 +129,8 @@ impl Sim<'_, L> { self.note_trigger_event(pos, state); true } else if data.is(super::classes::Class::Bell) { - // BellBlockEntity.triggerEvent handles event 1; the server - // broadcasts handled events to the clients. - if a == 1 { - self.emit(LevelEvent::BlockEntityEvent { pos, state, a, b }); - } + // BellBlockEntity.triggerEvent handles event 1; the caller + // reports handled events (`runBlockEvents` broadcasts them). a == 1 } else { false @@ -164,7 +164,9 @@ impl Sim<'_, L> { let Some(piston) = self.moving_piston(pos) else { return; }; - if piston.progress_o >= 1.0 { + // finalTick: `progressO < 1.0 || level.isClientSide` — a client + // finishes its copy even at full progress. + if piston.progress_o >= 1.0 && !self.level.is_client_side() { return; } self.remove_moving_piston(pos); @@ -189,6 +191,20 @@ impl Sim<'_, L> { piston.last_ticked = self.level.game_time(); piston.progress_o = piston.progress; if piston.progress_o >= 1.0 { + if self.level.is_client_side() && piston.death_ticks < 5 { + // The client's copy waits for the server's state before + // placing the block itself (deathTicks < 5). + piston.death_ticks += 1; + if let Some(entry) = self + .ticks + .moving_pistons + .iter_mut() + .find(|(p, _)| *p == pos) + { + entry.1 = piston; + } + return; + } self.remove_moving_piston(pos); if b.is_block(self.state(pos), b.named.moving_piston) { let mut new = self.update_from_neighbour_shapes(piston.moved_state, pos); @@ -527,6 +543,12 @@ impl Sim<'_, L> { for pos in to_destroy.iter().rev() { let state = self.state(*pos); self.drop_resources(state, *pos); + // The client's copy plays the destroy effect itself (the + // server sends no 2001 for piston moves). + let fire = b.is_block(state, b.named.fire) || b.is_block(state, b.named.soul_fire); + if !fire && self.level.is_client_side() { + self.level_event(2001, *pos, state.0 as i32); + } self.set_block(*pos, b.air(), 18); self.game_event(*pos, "minecraft:block_destroy"); to_update.push(state); @@ -551,6 +573,7 @@ impl Sim<'_, L> { progress: 0.0, progress_o: 0.0, last_ticked: 0, + death_ticks: 0, id: 0, }, ); @@ -576,6 +599,7 @@ impl Sim<'_, L> { progress: 0.0, progress_o: 0.0, last_ticked: 0, + death_ticks: 0, id: 0, }, ); @@ -624,13 +648,17 @@ impl Sim<'_, L> { let direction = b.facing(state); let extended_state = b.table.set_bool(state, p.extended, true); let sticky = self.is_sticky_piston(state); - let extend = self.piston_neighbor_signal(pos, direction); - if extend && (a == 1 || a == 2) { - self.set_block(pos, extended_state, 2); - return false; - } - if !extend && a == 0 { - return false; + // The signal re-check is server-only (`!level.isClientSide`): a + // client trusts the event as sent. + if !self.level.is_client_side() { + let extend = self.piston_neighbor_signal(pos, direction); + if extend && (a == 1 || a == 2) { + self.set_block(pos, extended_state, 2); + return false; + } + if !extend && a == 0 { + return false; + } } if a == 0 { if !self.piston_move_blocks(pos, direction, true, sticky) { @@ -664,6 +692,7 @@ impl Sim<'_, L> { progress: 0.0, progress_o: 0.0, last_ticked: 0, + death_ticks: 0, id: 0, }, ); @@ -748,8 +777,18 @@ impl Behaviours { } let mut sim = self.sim(level, ticks); let state = sim.state(event.pos); - if self.block(state) == event.block { - sim.trigger_event(state, event.pos, event.param_a, event.param_b); + if self.block(state) == event.block + && sim.trigger_event(state, event.pos, event.param_a, event.param_b) + { + // ServerLevel.runBlockEvents broadcasts a handled event to + // the clients (`ClientboundBlockEventPacket`); their copy of + // the block re-runs `triggerEvent` (a piston's `moveBlocks`). + sim.emit(LevelEvent::BlockEntityEvent { + pos: event.pos, + state, + a: event.param_a, + b: event.param_b, + }); } } for event in reschedule { @@ -779,4 +818,85 @@ impl Behaviours { self.sim(level, ticks).moving_piston_tick(pos); } } + /// `ClientLevel.blockEvent`: the client re-runs the block's + /// `triggerEvent` on its own level (a piston's `moveBlocks` builds the + /// moving block entities it then animates) instead of waiting for the + /// server's states. No queue and no ticking-chunk gate: a client runs + /// the event where the packet lands. + pub fn client_block_event( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + a: i32, + b: i32, + ) -> bool { + let triggered = { + let mut sim = self.sim(level, ticks); + let state = sim.state(pos); + let triggered = sim.trigger_event(state, pos, a, b); + if triggered { + // The client's copy of a handled event reaches the client + // copy of the block entity (a bell's ring). + sim.emit(LevelEvent::BlockEntityEvent { pos, state, a, b }); + } + triggered + }; + self.client_drain_block_events(level, ticks); + triggered + } + /// `ClientLevel.tickBlockEntities` for moving pistons: the client copy of + /// [`Behaviours::tick_block_entities`], without the server's + /// ticking-chunk gate (a client ticks every loaded block entity). One + /// whose block was replaced is dropped (`TickingBlockEntity.isRemoved`). + pub fn client_tick_block_entities( + &self, + level: &mut L, + ticks: &mut Ticks, + ) { + let tickers: Vec<(BlockPos, u64)> = ticks + .moving_pistons + .iter() + .map(|(p, m)| (*p, m.id)) + .collect(); + for (pos, id) in tickers { + if !ticks + .moving_pistons + .iter() + .any(|(p, m)| *p == pos && m.id == id) + { + continue; + } + { + let mut sim = self.sim(level, ticks); + let state = sim.state(pos); + if sim.b.is_block(state, sim.b.named.moving_piston) { + sim.moving_piston_tick(pos); + } else { + sim.remove_moving_piston(pos); + } + } + self.client_drain_block_events(level, ticks); + } + } + /// Block events a client-side `triggerEvent` queued + /// (`PistonBaseBlock.checkIfExtend` in a neighbour update): a client + /// runs them as they come (`ClientLevel.blockEvent`), not in a tick pass. + fn client_drain_block_events(&self, level: &mut L, ticks: &mut Ticks) { + while let Some(event) = ticks.block_events.first().copied() { + ticks.block_events.remove(0); + let mut sim = self.sim(level, ticks); + let state = sim.state(event.pos); + if self.block(state) == event.block + && sim.trigger_event(state, event.pos, event.param_a, event.param_b) + { + sim.emit(LevelEvent::BlockEntityEvent { + pos: event.pos, + state, + a: event.param_a, + b: event.param_b, + }); + } + } + } } diff --git a/crates/horizon-world/src/level/tests.rs b/crates/horizon-world/src/level/tests.rs index 8a4b6c34f..4777ec66e 100644 --- a/crates/horizon-world/src/level/tests.rs +++ b/crates/horizon-world/src/level/tests.rs @@ -919,6 +919,68 @@ fn pistons_push_and_sticky_pistons_pull() { assert_eq!(w.get(BlockPos::new(2, 1, 0)), air); } +/// `ServerLevel.runBlockEvents` reports a handled event for the clients +/// (`ClientboundBlockEventPacket`), carrying the block the event named. +#[test] +fn a_handled_block_event_reaches_the_clients() { + let mut w = world!(); + w.floor(0, 10, "stone"); + let piston = w.id("piston", &[("facing", "east")]); + let block = w.id("redstone_block", &[]); + w.set(BlockPos::new(0, 1, 0), piston); + w.set(BlockPos::new(-1, 1, 0), block); + w.level.events.clear(); + w.full_tick(); + assert!(w.level.events.iter().any(|e| matches!( + e, + LevelEvent::BlockEntityEvent { + pos, + state, + a: 0, + .. + } if *pos == BlockPos::new(0, 1, 0) && *state == piston + ))); +} + +/// `ClientLevel.blockEvent`: the client re-runs `triggerEvent` on its own +/// level, which builds the moving block entities a piston's `moveBlocks` +/// makes, and ticks them to the placed block. +#[test] +fn a_client_replays_a_pistons_block_event() { + let mut w = world!(); + w.floor(0, 10, "stone"); + let piston = w.id("sticky_piston", &[("facing", "east")]); + let dirt = w.id("dirt", &[]); + let block = w.id("redstone_block", &[]); + w.put(BlockPos::new(0, 1, 0), piston); + w.put(BlockPos::new(1, 1, 0), dirt); + w.put(BlockPos::new(-1, 1, 0), block); + w.f.behaviours.client_block_event( + &mut w.level, + &mut w.ticks, + BlockPos::new(0, 1, 0), + 0, + Direction::East as i32, + ); + assert!( + w.ticks + .moving_pistons + .iter() + .any(|(p, _)| *p == BlockPos::new(2, 1, 0)) + ); + for _ in 0..3 { + w.level.time += 1; + w.f.behaviours + .client_tick_block_entities(&mut w.level, &mut w.ticks); + } + assert_eq!(w.get(BlockPos::new(2, 1, 0)), dirt); + assert_eq!( + w.name(BlockPos::new(1, 1, 0)), + "piston_head[facing=east,short=false,type=sticky]" + ); + assert!(w.ticks.moving_pistons.is_empty()); +} + #[test] fn pistons_pop_fragile_blocks_and_refuse_obsidian() { let mut w = world!(); From 545370b02370e6eab59fe6640d529f7a15379315 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:41:11 +0100 Subject: [PATCH 39/51] Key binds: press a shared default key once --- crates/horizon-client/src/keybinds.rs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/keybinds.rs b/crates/horizon-client/src/keybinds.rs index 99eb5a15a..7575fb953 100644 --- a/crates/horizon-client/src/keybinds.rs +++ b/crates/horizon-client/src/keybinds.rs @@ -275,6 +275,20 @@ impl Default for KeyBinds { } } } +/// Each default key once, in order: two mappings that share a default key +/// (Advancements and the debug profiler both on L) are one press of it, not +/// two (the second would close the screen the first opened). Vanilla clicks +/// both mappings, but the profiler one only acts with F3 held. +fn distinct(keys: Vec) -> Vec { + let mut out = Vec::with_capacity(keys.len()); + for k in keys { + if !out.contains(&k) { + out.push(k); + } + } + out +} + impl KeyBinds { pub fn get(&self, name: &str) -> &str { self.keys @@ -356,7 +370,7 @@ impl KeyBinds { }) .collect(); if !bound.is_empty() { - return bound; + return distinct(bound); } // An unbound key whose default meaning was moved elsewhere is inert. if MAPPINGS @@ -385,7 +399,7 @@ impl KeyBinds { }) .collect(); if !bound.is_empty() { - return bound; + return distinct(bound); } if MAPPINGS .iter() From 2394d6e7dc1ee0bcbf59c94fa9a37e7f3bf910f9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:14:21 +0100 Subject: [PATCH 40/51] Pistons: a client's replay starts no piston and plays no sound A client's copy of a block event (`client_block_event`) ran the server's neighbour logic: a block it moved could start another piston on the client alone (`PistonBaseBlock.checkIfExtend` is only called server-side), and the re-run's `playSound(null, ...)` played the piston and note sounds a second time next to the server's (`ClientLevel.playSeededSound` plays only for the local player as the excluded one). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 4 +++ crates/horizon-world/src/level/pistons.rs | 7 ++++- crates/horizon-world/src/level/tests.rs | 38 +++++++++++++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 834bcfbe1..efc225d50 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -867,6 +867,10 @@ impl LevelAccess for GameLevel<'_> { self.drop_resources_now(pos, state) } LevelEvent::DropResources { .. } => {} + // `ClientLevel.playSeededSound` plays only when the excluded + // player is this client's own: the block's `playSound(null, ...)` + // (a piston's move, a note) reaches it from the server instead. + LevelEvent::Sound { .. } if self.client_side => {} // Block.popResource of the block's own item (tall flowers, flower beds). LevelEvent::BlockEvent { pos, diff --git a/crates/horizon-world/src/level/pistons.rs b/crates/horizon-world/src/level/pistons.rs index 5a34433e1..45e469efd 100644 --- a/crates/horizon-world/src/level/pistons.rs +++ b/crates/horizon-world/src/level/pistons.rs @@ -257,8 +257,13 @@ impl Sim<'_, L> { direction != Direction::Down && self.has_signal(rel(up, direction), direction) }) } - /// `PistonBaseBlock.checkIfExtend`. + /// `PistonBaseBlock.checkIfExtend`, which `neighborChanged`, `onPlace` + /// and `setPlacedBy` call only server-side: a client moves its pistons on + /// the server's block events alone. pub(crate) fn piston_check_if_extend(&mut self, pos: BlockPos, state: BlockStateId) { + if self.level.is_client_side() { + return; + } let b = self.b; let direction = b.facing(state); let extend = self.piston_neighbor_signal(pos, direction); diff --git a/crates/horizon-world/src/level/tests.rs b/crates/horizon-world/src/level/tests.rs index 4777ec66e..da75083d2 100644 --- a/crates/horizon-world/src/level/tests.rs +++ b/crates/horizon-world/src/level/tests.rs @@ -47,6 +47,8 @@ pub(crate) struct TestLevel { pub day_time: i64, pub events: Vec, pub block_light: HashMap, + /// `Level.isClientSide`. + pub client_side: bool, } impl TestLevel { fn new(b: &Behaviours) -> Self { @@ -58,10 +60,14 @@ impl TestLevel { day_time: 0, events: Vec::new(), block_light: HashMap::new(), + client_side: false, } } } impl LevelAccess for TestLevel { + fn is_client_side(&self) -> bool { + self.client_side + } fn block_state(&self, pos: BlockPos) -> BlockStateId { self.blocks.get(&pos).copied().unwrap_or(self.air) } @@ -981,6 +987,38 @@ fn a_client_replays_a_pistons_block_event() { assert!(w.ticks.moving_pistons.is_empty()); } +/// A client's copy of a move doesn't start the pistons the moved block +/// powers (`checkIfExtend` is server-only): their own block events come from +/// the server. +#[test] +fn a_client_replay_starts_no_other_piston() { + let mut w = world!(); + w.floor(0, 10, "stone"); + w.level.client_side = true; + let piston = w.id("piston", &[("facing", "east")]); + let block = w.id("redstone_block", &[]); + let up = w.id("piston", &[("facing", "up")]); + w.put(BlockPos::new(0, 1, 0), piston); + w.put(BlockPos::new(1, 1, 0), block); + w.put(BlockPos::new(2, 2, 0), up); + w.f.behaviours.client_block_event( + &mut w.level, + &mut w.ticks, + BlockPos::new(0, 1, 0), + 0, + Direction::East as i32, + ); + for _ in 0..10 { + w.level.time += 1; + w.f.behaviours + .client_tick_block_entities(&mut w.level, &mut w.ticks); + } + assert_eq!(w.get(BlockPos::new(2, 1, 0)), block); + assert_eq!(w.get(BlockPos::new(2, 2, 0)), up); + assert!(w.ticks.moving_pistons.is_empty()); + assert!(w.ticks.block_events.is_empty()); +} + #[test] fn pistons_pop_fragile_blocks_and_refuse_obsidian() { let mut w = world!(); From 68aa70108f3c757bcef066c473645533d7e1d656 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:23:05 +0100 Subject: [PATCH 41/51] Piglin AI: name the hoglin repellent finder for its mob #2191 and #2192 each add a `find_repellent` to piglin.rs, one for hoglins and one for piglins; merged together they would collide. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/mobs/piglin.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/mobs/piglin.rs b/crates/horizon-client/src/mobs/piglin.rs index 6bf0aa096..fff536932 100644 --- a/crates/horizon-client/src/mobs/piglin.rs +++ b/crates/horizon-client/src/mobs/piglin.rs @@ -214,7 +214,7 @@ impl Goal for GoToWantedItem { } /// `HoglinSpecificSensor.findNearestRepellent`: the nearest `#hoglin_repellents` /// block within 8 blocks sideways and 4 up or down. -fn find_repellent(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> { +fn find_hoglin_repellent(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> { let tag = w.block_tags.get("minecraft:hoglin_repellents")?; let at = [ m.position.x.floor() as i32, @@ -235,7 +235,7 @@ fn hoglin_repellent(m: &mut Mob, w: &MobWorld) { m.extra.ints[0] = 0; } if m.age.wrapping_add(m.id).is_multiple_of(20) { - m.extra.repellent = find_repellent(m, w); + m.extra.repellent = find_hoglin_repellent(m, w); } if m.extra.ints[0] <= 0 && m.extra.repellent.is_some() { m.extra.ints[0] = 200; From dbbe3a45d97da62cca77f2810bc5013e493c8b7b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:29:09 +0100 Subject: [PATCH 42/51] CI: check the launcher's workspace on every push to main and on pull requests that touch it verify's cargo runs never build launcher/ (its own workspace), so #2059 and the registry ratings commit each passed alone and left main's launcher failing to compile (E0061). The new launcher job runs its rustfmt, clippy -D warnings and lib tests when a pull request changes the launcher, a crate it builds or the root manifests, and on every push to main. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 36 +++++++++++++++++++++++++++++++++++ tests/test_ci_rust_changes.py | 13 ++++++++++++- tools/ci/rust_changes.py | 27 ++++++++++++++++++++++++-- 3 files changed, 73 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index eff82fa99..39ea920da 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -73,6 +73,42 @@ jobs: run: | cargo +stable test --workspace --lib --bins --tests --features horizon-client/mods,horizon-mods/pack cargo +stable test --workspace --doc --features horizon-client/mods,horizon-mods/pack + # The launcher is its own workspace (launcher/Cargo.toml), so verify's cargo runs never build it. A pull request that + # changes it or a crate it builds is checked here, and so is every push to main: two pull requests can each pass + # alone and break it together (#2059 and the registry ratings did, 2026-10-26). + launcher: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Does this pull request change the launcher or a crate it builds? + if: github.event_name == 'pull_request' + id: launcher + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: python3 tools/ci/rust_changes.py --launcher "$BASE_SHA" "$HEAD_SHA" >> "$GITHUB_OUTPUT" + - name: Install Rust and the headers GPUI links against + if: steps.launcher.outputs.required != 'false' + run: | + sudo apt-get update && sudo apt-get install -y --no-install-recommends libxkbcommon-x11-dev libwayland-dev \ + libx11-xcb-dev libfontconfig-dev libvulkan-dev libasound2-dev libudev-dev + rustup toolchain install stable --profile minimal --component rustfmt --component clippy + - uses: Swatinem/rust-cache@v2 + if: steps.launcher.outputs.required != 'false' + with: + workspaces: launcher + shared-key: launcher + save-if: ${{ github.ref == 'refs/heads/main' }} + - name: Check the launcher's formatting, lint and tests + if: steps.launcher.outputs.required != 'false' + working-directory: launcher + run: | + cargo +stable fmt --check + cargo +stable clippy --all-targets --locked -- -D warnings + cargo +stable test --locked --lib # Most pull requests leave the harnesses to parity-main, which runs them on main a batch of merges at a time # (.github/workflows/parity-main.yml; releases wait for it). A pull request still runs them itself when it changes # a harness, an oracle, a probe or the runner, or carries the run-parity label (run-parity.yml, when it is added). diff --git a/tests/test_ci_rust_changes.py b/tests/test_ci_rust_changes.py index 6fd7621da..6db218b9f 100644 --- a/tests/test_ci_rust_changes.py +++ b/tests/test_ci_rust_changes.py @@ -4,7 +4,7 @@ import subprocess import tempfile import unittest -from tools.ci.rust_changes import changed_paths, needs_rust +from tools.ci.rust_changes import changed_paths, needs_launcher, needs_rust class RustChangesTests(unittest.TestCase): @@ -21,6 +21,17 @@ class RustChangesTests(unittest.TestCase): with self.subTest(path=path): self.assertTrue(needs_rust(["README.md", path])) + def test_launcher_checks_follow_the_crates_it_builds(self): + for path in ["crates/horizon-client/src/game.rs", "launcher/links.json", "launcher/docs/a.md", + "launcher/README.md", "website/src/index.html", "tools/pr_ready.py"]: + with self.subTest(path=path): + self.assertFalse(needs_launcher([path])) + for path in ["launcher/src/main.rs", "launcher/Cargo.lock", "crates/horizon-port-pack/src/net.rs", + "crates/horizon-theme/src/lib.rs", "Cargo.toml", "Cargo.lock", + ".github/workflows/ci.yml"]: + with self.subTest(path=path): + self.assertTrue(needs_launcher(["README.md", path])) + def test_moving_source_into_docs_still_requires_rust(self): with tempfile.TemporaryDirectory() as directory: def git(*args): diff --git a/tools/ci/rust_changes.py b/tools/ci/rust_changes.py index d2bf41713..f856778e9 100644 --- a/tools/ci/rust_changes.py +++ b/tools/ci/rust_changes.py @@ -1,8 +1,21 @@ #!/usr/bin/env python3 -"""Keep verify's Rust steps for any change beyond website content or documentation.""" +"""Keep verify's Rust steps for any change beyond website content or documentation. + +--launcher: whether the change is built into the launcher, its own workspace (release_train.LAUNCHER_PATHS). +""" import argparse import subprocess +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +import release_train # noqa: E402 + +# The root workspace's manifest and toolchain files: the launcher's path crates inherit from them. +ROOT_RUST = {"Cargo.toml", "Cargo.lock", "rust-toolchain.toml", "rustfmt.toml", "clippy.toml"} +# The check itself: a change to it runs it. +LAUNCHER_CHECK = {".github/workflows/ci.yml", "tools/ci/rust_changes.py", "tools/release_train.py"} def needs_rust(paths): @@ -12,6 +25,14 @@ def needs_rust(paths): ) for path in paths) +def needs_launcher(paths): + return any(path in ROOT_RUST or path in LAUNCHER_CHECK or ( + path.startswith(tuple(release_train.LAUNCHER_PATHS)) + and not path.startswith(tuple(release_train.LAUNCHER_IGNORED)) + and not path.endswith(".md") + ) for path in paths) + + def changed_paths(base, head): # Renames must include deletions too: moving source into docs still affects Rust. output = subprocess.check_output([ @@ -24,5 +45,7 @@ if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("base") parser.add_argument("head") + parser.add_argument("--launcher", action="store_true", help="answer for the launcher instead") args = parser.parse_args() - print(f"required={str(needs_rust(changed_paths(args.base, args.head))).lower()}") + needs = needs_launcher if args.launcher else needs_rust + print(f"required={str(needs(changed_paths(args.base, args.head))).lower()}") From 4fe648b674bb46026b7f200a68d228dd7c5378bb Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:39:31 +0100 Subject: [PATCH 43/51] Move the website to its own repository (ludovic111/horizon-site) playhorizon.dev now deploys from the private ludovic111/horizon-site, which holds website/'s history. The files its build still reads from here move out of website/: - the design tokens to crates/horizon-theme/tokens.css (xtask tokens writes them, tokens_css_is_up_to_date checks them); - the roadmap's JSON to roadmap/roadmap.json (tools/roadmap.py build); - the benchmark fixtures to crates/horizon-telemetry-server/tests/fixtures/benchmarks/ (the site keeps a copy); - the web icons to docs/media/brand/web/ (xtask icons). pr_ready loses its website area and the tokens special case; rust_changes, the roadmap's links and every doc that pointed into website/ follow. Co-Authored-By: Claude Opus 5.5 --- .dockerignore | 1 - .gitattributes | 2 +- AGENTS.md | 3 +- CONTRIBUTING.md | 4 +- ROADMAP.md | 12 +- crates/horizon-server/panel/panel.css | 2 +- crates/horizon-telemetry-server/README.md | 2 +- .../horizon-telemetry-server/src/classes.rs | 2 +- .../horizon-telemetry-server/src/summary.rs | 6 +- .../tests}/fixtures/benchmarks/README.md | 5 +- .../tests}/fixtures/benchmarks/expected.json | 0 .../tests}/fixtures/benchmarks/items.jsonl | 0 .../horizon-telemetry-server/tests/summary.rs | 9 +- crates/horizon-theme/src/lib.rs | 16 +- .../src => crates/horizon-theme}/tokens.css | 0 docs/agent-control.md | 2 +- docs/api/README.md | 2 +- docs/design-system.md | 8 +- docs/media/banner.html | 8 +- docs/media/brand/README.md | 9 +- docs/media/brand/social/card.html | 6 +- .../media/brand/web}/apple-touch-icon.png | Bin .../media/brand/web}/favicon-32.png | Bin .../media/brand/web}/favicon.svg | 0 docs/telemetry.md | 2 +- docs/versioning.md | 2 +- launcher/src/backend.rs | 2 +- packaging/macos/background.html | 6 +- roadmap/README.md | 4 +- {website/data => roadmap}/roadmap.json | 12 +- roadmap/roadmap.toml | 12 +- tests/test_ci_rust_changes.py | 4 +- tests/test_pr_ready.py | 2 +- tools/ci/rust_changes.py | 7 +- tools/pr_ready.py | 18 +- tools/roadmap.py | 15 +- website/.gitignore | 3 - website/Caddyfile | 73 -- website/Dockerfile | 20 - website/LEGAL.md | 88 -- website/README.md | 153 --- website/build.mjs | 554 ----------- .../desktop/horizon-desktop-rd12.json | 774 --------------- .../desktop/horizon-desktop-rd32.json | 774 --------------- .../desktop/vanilla-desktop-rd12.json | 723 -------------- .../desktop/vanilla-desktop-rd32.json | 723 -------------- website/data/benchmarks/fleet.json | 73 -- .../macmini/horizon-macmini-rd12.json | 758 -------------- .../macmini/horizon-macmini-rd32.json | 758 -------------- .../macmini/vanilla-macmini-rd12.json | 707 ------------- .../macmini/vanilla-macmini-rd32.json | 707 ------------- .../thinkpad/horizon-thinkpad-rd12.json | 606 ----------- .../thinkpad/vanilla-thinkpad-r1-rd12.json | 371 ------- .../thinkpad/vanilla-thinkpad-r2-rd12.json | 371 ------- website/docs/agents.md | 126 --- website/docs/apis.md | 34 - website/docs/content-mods.md | 124 --- website/docs/contributing.md | 56 -- website/docs/faq.md | 75 -- website/docs/hosting.md | 162 --- website/docs/how-horizon-is-built.md | 39 - website/docs/index.md | 34 - website/docs/install.md | 52 - website/docs/make-a-mod.md | 88 -- website/docs/mod-code.md | 190 ---- website/docs/mod-manifest.md | 60 -- website/docs/modpacks.md | 52 - website/docs/mods.md | 64 -- website/docs/multiplayer.md | 43 - website/docs/nav.json | 10 - website/docs/performance.md | 74 -- website/docs/publish-a-mod.md | 57 -- website/docs/settings.md | 70 -- website/docs/test-a-mod.md | 59 -- website/docs/troubleshooting.md | 55 - website/package-lock.json | 642 ------------ website/package.json | 19 - website/public/benchmarks.json | 523 ---------- website/public/fonts/Geist-Medium.woff2 | Bin 46512 -> 0 bytes website/public/fonts/Geist-Regular.woff2 | Bin 45288 -> 0 bytes website/public/fonts/Geist-SemiBold.woff2 | Bin 46508 -> 0 bytes website/public/fonts/GeistMono-Regular.woff2 | Bin 50408 -> 0 bytes website/public/fonts/OFL-Geist.txt | 93 -- website/public/fonts/OFL-PixelifySans.txt | 93 -- website/public/fonts/PixelifySans-Bold.woff2 | Bin 27276 -> 0 bytes .../public/fonts/PixelifySans-Medium.woff2 | Bin 27308 -> 0 bytes .../public/fonts/PixelifySans-SemiBold.woff2 | Bin 27796 -> 0 bytes .../public/media/docs/servers-backups.webp | Bin 26474 -> 0 bytes website/public/media/docs/servers-create.webp | Bin 23592 -> 0 bytes .../public/media/docs/servers-dashboard.webp | Bin 35428 -> 0 bytes website/public/media/docs/servers-invite.webp | Bin 40448 -> 0 bytes website/public/media/launcher-800.webp | Bin 9498 -> 0 bytes website/public/media/launcher.webp | Bin 18696 -> 0 bytes website/public/media/nether-800.webp | Bin 31114 -> 0 bytes website/public/media/nether.webp | Bin 115484 -> 0 bytes website/public/media/night-800.webp | Bin 9182 -> 0 bytes website/public/media/night.webp | Bin 36558 -> 0 bytes website/public/media/scene-dark.png | Bin 757 -> 0 bytes website/public/media/scene-light.png | Bin 758 -> 0 bytes website/public/media/settings-800.webp | Bin 20210 -> 0 bytes website/public/media/settings.webp | Bin 40646 -> 0 bytes website/public/media/stone-dark.png | Bin 1400 -> 0 bytes website/public/media/stone-light.png | Bin 1413 -> 0 bytes website/public/media/sunset-800.webp | Bin 20878 -> 0 bytes website/public/media/sunset.webp | Bin 78340 -> 0 bytes website/public/media/survival-800.webp | Bin 19912 -> 0 bytes website/public/media/survival.webp | Bin 71260 -> 0 bytes website/public/media/underwater-800.webp | Bin 19864 -> 0 bytes website/public/media/underwater.webp | Bin 75120 -> 0 bytes website/public/media/village-800.webp | Bin 48818 -> 0 bytes website/public/media/village.webp | Bin 219600 -> 0 bytes website/public/og.html | 30 - website/public/og.png | Bin 50427 -> 0 bytes website/public/robots.txt | 4 - website/railway.json | 14 - website/scripts/art.mjs | 151 --- website/scripts/assets.mjs | 60 -- website/scripts/benchmarks.mjs | 240 ----- website/scripts/benchmarks.test.mjs | 91 -- website/scripts/shots.mjs | 99 -- website/serve.mjs | 42 - website/src/404.html | 27 - website/src/bench.js | 167 ---- website/src/benchmarks-page.js | 108 -- website/src/benchmarks.html | 105 -- website/src/chrome.js | 90 -- website/src/contributors.js | 39 - website/src/docs-page.js | 5 - website/src/docs.html | 55 - website/src/estimate.js | 110 -- website/src/estimate.test.mjs | 101 -- website/src/hardware.js | 88 -- website/src/hub-page.js | 270 ----- website/src/hub.html | 170 ---- website/src/hub.js | 457 --------- website/src/hub.test.mjs | 159 --- website/src/index.html | 216 ---- website/src/main.js | 265 ----- website/src/markdown.js | 203 ---- website/src/markdown.test.mjs | 25 - website/src/mods-page.js | 146 --- website/src/mods-submit.js | 80 -- website/src/mods.html | 37 - website/src/mods.js | 249 ----- website/src/mods.test.mjs | 110 -- website/src/privacy.html | 72 -- website/src/releases-page.js | 78 -- website/src/releases.html | 49 - website/src/releases.js | 156 --- website/src/releases.test.mjs | 13 - website/src/style.css | 937 ------------------ website/src/versions.js | 59 -- website/src/versions.test.mjs | 21 - xtask/src/main.rs | 14 +- 154 files changed, 97 insertions(+), 16630 deletions(-) rename {website/scripts => crates/horizon-telemetry-server/tests}/fixtures/benchmarks/README.md (72%) rename {website/scripts => crates/horizon-telemetry-server/tests}/fixtures/benchmarks/expected.json (100%) rename {website/scripts => crates/horizon-telemetry-server/tests}/fixtures/benchmarks/items.jsonl (100%) rename {website/src => crates/horizon-theme}/tokens.css (100%) rename {website/public => docs/media/brand/web}/apple-touch-icon.png (100%) rename {website/public => docs/media/brand/web}/favicon-32.png (100%) rename {website/public => docs/media/brand/web}/favicon.svg (100%) rename {website/data => roadmap}/roadmap.json (99%) delete mode 100644 website/.gitignore delete mode 100644 website/Caddyfile delete mode 100644 website/Dockerfile delete mode 100644 website/LEGAL.md delete mode 100644 website/README.md delete mode 100644 website/build.mjs delete mode 100644 website/data/benchmarks/desktop/horizon-desktop-rd12.json delete mode 100644 website/data/benchmarks/desktop/horizon-desktop-rd32.json delete mode 100644 website/data/benchmarks/desktop/vanilla-desktop-rd12.json delete mode 100644 website/data/benchmarks/desktop/vanilla-desktop-rd32.json delete mode 100644 website/data/benchmarks/fleet.json delete mode 100644 website/data/benchmarks/macmini/horizon-macmini-rd12.json delete mode 100644 website/data/benchmarks/macmini/horizon-macmini-rd32.json delete mode 100644 website/data/benchmarks/macmini/vanilla-macmini-rd12.json delete mode 100644 website/data/benchmarks/macmini/vanilla-macmini-rd32.json delete mode 100644 website/data/benchmarks/thinkpad/horizon-thinkpad-rd12.json delete mode 100644 website/data/benchmarks/thinkpad/vanilla-thinkpad-r1-rd12.json delete mode 100644 website/data/benchmarks/thinkpad/vanilla-thinkpad-r2-rd12.json delete mode 100644 website/docs/agents.md delete mode 100644 website/docs/apis.md delete mode 100644 website/docs/content-mods.md delete mode 100644 website/docs/contributing.md delete mode 100644 website/docs/faq.md delete mode 100644 website/docs/hosting.md delete mode 100644 website/docs/how-horizon-is-built.md delete mode 100644 website/docs/index.md delete mode 100644 website/docs/install.md delete mode 100644 website/docs/make-a-mod.md delete mode 100644 website/docs/mod-code.md delete mode 100644 website/docs/mod-manifest.md delete mode 100644 website/docs/modpacks.md delete mode 100644 website/docs/mods.md delete mode 100644 website/docs/multiplayer.md delete mode 100644 website/docs/nav.json delete mode 100644 website/docs/performance.md delete mode 100644 website/docs/publish-a-mod.md delete mode 100644 website/docs/settings.md delete mode 100644 website/docs/test-a-mod.md delete mode 100644 website/docs/troubleshooting.md delete mode 100644 website/package-lock.json delete mode 100644 website/package.json delete mode 100644 website/public/benchmarks.json delete mode 100644 website/public/fonts/Geist-Medium.woff2 delete mode 100644 website/public/fonts/Geist-Regular.woff2 delete mode 100644 website/public/fonts/Geist-SemiBold.woff2 delete mode 100644 website/public/fonts/GeistMono-Regular.woff2 delete mode 100644 website/public/fonts/OFL-Geist.txt delete mode 100644 website/public/fonts/OFL-PixelifySans.txt delete mode 100644 website/public/fonts/PixelifySans-Bold.woff2 delete mode 100644 website/public/fonts/PixelifySans-Medium.woff2 delete mode 100644 website/public/fonts/PixelifySans-SemiBold.woff2 delete mode 100644 website/public/media/docs/servers-backups.webp delete mode 100644 website/public/media/docs/servers-create.webp delete mode 100644 website/public/media/docs/servers-dashboard.webp delete mode 100644 website/public/media/docs/servers-invite.webp delete mode 100644 website/public/media/launcher-800.webp delete mode 100644 website/public/media/launcher.webp delete mode 100644 website/public/media/nether-800.webp delete mode 100644 website/public/media/nether.webp delete mode 100644 website/public/media/night-800.webp delete mode 100644 website/public/media/night.webp delete mode 100644 website/public/media/scene-dark.png delete mode 100644 website/public/media/scene-light.png delete mode 100644 website/public/media/settings-800.webp delete mode 100644 website/public/media/settings.webp delete mode 100644 website/public/media/stone-dark.png delete mode 100644 website/public/media/stone-light.png delete mode 100644 website/public/media/sunset-800.webp delete mode 100644 website/public/media/sunset.webp delete mode 100644 website/public/media/survival-800.webp delete mode 100644 website/public/media/survival.webp delete mode 100644 website/public/media/underwater-800.webp delete mode 100644 website/public/media/underwater.webp delete mode 100644 website/public/media/village-800.webp delete mode 100644 website/public/media/village.webp delete mode 100644 website/public/og.html delete mode 100644 website/public/og.png delete mode 100644 website/public/robots.txt delete mode 100644 website/railway.json delete mode 100644 website/scripts/art.mjs delete mode 100644 website/scripts/assets.mjs delete mode 100644 website/scripts/benchmarks.mjs delete mode 100644 website/scripts/benchmarks.test.mjs delete mode 100644 website/scripts/shots.mjs delete mode 100644 website/serve.mjs delete mode 100644 website/src/404.html delete mode 100644 website/src/bench.js delete mode 100644 website/src/benchmarks-page.js delete mode 100644 website/src/benchmarks.html delete mode 100644 website/src/chrome.js delete mode 100644 website/src/contributors.js delete mode 100644 website/src/docs-page.js delete mode 100644 website/src/docs.html delete mode 100644 website/src/estimate.js delete mode 100644 website/src/estimate.test.mjs delete mode 100644 website/src/hardware.js delete mode 100644 website/src/hub-page.js delete mode 100644 website/src/hub.html delete mode 100644 website/src/hub.js delete mode 100644 website/src/hub.test.mjs delete mode 100644 website/src/index.html delete mode 100644 website/src/main.js delete mode 100644 website/src/markdown.js delete mode 100644 website/src/markdown.test.mjs delete mode 100644 website/src/mods-page.js delete mode 100644 website/src/mods-submit.js delete mode 100644 website/src/mods.html delete mode 100644 website/src/mods.js delete mode 100644 website/src/mods.test.mjs delete mode 100644 website/src/privacy.html delete mode 100644 website/src/releases-page.js delete mode 100644 website/src/releases.html delete mode 100644 website/src/releases.js delete mode 100644 website/src/releases.test.mjs delete mode 100644 website/src/style.css delete mode 100644 website/src/versions.js delete mode 100644 website/src/versions.test.mjs diff --git a/.dockerignore b/.dockerignore index 417a1867c..458330c93 100644 --- a/.dockerignore +++ b/.dockerignore @@ -2,7 +2,6 @@ target/ .local/ **/node_modules/ -website/ benchmarks/ packs/ mods/ diff --git a/.gitattributes b/.gitattributes index 358aeae7a..f9e1922d7 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,5 +2,5 @@ # where Git for Windows' core.autocrlf would check them out with CRLF. docs/launcher-commands.md text eol=lf docs/horizon-ctl-commands.md text eol=lf -website/src/tokens.css text eol=lf +crates/horizon-theme/tokens.css text eol=lf docs/api/*-reference.md text eol=lf diff --git a/AGENTS.md b/AGENTS.md index dcd4ca595..e1fa9e7fe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -54,7 +54,8 @@ Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-se Other top-level folders: `tools/` (harnesses and dev scripts), `tests/` (Python unit tests: `python3 -m unittest discover -s tests`), `mods/horizon/src/test/java/dev/horizonlab/parity/` (Java oracles), -`website/` (playhorizon.dev; its paths are relative to `website/`), `docs/`, `.github/workflows/`. +`docs/`, `.github/workflows/`. The website (playhorizon.dev) is the private ludovic111/horizon-site: its build +reads `README.md`, `launcher/links.json`, `docs/api/`, `roadmap/roadmap.json` and `crates/horizon-theme/tokens.css` from main. ## Build and test fast diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 21951c083..03f3bd97b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,8 +4,8 @@ Thanks for helping. Horizon is Minecraft: Java Edition 26.3 rewritten in Rust, a everything is that **it plays exactly like vanilla**. This page is the short version of how we work; questions are welcome on [Discord](https://discord.gg/HcTeMZxe5E). -This repository holds the game, the launcher and the website, plus the tools, tests and docs that build, check and -release them. Anything else (videos, Discord and other community material) lives elsewhere. +This repository holds the game and the launcher, plus the tools, tests and docs that build, check and release them. +The website (playhorizon.dev) is built in a separate repository from this one's README, `docs/api/` and roadmap. Anything else (videos, Discord and other community material) lives elsewhere. **Where to start: [playhorizon.dev/hub](https://playhorizon.dev/hub).** It shows what is being done now and next ([ROADMAP.md](ROADMAP.md) in the repository), the work board, good first tasks, and the forms to report a bug or diff --git a/ROADMAP.md b/ROADMAP.md index 4a2b90643..9b82f4fac 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -134,7 +134,7 @@ Better tools for mod makers: a test runner that needs no game window, templates `cargo horizon-mod test` runs a mod's test scripts against a fake game snapshot ([#1816](https://github.com/ludovic111/horizon/issues/1816)) and, for server mods, scripted server events ([#1837](https://github.com/ludovic111/horizon/issues/1837)); the content template and the guides are merged ([#1859](https://github.com/ludovic111/horizon/issues/1859), [#1810](https://github.com/ludovic111/horizon/issues/1810), [docs/api/stability.md](docs/api/stability.md)). Left: templates for hud, server and machine mods, typed wrappers in the SDK, a frozen 0.1 compatibility mod that every runtime must load, a CI check that fails when a stable reference entry is removed without a new major version, and the SDK on crates.io once the API is stable. -More: [website/docs/test-a-mod.md](website/docs/test-a-mod.md) +More: [https://playhorizon.dev/docs/test-a-mod](https://playhorizon.dev/docs/test-a-mod) @@ -310,7 +310,7 @@ Horizon should run well on small machines: integrated graphics, the Steam Deck, Partly done: an opt-in 60 FPS cap with fewer workers on battery, Far Detail Reduced for integrated GPUs and animated textures on the GPU (both shipped). Left: measured targets and fixes per class of machine (memory use, worker counts, startup) on a Steam Deck, old Intel and Apple Silicon Macs and 8 GB computers, reported on the Benchmarks page. -More: [docs/benchmark.md](docs/benchmark.md) · [website/docs/performance.md](website/docs/performance.md) +More: [docs/benchmark.md](docs/benchmark.md) · [https://playhorizon.dev/docs/performance](https://playhorizon.dev/docs/performance) @@ -600,7 +600,9 @@ You can port a mod to Horizon with your own AI agent on your own computer. Horiz
Technical -A player runs their own agent locally with `horizon-ctl` and the MCP servers ([docs/agent-control.md](docs/agent-control.md)), `cargo horizon-mod`, `horizon-port-pack` and the parity harnesses as the check. Horizon writes the guide ([website/docs/agents.md](website/docs/agents.md), [docs/modpacks.md](docs/modpacks.md)) and runs no agents, accounts or keys for players. The No AI switch turns all of it off. +A player runs their own agent locally with `horizon-ctl` and the MCP servers ([docs/agent-control.md](docs/agent-control.md)), `cargo horizon-mod`, `horizon-port-pack` and the parity harnesses as the check. Horizon writes the guide (playhorizon.dev/docs/agents, [docs/modpacks.md](docs/modpacks.md)) and runs no agents, accounts or keys for players. The No AI switch turns all of it off. + +More: [https://playhorizon.dev/docs/agents](https://playhorizon.dev/docs/agents)
@@ -936,7 +938,9 @@ Run Horizon's built-in benchmark and share the report: every new computer makes
Technical -`horizon-launcher play --arg=--benchmark --arg=standard` writes a JSON report; `horizon-launcher data benchmark ` shows what would be sent and uploads it ([website/docs/performance.md](website/docs/performance.md)). Results from three installs with the same hardware appear on the Benchmarks page. Example: [#1711](https://github.com/ludovic111/horizon/issues/1711). +`horizon-launcher play --arg=--benchmark --arg=standard` writes a JSON report; `horizon-launcher data benchmark ` shows what would be sent and uploads it (playhorizon.dev/docs/performance). Results from three installs with the same hardware appear on the Benchmarks page. Example: [#1711](https://github.com/ludovic111/horizon/issues/1711). + +More: [https://playhorizon.dev/docs/performance](https://playhorizon.dev/docs/performance)
diff --git a/crates/horizon-server/panel/panel.css b/crates/horizon-server/panel/panel.css index 7946b5f8f..994f5eac6 100644 --- a/crates/horizon-server/panel/panel.css +++ b/crates/horizon-server/panel/panel.css @@ -1,4 +1,4 @@ -/* The Horizon server panel. Colours and spacing are horizon-theme's tokens (website/src/tokens.css). */ +/* The Horizon server panel. Colours and spacing are horizon-theme's tokens (crates/horizon-theme/tokens.css). */ :root { --page: #fafafc; --plate-soft: #f3f3f8; diff --git a/crates/horizon-telemetry-server/README.md b/crates/horizon-telemetry-server/README.md index a401a72b0..c364e20c4 100644 --- a/crates/horizon-telemetry-server/README.md +++ b/crates/horizon-telemetry-server/README.md @@ -30,7 +30,7 @@ The totals are grouped per version, OS, GPU vendor and render distance. Each gro ## Benchmarks summary -`src/summary.rs` makes it with the same rules as `website/scripts/benchmarks.mjs`, which bakes the page's fallback copy; both are tested against the same fixtures (`website/scripts/fixtures/benchmarks/`). +`src/summary.rs` makes it with the same rules as the website's `scripts/benchmarks.mjs` (ludovic111/horizon-site), which bakes the page's fallback copy; both are tested against the same fixtures (`tests/fixtures/benchmarks/` here, copied in the site's repository). - Only reports that compare: a version 1 `horizon-benchmark-report` of the standard flight over the four scenes, VSync off, no frame cap, on screen, from Horizon or plain vanilla, naming its GPU and CPU. - A group (GPU, CPU, render distance, game) is published only with **at least 3 different installs**. Each install counts once: the median of its runs, then the median across installs. diff --git a/crates/horizon-telemetry-server/src/classes.rs b/crates/horizon-telemetry-server/src/classes.rs index fce2826fd..e39154b57 100644 --- a/crates/horizon-telemetry-server/src/classes.rs +++ b/crates/horizon-telemetry-server/src/classes.rs @@ -1,6 +1,6 @@ //! The hardware classes the public output breaks results down by. Coarse on purpose: a class //! holds many machines, and a published cell still needs `MIN_INSTALLS` different installs. -//! `website/scripts/benchmarks.mjs` has the same functions, tested on the same fixtures. +//! The website's `scripts/benchmarks.mjs` (ludovic111/horizon-site) has the same functions, tested on the same fixtures. //! //! The raw values (the exact memory, the driver, the screen) stay in the database for the //! retention period and are never published. diff --git a/crates/horizon-telemetry-server/src/summary.rs b/crates/horizon-telemetry-server/src/summary.rs index 05f94f5a0..deb3564dd 100644 --- a/crates/horizon-telemetry-server/src/summary.rs +++ b/crates/horizon-telemetry-server/src/summary.rs @@ -1,7 +1,7 @@ //! `GET /v1/benchmarks/summary`: players' benchmark uploads, grouped for the website's Benchmarks page. //! -//! The same rules as `website/scripts/benchmarks.mjs` (which builds the page's baked copy), checked against the -//! same fixtures (`website/scripts/fixtures/benchmarks/`): +//! The same rules as the website's `scripts/benchmarks.mjs` (ludovic111/horizon-site; it builds the page's baked +//! copy), checked against the same fixtures (`tests/fixtures/benchmarks/`, which the site's test keeps a copy of): //! //! - Only reports that compare: `horizon-benchmark-report` version 1, kind `game`, Horizon or plain vanilla, the //! standard flight over the four scenes, VSync off, no frame cap, drawn on a screen, with a GPU and CPU name. @@ -198,7 +198,7 @@ struct Group { versions: BTreeSet, } -/// Players' groups of at least `min_installs` installs, as `website/scripts/benchmarks.mjs` makes them. +/// Players' groups of at least `min_installs` installs, as the website's `scripts/benchmarks.mjs` makes them. pub fn groups(uploads: &[Upload], min_installs: usize) -> Vec { let mut by: BTreeMap<(String, String, i64, &str), Group> = BTreeMap::new(); for u in uploads { diff --git a/website/scripts/fixtures/benchmarks/README.md b/crates/horizon-telemetry-server/tests/fixtures/benchmarks/README.md similarity index 72% rename from website/scripts/fixtures/benchmarks/README.md rename to crates/horizon-telemetry-server/tests/fixtures/benchmarks/README.md index 562646a6f..51ebb9aac 100644 --- a/website/scripts/fixtures/benchmarks/README.md +++ b/crates/horizon-telemetry-server/tests/fixtures/benchmarks/README.md @@ -1,7 +1,8 @@ # Benchmark summary fixtures -Shared by the website's aggregator test (`website/scripts/benchmarks.test.mjs`) and the telemetry server's -`GET /v1/benchmarks/summary` test: the same `benchmark` items in, the same groups out. +Used by the telemetry server's `GET /v1/benchmarks/summary` test (`tests/summary.rs`) and, as a copy, by the +website's aggregator test (`scripts/benchmarks.test.mjs` in ludovic111/horizon-site, which checks its copy against +this one on main): the same `benchmark` items in, the same groups out. Change both together. - `items.jsonl`: one stored item per line (`install_id`, `day`, `version`, `data`: a benchmark report). Group RTX 4080 + i7-13700KF at render distance 12 has three installs (one with two runs); the same install at 32, diff --git a/website/scripts/fixtures/benchmarks/expected.json b/crates/horizon-telemetry-server/tests/fixtures/benchmarks/expected.json similarity index 100% rename from website/scripts/fixtures/benchmarks/expected.json rename to crates/horizon-telemetry-server/tests/fixtures/benchmarks/expected.json diff --git a/website/scripts/fixtures/benchmarks/items.jsonl b/crates/horizon-telemetry-server/tests/fixtures/benchmarks/items.jsonl similarity index 100% rename from website/scripts/fixtures/benchmarks/items.jsonl rename to crates/horizon-telemetry-server/tests/fixtures/benchmarks/items.jsonl diff --git a/crates/horizon-telemetry-server/tests/summary.rs b/crates/horizon-telemetry-server/tests/summary.rs index 3232b4f87..88ae2b283 100644 --- a/crates/horizon-telemetry-server/tests/summary.rs +++ b/crates/horizon-telemetry-server/tests/summary.rs @@ -1,5 +1,5 @@ -//! `GET /v1/benchmarks/summary` against the website's fixtures (website/scripts/fixtures/benchmarks/): the same -//! uploads must give the groups `website/scripts/benchmarks.mjs` gives. +//! `GET /v1/benchmarks/summary` against the shared fixtures (tests/fixtures/benchmarks/): the same uploads must +//! give the groups the website's `scripts/benchmarks.mjs` (ludovic111/horizon-site) gives on its copy of them. use std::sync::Arc; use std::sync::atomic::AtomicU32; @@ -15,10 +15,7 @@ use http_body_util::BodyExt; use serde_json::Value; use tower::ServiceExt; -const FIXTURES: &str = concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../website/scripts/fixtures/benchmarks" -); +const FIXTURES: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/benchmarks"); fn items() -> Vec { std::fs::read_to_string(format!("{FIXTURES}/items.jsonl")) diff --git a/crates/horizon-theme/src/lib.rs b/crates/horizon-theme/src/lib.rs index ca4704ead..b41536e5e 100644 --- a/crates/horizon-theme/src/lib.rs +++ b/crates/horizon-theme/src/lib.rs @@ -1,6 +1,6 @@ //! Horizon's design tokens, the one source of truth for the launcher (`launcher/src/theme.rs`), -//! the game's on-screen keyboard (`horizon-client`'s `ui_theme`) and the website (`website/src/tokens.css`, -//! generated from [`css`] by `cargo run -p xtask -- tokens`). Change a value here and all three +//! the game's on-screen keyboard (`horizon-client`'s `ui_theme`) and the website (`tokens.css` in this crate, +//! generated from [`css`] by `cargo run -p xtask -- tokens`, which the site's build reads from main). Change a value here and all three //! follow. The system is described in `docs/design-system.md`. //! //! Cool neutrals in two appearances and one violet accent; Geist and Geist Mono only, bundled @@ -528,7 +528,7 @@ pub fn contrast(a: u32, b: u32) -> f32 { (x.max(y) + 0.05) / (x.min(y) + 0.05) } -/// `website/src/tokens.css`: every token as a CSS custom property, the light palette by +/// `tokens.css`: every token as a CSS custom property, the light palette by /// default, the dark one when the system asks for it or the page sets `data-theme="dark"`. pub fn css() -> String { let mut s = String::new(); @@ -771,15 +771,15 @@ mod tests { assert!((bezier([0., 0., 1., 1.], 0.3) - 0.3).abs() < 1e-3); } - /// `website/src/tokens.css` is what [`css`] writes; regenerate it with - /// `cargo run -p xtask -- tokens`. + /// `tokens.css` (beside Cargo.toml, read by the website's build) is what [`css`] writes; + /// regenerate it with `cargo run -p xtask -- tokens`. #[test] - fn website_tokens_are_up_to_date() { - let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../website/src/tokens.css"); + fn tokens_css_is_up_to_date() { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/tokens.css"); let written = std::fs::read_to_string(path).unwrap_or_default(); assert!( written == css(), - "website/src/tokens.css is out of date: run `cargo run -p xtask -- tokens`" + "crates/horizon-theme/tokens.css is out of date: run `cargo run -p xtask -- tokens`" ); } } diff --git a/website/src/tokens.css b/crates/horizon-theme/tokens.css similarity index 100% rename from website/src/tokens.css rename to crates/horizon-theme/tokens.css diff --git a/docs/agent-control.md b/docs/agent-control.md index 903a48b2f..8573bb711 100644 --- a/docs/agent-control.md +++ b/docs/agent-control.md @@ -3,7 +3,7 @@ A player's own AI agent (Claude Code, Codex, Cursor, any MCP client) or a script can do everything a player does with the mouse and keyboard, in the launcher and in the game. This page covers developers: the surfaces, the full inventory, and the rules every new command follows. -Players read [Control Horizon with your AI agent](../website/docs/agents.md) +Players read [Control Horizon with your AI agent](https://playhorizon.dev/docs/agents) (playhorizon.dev/docs/agents). The command lists are generated, so they can't drift: diff --git a/docs/api/README.md b/docs/api/README.md index ef3649105..ce28dc262 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -53,4 +53,4 @@ Every page has the same parts: **Overview** (what you can build), **Guide** (whe The website shows these pages at [playhorizon.dev/docs/api](https://playhorizon.dev/docs/api), built from this folder, and a summary for players and authors at [playhorizon.dev/docs/apis](https://playhorizon.dev/docs/apis) -(`website/docs/apis.md`). +(in the website's repository, ludovic111/horizon-site). diff --git a/docs/design-system.md b/docs/design-system.md index 66767c0b7..0b171d4c2 100644 --- a/docs/design-system.md +++ b/docs/design-system.md @@ -8,8 +8,8 @@ Horizon's own settings are pages built from vanilla's widgets, the way mods add The tokens live in one place, `crates/horizon-theme`. The launcher (`launcher/src/theme.rs`) and the game (`crates/horizon-client/src/ui_theme.rs`) read them as Rust constants, and the website reads them as CSS custom properties generated from the same crate -(`cargo run -p xtask -- tokens` writes `website/src/tokens.css`; a test fails when the file is -out of date). Change a value in the crate and all three follow. +(`cargo run -p xtask -- tokens` writes `crates/horizon-theme/tokens.css`, which the website's build +reads from main; a test fails when the file is out of date). Change a value in the crate and all three follow. ## Where it comes from @@ -140,7 +140,7 @@ Geist (400, 500, 600) and Geist Mono (400), bundled under the SIL Open Font Lice landscape banner with the hero, the version picker and Play; Mods holds the mod, resource pack and modpack tabs; Versions and Patch notes are lists of panels; Settings is grouped panels of rows. Dark by default, Light or System in Settings (Appearance). -- **Website** (`website/`): the Blocks look below. The same page structure as before (what it +- **Website** (ludovic111/horizon-site): the Blocks look below. The same page structure as before (what it is, screenshots, parity, launcher, patch notes, community), headings in Pixelify Sans, lists as stacks of panels, the stone texture behind the page and Horizon's pixel landscape (a dawn or a sunset) behind the hero. Light and dark follow the system, with a toggle. A giant wordmark in @@ -177,7 +177,7 @@ of the main action. The game's menus keep `LIGHT` and `DARK`. (`TILE_SHADES`), never Minecraft's stone; the landscape is a banded sky, a sun cut in slices like the mark, hills and square trees (a sunset in dark, a dawn in light). The launcher bakes them in `launcher/src/art.rs` at the window's scale so each texel covers whole device pixels; the website - draws them in `website/scripts/art.mjs`. + draws them in its `scripts/art.mjs`. - **Icons**: Pixelarticons (MIT), 24 unit pixel SVGs in `crates/horizon-theme/icons/pixel/`, tinted with the text colour. - **Contrast**: every text colour meets WCAG AA (4.5:1) on the panels, the page and the lightest diff --git a/docs/media/banner.html b/docs/media/banner.html index 47037a7e2..2f727e8bd 100644 --- a/docs/media/banner.html +++ b/docs/media/banner.html @@ -1,10 +1,10 @@ + Rendered with Playwright (see docs/media/brand/README.md). --> - - -
- -
HorizonPLAYHORIZON.DEV
-

The game you know, rebuilt in Rust.

-

Minecraft: Java Edition 26.3, checked against vanilla by differential harnesses. Unofficial; not associated with Mojang or Microsoft.

-
- - diff --git a/website/public/og.png b/website/public/og.png deleted file mode 100644 index 1b9f270e71fa3d2a577a91c5e4317bc6591467a1..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 50427 zcmeGEXHZjb*gXoPsGvv_5kZQAfPjGX-VsEaf`D|S_aeOp6)DntCrTA*(mSDpbckT+ zQbX?qNJ2O_{+{Q|oS8H8&O7sdd1wCl;+`EQd++Pw_sl+w#Z<{MYp=GHtD2 z--d;G4-?ICmhhKs1xV=@44run{o47XnK?E#)-+GKYx>SqMppL2$E)9>#QH+1<$`fg z&ki0`%Y$8$Rs`mpmSoUs_uPLj8F?a^th4N`$#8jT@M&L?{qI0JhK%gLbA)%V{?EA& zveJbAzJ2(LknqaCqieUWJoy9) zWwgA>s1vJyuC-ll_vgPD3_N@v%#y=T;zo61ZN`r%CHgP=oTZ1z4(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ff --git a/website/public/robots.txt b/website/public/robots.txt deleted file mode 100644 index 7cd2cc71e..000000000 --- a/website/public/robots.txt +++ /dev/null @@ -1,4 +0,0 @@ -User-agent: * -Allow: / - -Sitemap: https://playhorizon.dev/sitemap.xml diff --git a/website/railway.json b/website/railway.json deleted file mode 100644 index 3bbe9dfb3..000000000 --- a/website/railway.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "$schema": "https://railway.com/railway.schema.json", - "build": { - "builder": "DOCKERFILE", - "dockerfilePath": "Dockerfile", - "watchPatterns": ["/website/**", "/README.md", "/launcher/links.json", "/docs/api/**"] - }, - "deploy": { - "healthcheckPath": "/", - "healthcheckTimeout": 60, - "restartPolicyType": "ON_FAILURE", - "restartPolicyMaxRetries": 5 - } -} diff --git a/website/scripts/art.mjs b/website/scripts/art.mjs deleted file mode 100644 index 160d64914..000000000 --- a/website/scripts/art.mjs +++ /dev/null @@ -1,151 +0,0 @@ -// Horizon's pixel art for the website, drawn in code like the launcher's (launcher/src/art.rs): -// the stone tile behind the pages and the landscape behind the hero, in both appearances. -// Each texel is one pixel of the PNG; the CSS scales them up with `image-rendering: pixelated`. -// Written by `npm run assets` (or `node scripts/art.mjs`) into public/media/. -import { readFile } from "node:fs/promises"; -import { join, dirname } from "node:path"; -import { fileURLToPath } from "node:url"; -import sharp from "sharp"; - -const site = join(dirname(fileURLToPath(import.meta.url)), ".."); -const repo = join(site, ".."); - -// The same small fixed random sequence as art.rs (xorshift), so the art is the same every time. -function rng(seed) { - let x = seed >>> 0; - return () => { - x = (x ^ (x << 13)) >>> 0; - x = (x ^ (x >>> 17)) >>> 0; - x = (x ^ (x << 5)) >>> 0; - return Math.fround((x >>> 8) / (1 << 24)); - }; -} - -const channels = (c) => [(c >> 16) & 255, (c >> 8) & 255, c & 255]; -const shade = (c, by) => channels(c).reduce((out, v) => (out << 8) | Math.min(255, Math.max(0, v + by)), 0); -const mix = (a, b, t) => { - const [x, y] = [channels(a), channels(b)]; - return x.reduce((out, v, i) => (out << 8) | Math.round(v + (y[i] - v) * t), 0); -}; - -// `n` by `n` texels of stone: the page colour in a few close shades, with darker flecks. -export function stone(page, shades, n) { - const s = shades.map((by) => shade(page, by)); - const next = rng(0x9e3779b9); - const out = Array.from({ length: n * n }, () => { - const v = next(); - return s[v < 0.5 ? 0 : v < 0.78 ? 1 : v < 0.93 ? 2 : 3]; - }); - for (let k = 0; k < Math.floor((n * n) / 50); k++) { - const x = Math.floor(next() * n); - const y = Math.floor(next() * n); - const len = 1 + Math.floor(next() * 3); - for (let i = 0; i < len; i++) { - out[y * n + ((x + i) % n)] = s[4]; - out[((y + 1) % n) * n + ((x + i + 1) % n)] = s[4]; - } - } - return out; -} - -export const SUNSET = { - sky: [0x0a0f2c, 0x26206a, 0x4b2a7e, 0x7c3a88, 0xc4527a, 0xee6e5a, 0xffb25e], - sun: [0xfff6cf, 0xffd272, 0xff9a44], - far: 0x4a2f7e, mid: 0x2b1f5e, near: 0x151a45, top: 0x3d2f80, trees: 0x0e1236, -}; -export const DAWN = { - sky: [0x8d7fd8, 0xa596e2, 0xbcaeea, 0xd2c4f0, 0xe7d2ee, 0xf6dce4, 0xffe6d6], - sun: [0xffffff, 0xfff1d0, 0xffd9a8], - far: 0xa898dc, mid: 0x8676c8, near: 0x6a5ab4, top: 0x9a8ae0, trees: 0x4c3e94, -}; - -// A blocky landscape, `w` by `h` texels: banded sky, a sun half set behind the far hills and cut -// into slices like Horizon's mark, flat clouds, three ridges of hills and a few square trees. -export function scene(p, seed, w, h) { - const next = rng((Math.imul(seed, 0x2545f491) | 1) >>> 0); - const out = new Array(w * h).fill(0); - const horizon = Math.floor((h * 62) / 100); - const band = horizon / p.sky.length; - for (let y = 0; y < h; y++) { - const f = y / band; - const i = Math.min(Math.floor(f), p.sky.length - 1); - const dither = f - i > 0.88 && i + 1 < p.sky.length; - for (let x = 0; x < w; x++) out[y * w + x] = dither && (x + y) % 2 === 1 ? p.sky[i + 1] : p.sky[i]; - } - const rect = (x, y, rw, rh, c) => { - for (let yy = Math.max(y, 0); yy < Math.min(y + rh, h); yy++) - for (let xx = Math.max(x, 0); xx < Math.min(x + rw, w); xx++) out[yy * w + xx] = c; - }; - for (let k = 0; k < 4; k++) { - const cx = Math.floor(next() * w); - const cy = Math.floor(horizon * (0.12 + next() * 0.4)); - const cw = 10 + Math.floor(next() * 14); - const under = p.sky[Math.min(Math.floor(cy / band) + 1, p.sky.length - 1)]; - const c = mix(under, 0xffffff, 0.12); - rect(cx, cy, cw, 2, c); - rect(cx + 3, cy - 2, Math.max(cw - 6, 0), 2, c); - } - const r = Math.floor(h * 0.2); - const [cx, cy] = [Math.floor(w * 0.68), horizon - Math.floor(h * 0.11)]; - for (let dy = -r; dy <= 0; dy++) { - const half = Math.round(Math.sqrt(r * r - dy * dy)); - const t = (dy + r) / r; - const c = p.sun[t < 0.4 ? 0 : t < 0.75 ? 1 : 2]; - if ((cy + dy) % 5 !== 0 || dy < -r * 0.6) rect(cx - half, cy + dy, half * 2, 1, c); - } - const ridge = (base, amp, rough) => { - let [y, v] = [base, 0]; - return Array.from({ length: w }, (_, x) => { - if (x % 2 === 0) { - v = (v + (next() - 0.5) * rough) * 0.86; - y += v + (base - y) * 0.06; - } - return Math.max(Math.round(Math.min(Math.max(y, base - amp), base + amp)), 0); - }); - }; - const layers = [ - [p.far, horizon - h * 0.1, h * 0.12, 3.2, null], - [p.mid, horizon + h * 0.02, h * 0.09, 2.6, null], - [p.near, horizon + h * 0.18, h * 0.07, 2.2, p.top], - ]; - let near = []; - for (const [c, base, amp, rough, top] of layers) { - const hs = ridge(base, amp, rough); - hs.forEach((y, x) => { - for (let yy = Math.min(y, h); yy < h; yy++) out[yy * w + x] = c; - if (top !== null && y < h) out[y * w + x] = top; - }); - near = hs; - } - for (let k = 0; k < Math.floor(w / 26); k++) { - const tx = 4 + Math.floor(next() * (w - 10)); - const ty = near[tx]; - rect(tx - 2, ty - 8, 5, 5, p.trees); - rect(tx - 1, ty - 10, 3, 2, p.trees); - rect(tx, ty - 3, 1, 3, p.trees); - } - return out; -} - -const png = (texels, w, h, file) => - sharp(Buffer.from(texels.flatMap(channels)), { raw: { width: w, height: h, channels: 3 } }) - .png({ compressionLevel: 9, palette: true }) - .toFile(file); - -// The page colours and the stone's shades come from crates/horizon-theme, like tokens.css. -export async function writeArt(media) { - const theme = await readFile(join(repo, "crates/horizon-theme/src/lib.rs"), "utf8"); - const page = (name) => parseInt(theme.match(new RegExp(`pub const ${name}: Blocks = Blocks \\{\\s*page: 0x([0-9a-f]{6})`))[1], 16); - const shades = JSON.parse(`[${theme.match(/TILE_SHADES: \[i16; 5\] = \[([^\]]*)\]/)[1]}]`); - const texels = Number(theme.match(/TILE_TEXELS: usize = (\d+)/)[1]) * 4; - await png(stone(page("BLOCKS_DARK"), shades, texels), texels, texels, join(media, "stone-dark.png")); - await png(stone(page("BLOCKS_LIGHT"), shades, texels), texels, texels, join(media, "stone-light.png")); - const [w, h] = [240, 72]; - await png(scene(SUNSET, 3, w, h), w, h, join(media, "scene-dark.png")); - await png(scene(DAWN, 3, w, h), w, h, join(media, "scene-light.png")); -} - -if (process.argv[1] === fileURLToPath(import.meta.url)) { - await writeArt(join(site, "public", "media")); - console.log("pixel art written to public/media/"); -} diff --git a/website/scripts/assets.mjs b/website/scripts/assets.mjs deleted file mode 100644 index 92b197e7e..000000000 --- a/website/scripts/assets.mjs +++ /dev/null @@ -1,60 +0,0 @@ -// Copies the launcher's fonts and the repo's screenshots into public/, draws the pixel art, -// converted for the web (woff2, webp in two widths). Run it after any of them change: -// `npm run assets`. Its output is committed, because Railway builds only website/. -import { mkdir, readFile, writeFile, copyFile } from "node:fs/promises"; -import { join, dirname } from "node:path"; -import { fileURLToPath } from "node:url"; -import sharp from "sharp"; -import wawoff2 from "wawoff2"; -import { writeArt } from "./art.mjs"; - -const site = join(dirname(fileURLToPath(import.meta.url)), ".."); -const repo = join(site, ".."); -const pub = join(site, "public"); - -const fonts = [ - "Geist-Regular.ttf", - "Geist-Medium.ttf", - "Geist-SemiBold.ttf", - "GeistMono-Regular.ttf", - "PixelifySans-Medium.ttf", - "PixelifySans-SemiBold.ttf", - "PixelifySans-Bold.ttf", -]; - -// [source, name]; every image becomes media/.webp and media/-800.webp. -export const images = [ - ["docs/media/sunset.jpg", "sunset"], - ["docs/media/village.jpg", "village"], - ["docs/media/survival.jpg", "survival"], - ["docs/media/nether.jpg", "nether"], - ["docs/media/night.jpg", "night"], - ["docs/media/underwater.jpg", "underwater"], - ["docs/media/settings-simple.png", "settings"], - ["docs/media/launcher-play.png", "launcher"], -]; - -await mkdir(join(pub, "fonts"), { recursive: true }); -await mkdir(join(pub, "media"), { recursive: true }); - -for (const font of fonts) { - const ttf = await readFile(join(repo, "crates/horizon-theme/fonts", font)); - await writeFile(join(pub, "fonts", font.replace(".ttf", ".woff2")), await wawoff2.compress(ttf)); -} -for (const licence of ["OFL-Geist.txt", "OFL-PixelifySans.txt"]) { - await copyFile(join(repo, "crates/horizon-theme/fonts", licence), join(pub, "fonts", licence)); -} - -for (const [source, name] of images) { - const input = join(repo, source); - await sharp(input).resize({ width: 1600, withoutEnlargement: true }).webp({ quality: 82 }).toFile(join(pub, "media", `${name}.webp`)); - await sharp(input).resize({ width: 800 }).webp({ quality: 78 }).toFile(join(pub, "media", `${name}-800.webp`)); -} - -// The stone tile and the hero's landscape, drawn in code (scripts/art.mjs). -await writeArt(join(pub, "media")); - -// The icons (favicon.svg, favicon-32.png, apple-touch-icon.png) come from Horizon's mark: -// `cargo run -p xtask -- icons` writes them with the rest of the brand (docs/media/brand). - -console.log("assets written to public/"); diff --git a/website/scripts/benchmarks.mjs b/website/scripts/benchmarks.mjs deleted file mode 100644 index 724834ea7..000000000 --- a/website/scripts/benchmarks.mjs +++ /dev/null @@ -1,240 +0,0 @@ -// Benchmark results for the site: benchmark reports (docs/benchmark-report.md) in, the summary the Benchmarks page -// reads out (public/benchmarks.json, and the telemetry server's GET /v1/benchmarks/summary in the same shape). -// -// node scripts/benchmarks.mjs --ours fleet.json [--telemetry items.jsonl] [-o public/benchmarks.json] -// -// --ours lists our own runs (tools/perf_bench.py reports, Horizon and vanilla, one machine each); --telemetry holds -// players' `benchmark` items as the server stores them ({ install_id, day, version, data: } per line). -// Players' results are grouped by GPU, CPU, render distance and game, and a group is published only with at least -// MIN_INSTALLS installs, so nobody can be picked out. install_id is used to count installs and to weigh each install -// once, and never leaves this script; neither do the day, OS version, driver, the exact RAM and VRAM, or the screen. -// A group also says how its installs split by hardware class (RAM, VRAM, drive, OS, integrated or discrete GPU), -// each class only with at least MIN_INSTALLS installs. The classes are the server's (src/classes.rs). -import { readFile, writeFile } from "node:fs/promises"; -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -export const FORMAT = "horizon-benchmark-summary"; -export const MIN_INSTALLS = 3; -export const SCENES = ["village", "forest", "ocean", "mountain"]; -export const FIELDS = ["avg_fps", "low_1pct_fps", "p95_ms", "world_ms", "chunk_load_ms", "rss_peak_mb", "rss_steady_mb"]; - -const mean = (xs) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : null); -const finite = (x) => typeof x === "number" && Number.isFinite(x); -export function median(xs) { - const v = xs.filter(finite).sort((a, b) => a - b); - if (!v.length) return null; - const m = v.length >> 1; - return v.length % 2 ? v[m] : (v[m - 1] + v[m]) / 2; -} -// fps to integers, milliseconds to a tenth under 10 and to integers above, megabytes to integers. -export function round(field, x) { - if (!finite(x)) return null; - if (field.endsWith("_ms")) return x < 10 ? Math.round(x * 10) / 10 : Math.round(x); - return Math.round(x); -} -const trim = (s) => (typeof s === "string" ? s.replace(/\(R\)|\(TM\)|\(tm\)/g, "").replace(/\s+/g, " ").trim() : ""); -const gameOf = (app) => (app?.name === "horizon-client" ? "horizon" : app?.name === "minecraft" && !(app.mods || []).some((m) => m.name !== "fabric-loader") ? "vanilla" : null); - -// --- Hardware classes: coarse, so that a class holds many machines --------------------------- - -export const DIMENSIONS = ["ram", "vram", "storage", "os", "gpu_kind"]; -export function ramClass(gb) { - if (!(gb > 0)) return null; - return gb <= 5 ? "4 GB or less" : gb <= 10 ? "8 GB" : gb <= 20 ? "16 GB" : gb <= 40 ? "32 GB" : "64 GB or more"; -} -export function gpuKindClass(s) { - return s === "integrated" || s === "IntegratedGpu" ? "integrated" : s === "discrete" || s === "DiscreteGpu" ? "discrete" : null; -} -// A GPU's own memory in MiB; an integrated GPU shares the system's. -export function vramClass(mb, kind) { - if (gpuKindClass(kind) === "integrated") return "shared"; - if (!(mb > 0)) return null; - for (const [max, name] of [[2560, "2 GB or less"], [4608, "4 GB"], [6656, "6 GB"], [8704, "8 GB"], [12800, "12 GB"], [16896, "16 GB"]]) if (mb <= max) return name; - return "more than 16 GB"; -} -const oneOf = (list) => (s) => (list.includes(s) ? s : null); -export const storageClass = oneOf(["nvme", "ssd", "hdd"]); -export const osClass = oneOf(["linux", "macos", "windows"]); -// A report's classes, in DIMENSIONS order. -export function classesOf(report) { - const hw = report?.hardware || {}; - const kind = hw.gpu?.kind; - return [ramClass(finite(hw.ram_mb) ? hw.ram_mb / 1024 : 0), vramClass(hw.gpu?.vram_mb, kind), storageClass(hw.storage), osClass(hw.os), gpuKindClass(kind)]; -} -// Per dimension, the classes with at least minInstalls installs, most first; dimensions without one are left out. -export function breakdowns(classes, minInstalls) { - const out = {}; - DIMENSIONS.forEach((dim, i) => { - const cells = [...classes[i]].map(([c, set]) => ({ class: c, installs: set.size })).filter((c) => c.installs >= minInstalls); - cells.sort((a, b) => b.installs - a.installs || (a.class < b.class ? -1 : a.class > b.class ? 1 : 0)); - if (cells.length) out[dim] = cells; - }); - return out; -} - -// Why a report can't be compared with the others, or null when it can: the standard flight over the four scenes, -// VSync off, no frame cap, drawn on a screen. -export function rejection(report) { - if (!report || report.format !== "horizon-benchmark-report" || report.version !== 1) return "not a version 1 benchmark report"; - if (report.kind !== "game") return "not a game run"; - if (!gameOf(report.app)) return "not Horizon or plain vanilla"; - const c = report.conditions || {}; - if (!(c.scenario === "standard" || c.scenario === "flight" || String(c.scenario || "").startsWith("perf_bench:"))) return "not the standard flight"; - if (c.vsync !== false) return "VSync on or unknown"; - if (c.fps_cap != null) return "frame rate capped"; - if (c.offscreen === true) return "offscreen"; - if (!finite(c.render_distance)) return "no render distance"; - const phases = new Set((report.frames || []).map((f) => f.phase)); - if (!SCENES.every((s) => phases.has(s))) return "not every scene"; - if (!trim(report.hardware?.gpu?.name) || !trim(report.hardware?.cpu)) return "no GPU or CPU name"; - return null; -} - -// One report's figures: frame figures averaged over every flight (scene and repeat), the rest from its metrics. -export function figures(report) { - const frames = report.frames || []; - const m = report.metrics || {}; - const metric = (name) => (finite(m[name]?.mean) ? m[name].mean : null); - const loads = Object.keys(m).filter((k) => /^chunks\.[^.]+\.load_ms$/.test(k)).map(metric).filter(finite); - const avg = (key) => mean(frames.map((f) => f[key]).filter(finite)); - return { - avg_fps: avg("avg_fps"), - low_1pct_fps: avg("low_1pct_fps"), - p95_ms: avg("p95_ms"), - world_ms: metric("startup.world_ms"), - chunk_load_ms: mean(loads), - rss_peak_mb: metric("memory.rss_peak_mb"), - rss_steady_mb: metric("memory.rss_steady_mb"), - cpu_p50_ms: avg("cpu_p50_ms"), - gpu_p50_ms: avg("gpu_p50_ms"), - }; -} - -const roundAll = (fig, fields) => Object.fromEntries(fields.map((f) => [f, round(f, fig[f])])); - -// Players' items -> groups of at least minInstalls installs. Each install counts once: its median first, then the -// median across installs. -export function aggregatePlayers(items, { minInstalls = MIN_INSTALLS } = {}) { - const groups = new Map(); - for (const item of items) { - const report = item?.data; - if (!item?.install_id || rejection(report)) continue; - const key = JSON.stringify([trim(report.hardware.gpu.name), trim(report.hardware.cpu), report.conditions.render_distance, gameOf(report.app)]); - if (!groups.has(key)) groups.set(key, { installs: new Map(), reports: 0, versions: new Set(), classes: DIMENSIONS.map(() => new Map()) }); - const g = groups.get(key); - g.reports++; - if (item.version) g.versions.add(item.version); - if (!g.installs.has(item.install_id)) g.installs.set(item.install_id, []); - g.installs.get(item.install_id).push(figures(report)); - classesOf(report).forEach((c, i) => { - if (!c) return; - if (!g.classes[i].has(c)) g.classes[i].set(c, new Set()); - g.classes[i].get(c).add(item.install_id); - }); - } - const out = []; - for (const [key, g] of groups) { - if (g.installs.size < minInstalls) continue; - const [gpu, cpu, render_distance, game] = JSON.parse(key); - const perInstall = [...g.installs.values()].map((runs) => Object.fromEntries(FIELDS.map((f) => [f, median(runs.map((r) => r[f]))]))); - const medians = Object.fromEntries(FIELDS.map((f) => [f, round(f, median(perInstall.map((r) => r[f])))])); - out.push({ gpu, cpu, render_distance, game, source: "players", installs: g.installs.size, reports: g.reports, versions: [...g.versions].sort(byVersionDesc).slice(0, 3), medians, breakdowns: breakdowns(g.classes, minInstalls) }); - } - // Most installs first, then by GPU, CPU, render distance and game, compared as plain strings (as the server does). - const cmp = (x, y) => (x < y ? -1 : x > y ? 1 : 0); - return out.sort((a, b) => b.installs - a.installs || cmp(a.gpu, b.gpu) || cmp(a.cpu, b.cpu) || a.render_distance - b.render_distance || cmp(a.game, b.game)); -} - -// "v0.2.10" after "v0.2.9", dated tags by their numbers; good enough to list the newest three. -function byVersionDesc(a, b) { - const n = (v) => (v.match(/\d+/g) || []).map(Number); - const [x, y] = [n(a), n(b)]; - for (let i = 0; i < Math.max(x.length, y.length); i++) if ((x[i] ?? -1) !== (y[i] ?? -1)) return (y[i] ?? -1) - (x[i] ?? -1); - return 0; -} - -// Our own runs: one row per machine, game and render distance, with what was measured and how. An entry holds one -// report (its runs are the report's repeats) or several (one game each); figures are medians over the reports. -export function ourRows(runs) { - const rows = []; - for (const { report, reports, machine, note, version, capped_fps } of runs) { - const list = reports || [report]; - for (const r of list) { - const why = rejection(r); - if (why) throw new Error(`${machine}: ${r?.label || "report"} can't be published: ${why}`); - } - const [first] = list; - const c = first.conditions; - if (list.some((r) => r.conditions.render_distance !== c.render_distance || gameOf(r.app) !== gameOf(first.app) || r.app.version !== first.app.version)) - throw new Error(`${machine}: reports of different games, versions or render distances in one entry`); - const figs = list.map(figures); - const fig = Object.fromEntries(Object.keys(figs[0]).map((k) => [k, median(figs.map((f) => f[k]))])); - const scenes = Object.fromEntries( - SCENES.map((s) => { - const fs = list.flatMap((r) => r.frames.filter((f) => f.phase === s)); - const loads = list.map((r) => r.metrics?.[`chunks.${s}.load_ms`]?.mean); - return [s, { avg_fps: round("avg_fps", mean(fs.map((f) => f.avg_fps))), low_1pct_fps: round("low_1pct_fps", mean(fs.map((f) => f.low_1pct_fps))), chunk_load_ms: round("chunk_load_ms", median(loads)) }]; - }), - ); - rows.push({ - gpu: trim(first.hardware.gpu.name), - cpu: trim(first.hardware.cpu), - render_distance: c.render_distance, - game: gameOf(first.app), - source: "us", - machine, - measured: list.map((r) => (r.created || "").slice(0, 10)).sort().at(-1), - // A release build reports its crate version; the entry can name the release it was. - version: version || first.app.version, - backend: first.hardware.gpu.backend || null, - os: first.hardware.os || null, - window: c.window || null, - repeats: list.reduce((n, r) => n + (r.conditions.repeats || 1), 0), - load_avg_1m: Math.max(...list.map((r) => r.conditions.load_avg_1m ?? 0)), - ...(note ? { note } : {}), - // The frame rate the display held this game to (a present mode VSync off doesn't lift): its average is a floor. - ...(capped_fps ? { capped_fps } : {}), - // A split of 0 means the backend gave no timing (Metal has no GPU timer here): unknown, not free. - medians: { ...roundAll(fig, FIELDS), cpu_p50_ms: fig.cpu_p50_ms > 0 ? round("cpu_p50_ms", fig.cpu_p50_ms) : null, gpu_p50_ms: fig.gpu_p50_ms > 0 ? round("gpu_p50_ms", fig.gpu_p50_ms) : null }, - scenes, - }); - } - return rows; -} - -export function summary({ ours = [], players = [], generated = new Date() } = {}) { - return { format: FORMAT, version: 1, generated: generated.toISOString().replace(/\.\d+Z$/, "Z"), min_installs: MIN_INSTALLS, groups: [...ours, ...players] }; -} - -// --- The command line ---------------------------------------------------------------------- - -async function main(argv) { - const arg = (name) => { - const i = argv.indexOf(name); - return i >= 0 ? argv[i + 1] : null; - }; - const site = resolve(dirname(fileURLToPath(import.meta.url)), ".."); - const out = arg("-o") || resolve(site, "public/benchmarks.json"); - let ours = []; - if (arg("--ours")) { - // [{ "machine": "Mac mini", "reports": ["path/to/report.json", ...], "version": "v…", "note": "..." }], paths - // relative to the list; "version" names the release when the report only has the crate version. - const listPath = resolve(arg("--ours")); - const list = JSON.parse(await readFile(listPath, "utf8")); - const load = async (path) => JSON.parse(await readFile(resolve(dirname(listPath), path), "utf8")); - const runs = []; - for (const entry of list) runs.push({ ...entry, reports: await Promise.all((entry.reports || [entry.report]).map(load)), report: undefined }); - ours = ourRows(runs); - } - let players = []; - if (arg("--telemetry")) { - const text = await readFile(resolve(arg("--telemetry")), "utf8"); - players = aggregatePlayers(text.split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l))); - } - const result = summary({ ours, players }); - await writeFile(out, JSON.stringify(result, null, 1) + "\n"); - console.log(`${out}: ${ours.length} rows measured by us, ${players.length} player groups`); -} - -if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await main(process.argv.slice(2)); diff --git a/website/scripts/benchmarks.test.mjs b/website/scripts/benchmarks.test.mjs deleted file mode 100644 index 87aec484b..000000000 --- a/website/scripts/benchmarks.test.mjs +++ /dev/null @@ -1,91 +0,0 @@ -// node --test (npm test in website/). The fixtures are shared with the telemetry server's summary test. -import { test } from "node:test"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import { aggregatePlayers, median, osClass, ourRows, ramClass, rejection, round, storageClass, summary, vramClass, gpuKindClass } from "./benchmarks.mjs"; - -const fixture = (name) => new URL(`./fixtures/benchmarks/${name}`, import.meta.url); -const items = readFileSync(fixture("items.jsonl"), "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l)); -const expected = JSON.parse(readFileSync(fixture("expected.json"), "utf8")); - -test("players' items give the expected groups", () => { - const s = summary({ players: aggregatePlayers(items) }); - assert.equal(s.format, "horizon-benchmark-summary"); - assert.equal(s.min_installs, expected.min_installs); - assert.deepEqual(s.groups, expected.groups); -}); - -test("nothing that identifies an install is published", () => { - const text = JSON.stringify(aggregatePlayers(items, { minInstalls: 1 })); - for (const secret of ["a1", "a2", "install_id", "secret-os-version", "secret-driver", "20394", "ram_mb", "2560", "16376", "32768", "vram_mb"]) assert.ok(!text.includes(secret), secret); -}); - -test("a group needs three installs, not three runs", () => { - const one = items.filter((i) => i.install_id === "a1"); - assert.equal(aggregatePlayers([...one, ...one, ...one]).length, 0); - assert.equal(aggregatePlayers(items, { minInstalls: 2 }).length, 2); -}); - -test("hardware classes are coarse, as the server's", () => { - assert.equal(ramClass(15.6), "16 GB"); - assert.equal(ramClass(31), "32 GB"); - assert.equal(ramClass(64), "64 GB or more"); - assert.equal(ramClass(0), null); - assert.equal(vramClass(16376, "discrete"), "16 GB"); - assert.equal(vramClass(8192, "DiscreteGpu"), "8 GB"); - assert.equal(vramClass(0, "integrated"), "shared"); - assert.equal(vramClass(0, ""), null); - assert.equal(storageClass("nvme"), "nvme"); - assert.equal(storageClass("tape"), null); - assert.equal(osClass("windows"), "windows"); - assert.equal(gpuKindClass("virtual"), null); -}); - -test("a breakdown cell needs three installs too", () => { - const [group] = aggregatePlayers(items); - assert.equal(group.breakdowns.ram, undefined); // 32 GB has two installs, 16 GB one - assert.equal(group.breakdowns.storage, undefined); - const [all] = aggregatePlayers(items, { minInstalls: 1 }); - assert.deepEqual(all.breakdowns.ram, [{ class: "32 GB", installs: 2 }, { class: "16 GB", installs: 1 }]); - assert.deepEqual(all.breakdowns.storage, [{ class: "nvme", installs: 2 }, { class: "ssd", installs: 1 }]); -}); - -test("only comparable runs count", () => { - const reasons = items.map((i) => rejection(i.data)); - assert.deepEqual(reasons.filter(Boolean), ["VSync on or unknown", "offscreen", "frame rate capped", "not every scene", "not the standard flight", "not a version 1 benchmark report"]); -}); - -test("medians and rounding", () => { - assert.equal(median([3, 1, 2]), 2); - assert.equal(median([4, 1, 2, 3]), 2.5); - assert.equal(median([null, NaN]), null); - assert.equal(round("p95_ms", 3.46), 3.5); - assert.equal(round("world_ms", 4512.4), 4512); - assert.equal(round("avg_fps", 99.5), 100); -}); - -test("our runs keep the machine and how it was measured", () => { - const [row] = ourRows([{ machine: "Desktop", report: items[0].data }]); - assert.equal(row.source, "us"); - assert.equal(row.machine, "Desktop"); - assert.equal(row.game, "horizon"); - assert.equal(row.medians.avg_fps, 415); - assert.equal(row.scenes.ocean.avg_fps, 420); - assert.throws(() => ourRows([{ machine: "x", report: items[4].data }]), /VSync/); - // Several one-game reports: medians over them. - const [both] = ourRows([{ machine: "Desktop", reports: [items[0].data, items[1].data] }]); - assert.equal(both.medians.avg_fps, 515); - assert.equal(both.repeats, 2); - assert.throws(() => ourRows([{ machine: "x", reports: [items[0].data, items[9].data] }]), /different/); -}); - -test("a display cap on our run is kept, and the comparison says at least", async () => { - const [row] = ourRows([{ machine: "Mac", report: items[0].data, capped_fps: 144, version: "v1" }]); - assert.equal(row.capped_fps, 144); - assert.equal(row.version, "v1"); - const { compareRows, METRICS } = await import("../src/bench.js"); - const fps = METRICS[0]; - const h = { capped_fps: 144, medians: { avg_fps: 144 } }; - assert.equal(compareRows(fps, h, { medians: { avg_fps: 120 } }).text, "at least 1.2x faster"); - assert.equal(compareRows(fps, h, { medians: { avg_fps: 200 } }).wins, "none"); -}); diff --git a/website/scripts/shots.mjs b/website/scripts/shots.mjs deleted file mode 100644 index c0b86f40d..000000000 --- a/website/scripts/shots.mjs +++ /dev/null @@ -1,99 +0,0 @@ -// Full-page screenshots of the built site at every width that matters, plus the social -// preview image. Run `npm run build` first; `npm run shots` serves dist/ and writes -// shots/*.png (gitignored: full-page PNGs are too heavy for the repo), 390-menu.png (the open -// menu) and 1440-hero.png, and public/og.png (rebuild after). It also checks each width for -// horizontal scroll, small tap targets and line lengths. `SHOTS=dir` writes them elsewhere. -import { chromium } from "playwright"; -import { spawn } from "node:child_process"; -import { mkdir } from "node:fs/promises"; -import { join, dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -const site = join(dirname(fileURLToPath(import.meta.url)), ".."); -const port = 4199; -const url = `http://localhost:${port}/`; -const server = spawn(process.execPath, [join(site, "serve.mjs")], { env: { ...process.env, PORT: String(port) }, stdio: "ignore" }); -await new Promise((r) => setTimeout(r, 400)); - -const widths = [360, 390, 430, 768, 1024, 1180, 1250, 1280, 1366, 1440, 1680, 1920]; -const sizes = [...widths.map((w) => [w, w < 900 ? 800 : 900]), [1250, 700]]; -const only = process.argv.slice(2); -const out = process.env.SHOTS ? resolve(process.env.SHOTS) : join(site, "shots"); - -await mkdir(out, { recursive: true }); -const browser = await chromium.launch(); -let problems = 0; - -for (const [width, height] of sizes) { - const name = height === 700 ? `${width}x${height}` : `${width}`; - if (only.length && !only.includes(name)) continue; - const touch = width < 900; - const page = await browser.newPage({ viewport: { width, height }, deviceScaleFactor: 1, hasTouch: touch, isMobile: touch }); - await page.goto(url, { waitUntil: "networkidle" }); - // Reveal every section, as scrolling would, and let the fades finish. - await page.evaluate(async () => { - for (let y = 0; y < document.body.scrollHeight; y += 400) { - scrollTo({ top: y, behavior: "instant" }); - await new Promise((r) => setTimeout(r, 30)); - } - scrollTo({ top: 0, behavior: "instant" }); - }); - await page.waitForTimeout(800); - const report = await page.evaluate((touch) => { - const out = []; - const doc = document.documentElement; - if (doc.scrollWidth > innerWidth) out.push(`horizontal scroll: ${doc.scrollWidth} > ${innerWidth}`); - for (const el of document.querySelectorAll("body *")) { - const r = el.getBoundingClientRect(); - if (r.width && r.right > innerWidth + 1 && !el.closest(".lightbox, .menu, .hero-media, .footer-word")) { - out.push(`overflows: ${el.tagName.toLowerCase()}.${el.className} right ${Math.round(r.right)}`); - } - } - if (touch) { - for (const el of document.querySelectorAll("a, button, summary")) { - if (el.closest(".menu, .lightbox, .skip") || el.closest(".prose, .footer-cols, .fact p, .system-detail, .download-meta, .meta")) continue; - const r = el.getBoundingClientRect(); - if (r.width && r.height < 44) out.push(`small target: ${el.textContent.trim().slice(0, 30)} (${Math.round(r.height)}px)`); - } - } - // Characters per line of the longest running-text paragraphs. - const lengths = [...document.querySelectorAll(".prose p, .lede, .hero-line, .fact p, .features p, .system-detail, .count-label, .footer-cols p")] - .filter((p) => p.textContent.length > 160) - .map((p) => { - const lh = parseFloat(getComputedStyle(p).lineHeight); - const n = Math.round(p.textContent.length / Math.max(1, Math.round(p.getBoundingClientRect().height / lh))); - return [n, `${p.parentElement.id || p.parentElement.className}>${p.className || p.tagName}`]; - }) - .sort((a, b) => a[0] - b[0]); - const [lo, hi] = [lengths[0], lengths[lengths.length - 1]]; - out.push(`chars per line: ${lo[0]} (${lo[1]})–${hi[0]} (${hi[1]})`); - return out.slice(0, 12); - }, touch); - const issues = report.filter((l) => !l.startsWith("chars")); - problems += issues.length; - console.log(`${name}: ${issues.length ? issues.join("; ") : "ok"} · ${report.find((l) => l.startsWith("chars"))}`); - await page.screenshot({ path: join(out, `${name}.png`), fullPage: height !== 700 }); - if (width === 1440) await page.screenshot({ path: join(out, "1440-hero.png") }); - if (width === 390) { - await page.click(".menu-button"); - await page.waitForTimeout(800); - await page.screenshot({ path: join(out, "390-menu.png") }); - } - await page.close(); -} - -if (!only.length || only.includes("og")) { - const page = await browser.newPage({ viewport: { width: 1200, height: 630 } }); - await page.goto(`${url}og.html`, { waitUntil: "networkidle" }); - await page.waitForTimeout(700); - await page.screenshot({ path: join(site, "public/og.png") }); - await page.close(); -} - -await browser.close(); -server.kill(); - -if (problems) { - console.log(`${problems} problems`); - process.exitCode = 1; -} diff --git a/website/serve.mjs b/website/serve.mjs deleted file mode 100644 index 553a3ff9b..000000000 --- a/website/serve.mjs +++ /dev/null @@ -1,42 +0,0 @@ -// A dependency-free static server for dist/, for local checks (`npm run dev`). -// Railway uses Caddy instead (see Dockerfile). -import { createServer } from "node:http"; -import { readFile, stat } from "node:fs/promises"; -import { join, extname, normalize } from "node:path"; -import { fileURLToPath } from "node:url"; - -const root = join(fileURLToPath(new URL(".", import.meta.url)), "dist"); -const types = { ".html": "text/html; charset=utf-8", ".css": "text/css", ".js": "text/javascript", ".webp": "image/webp", ".png": "image/png", ".svg": "image/svg+xml", ".woff2": "font/woff2", ".txt": "text/plain; charset=utf-8", ".md": "text/plain; charset=utf-8", ".json": "application/json", ".xml": "application/xml" }; -const port = Number(process.env.PORT) || 4173; - -createServer(async (req, res) => { - let path = normalize(decodeURIComponent(new URL(req.url, "http://x").pathname)).replace(/^(\.\.[/\\])+/, ""); - if (path === "/docs/api/") { - res.writeHead(301, { Location: "/docs/api" }); - return res.end(); - } - if (path.endsWith("/")) path += "index.html"; - // The server guide is part of the docs now, as the Caddyfile redirects it. - if (path === "/server" || path === "/server.html") { - res.writeHead(301, { Location: "/docs/hosting" }); - return res.end(); - } - // The roadmap page became the hub's Roadmap tab. - if (path === "/roadmap") { - res.writeHead(301, { Location: "/hub#roadmap" }); - return res.end(); - } - if (path === "/docs") path = "/docs/index.html"; - // /privacy, /docs/ and /docs/api/ are .html files, as the Caddyfile rewrites them. - if (!extname(path)) path += ".html"; - let file = join(root, path); - let status = 200; - try { - if (!(await stat(file)).isFile()) throw 0; - } catch { - file = join(root, "404.html"); - status = 404; - } - res.writeHead(status, { "Content-Type": types[extname(file)] || "application/octet-stream" }); - res.end(await readFile(file)); -}).listen(port, () => console.log(`http://localhost:${port}`)); diff --git a/website/src/404.html b/website/src/404.html deleted file mode 100644 index 3ac1e017a..000000000 --- a/website/src/404.html +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - Not found · Horizon - - - - - - - - - -
-
-

404Not found

-

Not here.

-

This page doesn't exist. The rest of Horizon is one page away.

- -

Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

-
-
- - - diff --git a/website/src/bench.js b/website/src/bench.js deleted file mode 100644 index 40185c79d..000000000 --- a/website/src/bench.js +++ /dev/null @@ -1,167 +0,0 @@ -// The Benchmarks page's tables, from the summary (public/benchmarks.json, or the telemetry server's -// GET /v1/benchmarks/summary in the same shape). Shared by build.mjs (baked) and benchmarks-page.js (live). -import { escape } from "./markdown.js"; - -export const METRICS = [ - { key: "avg_fps", label: "Average FPS", kind: "fps", better: "high" }, - { key: "low_1pct_fps", label: "1% low FPS", kind: "fps", better: "high", hint: "the slowest 1% of frames, as FPS" }, - { key: "p95_ms", label: "Frame time, 95th percentile", kind: "ms", better: "low" }, - { key: "world_ms", label: "Start to in-world", kind: "ms", better: "low", hint: "process start to the spawn area loaded and drawn" }, - { key: "chunk_load_ms", label: "Chunk load after a teleport", kind: "ms", better: "low", hint: "the four scenes' average" }, - { key: "rss_steady_mb", label: "Memory while playing", kind: "mb", better: "low" }, - { key: "rss_peak_mb", label: "Memory, peak", kind: "mb", better: "low" }, -]; - -export function format(kind, x) { - if (x == null || !Number.isFinite(x)) return "–"; - if (kind === "fps") return x >= 100 ? Math.round(x).toLocaleString("en") : x.toFixed(x >= 10 ? 0 : 1); - if (kind === "ms") return x >= 1000 ? `${(x / 1000).toFixed(x >= 10000 ? 0 : 1)} s` : `${x < 10 ? x.toFixed(1) : Math.round(x)} ms`; - if (kind === "mb") return x >= 1000 ? `${(x / 1024).toFixed(1)} GB` : `${Math.round(x)} MB`; - return String(x); -} - -// "2.4x faster", "1.3x slower", "2.0x less" (memory), from Horizon's side. -export function compare(metric, horizon, java) { - if (horizon == null || java == null || !horizon || !java) return null; - const ratio = metric.better === "high" ? horizon / java : java / horizon; - if (Math.abs(ratio - 1) < 0.05) return { text: "about the same", wins: "tie" }; - const word = metric.kind === "mb" ? (ratio > 1 ? "less" : "more") : ratio > 1 ? "faster" : "slower"; - const r = ratio > 1 ? ratio : 1 / ratio; - return { text: `${r.toFixed(r >= 10 ? 0 : 1)}x ${word}`, wins: ratio > 1 ? "horizon" : "java" }; -} - -// The game's average frame rate sat at a display cap (`capped_fps`): the real one is at least that. -export const capped = (row) => Boolean(row?.capped_fps && row.medians?.avg_fps >= row.capped_fps * 0.97); - -// compare() between two rows, saying "at least" where Horizon's average sat at a cap. -export function compareRows(metric, h, j) { - const c = compare(metric, h?.medians?.[metric.key], j?.medians?.[metric.key]); - if (!c || metric.key !== "avg_fps" || !capped(h)) return c; - return c.wins === "horizon" ? { ...c, text: `at least ${c.text}` } : { text: "capped, can't tell", wins: "none" }; -} - -export const cell = (metric, row) => { - const v = format(metric.kind, row?.medians?.[metric.key]); - return metric.key === "avg_fps" && capped(row) ? `${v} (cap)` : v; -}; - -const machines = (groups) => { - const by = new Map(); - for (const g of groups.filter((g) => g.source === "us")) { - if (!by.has(g.machine)) by.set(g.machine, []); - by.get(g.machine).push(g); - } - return by; -}; - -const pick = (rows, game, rd) => rows.find((r) => r.game === game && r.render_distance === rd); - -// One machine we measured: Horizon and Java side by side at each render distance. -export function machineHtml(name, rows) { - const first = rows[0]; - const distances = [...new Set(rows.map((r) => r.render_distance))].sort((a, b) => a - b); - const horizon = rows.find((r) => r.game === "horizon"); - const java = rows.find((r) => r.game === "vanilla"); - const head = distances.map((rd) => `Render distance ${rd}`).join(""); - const sub = distances.map(() => `HorizonJavaHorizon against Java`).join(""); - const body = METRICS.map((m) => { - const cells = distances - .map((rd) => { - const h = pick(rows, "horizon", rd); - const j = pick(rows, "vanilla", rd); - const c = compareRows(m, h, j); - return `${cell(m, h)}${cell(m, j)}${c ? escape(c.text) : ""}`; - }) - .join(""); - return `${escape(m.label)}${m.hint ? `${escape(m.hint)}` : ""}${cells}`; - }).join(""); - const javaWins = METRICS.flatMap((m) => - distances.filter((rd) => compareRows(m, pick(rows, "horizon", rd), pick(rows, "vanilla", rd))?.wins === "java").map((rd) => `${m.label.toLowerCase()} at ${rd}`), - ); - // Per scene too: an average that Horizon wins can hide a scene where Java is faster. - const sceneName = { village: "the village", forest: "the forest", ocean: "the ocean", mountain: "the mountain" }; - for (const rd of distances) { - const h = pick(rows, "horizon", rd); - const j = pick(rows, "vanilla", rd); - for (const [scene, js] of Object.entries(j?.scenes || {})) { - const hs = h?.scenes?.[scene]; - if (!hs?.avg_fps || !js?.avg_fps || (h.capped_fps && hs.avg_fps >= h.capped_fps * 0.97)) continue; - if (js.avg_fps > hs.avg_fps * 1.05) javaWins.push(`average FPS over ${sceneName[scene] || scene} at ${rd} (${format("fps", js.avg_fps)} against ${format("fps", hs.avg_fps)})`); - } - } - const facts = [ - ["CPU", first.cpu], - ["GPU", first.gpu], - ["Horizon", horizon ? `${horizon.version} · ${horizon.backend || "?"}` : "not measured"], - ["Java", java ? `${java.version} (vanilla) · ${java.backend || "?"}` : "not measured"], - ["Measured", `${first.measured}${first.repeats ? ` · ${first.repeats} runs of each` : ""}${first.window ? ` · ${first.window.join("x")} window` : ""}`], - ]; - return `
-
-

Measured by us

-

${escape(name)}

-
${facts.map(([k, v]) => `
${k}
${escape(String(v))}
`).join("")}
- ${rows.find((r) => r.note) ? `

${escape(rows.find((r) => r.note).note)}

` : ""} -
-
- ${head}${sub} - ${body} -
- ${javaWins.length ? `

Where Java is ahead: ${escape(javaWins.join("; "))}.

` : `

Horizon is ahead on every figure here.

`} -
`; -} - -export function machinesHtml(summary) { - const by = machines(summary?.groups || []); - if (!by.size) return `

No measurements are published yet.

`; - return [...by].map(([name, rows]) => machineHtml(name, rows)).join("\n"); -} - -// The hardware breakdowns (the server's classes), in words. -export const DIMENSIONS = [ - { key: "ram", label: "Memory", word: (c) => `${c} RAM` }, - { key: "vram", label: "Graphics memory", word: (c) => (c === "shared" ? "shared graphics memory" : `${c} graphics memory`) }, - { key: "storage", label: "Drive", word: (c) => ({ nvme: "NVMe", ssd: "SSD", hdd: "hard disk" })[c] || c }, - { key: "os", label: "System", word: (c) => ({ linux: "Linux", macos: "macOS", windows: "Windows" })[c] || c }, - { key: "gpu_kind", label: "Graphics", word: (c) => (c === "integrated" ? "integrated GPU" : c === "discrete" ? "separate GPU" : c) }, -]; - -// A group's breakdowns in one line: "32 GB RAM (3) · NVMe (3) · Linux (3)". Empty without any. -export function breakdownLine(breakdowns) { - return DIMENSIONS.flatMap((d) => (breakdowns?.[d.key] || []).map((c) => `${d.word(c.class)} (${c.installs})`)).join(" · "); -} - -// GET /v1/aggregate's breakdowns: players' play sessions per hardware class. Empty without any. -export function hardwareHtml(aggregate) { - const b = aggregate?.breakdowns || {}; - const dims = DIMENSIONS.filter((d) => b[d.key]?.length); - if (!dims.length) return ""; - const rows = dims - .flatMap((d) => - b[d.key].map( - (c, i) => - `${i === 0 ? `${escape(d.label)}` : ""}${escape(d.word(c.class))}${c.installs}${Math.round(c.hours).toLocaleString("en")}${format("ms", c.p50_ms)}${format("ms", c.p99_ms)}`, - ), - ) - .join(""); - return `
- - ${rows} -
ByClassInstallsHours playedFrame time, medianFrame time, 99th percentile
`; -} - -// Players' groups: one row each, at least `min_installs` installs. -export function playersHtml(summary) { - const groups = (summary?.groups || []).filter((g) => g.source === "players"); - if (!groups.length) - return `

No player results yet. A GPU and CPU pair shows here once at least ${summary?.min_installs || 3} different installs have shared a benchmark with it.

`; - const rows = groups - .map( - (g) => `${escape(g.gpu)}${escape(g.cpu)}${g.render_distance}${g.game === "vanilla" ? "Java" : "Horizon"}${["avg_fps", "low_1pct_fps", "p95_ms", "world_ms", "rss_steady_mb"].map((k) => `${format(METRICS.find((m) => m.key === k).kind, g.medians?.[k])}`).join("")}From ${g.installs} players${breakdownLine(g.breakdowns) ? `${escape(breakdownLine(g.breakdowns))}` : ""}`, - ) - .join(""); - return `
- - ${rows} -
GPU and CPURender distanceGameAverage FPS1% lowp95To in-worldMemorySource
`; -} diff --git a/website/src/benchmarks-page.js b/website/src/benchmarks-page.js deleted file mode 100644 index 5d05848e3..000000000 --- a/website/src/benchmarks-page.js +++ /dev/null @@ -1,108 +0,0 @@ -// The Benchmarks page: players' results from the telemetry server (the baked summary when it doesn't answer) -// and the hardware picker (a measurement when there is one, else an estimate from src/estimate.js). -import { escape } from "./markdown.js"; -import { METRICS, cell, compareRows, format, hardwareHtml, playersHtml } from "./bench.js"; -import { estimate, measured, memoryNotes } from "./estimate.js"; -import { findCpu, findGpu } from "./hardware.js"; -import { setUpMenu, setUpTheme } from "./chrome.js"; - -const TELEMETRY = "https://telemetry.playhorizon.dev"; -const baked = JSON.parse(document.getElementById("bench-data").textContent); -let groups = baked.groups || []; - -async function live() { - try { - const res = await fetch(`${TELEMETRY}/v1/benchmarks/summary`, { signal: AbortSignal.timeout(3000) }); - if (!res.ok) throw new Error(String(res.status)); - const summary = await res.json(); - if (summary.format !== "horizon-benchmark-summary" || summary.version !== 1 || !Array.isArray(summary.groups)) throw new Error("format"); - // Our own rows stay the baked ones; players' come from the server. - const players = summary.groups.filter((g) => g.source === "players" && g.installs >= (summary.min_installs || 3)); - groups = [...groups.filter((g) => g.source === "us"), ...players]; - document.getElementById("players-table").innerHTML = playersHtml({ ...summary, groups: players }); - document.querySelector("[data-players-source]").textContent = `Live from the telemetry server, aggregated ${summary.generated.slice(0, 16).replace("T", " ")} UTC.`; - render(); - } catch { - // The baked results stay; the line under the heading already says when they were made. - } -} - -// Players' play sessions per hardware class (last 30 days); the section stays hidden until there are some. -async function hardware() { - try { - const res = await fetch(`${TELEMETRY}/v1/aggregate?days=30`, { signal: AbortSignal.timeout(3000) }); - if (!res.ok) return; - const html = hardwareHtml(await res.json()); - if (!html) return; - document.getElementById("players-hardware-table").innerHTML = html; - document.getElementById("players-hardware").hidden = false; - } catch { - // Nothing to show. - } -} - -const picker = document.getElementById("picker"); -const out = document.getElementById("pick-result"); - -const range = (kind, e) => { - if (!e) return "–"; - if (e.atLeast) return `at least ${format(kind, e.low)}`; - return e.low != null ? `${format(kind, e.low)} to ${format(kind, e.high)}` : format(kind, e.value); -}; - -function sourceBadge(row) { - return row.source === "us" ? `Measured by us · ${escape(row.machine)}` : `From ${row.installs} players`; -} - -function measuredTable(h, j) { - return `${METRICS.map((m) => { - const c = compareRows(m, h, j); - return ``; - }).join("")}
HorizonJavaHorizon against Java
${escape(m.label)}${cell(m, h)}${cell(m, j)}${c ? escape(c.text) : ""}
`; -} - -function estimateTable(h, j) { - return `${METRICS.map( - (m) => ``, - ).join("")}
Horizon (estimate)Java (estimate)
${escape(m.label)}${range(m.kind, h?.[m.key])}${range(m.kind, j?.[m.key])}
`; -} - -function render() { - const gpu = findGpu(picker.gpu.value); - const cpu = findCpu(picker.cpu.value); - const rd = Number(picker.rd.value); - const ramGb = Number(picker.ram.value) || null; - if (!gpu || !cpu) return; - // Horizon's and Java's notes, each once (the players' hardware is the same for both). - const notesHtml = (...lists) => { - const notes = [...new Set(lists.flat())]; - return notes.length ? `
    ${notes.map((n) => `
  • ${escape(n)}
  • `).join("")}
` : ""; - }; - const mh = measured(groups, gpu, cpu, rd, "horizon"); - const mj = measured(groups, gpu, cpu, rd, "vanilla"); - if (mh.length || mj.length) { - const h = mh[0]; - const j = mj[0]; - out.innerHTML = `

${[h, j].filter(Boolean).map(sourceBadge).join(" ")}

${measuredTable(h, j)}${notesHtml(...[h, j].filter(Boolean).map((row) => memoryNotes(row, gpu, ramGb)))}${ - h && h.source === "us" && h.measured ? `

Measured ${escape(h.measured)} with Horizon ${escape(h.version)}. The full table is under Measured by us.

` : "" - }`; - return; - } - const h = estimate(groups, gpu, cpu, rd, "horizon", { ramGb }); - const j = estimate(groups, gpu, cpu, rd, "vanilla", { ramGb }); - if (!h && !j) { - out.innerHTML = `

Nothing measured at render distance ${rd} to estimate from yet.

`; - return; - } - const base = (h || j).base; - const f = (h || j).factors; - const times = (x) => `${x >= 1 ? x.toFixed(x >= 10 ? 0 : 1) : x.toFixed(2)}x`; - out.innerHTML = `

Estimate From ${escape(base.source === "us" ? base.machine : `${base.gpu} with ${base.cpu}`)} (${escape(base.gpu)}, ${escape(base.cpu)}): GPU factor ${times(f.gpu)}, CPU factor ${times(f.cpu)}. How

${estimateTable(h, j)}${notesHtml(h?.notes || [], j?.notes || [])}

Ranges, not measurements: the real figure depends on drivers, the graphics API and cooling too. Memory is the measured machine's.

`; -} - -setUpTheme(); -setUpMenu(); -picker.addEventListener("change", render); -render(); -live(); -hardware(); diff --git a/website/src/benchmarks.html b/website/src/benchmarks.html deleted file mode 100644 index 41e270c5b..000000000 --- a/website/src/benchmarks.html +++ /dev/null @@ -1,105 +0,0 @@ - - - - - - Benchmarks: Horizon against Java Edition · Horizon - - - - - - - - - - - - - - - - - - - - -{{SITE_NAV}} -
-
-

BenchmarksHorizon against Java Edition 26.3

-

Same machine, same world, same flight.

-

We run Horizon and vanilla Minecraft: Java Edition 26.3 one after the other on the same computer: a fresh world from the same seed, the same settings, and the same four flights over a village, a forest, the ocean and a mountain. Every figure comes from the same code for both games. Where Java does better, the tables say so.

- -
-

Measured by us

-

The project's own machines, at render distance 12 (vanilla's default) and 32. VSync off, no frame cap, a 1280x720 window, simulation distance 12, everything else at vanilla's defaults. Each figure is the median over the runs; the frame figures are averaged over the four flights.

-
-{{MACHINES}} -
-
- -
-

Your hardware

-

Pick a graphics card, a processor and, if you know it, your memory. If we or at least three players have measured that pair, you see what was measured; otherwise an estimate from the nearest measured machine, as a range.

-
- - - -
Render distance - - -
-
-

The picker needs JavaScript; the tables above and the method below work without it.

-
- -
-

From players

-

Players who allow benchmark uploads in the launcher's data collection settings share the report of horizon-client --benchmark standard. Results are grouped by graphics card, processor and render distance, and a group shows only once at least 3 different installs are in it, so no one can be picked out. Only medians are published, with how the group's installs split by memory, graphics memory, drive and system in coarse classes (each class only with at least 3 installs too): no install ID, date, driver, exact memory or screen.

-

{{PLAYERS_SOURCE}}

-
-{{PLAYERS}} -
-
- - - -
-

How the estimates work

-
-

An estimate starts from the measured machine closest to the one you picked, then scales its figures with a small table of specifications we wrote ourselves (no benchmark database):

-
    -
  • GPU factor: the geometric mean of the two graphics cards' ratio of FP32 shader throughput (TFLOPS) and of memory bandwidth (GB/s), as their makers state them.
  • -
  • CPU factor: the ratio of the two processors' single-thread scores: top boost clock times a rough factor per chip generation (Zen 4 = 1).
  • -
  • Frame rate: when the measured run split each frame into CPU and GPU time, the slower side is scaled by its factor; otherwise by the geometric mean of both. Whatever the split, the real figure lies between the measured one scaled by the smaller and by the larger factor; we widen that by 15% for the roughness of the table, and show it as the range.
  • -
  • Load times are CPU work (generating, lighting and meshing chunks), scaled by the CPU factor. Memory is not scaled: it follows the world and the settings, not the speed.
  • -
  • Memory size: when players' results say how much memory and graphics memory their machines have, a measured group whose players have neither yours counts as further away, and the estimate says what they had. With your memory picked, it also says when the game's peak use is a large share of it.
  • -
-

Estimates ignore drivers, the graphics API, thermal limits and the operating system, which can matter as much as the chip. Treat them as a rough idea, and run horizon-client --benchmark standard on your own machine for the real figure.

-
-
- The specification table -
{{SPEC_TABLE}}
-
-
- -
-

How we measure

-
-

tools/perf_bench.py starts each game from a fresh world (seed 1234, creative), waits until every chunk around the spawn is loaded and drawn, then for each scene teleports, waits for the chunks, holds for 2 seconds and flies a straight 192-block path in 12 seconds. Every frame is recorded. Vanilla runs as players get it (your own client, the official launcher's Java options, Java 25), driven by a small development-only mod that only calls the game's own code; nothing of Minecraft is shipped. The full method and its caveats are in docs/benchmark.md, and every raw report is in the repository.

-

Measure your own computer with horizon-client --benchmark standard --render-distance 12: it writes a report to the benchmarks folder of the game folder.

-
-
-

Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

-
-
-{{SITE_FOOTER}} - - - diff --git a/website/src/chrome.js b/website/src/chrome.js deleted file mode 100644 index d11eb3370..000000000 --- a/website/src/chrome.js +++ /dev/null @@ -1,90 +0,0 @@ -// What every page with the site's top bar shares: the light and dark switch and the phone menu. -// Used by Home, Releases, Benchmarks and Docs. -const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches; - -// The page follows the system; the toggle picks the other appearance and remembers it. -export function setUpTheme() { - const root = document.documentElement; - const button = document.querySelector(".theme-toggle"); - if (!button) return; - const label = button.querySelector("[data-theme-label]"); - const system = matchMedia("(prefers-color-scheme: dark)"); - const dark = () => (root.dataset.theme ? root.dataset.theme === "dark" : system.matches); - const show = () => (label.textContent = dark() ? "Light" : "Dark"); - button.addEventListener("click", () => { - root.dataset.theme = dark() ? "light" : "dark"; - try { - localStorage.setItem("theme", root.dataset.theme); - } catch {} - show(); - }); - system.addEventListener("change", show); - show(); -} - -// The phone menu: a full-screen sheet; the page behind it is inert while it is open. -export function setUpMenu() { - const bar = document.querySelector(".nav"); - const button = document.querySelector(".menu-button"); - const menu = document.getElementById("menu"); - const content = document.querySelector("[data-menu-content]") || document.getElementById("main"); - if (!bar || !button || !menu) return; - const label = button.querySelector(".menu-label"); - const items = [...menu.querySelectorAll("nav a")]; - items.forEach((a, i) => a.style.setProperty("transition-delay", `${60 + i * 35}ms`)); - let closing; - const setOpen = (open) => { - clearTimeout(closing); - button.setAttribute("aria-expanded", String(open)); - label.textContent = open ? "Close" : "Menu"; - bar.classList.toggle("is-menu", open); - content.inert = open; - document.body.style.overflow = open ? "hidden" : ""; - if (open) { - menu.hidden = false; - requestAnimationFrame(() => requestAnimationFrame(() => menu.classList.add("is-open"))); - items[0].focus({ preventScroll: true }); - } else { - menu.classList.remove("is-open"); - closing = setTimeout(() => (menu.hidden = true), reducedMotion ? 0 : 320); - } - }; - button.addEventListener("click", () => setOpen(button.getAttribute("aria-expanded") !== "true")); - items.forEach((a) => a.addEventListener("click", () => setOpen(false))); - addEventListener("keydown", (e) => { - if (e.key === "Escape" && button.getAttribute("aria-expanded") === "true") { - setOpen(false); - button.focus(); - } - }); - matchMedia("(min-width: 1280px)").addEventListener("change", (e) => e.matches && setOpen(false)); -} - -// GitHub answers, cached for ten minutes in the tab. -export async function cached(key, load) { - try { - const hit = JSON.parse(sessionStorage.getItem(key) || "null"); - if (hit && Date.now() - hit.at < 10 * 60 * 1000) return hit.value; - } catch {} - const value = await load(); - try { - sessionStorage.setItem(key, JSON.stringify({ at: Date.now(), value })); - } catch {} - return value; -} - -export async function get(url, as = "json") { - const res = await fetch(url, { headers: as === "json" ? { Accept: "application/vnd.github+json" } : {} }); - if (!res.ok) throw new Error(`${res.status}`); - return as === "json" ? res.json() : res.text(); -} - -export const slim = (r) => ({ - tag_name: r.tag_name, - name: r.name, - published_at: r.published_at, - html_url: r.html_url, - prerelease: r.prerelease, - body: r.body || "", - assets: (r.assets || []).map((a) => ({ name: a.name, browser_download_url: a.browser_download_url, size: a.size })), -}); diff --git a/website/src/contributors.js b/website/src/contributors.js deleted file mode 100644 index 12bce9457..000000000 --- a/website/src/contributors.js +++ /dev/null @@ -1,39 +0,0 @@ -// The contributors: GitHub's list for the repository, without bots, the owner first. Shared by -// build.mjs (baked into the page) and main.js (refreshed from GitHub). -import { escape } from "./markdown.js"; - -const OWNER = "ludovic111"; -const AVATARS = "https://avatars.githubusercontent.com/"; - -// Reduces GitHub's contributor objects to what the page shows; bots (type Bot, or a login -// ending in [bot]) and anything without a login or a profile address are dropped. -export function contributorsFrom(list) { - if (!Array.isArray(list)) return []; - return list - .filter((c) => c && typeof c.login === "string" && c.login && c.type !== "Bot" && !/\[bot\]$/i.test(c.login)) - .map((c) => ({ - login: c.login, - html_url: typeof c.html_url === "string" ? c.html_url : `https://github.com/${c.login}`, - avatar_url: typeof c.avatar_url === "string" ? c.avatar_url : "", - contributions: Number(c.contributions) || 0, - })) - .sort((a, b) => (b.login === OWNER) - (a.login === OWNER) || b.contributions - a.contributions); -} - -// GitHub serves avatars at any size: 96 px is twice what the page draws, for sharp screens. -export function avatar(url) { - if (!url.startsWith(AVATARS)) return ""; - const u = new URL(url); - u.searchParams.set("s", "96"); - return u.href; -} - -export function contributorsHtml(list) { - return list - .map((c) => { - const src = avatar(c.avatar_url); - const count = `${c.contributions.toLocaleString("en-US")} ${c.contributions === 1 ? "commit" : "commits"}`; - return `
  • ${src ? `` : ``}${escape(c.login)}${count}
  • `; - }) - .join(""); -} diff --git a/website/src/docs-page.js b/website/src/docs-page.js deleted file mode 100644 index 99da35187..000000000 --- a/website/src/docs-page.js +++ /dev/null @@ -1,5 +0,0 @@ -// The Docs pages share the site's theme switch and phone menu. -import { setUpMenu, setUpTheme } from "./chrome.js"; - -setUpTheme(); -setUpMenu(); diff --git a/website/src/docs.html b/website/src/docs.html deleted file mode 100644 index 56ba89c09..000000000 --- a/website/src/docs.html +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - {{DOC_TITLE}} · Horizon docs - - - - - - - - - - - - - - - - - - - - -{{SITE_NAV}} - -
    -
    - Docs menu - -
    - - -
    -

    {{DOC_GROUP}}

    -

    {{DOC_TITLE}}

    -

    {{DOC_LEDE}}

    -{{DOC_TOC}} -
    -{{DOC_BODY}} -
    - -

    Edit this page on GitHub · Spotted something wrong? Open an issue or ask on Discord.

    -

    Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

    -
    -
    - - - diff --git a/website/src/estimate.js b/website/src/estimate.js deleted file mode 100644 index ccd053cc0..000000000 --- a/website/src/estimate.js +++ /dev/null @@ -1,110 +0,0 @@ -// Estimates for hardware nobody has measured yet, from the nearest measured machine and the spec table -// (src/hardware.js). The method, which the Benchmarks page explains: -// -// - GPU factor: the geometric mean of the two GPUs' FP32 throughput ratio and memory bandwidth ratio. -// - CPU factor: the ratio of the two CPUs' single-thread scores (boost clock x generation factor). -// - Frames: when the measured run split each frame into CPU and GPU time, the slower of the two is scaled by its -// own factor; otherwise the frame rate is scaled by the geometric mean of both factors. Whatever the split, the -// true figure lies between the measured one scaled by the smaller and by the larger factor, widened by 15% for -// the roughness of the table: that is the range shown. -// - World and chunk load times are CPU work (generation, lighting, meshing): scaled by the CPU factor. -// - Memory is not scaled: it depends on the world and settings, not on speed. -// - Memory size: players' groups say how their installs split by RAM and by the GPU's own memory (breakdowns). A -// base whose players have neither the picked RAM nor the picked GPU's memory class counts as further away, and -// the estimate says what the base's players had, and when the game's peak memory is a large share of the RAM. -import { findCpu, findGpu, ramClass, singleThread, vramClass } from "./hardware.js"; - -const MARGIN = 0.15; - -export function factors(fromGpu, fromCpu, toGpu, toCpu) { - const gpu = Math.sqrt((toGpu.tflops / fromGpu.tflops) * (toGpu.gbps / fromGpu.gbps)); - const cpu = singleThread(toCpu) / singleThread(fromCpu); - return { gpu, cpu }; -} - -const distance = (f) => Math.abs(Math.log(f.gpu)) + Math.abs(Math.log(f.cpu)); -// Added to the distance per memory class (RAM, VRAM) the base's players don't have: about a 20% speed gap. -const MEMORY_MISMATCH = 0.2; - -// The classes a row's installs have in a breakdown, or null when it has none (our own rows, older summaries). -const classesIn = (row, dim) => (row.breakdowns?.[dim]?.length ? row.breakdowns[dim].map((c) => c.class) : null); - -function mismatch(row, gpu, ramGb) { - let d = 0; - const vram = classesIn(row, "vram"); - if (vram && !vram.includes(vramClass(gpu))) d += MEMORY_MISMATCH; - const ram = classesIn(row, "ram"); - if (ram && ramGb && !ram.includes(ramClass(ramGb))) d += MEMORY_MISMATCH; - return d; -} - -// What to say about memory: the base's players' RAM and VRAM when they differ from the pick, and the game's peak -// memory against the picked RAM. -export function memoryNotes(row, gpu, ramGb) { - const notes = []; - const list = (dim) => row.breakdowns[dim].map((c) => `${c.class} (${c.installs})`).join(", "); - const vram = classesIn(row, "vram"); - if (vram && gpu && !vram.includes(vramClass(gpu))) notes.push(`The measured players' graphics cards have ${list("vram")} of their own memory; this one has ${gpu.vram_gb ? `${gpu.vram_gb} GB` : "none (it shares the system's)"}.`); - const ram = classesIn(row, "ram"); - if (ram && ramGb && !ram.includes(ramClass(ramGb))) notes.push(`The measured players have ${list("ram")} of memory, not ${ramGb} GB.`); - const peak = row.medians?.rss_peak_mb; - if (ramGb && peak && peak / 1024 > ramGb * 0.4) - notes.push(`${row.game === "vanilla" ? "Java" : "Horizon"} used up to ${(peak / 1024).toFixed(1)} GB here: with ${ramGb} GB, close other programs, or the system may swap and stutter.`); - return notes; -} - -// The rows (benchmarks.json groups) usable as a base: a known GPU and CPU. -function known(rows) { - return rows.map((row) => ({ row, gpu: findGpu(row.gpu), cpu: findCpu(row.cpu) })).filter((r) => r.gpu && r.cpu); -} - -// The measured row for exactly this GPU and CPU, players' first when there are some (more installs), or null. -export function measured(rows, gpu, cpu, rd, game) { - const hits = known(rows).filter((r) => r.gpu === gpu && r.cpu === cpu && r.row.render_distance === rd && r.row.game === game); - hits.sort((a, b) => (b.row.installs || 0) - (a.row.installs || 0)); - return hits.map((r) => r.row); -} - -// The nearest measured machine for a target GPU and CPU, for one game and render distance. -export function nearest(rows, gpu, cpu, rd, game, { ramGb } = {}) { - let best = null; - for (const r of known(rows)) { - if (r.row.render_distance !== rd || r.row.game !== game) continue; - const f = factors(r.gpu, r.cpu, gpu, cpu); - const d = distance(f) + mismatch(r.row, gpu, ramGb); - if (!best || d < best.d) best = { ...r, f, d }; - } - return best; -} - -export function estimate(rows, gpu, cpu, rd, game, { ramGb } = {}) { - const base = nearest(rows, gpu, cpu, rd, game, { ramGb }); - if (!base) return null; - const m = base.row.medians; - const { gpu: g, cpu: c } = base.f; - const lo = Math.min(g, c) * (1 - MARGIN); - const hi = Math.max(g, c) * (1 + MARGIN); - let scale = Math.sqrt(g * c); - if (m.cpu_p50_ms && m.gpu_p50_ms) { - const worst = Math.max(m.cpu_p50_ms, m.gpu_p50_ms); - scale = worst / Math.max(m.cpu_p50_ms / c, m.gpu_p50_ms / g); - } - scale = Math.min(hi, Math.max(lo, scale)); - const fps = (x) => (x == null ? null : { value: x * scale, low: x * lo, high: x * hi }); - // A base held to its display's refresh rate gives only a floor for the average. - const avg = fps(m.avg_fps); - if (avg && base.row.capped_fps && m.avg_fps >= base.row.capped_fps * 0.97) Object.assign(avg, { value: null, high: null, atLeast: true }); - const time = (x, f) => (x == null ? null : { value: x / f, low: x / (f * (1 + MARGIN)), high: x / (f * (1 - MARGIN)) }); - return { - base: base.row, - factors: base.f, - avg_fps: avg, - low_1pct_fps: fps(m.low_1pct_fps), - p95_ms: m.p95_ms == null ? null : { value: m.p95_ms / scale, low: m.p95_ms / hi, high: m.p95_ms / lo }, - world_ms: time(m.world_ms, c), - chunk_load_ms: time(m.chunk_load_ms, c), - rss_steady_mb: m.rss_steady_mb == null ? null : { value: m.rss_steady_mb }, - rss_peak_mb: m.rss_peak_mb == null ? null : { value: m.rss_peak_mb }, - notes: memoryNotes(base.row, gpu, ramGb), - }; -} diff --git a/website/src/estimate.test.mjs b/website/src/estimate.test.mjs deleted file mode 100644 index d46f9c4b5..000000000 --- a/website/src/estimate.test.mjs +++ /dev/null @@ -1,101 +0,0 @@ -// node --test website/src/ (npm test in website/) -import { test } from "node:test"; -import assert from "node:assert/strict"; -import { estimate, factors, measured, nearest } from "./estimate.js"; -import { CPUS, GPUS, findCpu, findGpu } from "./hardware.js"; - -const row = (gpu, cpu, medians, extra = {}) => ({ gpu, cpu, render_distance: 12, game: "horizon", source: "us", medians, ...extra }); -const mac = row("Apple M4 Pro", "Apple M4 Pro", { avg_fps: 500, low_1pct_fps: 100, p95_ms: 3, world_ms: 4000, chunk_load_ms: 1000, rss_peak_mb: 1500, rss_steady_mb: 1200 }); -const laptop = row("Mesa Intel HD Graphics 620 (KBL GT2)", "Intel Core i7-7500U CPU @ 2.70GHz", { avg_fps: 100, low_1pct_fps: 20, p95_ms: 15, world_ms: 12000, chunk_load_ms: 5000, rss_peak_mb: 1400, rss_steady_mb: 1100, cpu_p50_ms: 4, gpu_p50_ms: 9 }); - -test("every reported name of our machines is in the table", () => { - assert.equal(findGpu("Apple M4 Pro").name, "Apple M4 Pro (20-core GPU)"); - assert.equal(findGpu("Mesa Intel HD Graphics 620 (KBL GT2)").name, "Intel HD Graphics 620"); - assert.equal(findGpu("NVIDIA GeForce RTX 4080").name, "NVIDIA GeForce RTX 4080"); - assert.equal(findGpu("NVIDIA GeForce RTX 4080 SUPER"), null); - assert.equal(findCpu("13th Gen Intel Core i7-13700KF").name, "Intel Core i7-13700K / KF"); - assert.equal(findCpu("Intel Core i7-7500U CPU @ 2.70GHz").name, "Intel Core i7-7500U"); - for (const g of GPUS) assert.equal(findGpu(g.name), g, g.name); - for (const c of CPUS) assert.equal(findCpu(c.name), c, c.name); -}); - -test("an exact match is a measurement, not an estimate", () => { - assert.deepEqual(measured([mac, laptop], findGpu("Apple M4 Pro"), findCpu("Apple M4 Pro"), 12, "horizon"), [mac]); - assert.deepEqual(measured([mac], findGpu("Apple M4 Pro"), findCpu("Apple M4 Pro"), 32, "horizon"), []); -}); - -test("the nearest machine is the base, and the range holds the estimate", () => { - const gpu = findGpu("Intel Iris Xe Graphics (96 EU)"); - const cpu = findCpu("Intel Core i5-1135G7"); - assert.equal(nearest([mac, laptop], gpu, cpu, 12, "horizon").row, laptop); - const e = estimate([mac, laptop], gpu, cpu, 12, "horizon"); - const f = factors(findGpu(laptop.gpu), findCpu(laptop.cpu), gpu, cpu); - assert.ok(f.gpu > 1 && f.cpu > 1); - for (const key of ["avg_fps", "low_1pct_fps", "p95_ms", "world_ms", "chunk_load_ms"]) { - const { value, low, high } = e[key]; - assert.ok(low <= value && value <= high, key); - } - // GPU-bound frames (9 ms GPU, 4 ms CPU) follow the GPU factor. - assert.ok(Math.abs(e.avg_fps.value - 100 * Math.min(f.gpu, 9 / (4 / f.cpu))) < 1e-9); - assert.ok(Math.abs(e.world_ms.value - 12000 / f.cpu) < 1e-9); - assert.equal(e.rss_steady_mb.value, 1100); -}); - -test("no base, no estimate", () => { - assert.equal(estimate([mac], findGpu("Apple M4"), findCpu("Apple M4"), 32, "horizon"), null); - assert.equal(estimate([mac], findGpu("Apple M4"), findCpu("Apple M4"), 12, "vanilla"), null); -}); - -test("a base held to its display's refresh rate gives only a floor for the average", () => { - const held = { ...mac, capped_fps: 144, medians: { ...mac.medians, avg_fps: 144 } }; - const e = estimate([held], findGpu("NVIDIA GeForce RTX 4060"), findCpu("AMD Ryzen 5 5600X"), 12, "horizon"); - assert.equal(e.avg_fps.atLeast, true); - assert.equal(e.avg_fps.high, null); - assert.ok(e.avg_fps.low > 0); - // The lows sit under the cap: still a range. - assert.ok(e.low_1pct_fps.high > e.low_1pct_fps.low); -}); - -test("a release title of issue numbers falls back to its notes", async () => { - const { parts } = await import("./releases.js"); - const r = { tag_name: "v2026.10.22.07", name: "Horizon 2026.10.22.07: #1255, mob pushes, fix, #1222", body: "### Fixed\n- Fix #1222: single player runs in the frame again (#1257, fixes #1222)\n- Mob pushes: one list per mob (#1205)\n" }; - assert.equal(parts(r).line, "Single player runs in the frame again and 1 more"); - assert.equal(parts({ ...r, name: "Horizon 2026.10.22.05: Hoppers, mob tick, server tick" }).line, "Hoppers, mob tick, server tick"); -}); - -test("players' memory classes steer the base and the notes", async () => { - const { memoryNotes } = await import("./estimate.js"); - const { ramClass, vramClass } = await import("./hardware.js"); - assert.equal(vramClass(findGpu("NVIDIA GeForce RTX 4080")), "16 GB"); - assert.equal(vramClass(findGpu("NVIDIA GeForce RTX 3080")), "12 GB"); - assert.equal(vramClass(findGpu("Apple M4 Pro")), "shared"); - assert.equal(ramClass(16), "16 GB"); - // Two equally near groups: the one whose players have the picked GPU's memory class wins. - const players = (vram, ram, fps) => - row("NVIDIA GeForce RTX 4070", "AMD Ryzen 5 7600X", { avg_fps: fps, rss_peak_mb: 3600 }, { source: "players", installs: 3, breakdowns: { vram: [{ class: vram, installs: 3 }], ram: [{ class: ram, installs: 3 }] } }); - const a = players("8 GB", "16 GB", 400); - const b = { ...players("12 GB", "32 GB", 500), cpu: "AMD Ryzen 7 7800X3D" }; - const gpu = findGpu("NVIDIA GeForce RTX 4070 Ti"); - const cpu = findCpu("AMD Ryzen 5 7600X"); - assert.equal(nearest([a, b], gpu, cpu, 12, "horizon").row, b, "12 GB like the 4070 Ti, though the CPU differs"); - assert.equal(nearest([a, b], gpu, cpu, 12, "horizon", { ramGb: 16 }).row, a, "both classes count"); - assert.deepEqual(memoryNotes(b, gpu, 32), []); - const notes = memoryNotes(a, gpu, 8); - assert.equal(notes.length, 3); - assert.match(notes[0], /8 GB \(3\) of their own memory; this one has 12 GB/); - assert.match(notes[1], /16 GB \(3\) of memory, not 8 GB/); - assert.match(notes[2], /Horizon used up to 3\.5 GB/); - // Our own rows have no breakdowns: only the peak memory note. - assert.deepEqual(memoryNotes(mac, gpu, 32), []); - assert.equal(estimate([a], gpu, cpu, 12, "horizon", { ramGb: 8 }).notes.length, 3); -}); - -test("breakdowns read as words, and the hardware table shows only with data", async () => { - const { breakdownLine, hardwareHtml } = await import("./bench.js"); - assert.equal(breakdownLine({ ram: [{ class: "32 GB", installs: 3 }], storage: [{ class: "nvme", installs: 4 }], gpu_kind: [{ class: "discrete", installs: 3 }] }), "32 GB RAM (3) · NVMe (4) · separate GPU (3)"); - assert.equal(breakdownLine(undefined), ""); - assert.equal(hardwareHtml({ breakdowns: {} }), ""); - const html = hardwareHtml({ breakdowns: { os: [{ class: "linux", installs: 5, sessions: 9, hours: 4.5, p50_ms: 6.2, p99_ms: 14 }] } }); - assert.match(html, /Linux/); - assert.match(html, /6\.2 ms/); -}); diff --git a/website/src/hardware.js b/website/src/hardware.js deleted file mode 100644 index bf4c8bbbd..000000000 --- a/website/src/hardware.js +++ /dev/null @@ -1,88 +0,0 @@ -// The hardware the Benchmarks page can estimate for, from specifications only (our own table, no benchmark -// database): each GPU's FP32 shader throughput in TFLOPS and its memory bandwidth in GB/s as its maker states them, -// its own memory in GB (vram_gb; 0 for a GPU that shares the system's: integrated, Apple silicon), -// and each CPU's single-thread score = its top boost clock (GHz) x our rough per-generation factor (instructions per -// clock, Zen 4 = 1). The factors are round numbers, so estimates are ranges, and the page says so. -// `match` finds a reported name (the GPU and CPU strings in benchmark reports) in this table. - -export const GPUS = [ - { name: "NVIDIA GeForce RTX 4090", tflops: 82.6, gbps: 1008, vram_gb: 24, match: /RTX 4090/i }, - { name: "NVIDIA GeForce RTX 4080", tflops: 48.7, gbps: 717, vram_gb: 16, match: /RTX 4080(?! SUPER)/i }, - { name: "NVIDIA GeForce RTX 4070 Ti", tflops: 40.1, gbps: 504, vram_gb: 12, match: /RTX 4070 Ti/i }, - { name: "NVIDIA GeForce RTX 4070", tflops: 29.1, gbps: 504, vram_gb: 12, match: /RTX 4070(?! Ti)/i }, - { name: "NVIDIA GeForce RTX 4060 Ti", tflops: 22.1, gbps: 288, vram_gb: 8, match: /RTX 4060 Ti/i }, - { name: "NVIDIA GeForce RTX 4060", tflops: 15.1, gbps: 272, vram_gb: 8, match: /RTX 4060(?! Ti)/i }, - { name: "NVIDIA GeForce RTX 3080", tflops: 29.8, gbps: 760, vram_gb: 10, match: /RTX 3080(?! Ti)/i }, - { name: "NVIDIA GeForce RTX 3070", tflops: 20.3, gbps: 448, vram_gb: 8, match: /RTX 3070(?! Ti)/i }, - { name: "NVIDIA GeForce RTX 3060", tflops: 12.7, gbps: 360, vram_gb: 12, match: /RTX 3060(?! Ti)/i }, - { name: "NVIDIA GeForce RTX 3050", tflops: 9.1, gbps: 224, vram_gb: 8, match: /RTX 3050/i }, - { name: "NVIDIA GeForce RTX 2060", tflops: 6.5, gbps: 336, vram_gb: 6, match: /RTX 2060(?! SUPER)/i }, - { name: "NVIDIA GeForce GTX 1660 SUPER", tflops: 5.0, gbps: 336, vram_gb: 6, match: /GTX 1660 SUPER/i }, - { name: "NVIDIA GeForce GTX 1060 6GB", tflops: 4.4, gbps: 192, vram_gb: 6, match: /GTX 1060/i }, - { name: "NVIDIA GeForce GTX 1050 Ti", tflops: 2.1, gbps: 112, vram_gb: 4, match: /GTX 1050 Ti/i }, - { name: "AMD Radeon RX 7900 XTX", tflops: 61.4, gbps: 960, vram_gb: 24, match: /RX 7900 XTX/i }, - { name: "AMD Radeon RX 7800 XT", tflops: 37.3, gbps: 624, vram_gb: 16, match: /RX 7800 XT/i }, - { name: "AMD Radeon RX 7600", tflops: 21.8, gbps: 288, vram_gb: 8, match: /RX 7600(?! XT)/i }, - { name: "AMD Radeon RX 6700 XT", tflops: 13.2, gbps: 384, vram_gb: 12, match: /RX 6700 XT/i }, - { name: "AMD Radeon RX 6600", tflops: 8.9, gbps: 224, vram_gb: 8, match: /RX 6600(?! XT)/i }, - { name: "AMD Radeon RX 580", tflops: 6.2, gbps: 256, vram_gb: 8, match: /RX 580/i }, - { name: "AMD Radeon 780M (integrated)", tflops: 8.6, gbps: 89, vram_gb: 0, match: /780M/i }, - { name: "Steam Deck (AMD Van Gogh)", tflops: 1.6, gbps: 88, vram_gb: 0, match: /VanGogh|Van Gogh|Custom GPU 0405/i }, - { name: "Intel Arc A770", tflops: 19.7, gbps: 560, vram_gb: 16, match: /Arc.*A770/i }, - { name: "Intel Iris Xe Graphics (96 EU)", tflops: 2.1, gbps: 68, vram_gb: 0, match: /Iris\(?R?\)? Xe/i }, - { name: "Intel HD Graphics 620", tflops: 0.4, gbps: 34, vram_gb: 0, match: /\bU?HD Graphics 620\b/i }, - { name: "Apple M1", tflops: 2.6, gbps: 68, vram_gb: 0, match: /^Apple M1$/i }, - { name: "Apple M2", tflops: 3.6, gbps: 100, vram_gb: 0, match: /^Apple M2$/i }, - { name: "Apple M3", tflops: 4.1, gbps: 100, vram_gb: 0, match: /^Apple M3$/i }, - { name: "Apple M4", tflops: 4.3, gbps: 120, vram_gb: 0, match: /^Apple M4$/i }, - { name: "Apple M1 Pro (16-core GPU)", tflops: 5.2, gbps: 200, vram_gb: 0, match: /^Apple M1 Pro$/i }, - { name: "Apple M4 Pro (20-core GPU)", tflops: 8.5, gbps: 273, vram_gb: 0, match: /^Apple M4 Pro$/i }, - { name: "Apple M4 Max (40-core GPU)", tflops: 17.0, gbps: 546, vram_gb: 0, match: /^Apple M4 Max$/i }, -]; - -// ghz: top single-core boost clock; ipc: our per-generation factor (Zen 4 = 1). -export const CPUS = [ - { name: "Intel Core i7-7500U", ghz: 3.5, ipc: 0.62, match: /i7-7500U/i }, - { name: "Intel Core i5-7200U", ghz: 3.1, ipc: 0.62, match: /i5-7200U/i }, - { name: "Intel Core i5-8250U", ghz: 3.4, ipc: 0.62, match: /i5-8250U/i }, - { name: "Intel Core i5-9400F", ghz: 4.1, ipc: 0.62, match: /i5-9400/i }, - { name: "Intel Core i7-9700K", ghz: 4.9, ipc: 0.62, match: /i7-9700K/i }, - { name: "Intel Core i5-10400", ghz: 4.3, ipc: 0.62, match: /i5-10400/i }, - { name: "Intel Core i5-1135G7", ghz: 4.2, ipc: 0.78, match: /i5-1135G7/i }, - { name: "Intel Core i5-12400", ghz: 4.4, ipc: 0.95, match: /i5-12400/i }, - { name: "Intel Core i5-13600K", ghz: 5.1, ipc: 0.95, match: /i5-13600K/i }, - { name: "Intel Core i7-13700K / KF", ghz: 5.4, ipc: 0.95, match: /i7-13700K/i }, - { name: "Intel Core i9-14900K", ghz: 6.0, ipc: 0.95, match: /i9-14900K/i }, - { name: "AMD Ryzen 5 3600", ghz: 4.2, ipc: 0.72, match: /Ryzen 5 3600/i }, - { name: "AMD Ryzen 5 5600X", ghz: 4.6, ipc: 0.88, match: /Ryzen 5 5600X?\b/i }, - { name: "AMD Ryzen 7 5800X3D", ghz: 4.5, ipc: 0.88, match: /5800X3D/i }, - { name: "AMD Ryzen 5 7600X", ghz: 5.3, ipc: 1.0, match: /Ryzen 5 7600/i }, - { name: "AMD Ryzen 7 7800X3D", ghz: 5.0, ipc: 1.0, match: /7800X3D/i }, - { name: "AMD Ryzen 9 7950X", ghz: 5.7, ipc: 1.0, match: /Ryzen 9 7950X(?!3D)/i }, - { name: "AMD Ryzen 7 9700X", ghz: 5.5, ipc: 1.12, match: /Ryzen 7 9700X/i }, - { name: "AMD Ryzen 7 7840U / HS", ghz: 5.1, ipc: 1.0, match: /7840(U|HS)/i }, - { name: "Steam Deck (AMD Zen 2, 4 cores)", ghz: 3.5, ipc: 0.72, match: /AMD Custom APU 0405|Van ?Gogh/i }, - { name: "Apple M1", ghz: 3.2, ipc: 1.25, match: /^Apple M1$/i }, - { name: "Apple M2", ghz: 3.5, ipc: 1.28, match: /^Apple M2$/i }, - { name: "Apple M3", ghz: 4.05, ipc: 1.38, match: /^Apple M3$/i }, - { name: "Apple M4", ghz: 4.4, ipc: 1.5, match: /^Apple M4$/i }, - { name: "Apple M4 Pro", ghz: 4.5, ipc: 1.5, match: /^Apple M4 Pro$/i }, -]; - -export const singleThread = (cpu) => cpu.ghz * cpu.ipc; -export const findGpu = (name) => GPUS.find((g) => g.name === name || g.match.test(name || "")) || null; -export const findCpu = (name) => CPUS.find((c) => c.name === name || c.match.test(name || "")) || null; - -// The telemetry server's hardware classes (crates/horizon-telemetry-server/src/classes.rs), which players' -// results are broken down by: memory and a GPU's own memory in coarse steps. -export function ramClass(gb) { - if (!(gb > 0)) return null; - return gb <= 5 ? "4 GB or less" : gb <= 10 ? "8 GB" : gb <= 20 ? "16 GB" : gb <= 40 ? "32 GB" : "64 GB or more"; -} -export function vramClass(gpu) { - if (!gpu) return null; - if (!gpu.vram_gb) return "shared"; - const mb = gpu.vram_gb * 1024; - for (const [max, name] of [[2560, "2 GB or less"], [4608, "4 GB"], [6656, "6 GB"], [8704, "8 GB"], [12800, "12 GB"], [16896, "16 GB"]]) if (mb <= max) return name; - return "more than 16 GB"; -} diff --git a/website/src/hub-page.js b/website/src/hub-page.js deleted file mode 100644 index 9115c5ca4..000000000 --- a/website/src/hub-page.js +++ /dev/null @@ -1,270 +0,0 @@ -// The hub page (/hub): its tabs (one per #hash, so /hub#roadmap and /hub# can be linked), the -// Simple / Technical switch (remembered in localStorage), the area filter, and the live state of every -// linked issue and pull request, refreshed from GitHub's public API. Without JavaScript, every tab reads -// one after the other with what was baked at build time. -import { cached, get, setUpMenu, setUpTheme } from "./chrome.js"; -import { REPO, boardFilterHtml, boardFrom, boardHtml, journalFrom, journalHtml, overviewHtml, roadmapHtml, slimIssue } from "./hub.js"; - -const root = document.documentElement; -const data = JSON.parse(document.getElementById("hub-data").textContent); -const tabs = [...document.querySelectorAll('.hub-tabs [role="tab"]')]; -const pill = document.querySelector(".hub-tabs .tab-pill"); -let area = "all"; - -// --- Tabs ------------------------------------------------------------------------------------------------------ - -const panelOf = (tab) => document.getElementById(tab.getAttribute("aria-controls")); -const place = (tab) => { - pill.style.width = `${tab.offsetWidth}px`; - pill.style.height = `${tab.offsetHeight}px`; - pill.style.transform = `translate(${tab.offsetLeft}px, ${tab.offsetTop}px)`; -}; -function choose(tab, { focus = false, push = false } = {}) { - for (const t of tabs) { - const on = t === tab; - t.setAttribute("aria-selected", String(on)); - t.tabIndex = on ? 0 : -1; - panelOf(t).classList.toggle("is-active", on); - } - place(tab); - if (focus) tab.focus(); - if (push && location.hash !== `#${panelOf(tab).id}`) history.replaceState(null, "", `#${panelOf(tab).id}`); -} -// "#roadmap" opens its tab; "#" or "#help-wanted" opens the tab holding it and scrolls there. -function follow() { - const target = location.hash && document.getElementById(decodeURIComponent(location.hash.slice(1))); - const tab = tabs.find((t) => target && (panelOf(t) === target || panelOf(t).contains(target))) || tabs[0]; - choose(tab); - if (target && target !== panelOf(tab)) { - if (target.dataset.area && area !== "all" && target.dataset.area !== area) filter("all"); - requestAnimationFrame(() => target.scrollIntoView({ block: "start" })); - } -} -tabs.forEach((tab, i) => { - tab.addEventListener("click", () => choose(tab, { push: true })); - tab.addEventListener("keydown", (e) => { - const step = { ArrowRight: 1, ArrowLeft: -1 }[e.key]; - if (step) choose(tabs[(i + step + tabs.length) % tabs.length], { focus: true, push: true }); - }); -}); -// Links inside the page ("Help wanted", an item of the overview) switch tabs through the hash. -addEventListener("hashchange", follow); -addEventListener("resize", () => place(tabs.find((t) => t.getAttribute("aria-selected") === "true"))); -document.fonts?.ready.then(() => place(tabs.find((t) => t.getAttribute("aria-selected") === "true"))); - -// --- Simple / Technical ---------------------------------------------------------------------------------------- - -const detailButtons = [...document.querySelectorAll("[data-detail]")]; -function detail(mode) { - if (mode === "dev") root.dataset.detail = "dev"; - else delete root.dataset.detail; - detailButtons.forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.detail === mode))); -} -detailButtons.forEach((b) => - b.addEventListener("click", () => { - detail(b.dataset.detail); - try { - localStorage.setItem("hub:detail", b.dataset.detail); - } catch {} - }), -); -detail(root.dataset.detail === "dev" ? "dev" : "plain"); - -// --- Area filter ----------------------------------------------------------------------------------------------- - -const areaButtons = [...document.querySelectorAll("[data-area-filter]")]; -function filter(to) { - area = to; - areaButtons.forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.areaFilter === area))); - for (const section of document.querySelectorAll("[data-roadmap] .hub-section")) { - let shown = 0; - for (const item of section.querySelectorAll(".hub-item")) { - item.hidden = area !== "all" && item.dataset.area !== area; - if (!item.hidden) shown++; - } - section.hidden = shown === 0; - } -} -areaButtons.forEach((b) => b.addEventListener("click", () => filter(b.dataset.areaFilter))); - -// --- The board: a roadmap item's cards, and the long columns' "Show more" ---------------------------------------- - -const boardSelect = document.querySelector("[data-board-item]"); -function showItem() { - const want = boardSelect.value; - for (const card of document.querySelectorAll("[data-board] .hub-card")) { - card.hidden = want === "-" ? !card.dataset.item : want ? card.dataset.item !== want : false; - } - for (const column of document.querySelectorAll("[data-board] .hub-column")) { - column.querySelector("[data-count]").textContent = column.querySelectorAll(".hub-card:not([hidden])").length; - // A filtered column shows all its cards. - column.classList.toggle("is-open", Boolean(want) || column.classList.contains("was-opened")); - } -} -boardSelect?.addEventListener("change", showItem); -document.querySelector("[data-board]")?.addEventListener("click", (e) => { - const button = e.target.closest("[data-more-button]"); - if (!button) return; - button.closest(".hub-column").classList.add("is-open", "was-opened"); - button.remove(); -}); - -// --- Live state from GitHub ------------------------------------------------------------------------------------ - -// The open issues and pull requests, and those closed or merged lately: four requests at most, kept ten minutes. -async function loadLive() { - const list = []; - for (let page = 1; page <= 3; page++) { - const batch = await get(`https://api.github.com/repos/${REPO}/issues?state=open&per_page=100&page=${page}`); - list.push(...batch.map(slimIssue)); - if (batch.length < 100) break; - } - const closed = await get(`https://api.github.com/repos/${REPO}/issues?state=closed&sort=updated&direction=desc&per_page=100`); - return list.concat(closed.map(slimIssue)); -} -const loadReleases = () => get(`https://api.github.com/repos/${REPO}/releases?per_page=40`); - -async function refresh() { - const fresh = await cached("horizon:hub-live", loadLive).catch(() => null); - if (!fresh) return; - // What the build knew about older links stays; GitHub's answer wins for the rest. - const live = new Map([...data.live, ...fresh].map((i) => [i.n, i])); - document.querySelector("[data-overview]").innerHTML = overviewHtml(data.roadmap, live); - document.querySelector("[data-roadmap]").innerHTML = roadmapHtml(data.roadmap, live); - filter(area); - showVotes(); - const board = boardFrom(fresh, data.roadmap); - const chosen = boardSelect.value; - boardSelect.innerHTML = boardFilterHtml(board, data.roadmap); - boardSelect.value = [...boardSelect.options].some((o) => o.value === chosen) ? chosen : ""; - document.querySelector("[data-board]").innerHTML = boardHtml(board, data.roadmap); - showItem(); - const releases = await cached("horizon:hub-releases", loadReleases).catch(() => null); - if (releases) document.querySelector("[data-journal]").innerHTML = journalHtml(journalFrom(releases, fresh, data.roadmap), data.roadmap); - const note = document.querySelector("[data-live-note]"); - if (note) note.textContent = "Pull request and issue states are live from GitHub."; -} - -// --- Votes, bug reports and suggestions: the hub's server (crates/horizon-telemetry-server) -------------------- - -const saved = (key, fallback) => { - try { - return JSON.parse(localStorage.getItem(key)) ?? fallback; - } catch { - return fallback; - } -}; -const save = (key, value) => { - try { - localStorage.setItem(key, JSON.stringify(value)); - } catch {} -}; -const post = (path, body) => fetch(`${data.api}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); - -// This browser's random id (one vote per item per browser) and the items it voted for. Nothing else identifies it. -function voter() { - let id = saved("hub:voter", ""); - if (typeof id !== "string" || id.length < 16) { - id = crypto.randomUUID ? crypto.randomUUID() : [...crypto.getRandomValues(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, "0")).join(""); - save("hub:voter", id); - } - return id; -} -const mine = new Set(saved("hub:voted", [])); -let counts = null; // { item: votes } once the server answered; until then the buttons stay hidden - -function showVotes() { - if (!counts) return; - for (const button of document.querySelectorAll("[data-vote]")) { - const id = button.dataset.vote; - button.hidden = false; - button.setAttribute("aria-pressed", String(mine.has(id))); - button.querySelector(".hub-vote-label").textContent = mine.has(id) ? "Wanted" : "Want it"; - button.querySelector("[data-votes]").textContent = counts[id] ? String(counts[id]) : ""; - } -} - -async function vote(id) { - const up = !mine.has(id); - const apply = (on, step) => { - if (on) mine.add(id); - else mine.delete(id); - counts[id] = Math.max(0, (counts[id] || 0) + step); - save("hub:voted", [...mine]); - showVotes(); - }; - apply(up, up ? 1 : -1); - try { - const res = await post("/hub/vote", { item: id, voter: voter(), up }); - if (!res.ok) throw new Error(res.status); - counts[id] = (await res.json()).votes; - showVotes(); - } catch { - apply(!up, up ? -1 : 1); - } -} -document.addEventListener("click", (e) => { - const button = e.target.closest("[data-vote]"); - if (button && counts) vote(button.dataset.vote); -}); - -const LABELS = { title: "the title", did: "what you did", happened: "what happened", expected: "what you expected", version: "the version", system: "OS, CPU, GPU", text: "your idea", name: "your name" }; -// The server's answer in words: "did: 3 to 2000 characters" becomes "Check what you did: 3 to 2000 characters." -function trouble(code, answer) { - if (code === 429) return "Too many sent from your connection: try again in a few minutes."; - const said = typeof answer.error === "string" ? answer.error : ""; - const field = said.match(/^(\w+): (.+)$/); - if (code === 400 && field) return `Check ${LABELS[field[1]] || field[1]}: ${field[2]}.`; - return said ? `${said[0].toUpperCase()}${said.slice(1)}.` : "That didn't go through: try again in a moment."; -} - -function setUpForm(form, path, thanks) { - const status = form.querySelector("[data-status]"); - form.hidden = false; - form.parentElement.querySelector("[data-closed]").hidden = true; - form.addEventListener("submit", async (e) => { - e.preventDefault(); - if (!form.reportValidity()) return; - const button = form.querySelector('[type="submit"]'); - button.disabled = true; - status.textContent = "Sending…"; - try { - const res = await post(path, Object.fromEntries(new FormData(form))); - const answer = await res.json().catch(() => ({})); - if (res.ok) { - thanks(status, answer); - // A new report starts with the version filled in again; the name stays for the next one. - for (const field of form.querySelectorAll("textarea, input:not([name='version']):not([name='name'])")) field.value = ""; - } else status.textContent = trouble(res.status, answer); - } catch { - status.textContent = "Couldn't reach the server: try again, or use GitHub or Discord."; - } - button.disabled = false; - }); -} - -// The forms and the votes show once the server answers; without it the page points to GitHub and Discord. -async function connect() { - try { - // Revalidated: the server keeps the counts a minute, a browser's copy would miss this browser's own vote. - const res = await fetch(`${data.api}/hub/votes`, { cache: "no-cache" }); - if (!res.ok) return; - counts = (await res.json()).votes || {}; - } catch { - return; - } - showVotes(); - setUpForm(document.querySelector('[data-form="report"]'), "/hub/report", (status, answer) => { - const issue = typeof answer.issue === "string" && answer.issue.match(/^https:\/\/github\.com\/ludovic111\/horizon\/issues\/(\d+)$/); - status.innerHTML = issue ? `Thanks! It's issue #${issue[1]} on GitHub: follow it there.` : "Thanks! It will be on GitHub in a few minutes."; - }); - setUpForm(document.querySelector('[data-form="suggest"]'), "/hub/suggest", (status) => { - status.textContent = "Thanks! The maintainers read every suggestion."; - }); -} - -setUpTheme(); -setUpMenu(); -connect(); -follow(); -refresh().then(() => data.roadmap.items.some((i) => `#${i.id}` === location.hash) && follow()); diff --git a/website/src/hub.html b/website/src/hub.html deleted file mode 100644 index 167ffc15e..000000000 --- a/website/src/hub.html +++ /dev/null @@ -1,170 +0,0 @@ - - - - - - Hub · Horizon - - - - - - - - - - - - - - - - - - - - - -{{SITE_NAV}} -
    -
    -

    HubNow, next and how to help

    -

    Where Horizon is going

    -

    What is being done, what comes next, what shipped and where you can help. No dates: things are Now, Next or Later. Read it in plain words, or switch to the technical picture.

    -
    -
    - - - - - - -
    -
    - - -
    -
    - -
    -{{HUB_OVERVIEW}} -
    - -
    -
    -{{HUB_AREAS}} -
    -
    -{{HUB_ROADMAP}} -
    -

    The roadmap lives in the repository: ROADMAP.md, generated from roadmap/roadmap.toml. Pull requests carry the roadmap:<id> label of their item.

    -
    - -
    -
    -

    Every open issue and pull request, placed by its state on GitHub, as on Kira's work board in Discord.

    - -
    -
    -{{HUB_BOARD}} -
    -
    - -
    -

    Every release with what it changed, grouped by roadmap item in Technical, and a summary of each week. Also as journal.json.

    -
    -{{HUB_JOURNAL}} -
    -
    - -
    -
    -

    Good first tasks

    -

    Each one is a small difference from vanilla, with an issue that says how to see it.

    -

    Each links its issue; the technical text says where in the code and in vanilla to start.

    -
      {{HUB_HELP_WANTED}}
    -
    -
    -

    Ways to help

    -
    -
    -

    Tell us what differs

    -

    Something that doesn't play like vanilla is a bug. Say what you did, what happened and what vanilla does, with your Horizon version and system.

    -

    Report a bugSuggest something

    -
    -
    -

    Take a task

    -

    Pick a good first task or an open issue. On Discord, /claim 1234 tells everyone you are on issue 1234, so nobody starts the same work; /unclaim frees it.

    -

    Open issues

    -
    -
    -

    Bring your AI agent

    -

    On Discord, /agent connect gives your coding agent a personal token for Kira's MCP server: it reads the work board, claims tasks and posts its progress in your name.

    -

    Join the Discord

    -
    -
    -

    Benchmark your computer

    -

    Run the built-in benchmark and share the report: every new machine makes the performance work more accurate. No coding needed.

    -

    How to

    -
    -
    -
    -
    -

    Report a bug

    -

    One bug per report: something that breaks, or doesn't play like vanilla. It becomes an issue on GitHub, public, and you get its link to follow it. Search the open bugs first.

    - -

    Report it on GitHub or in #horizon-bugs on Discord, where Kira turns your post into an issue.

    -
    -
    -

    Suggest something

    -

    An idea for Horizon, or about something on the roadmap. The maintainers read every one, and the good ones become roadmap items. Nothing you send here is published.

    - -

    Post it in #horizon-ideas on Discord, or send it to Kira with /suggest.

    -
    -
    -

    The rules

    -
      -
    1. Vanilla is the specification. Wherever Minecraft 26.3 has the feature, Horizon does exactly what it does: read vanilla's code, then match it.
    2. -
    3. Small pull requests, proven. One change each, under about 500 lines, with the block python3 tools/pr_ready.py prints: formatting, Clippy, tests and the harnesses your change can affect.
    4. -
    5. Say who wrote it. If an AI agent wrote or posts it, the pull request says so, and commits keep its co-author line.
    6. -
    7. Never commit Mojang's files. No game jars, assets, decompiled code or prepared resources, and nothing taken from other mods' code.
    8. -
    -

    The contributing guideCONTRIBUTING.md

    -
    -
    -

    Contributors

    -

    Everyone with commits in Horizon. On Discord, /link-github <your login> credit:True adds your Discord name next to yours.

    -
      {{HUB_CREDIT}}
    -

    All contributors on GitHub

    -
    -
    -

    Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

    -
    -
    -{{SITE_FOOTER}} - - - diff --git a/website/src/hub.js b/website/src/hub.js deleted file mode 100644 index f11668d8c..000000000 --- a/website/src/hub.js +++ /dev/null @@ -1,457 +0,0 @@ -// The hub (/hub): the roadmap from website/data/roadmap.json (generated from roadmap/roadmap.toml by -// tools/roadmap.py), with each item's issues and pull requests in their live GitHub state. Shared by build.mjs -// (baked into the page) and hub-page.js (refreshed from GitHub in the browser). Every item says the same thing -// twice: `plain` (.hub-plain) for players and `dev` (.hub-dev) for contributors; the page's Simple / Technical -// switch shows one of them. -import { escape, inline } from "./markdown.js"; -import { parts, plainItem, sections } from "./releases.js"; -import { isGame, isLauncher } from "./versions.js"; -import { avatar } from "./contributors.js"; - -export const REPO = "ludovic111/horizon"; -const issueUrl = (n) => `https://github.com/${REPO}/issues/${n}`; -const fileUrl = (path) => `https://github.com/${REPO}/blob/main/${path}`; - -// The issues a pull request closes when merged: "Fixes #12", "closes #3, resolves #4" (as Kira's board reads them). -export function fixesIn(text) { - const out = new Set(); - for (const m of String(text ?? "").matchAll(/\b(?:fix(?:e[sd])?|close[sd]?|resolve[sd]?)\s*:?\s+((?:#\d+(?:\s*(?:,|and)\s*)?)+)/gi)) { - for (const n of m[1].matchAll(/#(\d+)/g)) out.add(Number(n[1])); - } - return [...out].sort((a, b) => a - b); -} - -// A GitHub issue or pull request (from /issues, which lists both) reduced to what the hub shows. -export function slimIssue(raw) { - const pr = Boolean(raw.pull_request); - const merged = pr && raw.pull_request.merged_at; - return { - n: raw.number, - title: String(raw.title || ""), - kind: pr ? "pr" : "issue", - state: merged ? "merged" : raw.state === "open" ? "open" : raw.state_reason === "not_planned" ? "dropped" : "closed", - draft: Boolean(raw.draft), - user: raw.user?.login || "", - labels: (raw.labels || []).map((l) => (typeof l === "string" ? l : l.name)).filter(Boolean), - assigned: (raw.assignees || []).length > 0, - fixes: pr ? fixesIn(raw.body) : [], - at: merged || raw.closed_at || raw.updated_at || "", - url: raw.html_url || issueUrl(raw.number), - }; -} - -const number = (link) => Number((String(link).match(/^#(\d+)$/) || [])[1]) || null; - -// "#12 in review", "#13 merged": a link's state, when GitHub told us. -function linkState(issue) { - if (!issue) return null; - if (issue.kind === "pr") return issue.state === "open" ? (issue.draft ? "in progress" : "in review") : issue.state; - return issue.state === "open" ? "open" : "closed"; -} - -function linkHtml(link, live) { - const n = number(link); - if (!n) { - const url = link.startsWith("https://") ? link : fileUrl(link); - return `${escape(link.replace(/^https:\/\//, ""))}`; - } - const issue = live.get(n); - const state = linkState(issue); - const label = issue ? `${issue.kind === "pr" ? "Pull request" : "Issue"} #${n}: ${issue.title}` : `#${n}`; - return `#${n}${state ? ` ${state}` : ""}`; -} - -// The technical text with its #N and the item's own paths as links. -function devHtml(item) { - let text = item.dev.replace(/(^|[^\w[/`])#(\d+)\b/g, (_, before, n) => `${before}[#${n}](${issueUrl(n)})`); - for (const link of item.links || []) { - if (!number(link) && !link.startsWith("https://")) text = text.replace(link, `[${link}](${fileUrl(link)})`); - } - return inline(text); -} - -// "2 pull requests in review · 3 merged · 1 issue open", from the item's links. -export function progress(item, live) { - const known = (item.links || []).map(number).filter(Boolean).map((n) => live.get(n)).filter(Boolean); - const pulls = known.filter((i) => i.kind === "pr"); - const count = (list, word) => (list.length ? `${list.length} ${word}` : ""); - const parts = [ - count(pulls.filter((p) => p.state === "open" && !p.draft), pulls.filter((p) => p.state === "open" && !p.draft).length === 1 ? "pull request in review" : "pull requests in review"), - count(pulls.filter((p) => p.state === "open" && p.draft), "in progress"), - count(pulls.filter((p) => p.state === "merged"), "merged"), - count(known.filter((i) => i.kind === "issue" && i.state === "open"), known.filter((i) => i.kind === "issue" && i.state === "open").length === 1 ? "issue open" : "issues open"), - ].filter(Boolean); - return parts.join(" · "); -} - -const areaName = (roadmap, id) => roadmap.areas.find((a) => a.id === id)?.name || id; - -// An item's vote button: hidden until the page has the counts from the hub's server (hub-page.js). -export function voteHtml(item) { - return ``; -} - -export function itemHtml(item, roadmap, live) { - const done = item.status === "shipped"; - const state = done ? "" : progress(item, live); - return `
    -

    ${escape(areaName(roadmap, item.area))}${done ? `${escape(item.shipped_in)}` : ""}${item.ongoing ? `Ongoing` : ""}${done ? "" : voteHtml(item)}

    -

    ${escape(item.title)}

    -

    ${inline(item.plain)}

    -

    ${devHtml(item)}

    - ${state ? `

    ${escape(state)}

    ` : ""} - -
    `; -} - -const SECTION_LEDE = { - now: "Being worked on, with pull requests open or just merged.", - next: "Decided, and up after what is being done now.", - later: "Decided, further out.", - "help-wanted": "Good first contributions: a clear vanilla behaviour, an issue with the steps, a place to start.", - shipped: "Out in a release. The journal has every change.", -}; - -// The Roadmap tab: one section per status, the items in the file's order (areas by priority). -export function roadmapHtml(roadmap, live = new Map()) { - const order = new Map(roadmap.areas.map((a, i) => [a.id, i])); - return roadmap.statuses - .map(({ id, name }) => { - const items = roadmap.items.filter((i) => i.status === id); - if (!items.length) return ""; - // Shipped stays newest first; the others go by the areas' priority. - if (id !== "shipped") items.sort((a, b) => order.get(a.area) - order.get(b.area)); - return `
    -

    ${escape(name)}

    ${escape(SECTION_LEDE[id] || "")}

    -
    -${items.map((item) => itemHtml(item, roadmap, live)).join("\n")} -
    -
    `; - }) - .join("\n"); -} - -// The area filter's buttons: every area that has an item. -export function areaFilterHtml(roadmap) { - const used = roadmap.areas.filter((a) => roadmap.items.some((i) => i.area === a.id)); - return [``] - .concat(used.map((a) => ``)) - .join("\n"); -} - -// The Overview tab: where Horizon is, the 3 to 5 things in focus, what is next, what shipped last, how to help. -export function overviewHtml(roadmap, live = new Map()) { - const o = roadmap.overview; - const focus = roadmap.items.filter((i) => i.focus); - const next = roadmap.items.filter((i) => i.status === "next"); - const shipped = roadmap.items.filter((i) => i.status === "shipped").slice(0, 3); - const row = (item, i, meta) => `
  • ${String(i + 1).padStart(2, "0")}${escape(item.title)}${inline(item.plain)}${inline(item.dev)}${escape(meta(item))}
  • `; - return `
    -

    ${inline(o.today_plain)}

    -

    ${inline(o.today_dev)}

    -
    -
    -

    Being done now

    -
      ${focus.map((item, i) => row(item, i, (x) => progress(x, live))).join("")}
    -
    -
    -

    Next

    -
      ${next.map((item, i) => row(item, i, (x) => areaName(roadmap, x.area))).join("")}
    -
    -
    -

    Recently shipped

    -
      ${shipped.map((item, i) => row(item, i, (x) => `In ${x.shipped_in}`)).join("")}
    -
    -
    -

    How to help

    -

    ${inline(o.help_plain)}

    -

    ${inline(o.help_dev)}

    -

    ContributeHelp wantedReport a bugSuggest something

    -
    `; -} - -// The Contribute tab's list of good first tasks. -export function helpWantedHtml(roadmap) { - return roadmap.items - .filter((i) => i.status === "help-wanted") - .map((item, i) => { - const first = (item.links || []).map(number).find(Boolean); - const href = first ? issueUrl(first) : `#${item.id}`; - return `
  • ${String(i + 1).padStart(2, "0")}${escape(item.title)}${inline(item.plain)}${inline(item.dev)}${first ? `#${first}` : ""}
  • `; - }) - .join(""); -} - -// --- The work board -------------------------------------------------------------------------------------------- - -export const COLUMNS = [ - { id: "todo", name: "To do", about: "Open and free: pick one, and say so with /claim on Discord." }, - { id: "progress", name: "In progress", about: "Claimed, assigned, or a draft pull request." }, - { id: "review", name: "In review", about: "A pull request is ready for review." }, - { id: "done", name: "Done", about: "Closed or merged in the last seven days." }, -]; -const DONE_DAYS = 7; - -// The roadmap item an issue or pull request moves: its roadmap: label, else the item linking it, else (for a -// pull request) the item linking an issue it fixes. -export function itemOf(issue, roadmap) { - const label = issue.labels.find((l) => l.startsWith("roadmap:")); - const ids = new Set(roadmap.items.map((i) => i.id)); - if (label && ids.has(label.slice(8))) return label.slice(8); - const linking = (n) => roadmap.items.find((i) => (i.links || []).includes(`#${n}`))?.id; - return linking(issue.n) || issue.fixes.map(linking).find(Boolean) || null; -} - -// The board from GitHub's open issues and pull requests and those closed lately, placed as Kira's work board places -// them: an issue goes to review when an open, ready pull request fixes it, to progress when a draft one does or it is -// claimed or assigned; a pull request that fixes no open issue is a card of its own. -export function boardFrom(list, roadmap, now = Date.now()) { - const columns = Object.fromEntries(COLUMNS.map((c) => [c.id, []])); - const open = list.filter((i) => i.state === "open"); - const openIssues = new Set(open.filter((i) => i.kind === "issue").map((i) => i.n)); - const fixing = (n) => open.filter((p) => p.kind === "pr" && p.fixes.includes(n)); - const card = (i, prs = []) => ({ n: i.n, kind: i.kind, title: i.title, user: i.user, url: i.url, item: itemOf(i, roadmap) || prs.map((p) => itemOf(p, roadmap)).find(Boolean) || null, prs: prs.map((p) => p.n) }); - for (const i of open) { - if (i.kind === "issue") { - const prs = fixing(i.n); - const claimed = i.assigned || i.labels.some((l) => /^(in progress|claimed)$/i.test(l)); - const column = prs.some((p) => !p.draft) ? "review" : prs.length || claimed ? "progress" : "todo"; - columns[column].push(card(i, prs)); - } else if (!i.fixes.some((n) => openIssues.has(n))) { - columns[i.draft ? "progress" : "review"].push(card(i)); - } - } - const since = now - DONE_DAYS * 864e5; - const seen = new Set(); - for (const i of list) { - if (seen.has(i.n) || !["merged", "closed"].includes(i.state) || !(Date.parse(i.at) >= since)) continue; - seen.add(i.n); - columns.done.push(card(i)); - } - columns.done.sort((a, b) => b.n - a.n); - return columns; -} - -const SHOWN = 20; // cards per column before "Show more" - -function cardHtml(c, roadmap, more) { - const item = c.item && roadmap.items.find((i) => i.id === c.item); - return `
  • ${c.kind === "pr" ? "PR" : "Issue"} #${c.n}${c.prs.length ? ` · ${c.prs.map((n) => `PR #${n}`).join(", ")}` : ""}${escape(c.title)}${item ? `${escape(item.title)}` : ""}${c.user ? `${escape(c.user)}` : ""}
  • `; -} - -export function boardHtml(columns, roadmap) { - return COLUMNS.map(({ id, name, about }) => { - const cards = columns[id]; - return `
    -

    ${escape(name)}${cards.length}

    -

    ${escape(about)}

    -
      ${cards.map((c, i) => cardHtml(c, roadmap, i >= SHOWN)).join("")}
    - ${cards.length > SHOWN ? `` : ""} -
    `; - }).join("\n"); -} - -// The board's roadmap filter: every item that has a card. -export function boardFilterHtml(columns, roadmap) { - const used = new Set(Object.values(columns).flat().map((c) => c.item).filter(Boolean)); - return [``, ``] - .concat(roadmap.items.filter((i) => used.has(i.id)).map((i) => ``)) - .join(""); -} - -// --- The journal ----------------------------------------------------------------------------------------------- - -export const JOURNAL_URL = "https://playhorizon.dev/hub#journal"; -const ENTRIES = 40; - -// The journal, newest first: each release with its changes grouped by roadmap item, the weekly summaries -// (roadmap/journal/), and what merged since the newest game release. releases: GitHub's release objects; list: the -// hub's issues and pull requests (their roadmap: labels place changes the roadmap doesn't link). -export function journalFrom(releases, list, roadmap) { - const prs = new Map(list.filter((i) => i.kind === "pr").map((i) => [i.n, i])); - const placed = (numbers) => { - for (const n of numbers) { - const known = prs.get(n); - const id = known ? itemOf(known, roadmap) : roadmap.items.find((i) => (i.links || []).includes(`#${n}`))?.id; - if (id) return id; - } - return null; - }; - const ours = releases.filter((r) => !r.draft && (isGame(r.tag_name) || isLauncher(r.tag_name))); - const entries = ours.map((r) => { - const changes = sections(r.body) - .filter((x) => /^(new|what's new|fixed)/i.test(x.title)) - .flatMap((x) => x.items.map((text) => ({ section: /^fixed/i.test(x.title) ? "fixed" : "new", text }))) - .map((c) => { - const numbers = [...c.text.matchAll(/#(\d+)/g)].map((m) => Number(m[1])); - return { ...c, text: plainItem(c.text), prs: numbers, item: placed(numbers) }; - }); - return { - id: r.tag_name, - kind: isLauncher(r.tag_name) ? "launcher" : "release", - date: r.published_at || "", - title: r.name || r.tag_name, - plain: parts(r).line, - url: r.html_url, - changes, - shipped: roadmap.items.filter((i) => i.status === "shipped" && i.shipped_in === r.tag_name).map((i) => i.id), - }; - }); - // Merged but in no release's notes yet: a release is cut from main a while after its last merge, so the newest - // releases' notes, not their dates, say what they hold. Pull requests players don't see (skip-release) never are. - const games = ours.filter((r) => isGame(r.tag_name)).map((r) => r.published_at).sort().reverse(); - const since = games[Math.min(4, games.length - 1)] || ""; - const noted = new Set(entries.flatMap((e) => e.changes.flatMap((c) => c.prs))); - const pending = list - .filter((i) => i.kind === "pr" && i.state === "merged" && i.at > since && !noted.has(i.n) && !i.labels.includes("skip-release")) - .sort((a, b) => b.at.localeCompare(a.at)); - if (pending.length) { - entries.push({ - id: "next-release", - kind: "merged", - date: pending[0].at, - title: "Merged, in the next release", - plain: `${pending.length} change${pending.length === 1 ? "" : "s"} merged since the last release.`, - url: `https://github.com/${REPO}/pulls?q=is%3Apr+is%3Amerged`, - changes: pending.map((p) => ({ section: "merged", text: p.title, prs: [p.n], item: itemOf(p, roadmap) })), - shipped: [], - }); - } - for (const w of roadmap.journal || []) { - // A week's summary sits after its last day's releases. - const end = new Date(Date.parse(w.date) + 7 * 864e5 - 1).toISOString(); - entries.push({ id: `week-${w.week}`, kind: "week", date: end, title: w.title, plain: w.plain, dev: w.dev, url: `${JOURNAL_URL.replace("#journal", "")}#week-${w.week}`, changes: [], shipped: [] }); - } - return entries.sort((a, b) => b.date.localeCompare(a.date)).slice(0, ENTRIES); -} - -const HUB = "https://playhorizon.dev/hub"; -const FEED = 300; - -// /data/journal.json, which Kira reads for #updates and X (kira's src/journal.js): one flat entry per merged pull -// request, release, shipped roadmap item and weekly summary, newest first. An entry's id never changes: Kira posts -// each id once. Shipped items carry `post` (at most 240 characters, tools/roadmap.py checks) and `announce`. -export function journalJson(releases, list, roadmap, generated = new Date().toISOString()) { - const items = new Map(roadmap.items.map((i) => [i.id, i])); - const ours = releases.filter((r) => !r.draft && (isGame(r.tag_name) || isLauncher(r.tag_name))); - const published = new Map(ours.map((r) => [r.tag_name, r.published_at || ""])); - const merges = list - .filter((i) => i.kind === "pr" && i.state === "merged") - .map((pr) => ({ pr, item: itemOf(pr, roadmap) })) - // What players see, and anything that moves a roadmap item. - .filter(({ pr, item }) => item || !pr.labels.includes("skip-release")) - .map(({ pr, item }) => ({ - id: `pr-${pr.n}`, - kind: "merge", - date: pr.at, - title: pr.title, - url: pr.url, - number: pr.n, - ...(item ? { item, item_title: items.get(item)?.title } : {}), - })); - const released = ours.map((r) => ({ - id: `release-${r.tag_name}`, - kind: "release", - date: r.published_at || "", - title: r.name || r.tag_name, - plain: parts(r).line, - url: r.html_url, - tag: r.tag_name, - })); - const shipped = roadmap.items - .filter((i) => i.status === "shipped") - .map((i) => ({ - id: `shipped-${i.id}`, - kind: "shipped", - date: published.get(i.shipped_in) || generated, - title: i.title, - plain: i.plain, - url: `${HUB}#${i.id}`, - item: i.id, - item_title: i.title, - shipped_in: i.shipped_in, - post: i.post || i.plain, - announce: Boolean(i.announce), - })); - // A week's summary is dated at the end of its week, after that week's releases. - const weekly = (roadmap.journal || []).map((w) => ({ - id: `weekly-${w.week}`, - kind: "weekly", - date: new Date(Date.parse(w.date) + 7 * 864e5 - 1000).toISOString(), - title: w.title, - plain: w.plain, - dev: w.dev, - url: `${HUB}#week-${w.week}`, - })); - const entries = [...merges, ...released, ...shipped, ...weekly].sort((a, b) => b.date.localeCompare(a.date) || a.id.localeCompare(b.id)); - return { format: "horizon-journal", version: 2, generated, url: `${HUB}#journal`, entries: entries.slice(0, FEED) }; -} - -const KIND = { release: "Game", launcher: "Launcher", merged: "Merged", week: "This week" }; - -function changesHtml(entry, roadmap) { - if (!entry.changes.length) return ""; - const line = (c) => `
  • ${inline(c.text)}${c.prs.length ? ` ${c.prs.map((n) => `#${n}`).join(" ")}` : ""}
  • `; - // Simple: what is new, then how many fixes. Technical: every change, under the roadmap item it moves. - const added = entry.changes.filter((c) => c.section !== "fixed"); - const fixes = entry.changes.length - added.length; - const simple = `
    ${added.length ? `
      ${added.map((c) => `
    • ${inline(c.text)}
    • `).join("")}
    ` : ""}${fixes ? `

    ${added.length ? "And " : ""}${fixes} fix${fixes === 1 ? "" : "es"}.

    ` : ""}
    `; - const groups = new Map(); - for (const c of entry.changes) groups.set(c.item || "", [...(groups.get(c.item || "") || []), c]); - const order = [...groups.keys()].sort((a, b) => (a === "") - (b === "")); - const dev = `
    ${order - .map((id) => { - const item = roadmap.items.find((i) => i.id === id); - return `

    ${item ? `${escape(item.title)}` : "Other changes"}

      ${groups.get(id).map(line).join("")}
    `; - }) - .join("")}
    `; - return simple + dev; -} - -export function journalHtml(entries, roadmap) { - return entries - .map((e) => { - const shipped = e.shipped.map((id) => roadmap.items.find((i) => i.id === id)).filter(Boolean); - const items = [...new Set(e.changes.map((c) => c.item).filter(Boolean))].map((id) => roadmap.items.find((i) => i.id === id)).filter(Boolean); - return `
    - -

    ${e.url ? `${escape(e.title)}` : escape(e.title)}

    - ${e.kind === "week" ? `

    ${inline(e.plain)}

    ${inline(e.dev.replace(/(^|[^\w[/`])#(\d+)\b/g, (_, b, n) => `${b}[#${n}](${issueUrl(n)})`))}

    ` : ""} - ${shipped.length ? `

    Shipped: ${shipped.map((i) => `${escape(i.title)}`).join(", ")}

    ` : ""} - ${items.length ? `

    ${items.map((i) => `${escape(i.title)}`).join("")}

    ` : ""} - ${changesHtml(e, roadmap)} -
    `; - }) - .join("\n"); -} - -// --- Contribute: the suggestion form's items and the contributors ------------------------------------------------ - -// The suggestion form's "About" choices: the items still to come. -export function suggestItemsHtml(roadmap) { - const open = roadmap.items.filter((i) => i.status !== "shipped"); - return [``] - .concat(open.map((i) => ``)) - .join(""); -} - -// The contributors, from GitHub (contributors.js's list), with the Discord name of those who linked their accounts -// on Kira and agreed to be credited (Kira's /contributors.json: { contributors: [{ github, discord }] }). -export function creditFrom(github, kira) { - const discord = new Map( - (Array.isArray(kira?.contributors) ? kira.contributors : []) - .filter((c) => c && typeof c.github === "string" && typeof c.discord === "string") - .map((c) => [c.github.toLowerCase(), c.discord]), - ); - return github.map((c) => ({ ...c, discord: discord.get(c.login.toLowerCase()) || "" })); -} - -export function creditHtml(list) { - return list - .map((c) => { - const src = avatar(c.avatar_url); - const count = `${c.contributions.toLocaleString("en-US")} ${c.contributions === 1 ? "commit" : "commits"}`; - return `
  • ${src ? `` : ``}${escape(c.login)}${count}${c.discord ? ` · ${escape(c.discord)} on Discord` : ""}
  • `; - }) - .join(""); -} diff --git a/website/src/hub.test.mjs b/website/src/hub.test.mjs deleted file mode 100644 index 4213d8a87..000000000 --- a/website/src/hub.test.mjs +++ /dev/null @@ -1,159 +0,0 @@ -import { test } from "node:test"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import { boardFrom, boardHtml, creditFrom, creditHtml, fixesIn, itemOf, journalFrom, journalHtml, journalJson, overviewHtml, progress, roadmapHtml, slimIssue, suggestItemsHtml } from "./hub.js"; - -const roadmap = JSON.parse(readFileSync(new URL("../data/roadmap.json", import.meta.url), "utf8")); - -const pr = (number, extra = {}) => ({ number, title: `PR ${number}`, state: "open", pull_request: { merged_at: null }, user: { login: "a" }, labels: [], assignees: [], body: "", ...extra }); -const issue = (number, extra = {}) => ({ number, title: `Issue ${number}`, state: "open", user: { login: "b" }, labels: [{ name: "bug" }], assignees: [], ...extra }); - -test("pull requests and issues reduce to their hub state", () => { - assert.deepEqual(fixesIn("Fixes #12, #13 and closes #4. Mentions #9."), [4, 12, 13]); - const merged = slimIssue(pr(5, { state: "closed", pull_request: { merged_at: "2030-01-01T00:00:00Z" }, body: "Fixes #3" })); - assert.equal(merged.kind, "pr"); - assert.equal(merged.state, "merged"); - assert.deepEqual(merged.fixes, [3]); - assert.equal(slimIssue(issue(6, { state: "closed", state_reason: "not_planned" })).state, "dropped"); - assert.deepEqual(slimIssue(issue(7)).labels, ["bug"]); -}); - -test("an item's progress counts its pull requests and issues", () => { - const live = new Map([ - [1, slimIssue(pr(1))], - [2, slimIssue(pr(2, { draft: true }))], - [3, slimIssue(pr(3, { state: "closed", pull_request: { merged_at: "2030-01-01T00:00:00Z" } }))], - [4, slimIssue(issue(4))], - ]); - const item = { links: ["#1", "#2", "#3", "#4", "#99", "docs/x.md"] }; - assert.equal(progress(item, live), "1 pull request in review · 1 in progress · 1 merged · 1 issue open"); - assert.equal(progress(item, new Map()), ""); -}); - -test("the roadmap renders every item once, with both texts, in its status's section", () => { - const html = roadmapHtml(roadmap); - for (const item of roadmap.items) { - assert.equal(html.split(`id="${item.id}"`).length, 2, item.id); - } - assert.ok(html.indexOf('id="now"') < html.indexOf('id="next"')); - assert.ok(html.includes('class="hub-plain"') && html.includes('class="hub-dev"')); - // Shipped items say which release had them. - assert.ok(html.includes(`>${roadmap.items.find((i) => i.status === "shipped").shipped_in}<`)); -}); - -test("an item is its own anchor (hub#, as Kira links it) and takes no other id of the page", () => { - const week = { week: "2030-01", date: "2029-12-31", title: "A week", plain: "p", dev: "d" }; - const release = { tag_name: "v0.2.2", name: "0.2.2", published_at: "2030-01-02T00:00:00Z", html_url: "u", body: "" }; - const journal = journalHtml(journalFrom([release], [], { ...roadmap, journal: [week] }), roadmap); - const board = boardHtml(boardFrom([], roadmap), roadmap); - const page = readFileSync(new URL("./hub.html", import.meta.url), "utf8") + roadmapHtml(roadmap) + overviewHtml(roadmap) + board + journal; - const ids = [...page.matchAll(/ id="([^"]+)"/g)].map((m) => m[1]); - assert.deepEqual(ids.filter((id, i) => ids.indexOf(id) !== i), []); - for (const item of roadmap.items) assert.ok(ids.includes(item.id), item.id); -}); - -test("the overview lists the focus items and never nests links", () => { - const html = overviewHtml(roadmap); - for (const item of roadmap.items.filter((i) => i.focus)) assert.ok(html.includes(`href="#${item.id}"`), item.id); - for (const row of html.match(/
  • [\s\S]*?<\/li>/g)) assert.equal(row.split(" { - const now = Date.parse("2030-01-10T00:00:00Z"); - const list = [ - issue(1), - issue(2), - issue(3, { assignees: [{ login: "x" }] }), - pr(10, { body: "Fixes #1" }), - pr(11, { body: "Fixes #2", draft: true }), - pr(12, { labels: [{ name: `roadmap:${roadmap.items[0].id}` }] }), - pr(13, { draft: true }), - pr(14, { state: "closed", pull_request: { merged_at: "2030-01-09T00:00:00Z" } }), - pr(15, { state: "closed", pull_request: { merged_at: "2029-12-01T00:00:00Z" } }), - ].map(slimIssue); - const board = boardFrom(list, roadmap, now); - const ids = (column) => board[column].map((c) => c.n); - assert.deepEqual(ids("todo"), []); - assert.deepEqual(ids("progress"), [2, 3, 13]); - assert.deepEqual(ids("review"), [1, 12]); - assert.deepEqual(ids("done"), [14]); - assert.deepEqual(board.review[0].prs, [10]); - assert.equal(board.review[1].item, roadmap.items[0].id); - assert.equal(itemOf(slimIssue(pr(16, { body: "Fixes #1438" })), roadmap), "end-city-banners"); -}); - -test("the journal groups a release's changes by roadmap item and lists what awaits a release", () => { - const releases = [ - { tag_name: "v0.2.2", name: "Horizon 0.2.2: Rich presence", published_at: "2030-01-02T00:00:00Z", html_url: "u2", body: "### New\n- Discord Rich Presence (#1787)\n\n### Fixed\n- A fix (#5, fixes #4)\n" }, - { tag_name: "launcher@0.2.1", name: "Horizon launcher 0.2.1", published_at: "2030-01-01T00:00:00Z", html_url: "u1", body: "### Fixed\n- Window (#6)\n" }, - ]; - const list = [ - pr(1788, { state: "closed", pull_request: { merged_at: "2030-01-03T00:00:00Z" } }), - pr(7, { state: "closed", pull_request: { merged_at: "2030-01-03T00:00:00Z" }, labels: [{ name: "skip-release" }] }), - ].map(slimIssue); - const entries = journalFrom(releases, list, { ...roadmap, journal: [] }); - assert.deepEqual(entries.map((e) => e.id), ["next-release", "v0.2.2", "launcher@0.2.1"]); - assert.deepEqual(entries[0].changes.map((c) => [c.prs, c.item]), [[[1788], "discord-presence"]]); - assert.deepEqual(entries[1].changes.map((c) => [c.section, c.text, c.item]), [["new", "Discord Rich Presence", "discord-presence"], ["fixed", "A fix", null]]); - const html = journalHtml(entries, roadmap); - assert.ok(html.includes('href="#discord-presence"')); - assert.ok(html.includes("And 1 fix.")); -}); - -test("journal.json is the flat feed Kira reads: merges, releases, shipped items, weeks, ids that never change", () => { - const releases = [ - { tag_name: "v0.2.48", name: "Horizon 0.2.48", published_at: "2030-01-02T00:00:00Z", html_url: "https://github.com/ludovic111/horizon/releases/tag/v0.2.48", body: "### New\n- Packs (#1)\n" }, - { tag_name: "nightly-1", name: "Nightly", published_at: "2030-01-03T00:00:00Z", html_url: "u", body: "" }, - ]; - const list = [ - pr(1788, { state: "closed", pull_request: { merged_at: "2030-01-04T00:00:00Z" }, html_url: "https://github.com/ludovic111/horizon/pull/1788" }), - pr(7, { state: "closed", pull_request: { merged_at: "2030-01-04T00:00:00Z" }, labels: [{ name: "skip-release" }] }), - pr(8, { state: "closed", pull_request: { merged_at: "2030-01-04T00:00:00Z" }, labels: [{ name: "skip-release" }, { name: "roadmap:lean-code" }] }), - pr(9), - ].map(slimIssue); - const week = { week: "2030-01", date: "2029-12-31", title: "A week", plain: "p", dev: "d" }; - const feed = journalJson(releases, list, { ...roadmap, journal: [week] }, "2030-01-05T00:00:00Z"); - const byId = new Map(feed.entries.map((e) => [e.id, e])); - // A merged pull request, with its roadmap item; skip-release ones only when they move an item; open ones never. - assert.deepEqual(byId.get("pr-1788"), { id: "pr-1788", kind: "merge", date: "2030-01-04T00:00:00Z", title: "PR 1788", url: "https://github.com/ludovic111/horizon/pull/1788", number: 1788, item: "discord-presence", item_title: "Discord Rich Presence" }); - assert.ok(!byId.has("pr-7") && byId.get("pr-8").item === "lean-code" && !byId.has("pr-9")); - // Game and launcher releases only. - assert.equal(byId.get("release-v0.2.48").tag, "v0.2.48"); - assert.ok(!byId.has("release-nightly-1")); - // Every shipped item, dated by its release when the feed has it, with its post and the announce flag. - const shipped = roadmap.items.filter((i) => i.status === "shipped"); - for (const item of shipped) { - const e = byId.get(`shipped-${item.id}`); - assert.equal(e.kind, "shipped"); - assert.equal(e.url, `https://playhorizon.dev/hub#${item.id}`); - assert.ok(e.post.length <= 240 && typeof e.announce === "boolean", item.id); - } - assert.equal(byId.get("shipped-server-resource-packs").date, "2030-01-02T00:00:00Z"); - assert.equal(byId.get("weekly-2030-01").date, "2030-01-06T23:59:59.000Z"); - // Newest first; every entry has what Kira needs, and links only where Kira shows them. - assert.deepEqual(feed.entries.map((e) => e.date), feed.entries.map((e) => e.date).sort().reverse()); - for (const e of feed.entries) { - assert.ok(e.id && ["merge", "release", "weekly", "shipped"].includes(e.kind) && e.date && e.title, e.id); - assert.match(e.url, /^https:\/\/(github\.com|playhorizon\.dev)\//, e.id); - } -}); - -test("items still to come take votes and suggestions; shipped ones don't", () => { - const html = roadmapHtml(roadmap); - for (const item of roadmap.items) { - assert.equal(html.includes(`data-vote="${item.id}"`), item.status !== "shipped", item.id); - assert.equal(suggestItemsHtml(roadmap).includes(`value="${item.id}"`), item.status !== "shipped", item.id); - } - // Hidden until the hub's server answers. - assert.ok(html.includes('aria-pressed="false" hidden>')); -}); - -test("the contributors carry the Discord name of those who agreed on Kira", () => { - const github = [{ login: "Alex", html_url: "https://github.com/Alex", avatar_url: "", contributions: 3 }, { login: "sam", html_url: "https://github.com/sam", avatar_url: "", contributions: 1 }]; - const kira = { contributors: [{ github: "alex", discord: "Alex " }, { github: 5 }, null] }; - const credit = creditFrom(github, kira); - assert.deepEqual(credit.map((c) => c.discord), ["Alex ", ""]); - const html = creditHtml(credit); - assert.ok(html.includes("3 commits · Alex <b> on Discord") && html.includes("1 commit")); - assert.deepEqual(creditFrom(github, "not json").map((c) => c.discord), ["", ""]); -}); diff --git a/website/src/index.html b/website/src/index.html deleted file mode 100644 index 3776733c6..000000000 --- a/website/src/index.html +++ /dev/null @@ -1,216 +0,0 @@ - - - - - - Horizon: a Rust rewrite for Minecraft: Java Edition 26.3 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -{{SITE_NAV}} - -
    -
    -
    -

    Minecraft: Java Edition 26.3Rust

    -

    Horizon: The game you know, rebuilt in Rust.

    -

    The Minecraft: Java Edition 26.3 client and its game logic, rewritten in Rust and checked against the vanilla game by {{HARNESSES}} differential harnesses.

    - -

    For Linux x86-64, macOS on Apple Silicon and Windows x64.

    -
    -
    -
    -
      -
    1. 01Matches vanilla{{PERCENT}}
    2. -
    3. 02Differential harnesses{{HARNESSES}}
    4. -
    5. 03Drawn by Horizon5 shots
    6. -
    7. 04Recently addedReleases
    8. - -
    -

    Unofficial. Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

    -
    - -
    -
    -

    01What it is

    -

    Horizon rebuilds Minecraft: Java Edition 26.3 in Rust, one subsystem at a time, and holds every piece to the same inputs as the vanilla game until the outputs are identical.

    -
    -
    - -

    Your own copy

    -

    Install Java Edition with the official launcher and play 26.3 once. Horizon builds its resources from those files on your machine, and never downloads or shares game files.

    -
    -
    - -

    Native on three platforms

    -

    Linux, macOS on Apple Silicon and Windows. Worlds come from a Rust port of the vanilla generators, drawn with vanilla's block models, lighting, sky and fog.

    -
    -
    - -

    Open source

    -

    Horizon's code is MIT. It contains no Minecraft code, assets or data; those belong to Mojang and Microsoft under the Minecraft EULA.

    -
    -
    -
    -
    - -
    -
    -
    -

    02In game

    -

    Drawn by Horizon

    -

    Captured in the Rust client itself, with vanilla assets from the player's own copy and no mods or shaders.

    -
    -
    -
    01A plains village
    -
    02Moonrise
    -
    03A crimson forest in the Nether
    -
    04A coral reef
    -
    05Survival at dusk
    -
    -
    -
    - -
    -
    -

    03Parity

    -
    -
    - -

    {{HARNESSES}} differential harnesses drive the same inputs through Horizon and through the vanilla client and server, and compare what comes out.

    -
    -
    -

    {{PARITY_HEADLINE}}

    -
    {{PARITY_INTRO}}
    -

    Last audited {{AUDITED}}{{PERCENT}} of what the harnesses comparefrom the README on main

    -
    -
    -
      - {{PARITY_CELLS}} -
    -

    Each subsystem scores 0 (absent), 0.25 (started), 0.5 (playable, major features missing), 0.75 (mostly complete) or 1 (complete and verified against vanilla by differential tests).

    -
    -
    - -
    -
    -
    -

    04The launcher

    -

    One small app, then play

    -

    The launcher installs Horizon, prepares it from your copy of the game and keeps both up to date.

    -
      -
    • One-click install

      Pick a release and it installs the build for your platform into its own folder, then prepares the resources from your Java Edition 26.3 install.

    • -
    • Updates on its own

      It looks for a new Horizon release when it starts and every four hours, and updates itself from the launcher's own releases.

    • -
    • Client or server

      Start the client, or host a server from the Servers page: create it, start it, watch players and the console, change its settings and keep backups.

    • -
    • Logs and crash reports

      The Settings page shows where the game's logs and crash reports are, and horizon-launcher logs prints them.

    • -
    • Modpacks and packs

      The Modpacks page reads a Modrinth or CurseForge pack and carries over the mods Horizon can run. The Mods page installs resource packs and modpacks from Modrinth.

    • -
    -
    - Download the launcher -

    {{LAUNCHER_META}}

    -
    -
    - -
    -
    - - - -
    -
    -
    The launcher's Play page: the version, Client and Server, the version picker and Play, the prepared resources and the Minecraft folder as a numbered list
    -
    Vanilla's Video Settings screen with Horizon's own buttons at the top: Horizon Graphics and Advanced Graphics
    -
    -

    The launcher, and Horizon's graphics settings in the game: vanilla's menus, with Horizon's pages added the way mods add theirs.

    -
    -
    -
    - -
    -
    -
    -

    05Releases

    -

    Recently added

    -

    New versions come out many times a day, as changes land, and the launcher installs each one once it has passed its test. The newest, and what they added:

    -
    -
    - {{RECENT}} -
    -
    -
    - -
    - -
    -
    - -
    -
    - - - -
    - -
    - - -
    - - -
    - - - - diff --git a/website/src/main.js b/website/src/main.js deleted file mode 100644 index 72e8577a5..000000000 --- a/website/src/main.js +++ /dev/null @@ -1,265 +0,0 @@ -// The page's behaviour: the download buttons for this platform, the latest releases, the -// links and contributors, how many play now, the navigation, the menus' tabs, the lightbox -// and the motion. -// Everything degrades to the baked-in content when GitHub can't be reached. -import { escape } from "./markdown.js"; -import { recentHtml } from "./releases.js"; -import { contributorsFrom, contributorsHtml } from "./contributors.js"; -import { isGame, isLauncher as isLauncherTag, launcherVersion, newestFirst } from "./versions.js"; -import { cached, get, setUpMenu, setUpTheme, slim } from "./chrome.js"; - -const REPO = "ludovic111/horizon"; -const RELEASES_PAGE = `https://github.com/${REPO}/releases?q=launcher&expanded=true`; -const baked = JSON.parse(document.getElementById("baked").textContent); -const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches; - -// --- GitHub -------------------------------------------------------------------------- - -const isLauncher = (r) => isLauncherTag(r.tag_name) && !r.prerelease; - -// The newest 100 releases (GitHub's most per page). The newest game release that is not a pre-release (the old -// Alpha channel's, docs/release-flow.md) and the newest launcher release can be older than all of them. The game -// release is then GitHub's "latest" (pre-releases and launcher releases never are); the launcher release is looked up by its -// tag (the newest launcher@ tag with a published release, or launcher-v before 0.2: docs/versioning.md). -async function loadReleases() { - const list = (await get(`https://api.github.com/repos/${REPO}/releases?per_page=100`)).filter((r) => !r.draft).map(slim); - if (!list.some((r) => isGame(r.tag_name) && !r.prerelease)) { - const latest = await get(`https://api.github.com/repos/${REPO}/releases/latest`).catch(() => null); - if (latest && !latest.draft) list.push(slim(latest)); - } - if (list.some(isLauncher)) return list; - let tags = []; - for (const prefix of ["launcher@", "launcher-v"]) { - if (tags.length) break; - const refs = await get(`https://api.github.com/repos/${REPO}/git/matching-refs/tags/${prefix}`).catch(() => []); - tags = refs.map((r) => r.ref.replace("refs/tags/", "")).filter(isLauncherTag).sort(newestFirst); - } - for (const tag of tags.slice(0, 3)) { - const release = await get(`https://api.github.com/repos/${REPO}/releases/tags/${tag}`).catch(() => null); - if (release && !release.draft) return [...list, slim(release)]; - } - return list; -} - -const releases = cached("horizon:releases", loadReleases).catch(() => baked.releases); - -async function setUpContributors() { - let list = baked.contributors || []; - try { - list = contributorsFrom(await cached("horizon:contributors", () => get(`https://api.github.com/repos/${REPO}/contributors?per_page=100`))); - } catch {} - if (list.length) document.getElementById("contributors-list").innerHTML = contributorsHtml(list); - // With nobody to show, the block and its menu entries go, as an empty link's card does. - document.querySelectorAll("[data-contributors]").forEach((el) => (el.hidden = !list.length)); -} - -// --- Download ------------------------------------------------------------------------ - -function platform() { - const ua = navigator.userAgent; - const hint = (navigator.userAgentData && navigator.userAgentData.platform) || navigator.platform || ""; - if (/iPhone|iPad|iPod|Android/i.test(ua) || (navigator.maxTouchPoints > 1 && /Mac/.test(hint))) return null; - if (/Win/i.test(hint) || /Windows/.test(ua)) return { key: "windows-x64", label: "Windows x64" }; - if (/Mac/i.test(hint) || /Mac OS X/.test(ua)) return { key: "macos-arm64", label: "macOS on Apple Silicon" }; - if (/Linux|X11/i.test(hint) || /Linux/.test(ua)) return { key: "linux-x86_64", label: "Linux x86-64" }; - return null; -} - -async function setUpDownload() { - const os = platform(); - const list = await releases; - const launcher = list.filter(isLauncher).sort((a, b) => newestFirst(a.tag_name, b.tag_name))[0]; - if (!launcher) return; - const version = launcherVersion(launcher.tag_name); - const asset = os && launcher.assets.find((a) => a.name.includes(os.key)); - const others = `Other platforms`; - document.querySelectorAll("[data-download]").forEach((a) => (a.href = asset ? asset.browser_download_url : launcher.html_url || RELEASES_PAGE)); - const mb = asset && asset.size ? ` · ${(asset.size / 1e6).toFixed(0)} MB` : ""; - const meta = asset - ? `For ${escape(os.label)} · launcher ${escape(version)}${mb} · ${others}` - : `Launcher ${escape(version)} for Linux x86-64, macOS on Apple Silicon and Windows x64. It runs on a computer, not on phones or tablets.`; - document.querySelectorAll("[data-download-meta]").forEach((p) => (p.innerHTML = meta)); -} - -// --- Recently added and the links from main --------------------------------- - -// "Recently added": the newest game releases. -async function setUpRecent() { - const html = recentHtml((await releases).filter((r) => isGame(r.tag_name))); - if (html) document.getElementById("recent-releases").innerHTML = html; -} - -async function setUpLinks() { - let links = baked.links; - try { - const remote = await cached("horizon:links", () => get(`https://raw.githubusercontent.com/${REPO}/main/launcher/links.json`, "text").then(JSON.parse)); - links = { ...links }; - for (const key of Object.keys(links)) if (typeof remote[key] === "string") links[key] = remote[key].trim(); - } catch {} - document.querySelectorAll("[data-link]").forEach((a) => { - const url = links[a.dataset.link]; - // An empty address hides its card, as the launcher hides its button. - if (!url) a.hidden = true; - else if (/^https:\/\//.test(url)) a.href = url; - }); -} - -// --- Playing now --------------------------------------------------------------------- - -const TELEMETRY = "https://telemetry.playhorizon.dev"; - -// How many play right now, from the games' anonymous "I'm playing" pings (Privacy explains them). The -// server rounds it and makes it again at most every 15 seconds; the row stays hidden while nobody plays -// or the server doesn't answer. -async function setUpLive() { - const row = document.querySelector("[data-live]"); - if (!row) return; - const update = async () => { - try { - const res = await fetch(`${TELEMETRY}/v1/live`, { signal: AbortSignal.timeout(3000) }); - if (!res.ok) throw new Error(String(res.status)); - const { playing } = await res.json(); - if (!Number.isInteger(playing) || playing < 1) throw new Error("nobody"); - row.querySelector("[data-live-count]").textContent = playing.toLocaleString("en"); - row.hidden = false; - // It shows up after the others came in, so it skips their entrance. - row.classList.add("is-visible"); - } catch { - row.hidden = true; - } - }; - await update(); - setInterval(() => document.visibilityState === "visible" && update(), 60_000); -} - -// --- Navigation ---------------------------------------------------------------------- - -function setUpNav() { - // The home sections use the same root-relative links in every page's header. - const links = [...document.querySelectorAll('.nav-links a[href^="/#"]')]; - const sections = links.map((a) => document.querySelector(a.hash)); - - let current = null; - const update = () => { - const line = innerHeight * 0.4; - let index = -1; - sections.forEach((s, i) => { - if (s.getClientRects().length && s.getBoundingClientRect().top <= line) index = i; - }); - if (index !== current) { - current = index; - links.forEach((a, i) => (i === index ? a.setAttribute("aria-current", "true") : a.removeAttribute("aria-current"))); - } - }; - onScroll(update); - update(); -} - -// One rAF-throttled scroll listener for everything that follows the scroll. -const scrollers = []; -function onScroll(fn) { - scrollers.push(fn); -} -let queued = false; -const run = () => ((queued = false), scrollers.forEach((fn) => fn())); -addEventListener("scroll", () => !queued && ((queued = true), requestAnimationFrame(run)), { passive: true }); -addEventListener("resize", () => requestAnimationFrame(run)); - -// --- The menus' tabs ------------------------------------------------------------------ - -function setUpTabs() { - const list = document.querySelector(".tabs"); - const tabs = [...list.querySelectorAll('[role="tab"]')]; - const pill = list.querySelector(".tab-pill"); - const selected = () => tabs.find((t) => t.getAttribute("aria-selected") === "true"); - const place = (tab) => { - pill.style.width = `${tab.offsetWidth}px`; - pill.style.height = `${tab.offsetHeight}px`; - pill.style.transform = `translate(${tab.offsetLeft}px, ${tab.offsetTop}px)`; - }; - const choose = (tab, focus) => { - tabs.forEach((t) => { - const on = t === tab; - t.setAttribute("aria-selected", String(on)); - t.tabIndex = on ? 0 : -1; - const panel = document.getElementById(t.getAttribute("aria-controls")); - panel.classList.toggle("is-active", on); - panel.inert = !on; - panel.setAttribute("aria-hidden", String(!on)); - }); - place(tab); - if (focus) tab.focus(); - }; - tabs.forEach((tab, i) => { - tab.addEventListener("click", () => choose(tab)); - tab.addEventListener("keydown", (e) => { - const step = { ArrowRight: 1, ArrowLeft: -1 }[e.key]; - if (step) choose(tabs[(i + step + tabs.length) % tabs.length], true); - if (e.key === "Home") choose(tabs[0], true); - if (e.key === "End") choose(tabs[tabs.length - 1], true); - }); - }); - choose(selected()); - addEventListener("resize", () => place(selected())); - document.fonts?.ready.then(() => place(selected())); -} - -function setUpLightbox() { - const dialog = document.querySelector(".lightbox"); - const big = dialog.querySelector("img"); - const caption = dialog.querySelector(".lightbox-caption"); - document.querySelectorAll(".zoom").forEach((button) => { - button.addEventListener("click", () => { - const img = button.querySelector("img"); - big.src = img.currentSrc.replace("-800.webp", ".webp"); - big.alt = img.alt; - caption.textContent = img.alt; - dialog.showModal(); - }); - }); - dialog.addEventListener("click", (e) => { - if (e.target === dialog) dialog.close(); - }); -} - -// --- Motion --------------------------------------------------------------------------- - -function setUpReveal() { - // Siblings that enter together come in one after another. - const stagger = (els, step) => els.forEach((el, i) => el.style.setProperty("--d", `${i * step}ms`)); - document.querySelectorAll(".facts, .features, .cards, .mosaic, .hero-index").forEach((group) => stagger([...group.children], 40)); - document.querySelectorAll(".hero .container, .section-head, .parity-count, .parity-copy, .launcher-copy").forEach((group) => stagger([...group.querySelectorAll(":scope > .reveal")], 60)); - stagger([...document.querySelectorAll(".system")], 40); - - const count = document.querySelector("[data-digits]"); - count.innerHTML = [...count.textContent].map((c) => `${escape(c)}`).join(""); - - const items = document.querySelectorAll(".reveal, .reveal-media, .systems"); - if (reducedMotion || !("IntersectionObserver" in window)) { - items.forEach((el) => el.classList.add("is-visible")); - return; - } - const observer = new IntersectionObserver( - (entries) => - entries.forEach((e) => { - if (e.isIntersecting) { - e.target.classList.add("is-visible"); - observer.unobserve(e.target); - } - }), - { rootMargin: "0px 0px -10% 0px" }, - ); - items.forEach((el) => observer.observe(el)); -} - -setUpReveal(); -setUpTheme(); -setUpNav(); -setUpMenu(); -setUpTabs(); -setUpLightbox(); -setUpDownload(); -setUpRecent(); -setUpLinks(); -setUpContributors(); -setUpLive(); diff --git a/website/src/markdown.js b/website/src/markdown.js deleted file mode 100644 index 1735f7304..000000000 --- a/website/src/markdown.js +++ /dev/null @@ -1,203 +0,0 @@ -// A small Markdown renderer for release notes, the README and the docs: headings, paragraphs, -// lists (nested by indentation), fenced code, quotes, rules, tables, and inline code, bold, -// italic and links. Everything is escaped first, so its output never carries raw HTML. -// Shared by build.mjs (Node) and main.js (browser). - -const REPO_BLOB = "https://github.com/ludovic111/horizon/blob/main/"; - -export function escape(text) { - return text.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]); -} - -function href(url, site) { - url = url.trim(); - if (/^(https?:|mailto:)/i.test(url)) return url; - // The docs pages (`site`) link each other and their own headings; the README's anchors have no target here. - if (site && (/^\/(?!\/)/.test(url) || url.startsWith("#"))) return url; - if (url.startsWith("#")) return null; - if (/^[a-z]+:/i.test(url)) return null; // javascript: and the like - return REPO_BLOB + url.replace(/^\.?\//, ""); -} - -export function inline(text, site = false) { - const codes = []; - let out = text.replace(/`([^`]+)`/g, (_, code) => { - codes.push(code); - return `\u0000${codes.length - 1}\u0000`; - }); - const links = []; - out = out.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, label, url) => { - links.push([label, url]); - return `\u0001${links.length - 1}\u0001`; - }); - out = escape(out) - .replace(/\*\*([^*]+)\*\*/g, "$1") - .replace(/(^|[^\w*])\*([^*\s][^*]*)\*/g, "$1$2") - .replace(/(^|[^\w])_([^_\s][^_]*)_(?!\w)/g, "$1$2") - .replace(/<(https?:\/\/[^\s&]+)>/g, (_, u) => `${u}`); - out = out.replace(/\u0001(\d+)\u0001/g, (_, i) => { - const [label, url] = links[i]; - const target = href(url, site); - // The label's code spans are already placeholders: put them back for its own pass. - const body = inline(label.replace(/\u0000(\d+)\u0000/g, (_, c) => `\`${codes[c]}\``), site); - return target ? `${body}` : body; - }); - return out.replace(/\u0000(\d+)\u0000/g, (_, i) => `${escape(codes[i])}`); -} - -// A table: a row of cells, a rule row (`| --- | :-: |`), then body rows, until a line that isn't a row. -const ROW = /^\s*\|.*\|\s*$/; -const RULE = /^\s*\|(\s*:?-+:?\s*\|)+\s*$/; - -/** A row's cells: split on `|` outside code spans; `\|` is a literal bar. */ -function cells(row) { - const s = row.trim().slice(1, -1); - const out = [""]; - let code = false; - for (let i = 0; i < s.length; i++) { - if (s[i] === "\\" && s[i + 1] === "|") out[out.length - 1] += s[++i]; - else if (s[i] === "|" && !code) out.push(""); - else { - if (s[i] === "`") code = !code; - out[out.length - 1] += s[i]; - } - } - return out.map((c) => c.trim()); -} - -function table(lines, start, site) { - const row = (line, tag) => `${cells(line).map((c) => `<${tag}>${inline(c, site)}`).join("")}`; - let i = start + 2; - const body = []; - while (i < lines.length && ROW.test(lines[i])) body.push(row(lines[i++], "td")); - return [`
    ${row(lines[start], "th")}${body.join("")}
    `, i]; -} - -const indentOf = (line) => line.match(/^ */)[0].length; -const ITEM = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/; - -function list(lines, start, site) { - // Collects the items at this list's indentation; deeper lines belong to the item above. - const base = indentOf(lines[start]); - const ordered = /\d/.test(lines[start].match(ITEM)[2]); - const items = []; - let i = start; - while (i < lines.length) { - const line = lines[i]; - if (!line.trim()) { - const next = lines.slice(i + 1).find((l) => l.trim()); - if (next && ITEM.test(next) && indentOf(next) >= base) { - i++; - continue; - } - break; - } - const m = line.match(ITEM); - if (m && indentOf(line) === base) { - items.push({ text: [m[3]], children: [] }); - } else if (m && indentOf(line) > base) { - const [html, end] = list(lines, i, site); - items[items.length - 1].children.push(html); - i = end; - continue; - } else if (indentOf(line) > base && items.length) { - items[items.length - 1].text.push(line.trim()); - } else { - break; - } - i++; - } - const tag = ordered ? "ol" : "ul"; - const body = items.map((it) => `
  • ${inline(it.text.join(" "), site)}${it.children.join("")}
  • `).join(""); - return [`<${tag}>${body}`, i]; -} - -const slug = (text) => - text - .toLowerCase() - .replace(/`/g, "") - .replace(/[^a-z0-9]+/g, "-") - .replace(/^-|-$/g, ""); - -/** - * Renders Markdown; `shift` moves headings down (a `#` becomes `h{1 + shift}`). - * `site` is for the docs pages: links to the site's own pages and anchors stay as they are, `##` and `###` - * headings get an id (and are pushed onto `headings`, for a table of contents), and a line holding only - * `![caption](/media/…)` becomes a figure. - */ -export function markdown(source, { shift = 0, site = false, headings = null } = {}) { - const lines = source.replace(/\r\n?/g, "\n").split("\n"); - const out = []; - let i = 0; - while (i < lines.length) { - const line = lines[i]; - if (!line.trim() || /^\s*<\/?[a-z][^>]*>\s*$/i.test(line)) { - i++; // blank lines and lone HTML tags (the README's layout tables) are skipped - continue; - } - let m; - if ((m = line.match(/^(#{1,6})\s+(.*?)\s*#*$/))) { - const level = Math.min(6, m[1].length + shift); - let id = ""; - if (site && (m[1].length === 2 || m[1].length === 3)) { - const base = slug(m[2]); - id = base; - for (let n = 2; headings && headings.some((h) => h.id === id); n++) id = `${base}-${n}`; - headings?.push({ level: m[1].length, text: m[2].replace(/`/g, ""), id }); - } - out.push(`${inline(m[2], site)}`); - i++; - } else if (site && (m = line.match(/^!\[([^\]]*)\]\((\/media\/[\w./-]+)\)\s*$/))) { - out.push(`
    ${escape(m[1])}
    ${inline(m[1], true)}
    `); - i++; - } else if ((m = line.match(/^\s*(```|~~~)/))) { - const fence = m[1]; - const code = []; - i++; - while (i < lines.length && !lines[i].trim().startsWith(fence)) code.push(lines[i++]); - i++; - out.push(`
    ${escape(code.join("\n"))}
    `); - } else if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) { - out.push("
    "); - i++; - } else if (ROW.test(line) && RULE.test(lines[i + 1] || "")) { - const [html, end] = table(lines, i, site); - out.push(html); - i = end; - } else if (ITEM.test(line)) { - const [html, end] = list(lines, i, site); - out.push(html); - i = end; - } else if (line.startsWith(">")) { - const quote = []; - while (i < lines.length && lines[i].startsWith(">")) quote.push(lines[i++].replace(/^>\s?/, "")); - out.push(`
    ${markdown(quote.join("\n"), { shift, site })}
    `); - } else { - const para = []; - while ( - i < lines.length && - lines[i].trim() && - !/^(#{1,6}\s|>|\s*```|\s*~~~)/.test(lines[i]) && - !ITEM.test(lines[i]) - ) { - para.push(lines[i++].trim()); - } - out.push(`

    ${inline(para.join(" "), site)}

    `); - } - } - return out.join("\n"); -} - -/** The body of the section titled `title` (any heading level), up to the next heading at its level or above. */ -export function section(source, title) { - const lines = source.replace(/\r\n?/g, "\n").split("\n"); - const level = (l) => (l.match(/^(#{1,6})\s/) || [, ""])[1].length; - const start = lines.findIndex((l) => level(l) > 0 && l.replace(/^#+/, "").trim() === title); - if (start < 0) return null; - const depth = level(lines[start]); - const end = lines.findIndex((l, i) => i > start && level(l) > 0 && level(l) <= depth); - return lines - .slice(start + 1, end < 0 ? undefined : end) - .join("\n") - .trim(); -} diff --git a/website/src/markdown.test.mjs b/website/src/markdown.test.mjs deleted file mode 100644 index 171348e45..000000000 --- a/website/src/markdown.test.mjs +++ /dev/null @@ -1,25 +0,0 @@ -// node --test src/: the Markdown the docs pages and release notes are rendered from. -import { test } from "node:test"; -import assert from "node:assert/strict"; -import { markdown } from "./markdown.js"; - -test("a table renders with its header, cells and inline Markdown", () => { - const html = markdown("| Way in | Status |\n| --- | :-: |\n| Rust | `cargo horizon-mod` |\n| Lua | planned \\| soon |\n\nAfter."); - assert.equal( - html, - '
    ' + - "
    Way inStatus
    Rustcargo horizon-mod
    Luaplanned | soon
    \n

    After.

    ", - ); -}); - -test("a bar inside a code span stays in its cell", () => { - assert.match(markdown("| a | b |\n|---|---|\n| `x | y` | z |"), /x \| y<\/code><\/td>z<\/td>/); -}); - -test("rows without a rule line are a paragraph", () => { - assert.equal(markdown("| a | b |\n| c | d |"), "

    | a | b | | c | d |

    "); -}); - -test("a link whose label is code keeps it", () => { - assert.equal(markdown("See [`AGENTS.md`](/docs/agents).", { site: true }), '

    See AGENTS.md.

    '); -}); diff --git a/website/src/mods-page.js b/website/src/mods-page.js deleted file mode 100644 index 335e863bd..000000000 --- a/website/src/mods-page.js +++ /dev/null @@ -1,146 +0,0 @@ -// /mods and /mods/: 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 = 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 ? `

    ${escape(message)}

    ` : ""); -} - -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, ratings ? ratingOf(ratings, p.id) : undefined); - document.title = `${p.name} · Horizon`; - showRate(p); - } else { - page.outerHTML = `

    Not in the registry

    No project is called ${id} here. It may not be published yet, or it was taken down.

    Every mod
    `; - } -} - -function render() { - if (id) showProject(); - else showList(); -} - -// 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; - showList(); - }), - ); - root.querySelector("#mod-search")?.addEventListener("input", (e) => { - text = e.target.value; - showList(); - }); - 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(); -setUpMenu(); -render(); -cached("horizon:mod-index", () => fetch(INDEX_URL).then((r) => (r.ok ? r.json() : Promise.reject(new Error(`${r.status}`))))) - .then((index) => { - const fresh = readIndex(index); - if (fresh) { - projects = fresh; - render(); - } - }) - .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(() => {}); diff --git a/website/src/mods-submit.js b/website/src/mods-submit.js deleted file mode 100644 index c1024495b..000000000 --- a/website/src/mods-submit.js +++ /dev/null @@ -1,80 +0,0 @@ -// /mods/submit: signs in with GitHub through the registry's service, then sends the page and the file. The service -// checks the file and answers with the pull request it opened, or with what to fix. -import { API, entryFrom } from "./mods.js"; -import { setUpMenu, setUpTheme } from "./chrome.js"; -import { escape } from "./markdown.js"; - -const auth = document.getElementById("submit-auth"); -const form = document.getElementById("submit-form"); -const result = document.getElementById("submit-result"); -let csrf = ""; -// The form's own controls by name (form.id and form.name are the form's attributes). -const control = (name) => form.elements.namedItem(name); - -function signedOut(message) { - auth.innerHTML = `

    ${message}

    Sign in with GitHub

    It only reads your public profile: your GitHub name goes on the pull request and in the project's owners.

    `; - form.hidden = true; -} - -async function start() { - let me; - try { - const r = await fetch(`${API}/me`, { credentials: "same-origin" }); - if (r.status === 401) return signedOut("Sign in to submit: reviewers and updates go through your GitHub account."); - if (!r.ok) throw new Error(String(r.status)); - me = await r.json(); - } catch { - auth.innerHTML = `

    The form isn't open right now. You can open a pull request by hand.

    `; - return; - } - csrf = me.csrf; - auth.innerHTML = `

    Signed in as ${escape(me.login)}.

    `; - document.getElementById("sign-out").addEventListener("click", async () => { - await fetch(`${API}/auth/logout`, { method: "POST", credentials: "same-origin" }); - signedOut("Signed out."); - }); - form.hidden = false; -} - -// A file named -. fills in the two fields and the kind. -form.querySelector("#f-file").addEventListener("change", (e) => { - const name = e.target.files[0]?.name || ""; - const m = name.match(/^([a-z0-9_]{1,64})-([A-Za-z0-9][A-Za-z0-9._-]*)\.(hmod|hpack|zip)$/); - const kind = { hmod: "mod", hpack: "modpack", zip: "resourcepack" }[name.split(".").pop()]; - if (kind) control("kind").value = kind; - if (m) { - if (!control("id").value) control("id").value = m[1]; - if (!control("version").value) control("version").value = m[2]; - } -}); - -form.addEventListener("submit", async (e) => { - e.preventDefault(); - const send = form.querySelector("#f-send"); - const values = Object.fromEntries(["id", "kind", "name", "summary", "description", "authors", "license", "source", "icon", "key", "version", "game", "changelog"].map((k) => [k, control(k).value])); - const sig = form.querySelector("#f-signature").files[0]; - values.signature = sig ? await sig.text() : ""; - const body = new FormData(); - body.append("entry", JSON.stringify(entryFrom(values))); - body.append("file", form.querySelector("#f-file").files[0]); - send.disabled = true; - result.innerHTML = `

    Checking the file and opening the pull request…

    `; - try { - const r = await fetch(`${API}/submit`, { method: "POST", body, credentials: "same-origin", headers: { "X-CSRF-Token": csrf } }); - const json = await r.json().catch(() => ({})); - if (r.ok && /^https:\/\/github\.com\//.test(json.pull_request || "")) { - result.innerHTML = `

    Submitted. Follow the review in its pull request: the checks' report is there, and reviewers answer there.

    `; - form.reset(); - } else { - result.innerHTML = `

    ${escape(json.error || `The service answered ${r.status}.`)}

    `; - } - } catch { - result.innerHTML = `

    The service didn't answer. Try again in a minute.

    `; - } finally { - send.disabled = false; - } -}); - -setUpTheme(); -setUpMenu(); -start(); diff --git a/website/src/mods.html b/website/src/mods.html deleted file mode 100644 index 0c0e5eea2..000000000 --- a/website/src/mods.html +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - {{MODS_TITLE}} · Horizon - - - - - - - - - - - - - - - - - - - - -{{SITE_NAV}} -
    -
    -{{MODS_MAIN}} -

    Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

    -
    -
    -{{SITE_FOOTER}} - - - diff --git a/website/src/mods.js b/website/src/mods.js deleted file mode 100644 index 28c31b9fe..000000000 --- a/website/src/mods.js +++ /dev/null @@ -1,249 +0,0 @@ -// Horizon's registry on the site (/mods): the list with its kind filter and search, and a page per project. -// Shared by build.mjs (baked into the pages) and mods-page.js (refreshed from the published index). -// The index's format is docs/api/mod-index.md in the repository. -import { markdown, escape } from "./markdown.js"; - -export const INDEX_URL = "https://ludovic111.github.io/horizon-mods/index.json"; -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: {: {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. -export const KINDS = [ - ["mod", "Mods"], - ["modpack", "Modpacks"], - ["resourcepack", "Resource packs"], - ["shader", "Shader packs"], -]; -const KIND_NAMES = { mod: "Mod", modpack: "Modpack", resourcepack: "Resource pack", shader: "Shader pack" }; - -// What a capability lets a mod do, as the game and the launcher say it (horizon_mods::Capability::describe). -export const CAPABILITIES = { - "game-read": "see your position, health and the time", - chat: "show you chat messages", - hud: "draw text on your screen", - storage: "save its own settings to disk", - registries: "add blocks and items to your worlds", -}; - -// The index's projects this site can show, or null when it isn't an index it reads. -export function readIndex(index) { - if (!index || typeof index !== "object" || index.schema > SCHEMA || !Array.isArray(index.projects)) return null; - const known = new Set(KINDS.map(([k]) => k)); - return index.projects.filter((p) => known.has(p.kind) && /^[a-z0-9_]{1,64}$/.test(p.id) && p.versions?.length); -} - -const https = (url) => (typeof url === "string" && url.startsWith("https://") ? url : ""); -const size = (bytes) => (bytes >= 1 << 20 ? `${(bytes / (1 << 20)).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`); -const trust = (p) => - p.key ? `Signed` : `Unsigned`; -const initial = (p) => escape((p.name || p.id).trim().charAt(0).toUpperCase()); -const icon = (p) => - https(p.icon) ? `` : ``; - -// 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 `No ratings yet`; - const on = Math.min(5, Math.max(0, Math.round(r.average))); - const mean = r.average.toFixed(1); - return `Rated ${mean} out of 5 ${mean} (${count(r.count)})`; -} - -// 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; its kind, ratings (once `ratings` is known), downloads and newest version on the right. -export function listHtml(projects, ratings = null) { - if (!projects.length) return `

    Nothing here yet. Submit yours.

    `; - return projects - .map( - (p) => ` - ${icon(p)} - ${escape(p.name)}${escape(p.summary || "")} - ${escape(KIND_NAMES[p.kind] || p.kind)}${ratings ? `${starsHtml(ratingOf(ratings, p.id))} · ` : ""}${downloads(p)}${escape(p.versions[0].version)} · ${escape((p.authors || []).join(", "))} -`, - ) - .join("\n"); -} - -function installHtml(p, v) { - const file = escape(v.file.name); - const cli = `horizon-launcher mods install --source horizon ${p.id}`; - const where = { - mod: `put it in horizon-mods/ beside options.txt in the game folder, then turn it on in the game: Options > Mods`, - resourcepack: `put it in resourcepacks/ beside options.txt, then turn it on in Options > Resource Packs`, - modpack: `a modpack lists registry mods: install them one by one, or wait for the launcher to install modpacks`, - shader: `Horizon's own shader packs aren't installed yet`, - }[p.kind]; - return `
      -
    1. In the launcher: Mods, pick Horizon beside Modrinth, find ${escape(p.name)} and press Install. It checks the file's checksum${p.key ? " and signature" : ""} first.
    2. -
    3. From a terminal or an agent: ${escape(cli)}
    4. -
    5. By hand: download ${file} (${size(v.file.size)}), check its SHA-256 below, and ${where}.
    6. -
    `; -} - -// GitHub's rule for a login: letters, digits and single dashes, at most 39. -const LOGIN = /^(?!-)(?!.*--)[A-Za-z0-9-]{1,39}(? LOGIN.test(o)); - if (!owners.length) return ""; - const links = owners - .map((o) => `@${o}`) - .join(" "); - return `

    Published by ${links}

    `; -} - -// 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 `Sign in with GitHub to rate`; - if ((p.owners || []).some((o) => o.toLowerCase() === String(me.login).toLowerCase())) return `

    You publish it: players rate it.

    `; - const stars = [1, 2, 3, 4, 5] - .map((n) => ``) - .join(""); - return `${mine ? "Your rating" : "Rate it"}${stars}`; -} - -// 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 - ? `
      ${caps.map((c) => `
    • May ${escape(CAPABILITIES[c] || c)}
    • `).join("")}
    ` - : `

    It asks for nothing beyond writing its own log.

    `; - const requires = (v.requires || []).length - ? `

    Its mods

    ` - : ""; - const versions = p.versions - .map((x) => `
  • ${escape(x.version)} ${escape(x.published || "")} · for ${escape(x.game)}${x.api ? ` · API ${escape(x.api)}` : ""}${x.changelog ? `
    ${markdown(x.changelog)}
    ` : ""}
  • `) - .join(""); - return `
    -
    ${icon(p)}

    ${escape(KIND_NAMES[p.kind] || p.kind)}${escape((p.authors || []).join(", "))}

    ${ownersHtml(p)} -

    ${escape(p.name)}

    ${escape(p.summary || "")}

    -

    ${trust(p)} ${escape(p.license)} ${escape(v.version)}${v.side ? ` ${escape(v.side)}` : ""}

    -

    ${rating === undefined ? "" : `${starsHtml(rating)} · `}${downloads(p)}

    -
    - ${p.description ? `
    ${markdown(p.description)}
    ` : ""} - ${p.kind === "mod" ? `

    What it may do

    ${capsHtml}

    Mods run in a sandbox with no file, network or clock access. The game refuses a mod whose code uses more than this list.

    ` : ""} - ${requires} -

    Install

    - ${installHtml(p, v)} -

    File

    -
    Name
    ${escape(v.file.name)}
    Size
    ${size(v.file.size)}
    SHA-256
    ${escape(v.file.sha256)}
    ${p.key ? `
    Signing key
    ${escape(p.key)}
    ` : ""}
    -

    Versions

    -
      ${versions}
    - -
    `; -} - -// /mods/submit: the form. Its script (mods-submit.js) signs in, then sends the page and the file to the service, which -// checks the file and opens the pull request the reviewers read. -const field = (name, label, input, hint = "") => - ``; -const text = (name, attrs = "") => ``; - -export function submitHtml() { - return `

    ModsSubmit

    -

    Submit to the registry

    -

    A mod, a modpack of registry mods, or a resource pack made for Horizon. The form checks the file and opens a pull request; a reviewer reads it, its source and the checks' report, and merging publishes it to this site and the launcher.

    -

    First time? Publish a mod walks through building, checking and signing the file, and Make a mod starts from the beginning.

    -
    -

    The form needs JavaScript. You can also open a pull request by hand.

    -
    - `; -} - -// The service's "entry" from the form's values (strings), as it reads it. -export function entryFrom(v) { - const optional = (x) => (x && x.trim() ? x.trim() : undefined); - return { - id: v.id.trim(), - kind: v.kind, - name: v.name.trim(), - summary: v.summary.trim(), - description: v.description || "", - authors: (v.authors || "").split(",").map((a) => a.trim()).filter(Boolean), - license: v.license.trim(), - source: v.source.trim(), - icon: optional(v.icon), - key: optional(v.key), - signature: optional(v.signature), - version: v.version.trim(), - game: v.game.trim(), - changelog: v.changelog || "", - }; -} diff --git a/website/src/mods.test.mjs b/website/src/mods.test.mjs deleted file mode 100644 index d94cc3e07..000000000 --- a/website/src/mods.test.mjs +++ /dev/null @@ -1,110 +0,0 @@ -import { test } from "node:test"; -import assert from "node:assert/strict"; -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"], - license: "MIT", source: "https://example.org/src", - versions: [{ version: "0.1.0", api: "0.1", side: "client", capabilities: ["game-read", "hud"], game: "26.3", - file: { name: "coords_hud-0.1.0.hmod", url: "https://github.com/ludovic111/horizon-mods/releases/download/x/coords_hud-0.1.0.hmod", size: 438, sha256: "e".repeat(64) } }], - ...over, -}); - -test("reads schema 1, keeps the kinds it knows and refuses a newer schema", () => { - const index = { schema: 1, projects: [project(), project({ id: "map", kind: "world" }), project({ id: "Bad id" })] }; - assert.deepEqual(readIndex(index).map((p) => p.id), ["coords_hud"]); - assert.equal(readIndex({ schema: 2, projects: [project()] }), null); - assert.equal(readIndex(null), null); -}); - -test("filters by kind and every word", () => { - const p = project(); - assert.ok(matches(p, "all", "coordinates horizon")); - assert.ok(matches(p, "mod", "")); - assert.ok(!matches(p, "modpack", "")); - assert.ok(!matches(p, "all", "zoom")); -}); - -test("escapes what authors wrote and only links https addresses", () => { - const evil = project({ name: "", source: "javascript:alert(1)", summary: '">' }); - const html = listHtml([evil]) + projectHtml(evil); - assert.ok(!html.includes(" - - -
    -
    -

    PrivacyData collection

    -

    Nothing leaves without your yes.

    -

    The Horizon launcher can send a few things that help make the game faster and steadier. It asks first, each kind has its own switch, and every switch is off until you turn it on.

    -
    -

    What can be sent

    -

    Only the kinds you allow, from the launcher's first-run question or Settings → Data collection:

    -
      -
    • Performance statistics, after each play session of a minute or more. These are the frame-time and tick-time percentiles and a 14-bucket histogram (never a recording of each frame), the peak memory, how long the game took to start and to load the world, and the settings that change performance (render and simulation distance, frame limit, VSync, fullscreen, graphics mode).
    • -
    • Crash reports, when the game crashes. They hold the error, where it happened in Horizon's code, your graphics adapter and settings. They hold no log, no world, no server and no resource packs.
    • -
    • Bug reports that you write and send yourself. The end of the game's log goes with one only if you add it after reading it, and lines of chat are removed first.
    • -
    • Benchmark uploads of the benchmarks you run. They are shown publicly on the Benchmarks page, only as medians of groups of at least 3 different installs with the same graphics card, processor and render distance; never one by one, and never with your install ID, the day, your OS version, driver, exact memory or screen.
    • -
    -

    Each one also carries the Horizon version, the day it was made (not the time), and a description of your machine, because that is what explains how fast the game runs on it:

    -
      -
    • the operating system, its version and the processor architecture;
    • -
    • the processor model, its cores and threads, and its base and boost clock where the system gives them;
    • -
    • the memory, rounded to the gigabyte;
    • -
    • the graphics card the game draws with: its model, maker, whether it is built into the processor or separate, its own memory, its driver version and the graphics interface (Vulkan, Metal, DirectX 12);
    • -
    • the kind of drive the game folder is on (NVMe, SSD or hard disk);
    • -
    • the screen the game opened on: its size in pixels, refresh rate and scaling;
    • -
    • whether the computer is a laptop or a desktop, and whether it runs on battery.
    • -
    -

    No serial number, computer name, user name, network address or file path is read. Each item also carries a random install ID. The launcher makes that ID the first time you allow something; it says nothing about you and exists only so that your data can be deleted.

    -

    Never sent: your Microsoft or Minecraft account name or UUID, world names, server or LAN addresses, chat, and your user name or home folder in file paths. Before anything is kept, those are replaced with placeholders, along with e-mail and IP addresses. The server does not store the IP address requests come from.

    -

    The launcher shows exactly what would be sent: Settings → Data collection → View what would be sent, or horizon-launcher data show. Every field is listed in docs/telemetry.md.

    - -

    The "I'm playing" ping

    -

    The game sends an anonymous "I'm playing" ping, so the launcher can show how many people play Horizon right now. It is sent once a minute while you play, whatever the switches say.

    -

    It holds: a random number made when the game starts and forgotten when it closes, the Horizon version, your operating system (Linux, macOS or Windows), and whether you have a world open to LAN or to friends. It does not hold: your account, your install ID, world or server names, your hardware or settings, or anything you do in the game. The random number changes every time you start the game, so two of your sessions can't be linked to each other or to you.

    -

    The server keeps the pings in memory only, never on disk, and not with the address they came from (that is used only to stop abuse, as below). A session counts while it pinged in the last two minutes and is then forgotten. What it shows is the number playing now, per version and with a world open, rounded.

    - -

    Why

    -

    To find what is slow or crashes on which machines, and fix it. The ping shows players, and Horizon, how many people play right now. Benchmark uploads also show other players how Horizon runs on hardware like theirs. Nothing is sold, shared for advertising, or used to identify you.

    - -

    On what basis

    -

    For the switches: your consent (Article 6(1)(a) of the EU's General Data Protection Regulation). It is given kind by kind, recorded on your computer with the version of the question you answered and when, and withdrawn at any time with the same switches. Withdrawing deletes what was waiting to be sent. When what is collected changes, the launcher asks again, and nothing new is sent until you answer. The ping holds nothing that identifies you; the address it comes from is used only to limit how often one address may send, kept in memory for an hour at most and never stored.

    - -

    Where and how long

    -

    Items wait on your computer (telemetry/ in the game folder) and are sent compressed when the launcher starts or closes, to Horizon's own server, telemetry.playhorizon.dev, hosted by Railway in the European Union (Amsterdam, the Netherlands). The server keeps them for 180 days, then deletes them. What stays after that are anonymous totals per day, Horizon version, operating system, GPU maker and render distance (for example "120 sessions on macOS with Apple GPUs at render distance 12"). They hold no install ID, and groups too small to be anonymous are never shown. Published results also show how players split by memory size (in steps: 8, 16, 32 GB…), graphics memory, drive type, operating system and built-in or separate graphics, each class only once it holds at least 3 different installs; the exact values, the driver, the clocks and the screen are never published.

    - -

    Deleting your data

    -

    Settings → Data collection → Delete my data, or horizon-launcher data delete. The server deletes everything sent under your install ID, your share of the totals is recomputed, anything waiting on your computer is removed, and you get a new install ID. You can also turn everything off, or delete the telemetry/ folder.

    - -

    Your rights and contact

    -

    Horizon is made by Ludovic Marie, who is responsible for this data. To ask for a copy of what was sent under your install ID, have it corrected or deleted, or ask anything about it, write through lu4ovic.com (give your install ID, shown in Settings → Data collection). You can also complain to the data protection authority where you live.

    -

    This website itself sets no cookies and has no analytics; its footer says what it loads from GitHub.

    -
    - -

    Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

    -
    -
    - - - diff --git a/website/src/releases-page.js b/website/src/releases-page.js deleted file mode 100644 index ace84f63d..000000000 --- a/website/src/releases-page.js +++ /dev/null @@ -1,78 +0,0 @@ -// The Releases page: the list baked at build time, refreshed from GitHub when a newer release is out, and the -// channel filter. Without JavaScript the baked list reads as it is. -import { releasesPageHtml } from "./releases.js"; -import { isGame, isLauncher, newestFirst } from "./versions.js"; -import { cached, get, setUpMenu, setUpTheme, slim } from "./chrome.js"; - -const REPO = "ludovic111/horizon"; -const list = document.getElementById("release-list"); -const counter = document.querySelector("[data-release-count]"); -const buttons = [...document.querySelectorAll("[data-filter]")]; -let filter = "all"; - -const ours = (r) => !r.draft && (isGame(r.tag_name) || isLauncher(r.tag_name)); - -// Every release, a page of 100 at a time (GitHub's most), up to 500. -async function loadAll() { - const all = []; - for (let page = 1; page <= 5; page++) { - const batch = await get(`https://api.github.com/repos/${REPO}/releases?per_page=100&page=${page}`); - all.push(...batch.filter(ours).map(slim)); - if (batch.length < 100) break; - } - return all; -} - -function apply() { - const entries = [...list.querySelectorAll(".release-entry")]; - let shown = 0; - for (const el of entries) { - const on = filter === "all" || el.dataset.channel === filter; - el.hidden = !on; - if (on) shown++; - } - counter.textContent = `${shown} release${shown === 1 ? "" : "s"}`; - buttons.forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.filter === filter))); -} - -async function refresh() { - // One small request first: the full list only when GitHub has something newer than the page. - const newest = await cached("horizon:releases-newest", () => get(`https://api.github.com/repos/${REPO}/releases?per_page=5`)).catch(() => null); - if (!newest) return; - const top = newest.filter(ours).map((r) => r.tag_name).sort(newestFirst)[0]; - if (!top || top === list.dataset.newest) return; - const all = await cached("horizon:releases-all", loadAll).catch(() => null); - if (!all || !all.length) return; - const open = new Set([...list.querySelectorAll(".release-entry[open]")].map((el) => el.id)); - list.innerHTML = releasesPageHtml(all); - list.dataset.newest = top; - // Keep what the reader opened open. - open.forEach((id) => document.getElementById(id)?.setAttribute("open", "")); - apply(); -} - -// A link to one release (/releases#release-v0.2.1) opens it. -function openTarget() { - const el = location.hash && document.getElementById(location.hash.slice(1)); - if (el && el.classList.contains("release-entry")) { - if (el.hidden) { - filter = "all"; - apply(); - } - el.open = true; - el.scrollIntoView(); - } -} - -buttons.forEach((b) => - b.addEventListener("click", () => { - filter = b.dataset.filter; - apply(); - }), -); -addEventListener("hashchange", openTarget); -setUpTheme(); -setUpMenu(); -apply(); -openTarget(); -refresh().then(openTarget); diff --git a/website/src/releases.html b/website/src/releases.html deleted file mode 100644 index 989164653..000000000 --- a/website/src/releases.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - Releases · Horizon - - - - - - - - - - - - - - - - - - - - - -{{SITE_NAV}} -
    -
    -

    ReleasesEvery version, newest first

    -

    What's new in Horizon

    -

    Each release lists what it adds and fixes, then its full notes and its downloads. New versions come out many times a day as changes land, and the launcher installs each one once it has passed its test. The launcher has its own releases.

    -
    - - - -
    -

    {{RELEASE_COUNT}}

    -
    -{{RELEASE_LIST}} -
    -

    The releases on GitHub

    -

    Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

    -
    -
    -{{SITE_FOOTER}} - - diff --git a/website/src/releases.js b/website/src/releases.js deleted file mode 100644 index d4932e7f7..000000000 --- a/website/src/releases.js +++ /dev/null @@ -1,156 +0,0 @@ -// The release notes on the site: the home page's "Recently added" block and the Releases page (every release, -// newest first). Shared by build.mjs (baked into the pages) and the pages' scripts (refreshed from GitHub). -// Tags: the game's vX.Y.Z and the launcher's launcher@X.Y.Z from 0.2, vYYYY.MM.DD[.N] and launcher-vX.Y.Z before -// (src/versions.js). One channel (docs/release-flow.md, "One channel"): a release is the game's or the launcher's. -import { markdown, inline, escape } from "./markdown.js"; -import { isLauncher, launcherVersion, newestFirst } from "./versions.js"; - -const REPO = "ludovic111/horizon"; - -export const channel = (r) => (isLauncher(r.tag_name) ? "Launcher" : "Game"); -const anchor = (r) => `release-${r.tag_name.replace(/[^\w.-]/g, "-")}`; - -// "Horizon 0.2.3: Cave culling, weather" (before 0.2, "Horizon 2026.10.13: …") reads as the version and its line. -export function parts(r) { - const version = launcherVersion(r.tag_name) ?? r.tag_name.replace(/^v/, ""); - const name = (r.name || "").trim(); - let line = name.includes(": ") ? name.slice(name.indexOf(": ") + 2) : name.replace(/^Horizon( launcher)?\s*/i, "").replace(version, "").trim(); - if (junk(line)) line = fromNotes(r.body) || line; - return { version, line: line.charAt(0).toUpperCase() + line.slice(1), date: (r.published_at || "").slice(0, 10) }; -} - -// A title made of issue numbers and "fix" ("#1255, mob pushes, fix, #1222") says nothing. -const junk = (line) => { - const bits = line.split(",").map((b) => b.trim()).filter(Boolean); - return bits.length > 1 && bits.filter((b) => /^(#\d+|fix(es)?|fixed)$/i.test(b)).length * 2 >= bits.length; -}; - -// The first item that isn't a bare "Fix #123:" prefix, as the line: "Mob pushes: one list per mob… and 3 more fixes". -function fromNotes(body) { - const s = sections(body); - const items = [...s.filter((x) => /^new|what's new/i.test(x.title)), ...s.filter((x) => /^fixed/i.test(x.title))].flatMap((x) => x.items).map(plainItem); - const clean = items.map((i) => i.replace(/^(fix|fixes)\s+#\d+:\s*/i, "").replace(/^\w+\([^)]*\):\s*/, "")).filter(Boolean); - if (!clean.length) return ""; - const first = clean[0].replace(/[.]$/, ""); - return clean.length > 1 ? `${first} and ${clean.length - 1} more` : first; -} - -// The notes' "### Heading" sections and their top-level items, in order. -export function sections(body) { - const out = []; - let current = null; - for (const raw of (body || "").replace(/\r\n?/g, "\n").split("\n")) { - const heading = raw.match(/^#{2,3}\s+(.+?)\s*$/); - if (heading) out.push((current = { title: heading[1], items: [] })); - else if (current && /^[-*]\s+/.test(raw)) current.items.push(raw.replace(/^[-*]\s+/, "").trim()); - } - return out; -} - -// An item without its pull request references: "Riptide (#123, fixes #45)" -> "Riptide". -export const plainItem = (item) => item.replace(/\s*\((?:#\d+|fixes #\d+|[^()]*#\d+[^()]*)\)\s*/g, " ").replace(/\s+/g, " ").trim(); - -// A game release's notes open with an HTML block sending people to the launcher (PLAYERS in tools/release_train.py): -// GitHub's latest release is the game's. This site has its own download button, so it leaves the block out. -export const notesText = (body) => (body || "").replace(/^

    Want to play\?[^\n]*(?:\r?\n)*/, ""); - -// The notes' first sentence, for a release with no title line and no sections ("Rebuilt from the latest main."). -const firstLine = (body) => (notesText(body).split(/\r?\n/).find((l) => l.trim() && !/^#/.test(l)) || "").trim().replace(/[.:]$/, ""); - -const count = (n, one, many) => `${n} ${n === 1 ? one : many}`; - -// What a release changes, in a line: "12 new, 30 fixed, 2 known issues". -export function overview(r) { - const s = sections(r.body); - const by = (re) => s.filter((x) => re.test(x.title)).reduce((n, x) => n + x.items.length, 0); - const added = by(/^new|what's new/i); - const fixed = by(/^fixed/i); - const known = by(/^known/i); - const bits = []; - if (added) bits.push(count(added, "new feature", "new features")); - if (fixed) bits.push(count(fixed, "fix", "fixes")); - if (known) bits.push(count(known, "known issue", "known issues")); - return { added, fixed, known, text: bits.join(", ") }; -} - -export function highlights(r, n = 3) { - const added = sections(r.body).filter((x) => /^new|what's new/i.test(x.title)).flatMap((x) => x.items); - return added.slice(0, n).map(plainItem); -} - -const byTag = (a, b) => newestFirst(a.tag_name, b.tag_name); -const badge = (r) => `${channel(r)}`; - -// The home page: the newest releases on a line each, and what the newest ones added. -export function recentHtml(list, { rows = 5, picks = 3 } = {}) { - const sorted = [...list].sort(byTag); - const game = sorted.filter((r) => !isLauncher(r.tag_name)); - if (!game.length) return ""; - const lines = game - .slice(0, rows) - .map((r) => { - const p = parts(r); - return `
  • ${escape(p.version)}${escape(p.line || overview(r).text || firstLine(r.body) || "Release notes")}${badge(r)}
  • `; - }) - .join(""); - // What landed last: the "New" items of the newest releases with the highest pull request numbers (a release's - // notes list everything since the release before it, oldest first). - const pr = (item) => Math.max(0, ...[...item.matchAll(/#(\d+)/g)].map((m) => Number(m[1]))); - const seen = new Set(); - const picked = game - .slice(0, rows) - .flatMap((r) => sections(r.body).filter((x) => /^new|what's new/i.test(x.title)).flatMap((x) => x.items).map((raw) => ({ raw, item: plainItem(raw), r }))) - .filter(({ item }) => !seen.has(item) && seen.add(item)) - .sort((a, b) => pr(b.raw) - pr(a.raw)) - .slice(0, picks); - const picks_ = picked - .map(({ item, r }) => `
  • ${inline(item)}

    ${escape(parts(r).version)}
  • `) - .join(""); - return `
      ${lines}
    - ${picks_ ? `

    New lately

      ${picks_}
    ` : ""} -

    Every release, with its full notes

    `; -} - -const ASSET_LABELS = [ - [/linux-x86_64/, "Linux x86-64"], - [/macos-arm64/, "macOS, Apple Silicon"], - [/macos-x86_64/, "macOS, Intel"], - [/windows-x64/, "Windows x64"], -]; -function assetLabel(name) { - if (/^SHA256SUMS/.test(name)) return name.endsWith(".sig") ? "Checksums signature" : "Checksums"; - const os = ASSET_LABELS.find(([re]) => re.test(name)); - const what = /server/.test(name) ? "Server" : /launcher/.test(name) ? "Launcher" : /smoke-test/.test(name) ? "Smoke test" : "Game"; - return os ? `${what}, ${os[1]}` : name; -} -const size = (bytes) => (bytes >= 1e6 ? `${(bytes / 1e6).toFixed(0)} MB` : bytes >= 1e3 ? `${(bytes / 1e3).toFixed(0)} kB` : `${bytes} B`); - -function releaseHtml(r, open) { - const p = parts(r); - const o = overview(r); - const top = highlights(r, 4); - const downloads = (r.assets || []) - .map((a) => `
  • ${escape(assetLabel(a.name))}${escape(a.name)} · ${size(a.size || 0)}
  • `) - .join(""); - return `
    - ${escape(p.version)}${badge(r)}${escape(p.line)} -
    - ${o.text || top.length ? `
    - ${o.text ? `

    ${escape(o.text)}

    ` : ""} - ${top.length ? `
      ${top.map((t) => `
    • ${inline(t)}
    • `).join("")}
    ` : ""} -
    ` : ""} -
    ${markdown(notesText(r.body)) || "

    No notes for this release.

    "}
    - ${downloads ? `

    Downloads

      ${downloads}
    ` : ""} -

    This release on GitHub

    -
    -
    `; -} - -// The Releases page: every release, newest first; the newest few open. -export function releasesPageHtml(list, { open = 3 } = {}) { - const sorted = [...list].sort(byTag); - if (!sorted.length) return ""; - return sorted.map((r, i) => releaseHtml(r, i < open)).join("\n"); -} - -export const releasesUrl = `https://github.com/${REPO}/releases`; diff --git a/website/src/releases.test.mjs b/website/src/releases.test.mjs deleted file mode 100644 index acd1a0965..000000000 --- a/website/src/releases.test.mjs +++ /dev/null @@ -1,13 +0,0 @@ -// node --test src/: the release notes as the site shows them. -import { test } from "node:test"; -import assert from "node:assert/strict"; -import { notesText } from "./releases.js"; - -const players = '

    Want to play? Download the Horizon launcher, not the files below

    It installs this version.

    '; - -test("the block sending people to the launcher is left out, the notes stay", () => { - assert.equal(notesText(`${players}\n\n### Fixed\n- A fix (#1)\n`), "### Fixed\n- A fix (#1)\n"); - assert.equal(notesText(`${players}\r\n\r\nRebuilt from the latest main.\r\n`), "Rebuilt from the latest main.\r\n"); - assert.equal(notesText("

    Other HTML

    \n\n### New\n- A thing (#2)\n"), "

    Other HTML

    \n\n### New\n- A thing (#2)\n"); - assert.equal(notesText(undefined), ""); -}); diff --git a/website/src/style.css b/website/src/style.css deleted file mode 100644 index b78a6a8b0..000000000 --- a/website/src/style.css +++ /dev/null @@ -1,937 +0,0 @@ -/* Horizon's design language (docs/design-system.md), set as a page. The tokens come from - crates/horizon-theme through src/tokens.css, which build.mjs puts before this file: the - launcher's Blocks palettes, type, spacing and motion. The base below lays out the page; the - "Blocks" section at the end gives it the launcher's blocky, Minecraft-like look. */ - -@font-face { font-family: "Geist"; src: url("/fonts/Geist-Regular.woff2") format("woff2"); font-weight: 400; font-display: swap; } -@font-face { font-family: "Geist"; src: url("/fonts/Geist-Medium.woff2") format("woff2"); font-weight: 500; font-display: swap; } -@font-face { font-family: "Geist"; src: url("/fonts/Geist-SemiBold.woff2") format("woff2"); font-weight: 600; font-display: swap; } -@font-face { font-family: "Geist Mono"; src: url("/fonts/GeistMono-Regular.woff2") format("woff2"); font-weight: 400; font-display: swap; } - -:root { - --g: clamp(var(--gutter-narrow), 4.5vw, var(--gutter)); - --max: 1440px; - --nav: 72px; -} - -*, *::before, *::after { box-sizing: border-box; } - -html { - background: var(--page); - color: var(--ink); - font: 400 var(--text-body) / var(--text-body-line) var(--font); - font-synthesis: none; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; - text-rendering: optimizeLegibility; - scroll-behavior: smooth; - scroll-padding-top: calc(var(--nav) + 16px); - transition: background-color var(--move) var(--ease-move), color var(--move) var(--ease-move); -} -body { margin: 0; min-height: 100vh; overflow-x: clip; } -img { display: block; max-width: 100%; height: auto; } -h1, h2, h3 { margin: 0; font-weight: var(--text-heading-weight); } -p { margin: 0; } -ol, ul { margin: 0; padding: 0; list-style: none; } -::selection { background: var(--accent); color: var(--on-accent); } - -a { color: var(--accent); text-decoration: none; transition: color var(--quick) var(--ease-quick); } -a:hover { color: var(--ink); } -[hidden] { display: none !important; } -/* Links inside running text are underlined, so they don't rely on colour alone. */ -p a:not(.button):not(.link-arrow), li > p a, .prose a { - color: inherit; text-decoration: underline; text-decoration-color: var(--rule); - text-decoration-thickness: 1px; text-underline-offset: 3px; - transition: text-decoration-color var(--quick) var(--ease-quick); -} -p a:not(.button):not(.link-arrow):hover, li > p a:hover, .prose a:hover { text-decoration-color: currentColor; } -:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; border-radius: var(--radius); } - -code { - font: 0.86em/1.5 var(--mono); - background: var(--plate-soft); - border-radius: 4px; - padding: 1px 5px; - overflow-wrap: anywhere; -} - -.sr-only { - position: absolute; width: 1px; height: 1px; overflow: hidden; - clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; -} -.skip { - position: fixed; left: var(--g); top: 12px; z-index: 50; padding: 8px 14px; - background: var(--ink); color: var(--page); border-radius: var(--radius-pill); - transform: translateY(-200%); -} -.skip:focus { transform: none; } - -.container { width: 100%; max-width: var(--max); margin: 0 auto; padding: 0 var(--g); } - -/* --- Type ----------------------------------------------------------------------------- */ - -.display { - font-size: var(--text-display); line-height: var(--text-display-line); - letter-spacing: var(--text-display-tracking); font-weight: var(--text-display-weight); - text-wrap: balance; -} -.title { - font-size: var(--text-title); line-height: var(--text-title-line); - letter-spacing: var(--text-title-tracking); font-weight: var(--text-title-weight); - text-wrap: balance; -} -.lede { max-width: var(--measure); color: var(--muted); text-wrap: pretty; } -.kicker, .meta, .download-meta, .eyebrow, .row-index, .row-meta, .disclaimer { - font: var(--text-micro-weight) var(--text-micro) / var(--text-micro-line) var(--mono); - letter-spacing: var(--text-micro-tracking); - color: var(--muted); -} -.kicker { display: flex; gap: 16px; text-transform: uppercase; margin-bottom: 24px; } -.kicker span { color: var(--ink); } -.meta { margin-top: 16px; } -.download-meta { margin-top: 12px; } -.download-meta a { color: inherit; } - -/* --- Buttons --------------------------------------------------------------------------- */ - -.button { - display: inline-flex; align-items: center; justify-content: center; gap: 8px; - height: var(--control); padding: 0 16px; border: 0; border-radius: var(--radius-pill); - font: 500 var(--text-label) / 1 var(--font); cursor: pointer; white-space: nowrap; - transition: background-color var(--quick) var(--ease-quick), color var(--quick) var(--ease-quick), opacity var(--quick) var(--ease-quick); -} -.button.large { height: var(--control-large); padding: 0 22px; font-size: var(--text-ui); } -.button.small { height: 30px; padding: 0 14px; } -.button.primary { background: var(--accent); color: var(--on-accent); } -.button.primary:hover { color: var(--on-accent); opacity: 0.88; } -.button.secondary { background: var(--plate-soft); color: var(--ink); } -.button.secondary:hover { background: var(--plate); color: var(--ink); } -.button.ghost { background: transparent; color: var(--muted); } -.button.ghost:hover { background: var(--plate-soft); color: var(--ink); } -.button:active { opacity: 0.85; } - -.link-arrow { display: inline-flex; gap: 8px; color: var(--accent); font-weight: 500; } -.link-arrow span { transition: transform var(--quick) var(--ease-quick); } -.link-arrow:hover span { transform: translateX(3px); } - -/* --- Navigation ------------------------------------------------------------------------- */ - -.nav { - position: fixed; inset: 0 0 auto; z-index: 20; height: var(--nav); max-width: 100vw; - background: color-mix(in srgb, var(--page) 88%, transparent); - -webkit-backdrop-filter: blur(16px) saturate(1.2); backdrop-filter: blur(16px) saturate(1.2); - box-shadow: 0 1px 0 var(--rule); - transition: background-color var(--move) var(--ease-move), box-shadow var(--move) var(--ease-move); -} -.nav-inner { display: flex; align-items: center; gap: 24px; height: 100%; max-width: var(--max); margin: 0 auto; padding: 0 var(--g); } -.nav-mark { display: inline-flex; align-items: center; gap: 10px; color: var(--ink); font-weight: 500; font-size: var(--text-label); } -.nav-mark:hover { color: var(--ink); } -.mark { width: 18px; height: 18px; } -.mark-stem { fill: var(--ink); } -.mark-low { fill: var(--ink); opacity: 0.36; } -.mark-line { fill: var(--accent); } -.nav-links { display: flex; gap: 2px; margin-left: auto; white-space: nowrap; } -.nav-links a, .nav-github, .theme-toggle { - display: inline-flex; align-items: center; height: 32px; padding: 0 12px; - border-radius: var(--radius-pill); color: var(--muted); font-size: var(--text-label); - transition: background-color var(--quick) var(--ease-quick), color var(--quick) var(--ease-quick); -} -.nav-links a:hover, .nav-github:hover, .theme-toggle:hover { color: var(--ink); background: var(--plate-soft); } -.nav-links a[aria-current] { color: var(--ink); background: var(--plate-soft); } -.nav-end { display: flex; align-items: center; gap: 2px; } -.theme-toggle { - border: 0; background: none; cursor: pointer; - font: var(--text-micro) / 1 var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; -} -.nav-end .button { margin-left: 8px; } -.menu-button { - display: none; align-items: center; gap: 10px; height: 44px; padding: 0 4px 0 14px; margin-left: 4px; - border: 0; background: none; color: var(--ink); font: 500 var(--text-label) / 1 var(--font); cursor: pointer; -} -.menu-icon { position: relative; width: 18px; height: 10px; } -.menu-icon::before, .menu-icon::after { - content: ""; position: absolute; left: 0; right: 0; height: 1.5px; border-radius: 1px; background: currentColor; - transition: transform var(--move) var(--ease-move), top var(--move) var(--ease-move); -} -.menu-icon::before { top: 0; } -.menu-icon::after { top: 8px; } -.is-menu .menu-icon::before { top: 4px; transform: rotate(45deg); } -.is-menu .menu-icon::after { top: 4px; transform: rotate(-45deg); } - -.menu { - position: fixed; inset: var(--nav) 0 0; z-index: 19; display: flex; flex-direction: column; max-width: 100vw; - justify-content: space-between; gap: 24px; overflow-y: auto; padding: 24px var(--g) 32px; background: var(--page); - opacity: 0; transition: opacity var(--move) var(--ease-move); -} -.menu.is-open { opacity: 1; } -.menu nav { display: flex; flex-direction: column; flex-shrink: 0; } -.menu nav a { - display: flex; align-items: baseline; gap: 16px; padding: 12px 0; border-bottom: 1px solid var(--rule); - color: var(--ink); font-size: var(--text-title); line-height: var(--text-title-line); - letter-spacing: var(--text-title-tracking); font-weight: 500; - opacity: 0; transform: translateY(var(--rise)); - transition: opacity var(--enter) var(--ease-enter), transform var(--enter) var(--ease-enter); -} -.menu.is-open nav a { opacity: 1; transform: none; } -.menu-foot { display: flex; flex-direction: column; gap: 16px; flex-shrink: 0; } -.menu-foot p { font-size: var(--text-caption); color: var(--muted); } - -@media (max-width: 1279px) { - .nav-links, .nav-github { display: none; } - .menu-button { display: inline-flex; } - .nav-end { margin-left: auto; } -} -@media (max-width: 520px) { - .nav-end .button { display: none; } -} - -/* --- Index lists: the signature component ------------------------------------------------ */ - -.index { border-top: 1px solid var(--rule); } -.row { position: relative; border-bottom: 1px solid var(--rule); } -.row > a, .row.card { - position: relative; display: grid; grid-template-columns: var(--index) 1fr auto; align-items: baseline; - column-gap: 16px; padding: 18px 0; color: var(--ink); -} -.row-index { transition: color var(--quick) var(--ease-quick); } -.row-name { font-size: var(--text-title); line-height: var(--text-title-line); letter-spacing: var(--text-title-tracking); font-weight: 500; } -.row-meta { text-align: right; } -/* Hover: a soft plate fades in behind the row and reaches past it; the index turns to ink. */ -.row > a::before, .row.card::before { - content: ""; position: absolute; inset: 0 calc(-1 * var(--plate-bleed)); z-index: -1; - border-radius: var(--radius-plate); background: var(--plate-soft); opacity: 0; - transition: opacity var(--quick) var(--ease-quick); -} -.row > a, .row.card { z-index: 0; } -.row > a:hover::before, .row.card:hover::before { opacity: 1; } -.row > a:hover .row-index, .row.card:hover .row-index { color: var(--ink); } -.row > a:hover, .row.card:hover { color: var(--ink); } - -/* --- Hero -------------------------------------------------------------------------------- */ - -.hero { padding: calc(var(--nav) + clamp(48px, 9vw, 120px)) 0 clamp(64px, 8vw, 112px); } -.hero-title { max-width: 14ch; margin-bottom: 20px; } -.hero .lede { font-size: var(--text-body); } -.hero-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 32px; } -.hero-index { margin-top: clamp(48px, 7vw, 88px); } -.hero .disclaimer { margin-top: 24px; } - -/* --- Sections ------------------------------------------------------------------------------- */ - -.section { padding: clamp(72px, 10vw, 144px) 0; } -.section-head { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 16px 48px; align-items: end; margin-bottom: 48px; } -.section-head .kicker { grid-column: 1 / -1; margin-bottom: 0; } -.section .title { font-size: var(--text-display); line-height: var(--text-display-line); letter-spacing: var(--text-display-tracking); } - -.statement { - max-width: 28ch; font-size: var(--text-title); line-height: 1.15; - letter-spacing: var(--text-title-tracking); font-weight: 500; text-wrap: balance; -} -.facts { margin-top: 56px; } -.fact, .features li { - display: grid; grid-template-columns: var(--index) minmax(0, 18rem) minmax(0, 1fr); column-gap: 16px; - align-items: baseline; padding: 20px 0; -} -.fact h3, .features h3 { font-size: var(--text-heading); line-height: var(--text-heading-line); letter-spacing: var(--text-heading-tracking); } -.fact p, .features p { max-width: var(--measure); color: var(--muted); } - -/* Screenshots: no frames, the images themselves. */ -.mosaic { display: grid; grid-template-columns: repeat(6, 1fr); gap: 12px; } -.tile { margin: 0; grid-column: span 2; } -.tile-wide { grid-column: span 4; } -.tile-tall { grid-column: span 2; } -.tile-wide, .tile-tall { grid-row: span 1; } -.zoom { display: block; width: 100%; padding: 0; border: 0; background: var(--plate-soft); border-radius: var(--radius-plate); overflow: hidden; cursor: zoom-in; } -.zoom img { width: 100%; aspect-ratio: 16 / 9; object-fit: cover; transition: transform var(--enter) var(--ease-enter); } -.zoom:hover img { transform: scale(1.02); } -figcaption { display: flex; gap: 12px; margin-top: 10px; font-size: var(--text-caption); color: var(--muted); } -figcaption span { font-family: var(--mono); font-size: var(--text-micro); letter-spacing: var(--text-micro-tracking); padding-top: 1px; } - -/* Parity: the count, then every subsystem as an index row. */ -.parity-hero { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 48px; align-items: end; margin-bottom: 64px; } -.count { font-size: clamp(96px, 16vw, 220px); line-height: 0.85; letter-spacing: -0.05em; font-weight: 500; } -.count .digits span { display: inline-block; } -.count-label { margin-top: 20px; max-width: 32ch; color: var(--muted); } -.parity-copy .title { margin-bottom: 16px; } -.prose { color: var(--ink-soft); max-width: var(--measure); } -.prose > * + * { margin-top: 12px; } -.systems { border-top: 1px solid var(--rule); } -.system { - display: grid; grid-template-columns: var(--index) minmax(0, 1fr) auto; column-gap: 16px; row-gap: 6px; - padding: 20px 0; border-bottom: 1px solid var(--rule); position: relative; -} -.system-head { display: contents; } -.system-index { grid-column: 1; grid-row: 1; font: var(--text-micro) / var(--text-micro-line) var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); padding-top: 0.6em; } -.system h3 { grid-column: 2; grid-row: 1; font-size: var(--text-heading); line-height: var(--text-heading-line); letter-spacing: var(--text-heading-tracking); } -.system-state { - grid-column: 3; grid-row: 1; display: inline-flex; align-items: center; gap: 6px; padding-top: 0.5em; - font: var(--text-micro) / var(--text-micro-line) var(--mono); letter-spacing: var(--text-micro-tracking); - text-transform: uppercase; color: var(--muted); -} -.system.is-full .system-state { color: var(--success); } -.check { width: 12px; height: 12px; fill: none; stroke: currentColor; stroke-width: 1.6; } -.system-detail { grid-column: 2 / 4; max-width: 72ch; font-size: var(--text-caption); line-height: 1.6; color: var(--muted); } -.gap { color: var(--ink); font-weight: 500; } -.legend { max-width: 80ch; } - -/* The launcher: copy and features on the left, the menus on the right. */ -.launcher-grid { display: grid; grid-template-columns: minmax(0, 5fr) minmax(0, 7fr); gap: clamp(32px, 5vw, 80px); align-items: start; } -.launcher-copy .title { margin-bottom: 16px; } -.launcher-copy .features { margin-top: 40px; } -.features li { grid-template-columns: var(--index) minmax(0, 1fr); row-gap: 4px; } -.features li p { grid-column: 2; font-size: var(--text-ui); } -.launcher-actions { margin-top: 32px; } -.screens { position: sticky; top: calc(var(--nav) + 24px); } -.tabs { position: relative; display: inline-flex; padding: 2px; gap: 2px; margin-bottom: 16px; border-radius: var(--radius-pill); background: var(--plate-soft); } -.tabs button { - position: relative; z-index: 1; height: var(--segment); padding: 0 14px; border: 0; background: none; - border-radius: var(--radius-pill); color: var(--muted); font: 500 var(--text-label) / 1 var(--font); cursor: pointer; - transition: color var(--quick) var(--ease-quick); -} -.tabs button:hover { color: var(--ink); } -.tabs button[aria-selected="true"] { color: var(--page); } -.tab-pill { position: absolute; top: 0; left: 0; border-radius: var(--radius-pill); background: var(--ink); transition: transform var(--move) var(--ease-move), width var(--move) var(--ease-move); } -.screen { position: relative; aspect-ratio: 16 / 10; border-radius: var(--radius-plate); overflow: hidden; background: var(--plate-soft); } -.screen-panel { position: absolute; inset: 0; opacity: 0; transition: opacity var(--move) var(--ease-move); } -.screen-panel.is-active { opacity: 1; } -.screen-panel img { width: 100%; height: 100%; object-fit: cover; } -.screen-caption { margin-top: 12px; font-size: var(--text-caption); color: var(--muted); } - -/* Patch notes. */ -.eyebrow { text-transform: uppercase; } -.prose h2, .prose h3, .prose h4 { font-size: var(--text-heading); line-height: var(--text-heading-line); color: var(--ink); margin-top: 28px; } -.prose ul, .prose ol { padding-left: 18px; list-style: disc; } -.prose li + li { margin-top: 6px; } -.prose li::marker { color: var(--muted); } -.prose strong { color: var(--ink); font-weight: 500; } -.prose pre { padding: 16px; border-radius: var(--radius-plate); background: var(--plate-soft); overflow-x: auto; } -.prose pre code { background: none; padding: 0; } -.release { border-top: 1px solid var(--rule); } -.release:last-of-type { border-bottom: 1px solid var(--rule); } -.release summary { - display: grid; grid-template-columns: minmax(0, 12rem) minmax(0, 1fr) auto; gap: 16px; align-items: baseline; - padding: 18px 0; cursor: pointer; list-style: none; -} -.release summary::-webkit-details-marker { display: none; } -.release-tag { font-size: var(--text-heading); font-weight: 500; letter-spacing: var(--text-heading-tracking); } -.release-sub { color: var(--muted); font-size: var(--text-ui); } -.release time { font: var(--text-micro) / 1 var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); } -.release[open] summary .release-tag { color: var(--accent); } -.release .prose { padding: 0 0 24px 12rem; margin-left: 16px; font-size: var(--text-ui); } -.release-more { margin-top: 24px; } - -/* Community. */ -.cards { margin-top: 48px; } -.row.card { grid-template-columns: var(--index) minmax(0, 1fr) minmax(0, 1.4fr) auto; } -.card-title { font-size: var(--text-title); line-height: var(--text-title-line); letter-spacing: var(--text-title-tracking); font-weight: 500; } -.card-text { color: var(--muted); } -.card-arrow { color: var(--muted); transition: transform var(--quick) var(--ease-quick), color var(--quick) var(--ease-quick); } -.card:hover .card-arrow { color: var(--accent); transform: translateX(4px); } -.contributors { margin-top: 96px; } -.contributors-title { font-size: var(--text-heading); line-height: var(--text-heading-line); } -.contributors-text { margin-top: 8px; color: var(--muted); } -.contributors-list { margin-top: 24px; display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 0 24px; border-top: 1px solid var(--rule); } -.contributor { display: grid; grid-template-columns: 32px 1fr; column-gap: 12px; align-items: center; padding: 14px 0; border-bottom: 1px solid var(--rule); color: var(--ink); } -.contributor-avatar { grid-row: span 2; width: 32px; height: 32px; border-radius: 50%; background: var(--plate); } -.contributor-name { font-weight: 500; } -.contributor-count { font: var(--text-micro) / 1.4 var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); } -.contributor:hover .contributor-name { color: var(--accent); } - -/* --- Footer: small print, then the giant faint wordmark --------------------------------- */ - -.footer { padding: clamp(72px, 9vw, 120px) 0 0; overflow: hidden; } -.footer-disclaimer { max-width: 24ch; font-size: var(--text-heading); line-height: var(--text-heading-line); letter-spacing: var(--text-heading-tracking); font-weight: 500; } -.footer-cols { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 32px; margin-top: 40px; } -.footer-cols p { font-size: var(--text-caption); line-height: 1.7; color: var(--muted); } -.footer-bar { display: flex; justify-content: space-between; align-items: center; gap: 24px; margin-top: 56px; font-size: var(--text-caption); color: var(--muted); } -.footer-links { display: flex; flex-wrap: wrap; gap: 20px; } -.footer-links a { color: var(--muted); } -.footer-links a:hover { color: var(--ink); } -.footer-word { - box-sizing: border-box; width: 100%; margin: 24px auto 0; padding: 0 var(--g); max-width: var(--max); - font-size: var(--text-wordmark); line-height: var(--text-wordmark-line); letter-spacing: var(--text-wordmark-tracking); - font-weight: var(--text-wordmark-weight); color: var(--plate); white-space: nowrap; user-select: none; - translate: -0.05em 0.12em; -} -:root[data-theme="dark"] .footer-word { color: var(--plate-soft); } -@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .footer-word { color: var(--plate-soft); } } - -/* --- Lightbox ---------------------------------------------------------------------------- */ - -.lightbox { width: min(1400px, 94vw); max-height: 92vh; padding: 0; border: 0; border-radius: var(--radius-plate); background: var(--surface); color: var(--ink); } -.lightbox::backdrop { background: color-mix(in srgb, var(--page) 86%, transparent); -webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px); } -.lightbox img { width: 100%; } -.lightbox form { position: absolute; top: 12px; right: 12px; } -.lightbox-caption { padding: 14px 16px; font-size: var(--text-caption); color: var(--muted); } - -/* --- 404 --------------------------------------------------------------------------------- */ - -.lost { min-height: 100vh; display: flex; flex-direction: column; justify-content: space-between; } -.lost .hero { padding-top: clamp(96px, 16vh, 200px); } - -/* --- Motion: content arrives with a fade and a short rise, a few tens of ms apart --------- */ - -.js .reveal, .js .reveal-media { - opacity: 0; transform: translateY(var(--rise)); filter: blur(4px); - transition: opacity var(--enter) var(--ease-enter) var(--d, 0ms), transform var(--enter) var(--ease-enter) var(--d, 0ms), filter var(--enter) var(--ease-enter) var(--d, 0ms); -} -.js .reveal.is-visible, .js .reveal-media.is-visible { opacity: 1; transform: none; filter: none; } -.js .systems .system { opacity: 0; transform: translateY(var(--rise)); transition: opacity var(--enter) var(--ease-enter) var(--d, 0ms), transform var(--enter) var(--ease-enter) var(--d, 0ms); } -.js .systems.is-visible .system { opacity: 1; transform: none; } -@media (prefers-reduced-motion: reduce) { - html { scroll-behavior: auto; } - .js .reveal, .js .reveal-media, .js .systems .system { transform: none; filter: none; transition: opacity 200ms linear; } - .menu nav a { transform: none; } -} - -/* --- Touch: every target at least 44 px high ------------------------------------------- */ - -@media (pointer: coarse) { - .button, .button.large, .button.small, .tabs button { height: 44px; } - .nav-mark, .theme-toggle, .nav-github { min-height: 44px; } - .link-arrow, .footer-links a { display: inline-flex; align-items: center; min-height: 44px; } -} - -/* --- Narrow screens ------------------------------------------------------------------------ */ - -@media (max-width: 900px) { - .section-head, .parity-hero, .launcher-grid { grid-template-columns: minmax(0, 1fr); } - .section-head { gap: 16px; } - .screens { position: static; } - .fact { grid-template-columns: var(--index) minmax(0, 1fr); row-gap: 6px; } - .fact p { grid-column: 2; } - .mosaic { grid-template-columns: minmax(0, 1fr); } - .tile, .tile-wide, .tile-tall { grid-column: auto; } - .row.card { grid-template-columns: var(--index) minmax(0, 1fr) auto; row-gap: 4px; } - .card-text { grid-column: 2; grid-row: 2; font-size: var(--text-ui); } - .card-arrow { grid-row: 1; grid-column: 3; } - .release summary { grid-template-columns: minmax(0, 1fr) auto; } - .release-sub { grid-column: 1 / -1; grid-row: 2; } - .release .prose { padding-left: 0; margin-left: 0; } - .footer-cols { grid-template-columns: minmax(0, 1fr); } - .footer-bar { flex-direction: column; align-items: flex-start; } - .system { grid-template-columns: var(--index) minmax(0, 1fr); } - .system-state { grid-column: 2; grid-row: 2; padding-top: 0; } - .system-detail { grid-column: 2; } - .row > a { grid-template-columns: 28px 1fr auto; padding: 16px 0; } - :root { --index: 28px; } -} - -/* The privacy page: one long read under the hero type. */ -.privacy h1 { margin-bottom: 16px; } -.privacy .prose { margin: 40px 0; } -.privacy .disclaimer { margin-top: 32px; } - -/* --- Documentation (/docs): a left navigation and one page at a time --------------------- */ - -.docs { - display: grid; grid-template-columns: 248px minmax(0, 1fr); gap: clamp(32px, 6vw, 96px); - max-width: var(--max); margin: 0 auto; padding: calc(var(--nav) + 48px) var(--g) 0; align-items: start; -} -.docs-nav-wrap { position: sticky; top: calc(var(--nav) + 24px); max-height: calc(100vh - var(--nav) - 48px); overflow-y: auto; padding-bottom: 24px; } -.docs-nav-wrap summary { display: none; } -.docs-nav-group { margin: 28px 0 8px; font: var(--text-micro) / var(--text-micro-line) var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; color: var(--muted); } -.docs-nav-group:first-child { margin-top: 0; } -.docs-nav li a { display: block; padding: 6px 12px; margin-left: -12px; border-radius: var(--radius); color: var(--ink-soft); font-size: var(--text-ui); } -.docs-nav li a:hover { background: var(--plate-soft); color: var(--ink); } -.docs-nav li a[aria-current] { background: var(--plate-soft); color: var(--ink); font-weight: 500; } -.docs-main { min-width: 0; padding-bottom: 48px; } -.docs-main .title { margin-bottom: 16px; } -.docs-main .lede { max-width: 64ch; font-size: var(--text-heading); line-height: 1.45; } -.docs-toc { margin-top: 28px; max-width: 72ch; } -.docs-toc p { font: var(--text-micro) / var(--text-micro-line) var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; color: var(--muted); margin-bottom: 8px; } -.docs-toc ul { display: flex; flex-wrap: wrap; gap: 6px; } -.docs-toc a { display: block; padding: 4px 12px; border-radius: var(--radius-pill); background: var(--plate-soft); color: var(--ink-soft); font-size: var(--text-label); } -.docs-toc a:hover { background: var(--plate); color: var(--ink); } -.docs-prose { max-width: 72ch; margin-top: 40px; font-size: var(--text-body); } -.docs-prose > * + * { margin-top: 14px; } -.docs-prose h2 { margin-top: 56px; padding-top: 24px; border-top: 1px solid var(--rule); font-size: clamp(24px, 2.4vw, 30px); line-height: 1.2; letter-spacing: var(--text-title-tracking); scroll-margin-top: 80px; } -.docs-prose h2:first-child { margin-top: 0; padding-top: 0; border-top: 0; } -.docs-prose h3 { margin-top: 32px; scroll-margin-top: 80px; } -.docs-prose ol { list-style: decimal; } -.docs-prose pre { font: 0.86em/1.6 var(--mono); } -.docs-prose blockquote { padding: 2px 0 2px 16px; border-left: 2px solid var(--accent); color: var(--ink-soft); } -.docs-prose blockquote > * + * { margin-top: 8px; } -.docs-prose figure { margin: 28px 0; } -.docs-prose figure img { width: 100%; border-radius: var(--radius-plate); box-shadow: 0 0 0 1px var(--rule); } -.docs-prose figcaption { margin-top: 10px; font-size: var(--text-caption); color: var(--muted); } -.docs-pager { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; max-width: 72ch; margin-top: 56px; } -.docs-pager a { display: flex; flex-direction: column; gap: 2px; padding: 14px 16px; border-radius: var(--radius-plate); box-shadow: 0 0 0 1px var(--rule); color: var(--ink); font-weight: 500; } -.docs-pager a:hover { background: var(--plate-soft); color: var(--ink); } -.docs-pager a span { font: var(--text-micro) / var(--text-micro-line) var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; color: var(--muted); font-weight: 400; } -.docs-pager-next { grid-column: 2; text-align: right; } -.docs-edit { margin-top: 32px; font-size: var(--text-caption); color: var(--muted); } -.docs-edit a { color: inherit; text-decoration: underline; text-decoration-color: var(--rule); text-underline-offset: 3px; } -.docs-main .disclaimer { margin-top: 24px; } - -@media (max-width: 900px) { - .docs { grid-template-columns: minmax(0, 1fr); gap: 0; padding-top: calc(var(--nav) + 12px); } - .docs-nav-wrap { position: static; max-height: none; overflow: visible; margin-bottom: 24px; border-bottom: 1px solid var(--rule); } - .docs-nav-wrap summary { display: flex; align-items: center; min-height: 44px; cursor: pointer; font-weight: 500; list-style: none; } - .docs-nav-wrap summary::-webkit-details-marker { display: none; } - .docs-nav-wrap summary::after { content: "+"; margin-left: auto; color: var(--muted); } - .docs-nav-wrap[open] summary::after { content: "\2212"; } - .docs-pager { grid-template-columns: minmax(0, 1fr); } - .docs-pager-next { grid-column: 1; } -} -@media (pointer: coarse) { - .docs-nav li a, .docs-toc a { display: flex; align-items: center; min-height: 44px; } -} - -/* --- Blocks: the launcher's look on the page (docs/design-system.md, "Blocks") ------------- - Pixel type for headings and controls, square panels with a dark outline, a light bevel on top - and a darker lip below, the violet face for the main action, sunk wells, a stone texture - behind the page and Horizon's pixel landscape behind the hero. The art is drawn in code - (scripts/art.mjs, like launcher/src/art.rs); nothing in it comes from Minecraft. */ - -@font-face { font-family: "Pixelify Sans"; src: url("/fonts/PixelifySans-Medium.woff2") format("woff2"); font-weight: 500; font-display: swap; } -@font-face { font-family: "Pixelify Sans"; src: url("/fonts/PixelifySans-SemiBold.woff2") format("woff2"); font-weight: 600; font-display: swap; } -@font-face { font-family: "Pixelify Sans"; src: url("/fonts/PixelifySans-Bold.woff2") format("woff2"); font-weight: 700; font-display: swap; } - -:root { - --stone: url("/media/stone-light.png"); - --scene: url("/media/scene-light.png"); - --sky: #8d7fd8; - --panel-edges: inset 0 var(--block-bevel) 0 var(--bevel), inset 0 calc(-1 * var(--block-bevel)) 0 var(--lip); - --radius: 0px; --radius-plate: 0px; --radius-pill: 0px; -} -:root[data-theme="dark"] { --stone: url("/media/stone-dark.png"); --scene: url("/media/scene-dark.png"); --sky: #0a0f2c; } -@media (prefers-color-scheme: dark) { - :root:not([data-theme="light"]) { --stone: url("/media/stone-dark.png"); --scene: url("/media/scene-dark.png"); --sky: #0a0f2c; } -} - -/* The stone: 64 texels of the page colour in close shades, each texel 4 px. */ -body { position: relative; isolation: isolate; } -body::before { - content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none; - background: var(--stone) 0 0 / 256px 256px repeat; image-rendering: pixelated; -} - -/* Pixel type for what names and what you act on; paragraphs stay in Geist. */ -.display, .title, .statement, .row-name, .card-title, .release-tag, .count, -.fact h3, .features h3, .system h3, .contributors-title, .footer-disclaimer, .footer-word, -.nav-mark, .docs-prose h2, .docs-prose h3, .prose h2, .prose h3, .prose h4, .menu nav a { - font-family: var(--pixel); font-weight: 600; letter-spacing: 0; -} -.display, .count, .footer-word { font-weight: 700; } -.nav-mark { font-size: 18px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em; } -code { border-radius: 0; background: var(--well); box-shadow: 0 0 0 1px var(--outline); } - -/* Buttons: blocks with an outline, a bevel and a lip; they sink a pixel when pressed. */ -.button { - border: var(--block-outline) solid var(--outline); border-radius: 0; - font: 500 var(--text-ui) / 1 var(--pixel); - box-shadow: inset 0 var(--block-bevel) 0 var(--button-bevel), inset 0 calc(-1 * var(--block-lip)) 0 var(--lip); - padding-bottom: 2px; -} -.button.large { font-size: 18px; } -.button.primary { background: var(--face); color: var(--on-face); box-shadow: inset 0 var(--block-bevel) 0 var(--face-bevel), inset 0 calc(-1 * var(--block-lip)) 0 var(--face-lip); } -.button.primary:hover { opacity: 1; filter: brightness(1.08); } -.button.secondary { background: var(--button); } -.button.secondary:hover { background: var(--button); filter: brightness(1.06); } -.button.ghost { border-color: transparent; box-shadow: none; } -.button:active { opacity: 1; transform: translateY(1px); box-shadow: inset 0 var(--block-bevel) 0 var(--lip); } -:focus-visible { border-radius: 0; } - -/* The top bar: the sidebar colour with an outline under it, tabs with an accent underline. */ -.nav { background: var(--side); -webkit-backdrop-filter: none; backdrop-filter: none; box-shadow: 0 var(--block-outline) 0 var(--outline); } -.nav-links a, .nav-github, .theme-toggle { border-radius: 0; font-family: var(--pixel); font-weight: 500; font-size: 15px; } -.nav-links a:hover, .nav-github:hover, .theme-toggle:hover { background: var(--raised); } -.nav-links a[aria-current] { background: var(--raised); box-shadow: inset 0 -3px 0 var(--accent); } -.theme-toggle { text-transform: none; letter-spacing: 0; } -.menu { background: var(--side); } -.menu nav a { border-bottom: 0; } - -/* Lists become stacks of panels. */ -.index, .systems, .contributors-list { border-top: 0; display: grid; gap: 8px; } -.row, .system, .release, .release:last-of-type, .contributor { border-bottom: 0; border-top: 0; } -.row > a, .row.card, .fact.row, .features li, .system, .release, .contributor, .docs-pager a { - background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); - border-radius: 0; -} -.row > a, .row.card, .fact.row, .features li, .system { padding-left: 20px; padding-right: 20px; } -.row > a::before, .row.card::before { display: none; } -.row > a:hover, .row.card:hover, .contributor:hover, .docs-pager a:hover { background: var(--raised); } -.row > a:hover .row-index { color: var(--accent); } -.row-name { font-size: clamp(20px, 2.2vw, 28px); } -.release { padding: 0 20px; } -.release + .release { margin-top: 8px; } -.release .prose { padding-left: 12rem; } -.contributor { padding: 12px 14px; } -.contributors-list { grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 8px; } -.contributor-avatar { border-radius: 0; box-shadow: 0 0 0 2px var(--outline); image-rendering: pixelated; } -.system.is-full .system-state { color: var(--success); } - -/* Screenshots and the launcher's screens: square, outlined. */ -.zoom, .screen, .lightbox, .prose pre, .docs-prose figure img { border-radius: 0; box-shadow: 0 0 0 var(--block-outline) var(--outline); } -.tabs { border-radius: 0; background: var(--well); box-shadow: 0 0 0 var(--block-outline) var(--outline); } -.tabs button { border-radius: 0; font-family: var(--pixel); font-weight: 500; font-size: 15px; } -.tabs button[aria-selected="true"] { color: var(--on-face); } -.tab-pill { border-radius: 0; background: var(--face); box-shadow: inset 0 var(--block-bevel) 0 var(--face-bevel), inset 0 calc(-1 * var(--block-bevel)) 0 var(--face-lip); } - -/* The hero: Horizon's landscape under a veil of the page colour, the words on the left. */ -.hero { - position: relative; isolation: isolate; overflow: hidden; - background: var(--scene) 70% 100% / clamp(1200px, 135vw, 2400px) auto no-repeat, var(--sky); image-rendering: pixelated; - border-bottom: var(--block-outline) solid var(--outline); -} -.hero::before { - content: ""; position: absolute; inset: 0; z-index: -1; - background: - linear-gradient(90deg, color-mix(in srgb, var(--page) 92%, transparent) 0%, color-mix(in srgb, var(--page) 78%, transparent) 45%, color-mix(in srgb, var(--page) 0%, transparent) 78%), - linear-gradient(180deg, color-mix(in srgb, var(--page) 0%, transparent) 55%, color-mix(in srgb, var(--page) 70%, transparent) 100%); -} -.hero .kicker span, .hero .kicker { color: var(--ink-soft); } -.hero .lede { color: var(--ink-soft); } -.hero { padding-bottom: clamp(160px, 18vw, 280px); } -.hero-after { padding-top: 40px; } -.hero-after .hero-index { margin-top: 0; max-width: 860px; } -.hero-after .disclaimer { margin-top: 24px; } -@media (max-width: 900px) { - .hero::before { background: color-mix(in srgb, var(--page) 84%, transparent); } -} - -/* Documentation. */ -.docs-nav li a { border-radius: 0; } -.docs-nav li a[aria-current] { background: var(--raised); box-shadow: inset 4px 0 0 var(--accent); } -.docs-toc a { border-radius: 0; background: var(--button); box-shadow: 0 0 0 var(--block-outline) var(--outline); } -.docs-pager a { box-shadow: var(--panel-edges); } -.docs-prose h2 { border-top: var(--block-outline) solid var(--outline); } -.docs-prose blockquote { border-left: 4px solid var(--accent); background: var(--panel); padding: 10px 16px; box-shadow: 0 0 0 var(--block-outline) var(--outline); } - -/* The footer: the giant wordmark in pixels. */ -.footer { background: var(--side); border-top: var(--block-outline) solid var(--outline); margin-top: 48px; } -.footer-word { color: var(--raised); letter-spacing: 0.02em; } -:root[data-theme="dark"] .footer-word { color: var(--panel); } -@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .footer-word { color: var(--panel); } } - -/* --- Releases and Benchmarks pages, and the home page's "Recently added" ------------------ */ - -/* Pixelify Sans' "fi" ligature draws as "A" ("8 Axes"): no common ligatures anywhere. */ -:root { font-variant-ligatures: no-common-ligatures; } - -.page-main { padding-top: calc(var(--nav) + clamp(40px, 6vw, 80px)); } -.page-title { max-width: 18ch; margin-bottom: 20px; } -.page-main > .container > .lede { font-size: var(--text-body); } -.page-main .disclaimer { margin-top: 48px; } - -/* Release and source badges: small square tags. */ -.badge { - display: inline-flex; align-items: center; height: 22px; padding: 0 8px; margin-right: 10px; vertical-align: 2px; - font: 500 12px / 1 var(--pixel); letter-spacing: 0.02em; text-transform: uppercase; white-space: nowrap; - border: var(--block-outline) solid var(--outline); background: var(--well); color: var(--ink-soft); -} -.badge-game { background: color-mix(in srgb, var(--success) 22%, var(--panel)); color: var(--ink); } -.badge-launcher { background: color-mix(in srgb, var(--accent) 20%, var(--panel)); color: var(--ink); } -.badge-us { background: color-mix(in srgb, var(--accent) 20%, var(--panel)); color: var(--ink); } -.badge-players { background: color-mix(in srgb, var(--success) 22%, var(--panel)); color: var(--ink); } -.badge-estimate { background: color-mix(in srgb, var(--warn) 24%, var(--panel)); color: var(--ink); } - -/* Home: the newest releases on a line each, then what they added. */ -.recent-list .row > a { grid-template-columns: 8.5rem minmax(0, 13rem) minmax(0, 1fr) auto; align-items: baseline; } -.recent-line { color: var(--muted); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.recent-list .row-name { font-size: clamp(18px, 1.8vw, 22px); } -.recent-list .badge { margin-right: 0; } -.recent-picks { margin-top: 32px; } -.recent-picks .eyebrow { margin-bottom: 12px; } -.highlights { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; } -.highlight { - display: flex; flex-direction: column; justify-content: space-between; gap: 16px; padding: 18px 20px; - background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); -} -.highlight p { color: var(--ink); } -.highlight-from { font: var(--text-micro) / 1 var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); } -.highlight-from:hover { color: var(--accent); } - -/* Releases: a filter, then every release as a panel that opens. */ -.release-filter { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 32px; } -.release-filter .button[aria-pressed="true"], .hub-detail .button[aria-pressed="true"], .button.hub-vote[aria-pressed="true"] { background: var(--face); color: var(--on-face); box-shadow: inset 0 var(--block-bevel) 0 var(--face-bevel), inset 0 calc(-1 * var(--block-lip)) 0 var(--face-lip); } -.release-count { margin: 16px 0 12px; } -.release-list { display: grid; gap: 8px; } -.release-list .release + .release { margin-top: 0; } -.release-entry summary { grid-template-columns: minmax(0, 11rem) minmax(0, 1fr) auto; } -.release-entry .release-sub { display: flex; align-items: baseline; flex-wrap: wrap; row-gap: 4px; } -.release-detail { padding: 0 0 24px 11rem; margin-left: 16px; display: grid; gap: 20px; max-width: calc(11rem + 16px + var(--measure) + 120px); } -.release-detail .prose { padding: 0; margin: 0; font-size: var(--text-ui); max-width: none; } -.release-overview { padding: 16px 18px; background: var(--well); box-shadow: 0 0 0 var(--block-outline) var(--outline); } -.release-counts { font-family: var(--pixel); font-weight: 600; color: var(--ink); margin-bottom: 8px; } -.release-overview ul { list-style: square; padding-left: 18px; color: var(--ink-soft); font-size: var(--text-ui); } -.release-overview li + li { margin-top: 4px; } -.release-downloads ul { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 8px; margin-top: 8px; } -.release-downloads li { display: flex; flex-direction: column; gap: 2px; padding: 10px 12px; background: var(--button); box-shadow: 0 0 0 var(--block-outline) var(--outline); } -.release-downloads li a { font-weight: 500; } -.release-downloads li span { font: var(--text-micro) / 1.4 var(--mono); color: var(--muted); overflow-wrap: anywhere; } -.release-github { font-size: var(--text-caption); } -.release-entry:target { box-shadow: var(--panel-edges), 0 0 0 3px var(--accent); } - -/* Benchmarks. */ -.bench-section { margin-top: clamp(64px, 8vw, 112px); } -.bench-section > .title { margin-bottom: 16px; } -.bench-section > .lede { margin-bottom: 32px; } -.machines { display: grid; grid-template-columns: minmax(0, 1fr); gap: 24px; } -.machine { min-width: 0; padding: 24px; background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); } -.machine-head { display: grid; gap: 10px; margin-bottom: 20px; } -.machine-name { font-family: var(--pixel); font-weight: 600; font-size: var(--text-title); line-height: var(--text-title-line); } -.machine-facts { display: flex; flex-wrap: wrap; gap: 6px 28px; margin: 0; } -.machine-facts div { display: flex; gap: 8px; min-width: 0; } -.machine-facts dt { font: var(--text-micro) / 1.6 var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; color: var(--muted); } -.machine-facts dd { margin: 0; min-width: 0; overflow-wrap: anywhere; font-size: var(--text-caption); color: var(--ink-soft); } -.machine-note { font-size: var(--text-caption); color: var(--muted); max-width: 90ch; } -/* relative: the screen-reader-only labels inside are absolute and would escape the scroll box otherwise. */ -.table-wrap { position: relative; overflow-x: auto; } -.bench-table { width: 100%; border-collapse: collapse; font-size: var(--text-ui); } -.bench-table th, .bench-table td { padding: 9px 12px; text-align: left; border-bottom: 1px solid var(--rule); vertical-align: baseline; } -.bench-table thead th { font: var(--text-micro) / 1.4 var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; color: var(--muted); font-weight: 400; } -.bench-table thead tr:first-child th { color: var(--ink); } -.bench-table tbody th { font-weight: 500; color: var(--ink); } -.bench-table td.num { font-variant-numeric: tabular-nums; white-space: nowrap; } -.bench-table td.wins { color: var(--ink); font-weight: 600; } -.bench-table td.vs { font-size: var(--text-caption); white-space: nowrap; } -.md-table { width: 100%; border-collapse: collapse; font-size: var(--text-ui); } -.md-table th, .md-table td { padding: 8px 12px 8px 0; text-align: left; border-bottom: 1px solid var(--rule); vertical-align: baseline; } -.md-table th { font-weight: 500; color: var(--ink); } -.md-table td code, .md-table th code { overflow-wrap: anywhere; } -.vs-horizon { color: var(--success); } -.vs-java { color: var(--danger); } -.vs-tie, .vs-none { color: var(--muted); } -.capped { font: var(--text-micro) / 1 var(--mono); color: var(--warn); cursor: help; } -.metric-hint { display: block; font: var(--text-micro) / 1.4 var(--mono); color: var(--muted); font-weight: 400; } -.java-wins { margin-top: 16px; font-size: var(--text-caption); color: var(--ink-soft); } -.picker { display: flex; flex-wrap: wrap; gap: 16px 24px; align-items: end; padding: 20px; background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); } -.picker label { display: grid; gap: 6px; } -.picker label > span, .picker legend { font: var(--text-micro) / 1.4 var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; color: var(--muted); } -.picker select { - min-width: min(320px, 80vw); height: var(--control); padding: 0 10px; font: inherit; font-size: var(--text-ui); color: var(--ink); - background: var(--well); border: var(--block-outline) solid var(--outline); border-radius: 0; -} -.picker-rd { display: flex; gap: 16px; align-items: center; border: 0; padding: 0; margin: 0; } -.picker-rd legend { margin-bottom: 6px; } -.picker-rd label { display: inline-flex; align-items: center; gap: 6px; font-family: var(--pixel); font-weight: 500; height: var(--control); } -.picker-rd input { accent-color: var(--accent); width: 18px; height: 18px; } -.pick-result { margin-top: 16px; padding: 20px; background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); } -.pick-head { margin-bottom: 12px; font-size: var(--text-caption); color: var(--ink-soft); line-height: 1.8; } -.pick-result .meta { margin-top: 12px; } -.pick-notes { margin: 12px 0 0; padding-left: 20px; font-size: var(--text-caption); color: var(--ink-soft); line-height: 1.6; } -.players-hardware th[scope="rowgroup"] { vertical-align: top; } -.empty { color: var(--muted); } -.prose-section .prose { max-width: 80ch; } -.spec-table { margin-top: 24px; } -.spec-table summary { cursor: pointer; font-family: var(--pixel); font-weight: 600; } -.spec-table .bench-table { margin-top: 16px; max-width: 760px; } - -@media (max-width: 900px) { - .recent-list .row > a { grid-template-columns: minmax(0, 1fr) auto; row-gap: 4px; } - .recent-list .row-index { grid-column: 1; grid-row: 1; } - .recent-list .row-name { grid-column: 1; grid-row: 2; } - .recent-line { grid-column: 1 / -1; grid-row: 3; white-space: normal; } - .recent-list .row-meta { grid-column: 2; grid-row: 1; } - .highlights { grid-template-columns: minmax(0, 1fr); } - .release-entry summary { grid-template-columns: minmax(0, 1fr) auto; } - .release-detail { padding-left: 0; margin-left: 0; } - .machine { padding: 16px; } -} - -/* --- The hub (/hub): tabs, the Simple / Technical switch, roadmap items as panels ------------------- */ - -.hub-bar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 16px; margin-top: 32px; } -.hub-tabs { margin-bottom: 0; } -.hub-detail { display: flex; gap: 8px; } -/* A link to a tab (/hub#roadmap) lands with the tabs in view under the top bar. */ -.hub-panel { margin-top: 40px; scroll-margin-top: calc(var(--nav) + 120px); } -.js .hub-panel:not(.is-active) { display: none; } -/* Simple shows `plain`, Technical shows `dev`; without the switch (no JavaScript) Simple reads. */ -.hub .hub-dev { display: none; } -:root[data-detail="dev"] .hub .hub-dev { display: block; } -:root[data-detail="dev"] .hub .hub-plain { display: none; } -.hub-lead { max-width: 60ch; font-size: var(--text-heading); line-height: var(--text-heading-line); color: var(--ink); } -.hub-block { margin-top: 56px; } -.hub-block > .title { margin-bottom: 16px; } -.hub-intro { margin-bottom: 16px; color: var(--ink-soft); max-width: var(--measure); } -.hub-rows .row > a { grid-template-columns: var(--index) minmax(0, 1fr) auto; align-items: baseline; } -.hub-row-body { display: grid; gap: 4px; min-width: 0; } -.hub-row-title { font-size: clamp(18px, 1.8vw, 22px); font-weight: 500; color: var(--ink); } -.hub-row-body .hub-plain, .hub-row-body .hub-dev { color: var(--ink-soft); font-size: var(--text-ui); max-width: 80ch; } -.hub-rows .row-meta { max-width: 16rem; } -.hub-section { margin-top: 48px; } -.hub-section-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: 8px 20px; } -.hub-items { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 340px), 1fr)); gap: 8px; margin-top: 16px; } -.hub-item { - display: flex; flex-direction: column; gap: 10px; padding: 18px 20px; scroll-margin-top: calc(var(--nav) + 24px); - background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); -} -.hub-item:target { box-shadow: var(--panel-edges), 0 0 0 3px var(--accent); } -.hub-item-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; } -.hub-item-meta .badge { margin-right: 0; } -.hub-ongoing { font: var(--text-micro) / 1 var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); } -.hub-item-title { font-size: var(--text-heading); line-height: var(--text-heading-line); } -.hub-item .hub-plain, .hub-item .hub-dev { font-size: var(--text-ui); color: var(--ink-soft); } -.hub-progress { font: var(--text-micro) / 1.4 var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--ink); } -.hub-links { display: flex; flex-wrap: wrap; gap: 6px; margin-top: auto; padding-top: 4px; } -.hub-link { - display: inline-flex; gap: 6px; align-items: baseline; padding: 3px 7px; font: var(--text-micro) / 1.3 var(--mono); - color: var(--ink-soft); background: var(--well); box-shadow: 0 0 0 var(--block-outline) var(--outline); -} -.hub-link span { color: var(--muted); } -.hub-link:hover { color: var(--accent); } -.hub-link.is-merged { background: color-mix(in srgb, var(--success) 18%, var(--well)); } -.hub-link.is-in-review { background: color-mix(in srgb, var(--accent) 18%, var(--well)); } -.hub-link.is-in-progress { background: color-mix(in srgb, var(--warn) 22%, var(--well)); } -.hub-link.is-merged span, .hub-link.is-in-review span, .hub-link.is-in-progress span { color: var(--ink); } -.hub-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 260px), 1fr)); gap: 8px; } -.hub-cards .highlight { justify-content: flex-start; } -.hub-cards h3 { font-size: var(--text-heading); line-height: var(--text-heading-line); } -.hub-cards p { color: var(--ink-soft); font-size: var(--text-ui); } -.hub-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 16px; } -.hub-cards .hub-actions { margin-top: auto; } -.hub-rules { list-style: decimal; padding-left: 20px; max-width: var(--measure); } -.hub-rules li + li { margin-top: 10px; } -.hub-rules li::marker { color: var(--muted); font-family: var(--mono); } -.hub-source { margin-top: 40px; max-width: var(--measure); } -.hub-board-head { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px 24px; } -.hub-board-head .hub-intro { margin-bottom: 0; } -.hub-select { display: inline-flex; align-items: center; gap: 10px; } -.hub-select select { - height: 32px; max-width: 22rem; padding: 0 10px; font: var(--text-label) / 1 var(--font); color: var(--ink); - background: var(--well); border: 0; box-shadow: 0 0 0 var(--block-outline) var(--outline); -} -.hub-board { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; margin-top: 24px; align-items: start; } -.hub-column { padding: 14px; background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); } -.hub-column h3 { display: flex; justify-content: space-between; align-items: baseline; font-size: var(--text-heading); } -.hub-count { font: var(--text-micro) / 1 var(--mono); color: var(--muted); } -.hub-column > .meta { margin: 6px 0 12px; } -.hub-cards-list { display: grid; gap: 6px; } -.js .hub-column:not(.is-open) .hub-card[data-more] { display: none; } -.hub-card a { display: grid; gap: 4px; padding: 10px 12px; background: var(--well); box-shadow: 0 0 0 var(--block-outline) var(--outline); color: var(--ink); } -.hub-card a:hover { box-shadow: 0 0 0 var(--block-outline) var(--accent); } -.hub-card-ref, .hub-card-meta { font: var(--text-micro) / 1.4 var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); } -.hub-card-title { font-size: var(--text-label); line-height: 1.4; overflow-wrap: anywhere; } -.hub-card-meta { display: flex; flex-wrap: wrap; gap: 4px 10px; } -.hub-card-item { color: var(--accent); } -.hub-more { margin-top: 10px; width: 100%; justify-content: center; } -.hub-journal { display: grid; gap: 8px; margin-top: 24px; max-width: 56rem; } -.hub-entry { display: grid; gap: 10px; padding: 18px 20px; background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); scroll-margin-top: calc(var(--nav) + 24px); } -.hub-entry-week { background: color-mix(in srgb, var(--accent) 8%, var(--panel)); } -.hub-entry-meta { display: flex; align-items: center; gap: 10px; font: var(--text-micro) / 1 var(--mono); color: var(--muted); } -.hub-entry-meta .badge { margin-right: 0; } -.hub-entry-title { font-size: var(--text-heading); line-height: var(--text-heading-line); } -.hub-entry-title a { color: var(--ink); } -.hub-entry-title a:hover { color: var(--accent); } -.hub-entry .hub-plain, .hub-entry .hub-dev { font-size: var(--text-ui); color: var(--ink-soft); } -.hub-entry-items { display: flex; flex-wrap: wrap; gap: 6px; } -.hub-shipped { font-size: var(--text-ui); color: var(--ink); } -.hub-changes { list-style: square; padding-left: 18px; font-size: var(--text-ui); color: var(--ink-soft); } -.hub-changes li + li { margin-top: 4px; } -.hub-ref { font: var(--text-micro) / 1 var(--mono); } -.hub-group { margin-top: 8px; font: 500 var(--text-label) / 1.4 var(--font); } -.hub-group:first-child { margin-top: 0; } -@media (max-width: 1100px) { .hub-board { grid-template-columns: repeat(2, minmax(0, 1fr)); } } -@media (max-width: 720px) { - .hub-board { grid-template-columns: minmax(0, 1fr); } - .hub-rows .row > a { grid-template-columns: var(--index) minmax(0, 1fr); } - .hub-rows .row-meta { grid-column: 2; text-align: left; } -} - -/* --- Hub: votes, the report and suggestion forms, the contributors ---------------------- */ -.hub-vote { margin-left: auto; } -.hub-vote-count { margin-left: -2px; } -.hub-vote-count:empty { display: none; } -.hub-form { display: grid; gap: 16px; max-width: 46rem; margin-top: 8px; } -.hub-form-pair { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; } -.hub-field { display: grid; gap: 6px; font-size: var(--text-label); color: var(--ink-soft); } -.hub-field input, .hub-field textarea, .hub-field select { - width: 100%; min-height: 36px; padding: 8px 10px; font: var(--text-ui) / 1.4 var(--font); color: var(--ink); - background: var(--well); border: 0; box-shadow: 0 0 0 var(--block-outline) var(--outline); -} -.hub-field textarea { resize: vertical; } -.hub-field input:focus-visible, .hub-field textarea:focus-visible, .hub-field select:focus-visible { outline: 1px solid var(--accent); outline-offset: 2px; } -.hub-field input::placeholder, .hub-field textarea::placeholder { color: var(--muted); } -.hub-trap { position: absolute; left: -10000px; width: 1px; height: 1px; overflow: hidden; } -.hub-form-foot { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; } -.hub-form-foot [data-status] { color: var(--ink); } -.hub-form-foot .button:disabled { opacity: 0.4; cursor: default; } -.hub-form-closed { color: var(--ink-soft); } -@media (max-width: 720px) { - .hub-form-pair { grid-template-columns: minmax(0, 1fr); } -} - -/* The registry (/mods): a search and the kind filter, rows as panels, then a page per project. */ -.mod-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 24px; } -.mod-tools { display: flex; flex-wrap: wrap; align-items: center; gap: 16px; margin-top: 32px; } -.mod-tools .release-filter { margin-top: 0; } -.mod-search { - height: 36px; min-width: min(320px, 100%); padding: 0 12px; font: var(--text-ui) / 1 var(--sans); color: var(--ink); - background: var(--well); border: var(--block-outline) solid var(--outline); border-radius: 0; -} -.mod-search:focus-visible { outline: 2px solid var(--accent); outline-offset: 0; } -.mod-list { display: grid; gap: 8px; } -.mod-row { - display: grid; grid-template-columns: 48px minmax(0, 1fr) auto; align-items: center; gap: 16px; padding: 14px 20px; - background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); color: var(--ink); text-decoration: none; -} -.mod-row:hover { background: var(--raised); } -.mod-row:hover .mod-name { color: var(--accent); } -.mod-icon { - display: grid; place-items: center; width: 48px; height: 48px; flex: none; image-rendering: pixelated; - font: 600 22px / 1 var(--pixel); color: var(--ink); background: var(--well); box-shadow: 0 0 0 var(--block-outline) var(--outline); -} -.mod-text { display: grid; gap: 4px; min-width: 0; } -.mod-name { font: 500 var(--text-heading) / 1.2 var(--pixel); } -.mod-summary { color: var(--muted); font-size: var(--text-ui); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.mod-side { display: grid; justify-items: end; gap: 6px; } -.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); } -.mod-page .heading { margin-top: 24px; } -.mod-head { display: grid; grid-template-columns: 96px minmax(0, 1fr); gap: 24px; align-items: start; } -.mod-owners { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 4px 0 0; } -.mod-owner { display: inline-flex; align-items: center; gap: 6px; } -.mod-owner img { border-radius: 50%; } -.mod-head .mod-icon { width: 96px; height: 96px; font-size: 44px; } -.mod-head .page-title { margin-top: 0; } -.mod-badges { margin-top: 16px; } -.mod-caps, .mod-steps, .mod-versions { display: grid; gap: 8px; padding-left: 20px; font-size: var(--text-ui); } -.mod-caps li::marker, .mod-steps li::marker { color: var(--accent); } -.mod-file { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 8px 16px; font-size: var(--text-ui); } -.mod-file dt { color: var(--muted); } -.mod-file code, .mod-steps code { font-family: var(--mono); font-size: 13px; overflow-wrap: anywhere; } -.mod-links { display: flex; flex-wrap: wrap; gap: 24px; margin-top: 24px; } -/* /mods/submit */ -.mod-form { display: grid; gap: 24px; max-width: var(--measure); margin-top: 32px; } -.mod-form fieldset { display: grid; gap: 16px; margin: 0; padding: 0; border: 0; } -.mod-form legend { padding: 0; margin-bottom: 8px; } -.mod-field { display: grid; gap: 6px; } -.mod-label { font-size: var(--text-ui); font-weight: 500; } -.mod-form .mod-search { width: 100%; } -.mod-form textarea.mod-search { height: auto; padding: 10px 12px; line-height: 1.5; resize: vertical; } -.mod-check { display: flex; gap: 10px; align-items: flex-start; font-size: var(--text-ui); } -.mod-auth { margin-top: 24px; } -.mod-error { color: var(--danger); font-size: var(--text-ui); } -.js .no-script { display: none; } -@media (max-width: 640px) { - .mod-row { grid-template-columns: 40px minmax(0, 1fr); } - .mod-side { grid-column: 2; justify-items: start; } - .mod-icon { width: 40px; height: 40px; } - .mod-head { grid-template-columns: 1fr; } -} diff --git a/website/src/versions.js b/website/src/versions.js deleted file mode 100644 index b2483b4ed..000000000 --- a/website/src/versions.js +++ /dev/null @@ -1,59 +0,0 @@ -// Horizon's release tags (docs/versioning.md). From 0.2 the game is vX.Y.Z and the launcher launcher@X.Y.Z; -// before, vYYYY.MM.DD[.N] and launcher-vX.Y.Z. Every 0.2 tag is newer than every tag from before. Shared by -// build.mjs and main.js, and the same order as the launcher's and tools/release_train.py's. - -const SEMVER = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/; -// Semver's majors stay below this; a date tag's first number is a year. -const FIRST_YEAR = 1000; - -const semver = (version) => { - const m = SEMVER.exec(version); - return m && Number(m[1]) < FIRST_YEAR ? m : null; -}; - -export const isGame = (tag) => /^v\d{4}\.\d{1,2}\.\d{1,2}(\.\d+)?$/.test(tag) || (tag.startsWith("v") && !!semver(tag.slice(1))); - -// The version in a launcher tag (launcher@0.2.0, launcher-v0.16.0), or null. -export function launcherVersion(tag) { - if (tag.startsWith("launcher@") && semver(tag.slice(9))) return tag.slice(9); - const old = /^launcher-v(\d+\.\d+\.\d+)$/.exec(tag); - return old ? old[1] : null; -} - -export const isLauncher = (tag) => launcherVersion(tag) !== null; - -// [line, numbers, pre-release]: tags from before 0.2 by their numbers, then 0.2 tags in semver's order. -function key(tag) { - const version = tag.startsWith("launcher@") ? tag.slice(9) : tag.startsWith("v") ? tag.slice(1) : null; - const m = version !== null && semver(version); - if (!m) return [0, (tag.match(/\d+/g) || []).map(Number), []]; - const pre = m[4] ? m[4].split(".").map((id) => (/^\d+$/.test(id) ? [0, Number(id)] : [1, id])) : null; - return [1, [m[1], m[2], m[3]].map(Number), pre]; -} - -const cmpList = (a, b, cmp) => { - for (let i = 0; i < Math.min(a.length, b.length); i++) { - const d = cmp(a[i], b[i]); - if (d) return d; - } - return a.length - b.length; -}; -const cmpNumbers = (a, b) => { - const strip = (l) => { const c = [...l]; while (c.length && c[c.length - 1] === 0) c.pop(); return c; }; - return cmpList(strip(a), strip(b), (x, y) => x - y); -}; -const cmpId = ([ka, va], [kb, vb]) => ka - kb || (ka ? (va < vb ? -1 : va > vb ? 1 : 0) : va - vb); - -// Negative when tag a is older than tag b. -export function compareTags(a, b) { - const [la, na, pa] = key(a); - const [lb, nb, pb] = key(b); - if (la !== lb) return la - lb; - const d = cmpNumbers(na, nb); - if (d || !la) return d; - // A release follows its pre-releases. - if (!pa || !pb) return (pa ? -1 : 0) - (pb ? -1 : 0); - return cmpList(pa, pb, cmpId); -} - -export const newestFirst = (a, b) => compareTags(b, a); diff --git a/website/src/versions.test.mjs b/website/src/versions.test.mjs deleted file mode 100644 index eed334429..000000000 --- a/website/src/versions.test.mjs +++ /dev/null @@ -1,21 +0,0 @@ -// node --test website/src/ (npm test in website/) -import { test } from "node:test"; -import assert from "node:assert/strict"; -import { compareTags, isGame, isLauncher, launcherVersion, newestFirst } from "./versions.js"; - -test("0.2 tags follow every tag from before", () => { - const order = ["v2026.10.19.15", "v2026.10.21", "v0.2.0-beta.1", "v0.2.0", "v0.2.1-beta", "v0.2.1-beta.2", - "v0.2.1-beta.11", "v0.2.1-rc.1", "v0.2.1", "v0.2.9", "v0.2.10", "v0.3.0-1", "v0.3.0-alpha", "v0.3.0", "v1.0.0"]; - assert.deepEqual([...order].reverse().sort(compareTags), order); - assert.deepEqual(["launcher-v0.16.0", "launcher@0.2.0", "launcher-v0.17.0", "launcher@0.2.1"].sort(newestFirst), - ["launcher@0.2.1", "launcher@0.2.0", "launcher-v0.17.0", "launcher-v0.16.0"]); - assert.equal(compareTags("v2026.10.19", "v2026.10.19.0"), 0); -}); - -test("game and launcher tags never mix", () => { - for (const tag of ["v0.2.0", "v0.3.0-rc.1", "v2026.10.21", "v2026.10.19.15"]) assert.ok(isGame(tag), tag); - for (const tag of ["launcher@0.2.0", "launcher-v0.16.0", "v0.2", "vnext", "v2026.10.21-x"]) assert.ok(!isGame(tag), tag); - assert.equal(launcherVersion("launcher@0.2.0"), "0.2.0"); - assert.equal(launcherVersion("launcher-v0.16.0"), "0.16.0"); - assert.ok(!isLauncher("v0.2.0") && !isLauncher("launcher-vnext")); -}); diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 2682b1f82..b71910da4 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -10,7 +10,7 @@ //! (`cargo build --release -p horizon-client --no-default-features`, without sound or controllers) //! as horizon-engine, with horizon-prepare and horizon-server from beside it and the same sources. //! -//! `tokens`: writes `website/src/tokens.css`, the design tokens of `crates/horizon-theme` as CSS +//! `tokens`: writes `crates/horizon-theme/tokens.css`, the design tokens of `crates/horizon-theme` as CSS //! custom properties (a horizon-theme test fails when the file is out of date). //! //! `icons`: renders the icon masters in `docs/media/brand` (with `rsvg-convert`, from librsvg) @@ -79,9 +79,9 @@ fn git(repo: &Path, args: &[&str]) -> Result, String> { } fn tokens() -> Result<(), String> { - let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../website/src/tokens.css"); + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../crates/horizon-theme/tokens.css"); fs::write(&path, horizon_theme::css()).map_err(|e| format!("{}: {e}", path.display()))?; - println!("wrote website/src/tokens.css"); + println!("wrote crates/horizon-theme/tokens.css"); Ok(()) } @@ -195,7 +195,7 @@ fn icons() -> Result<(), String> { &repo.join("crates/horizon-theme/icons/horizon-64.png"), &render(&square, (64, 64))?, )?; - // Avatars and the website's icons. + // Avatars, and the website's icons (horizon-site copies docs/media/brand/web/ into its public/). let avatar = brand.join("avatar.svg"); for (svg, size, out) in [ ( @@ -203,15 +203,15 @@ fn icons() -> Result<(), String> { 500, "docs/media/brand/social/github-avatar-500.png", ), - (&avatar, 180, "website/public/apple-touch-icon.png"), - (&square, 32, "website/public/favicon-32.png"), + (&avatar, 180, "docs/media/brand/web/apple-touch-icon.png"), + (&square, 32, "docs/media/brand/web/favicon-32.png"), (&square, 1024, "docs/media/brand/icon-1024.png"), (&macos, 1024, "docs/media/brand/icon-macos-1024.png"), ] { write(&repo.join(out), &render(svg, (size, size))?)?; } write( - &repo.join("website/public/favicon.svg"), + &repo.join("docs/media/brand/web/favicon.svg"), &fs::read(&square).map_err(|e| format!("{}: {e}", square.display()))?, )?; println!("wrote packaging/icons, the window icon, the avatars and the website's icons"); From 0bd6a576a989be5a78ce7a8f5310efbe119610e7 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:12:10 +0100 Subject: [PATCH 44/51] Tools: the ThinkPad no longer runs harnesses or builds; playhorizon is the Linux host Co-Authored-By: Claude Opus 5.5 --- docs/parity-workflow.md | 6 +++--- tools/ci/linux-runner.sh | 2 +- tools/parity_hosts.json | 14 +------------- tools/pr_ready.py | 6 ++---- 4 files changed, 7 insertions(+), 21 deletions(-) diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index 5eaac1a1d..27505d9de 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -13,7 +13,7 @@ python3 tools/parity.py --failed # the ones that failed last time python3 tools/parity.py --all # everything, from scratch: the audit (26 minutes on the Mac mini alone) python3 tools/parity.py --fresh food # don't reuse vanilla oracle results python3 tools/parity.py --repeat 3 food # run it three times; the runs must agree -python3 tools/parity.py --hosts macmini,thinkpad # with other machines (default: tools/parity_hosts.json's default list, empty) +python3 tools/parity.py --hosts macmini,playhorizon # with other machines (default: tools/parity_hosts.json's default list, empty) python3 tools/parity.py --list # what would run python3 tools/parity.py --status # last result of each harness python3 tools/parity.py --changed origin/main # those a branch's changes can affect (CI's parity job) @@ -40,9 +40,9 @@ The game logs into `HORIZON_HOME` and falls back to the player's own game folder ### Other machines -Harnesses can also run on the Mac mini, the ThinkPad and the desktop (`tools/parity_hosts.json` describes them; `desktop` uses its CI runner's environment and vanilla data, and refuses work, or stops it, while someone uses it: docs/release-flow.md, "The desktop's runner"; its `default` list is empty, so pass `--hosts macmini,thinkpad` or set `PARITY_HOSTS`, after copying `shared-local/` to `~/code/horizon-parity/shared-local` on each host). The runner mirrors the worktree there with rsync (not `.git`, `.local`, `target` or ignored files) into `~/code/horizon-parity/remote/`, whose `.local` links to the vanilla data in `~/code/horizon-parity/shared-local`, and starts `tools/parity.py --worker` over ssh. The worker builds the probes (about 80 s the first time) and runs what it is sent under the same tracer, admitting harnesses against its own free memory. One queue, longest first, feeds every machine, remote ones first: the Mac takes up to 14 harnesses, the desktop 8. Each pass comes back with the content hash of every file it depended on, so it is keyed on exactly what ran, and logs come back to `.local/parity-runner/logs/`; state, sharing and `gate.py` work as before. If a host can't be reached, or drops out, its harnesses run here. +Harnesses can also run on the Mac mini, the desktop and playhorizon (`tools/parity_hosts.json` describes them; `desktop` and `playhorizon` use their CI runner's environment and vanilla data, and the desktop refuses work, or stops it, while someone uses it: docs/release-flow.md, "The desktop's runner"; its `default` list is empty, so pass `--hosts macmini,playhorizon` or set `PARITY_HOSTS`, after copying `shared-local/` to `~/code/horizon-parity/shared-local` on each host). The runner mirrors the worktree there with rsync (not `.git`, `.local`, `target` or ignored files) into `~/code/horizon-parity/remote/`, whose `.local` links to the vanilla data in `~/code/horizon-parity/shared-local`, and starts `tools/parity.py --worker` over ssh. The worker builds the probes (about 80 s the first time) and runs what it is sent under the same tracer, admitting harnesses against its own free memory. One queue, longest first, feeds every machine, remote ones first: the Mac takes up to 14 harnesses, the desktop 8, playhorizon 6. Each pass comes back with the content hash of every file it depended on, so it is keyed on exactly what ran, and logs come back to `.local/parity-runner/logs/`; state, sharing and `gate.py` work as before. If a host can't be reached, or drops out, its harnesses run here. -Harnesses a host can't run are listed in the file: `local_only` (`save_roundtrip` runs the game on a virtual screen) and each host's `exclude`. The Mac excludes nothing: vanilla's `Math.sin`, `pow`, `log` and the like don't round the same on an Apple silicon Mac as on Linux (HotSpot uses fdlibm there, Intel's stubs on x86-64), and Rust's float functions round like neither (they call the platform libm), so code that mirrors a vanilla `Math` call uses `horizon_core::jmath`, which computes what HotSpot computes on the host architecture. The ThinkPad helps too, gently: Linux, 2 harnesses at `nice 19`, since it hosts the Claude account pool; it finds ALSA through `~/code/horizon-parity/alsa-dev` like the desktop. +Harnesses a host can't run are listed in the file: `local_only` (`save_roundtrip` runs the game on a virtual screen) and each host's `exclude`. The Mac excludes nothing: vanilla's `Math.sin`, `pow`, `log` and the like don't round the same on an Apple silicon Mac as on Linux (HotSpot uses fdlibm there, Intel's stubs on x86-64), and Rust's float functions round like neither (they call the platform libm), so code that mirrors a vanilla `Math` call uses `horizon_core::jmath`, which computes what HotSpot computes on the host architecture. The ThinkPad no longer runs harnesses (2026-10-26): playhorizon is the Linux host that is always on. ### Shards and Rust scopes diff --git a/tools/ci/linux-runner.sh b/tools/ci/linux-runner.sh index 5a5e72697..293428da1 100755 --- a/tools/ci/linux-runner.sh +++ b/tools/ci/linux-runner.sh @@ -1,6 +1,6 @@ #!/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; Ubuntu: playhorizon, a partner's server), as a systemd user service +# maintainer's (NixOS: ludodesktop; 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: # diff --git a/tools/parity_hosts.json b/tools/parity_hosts.json index b98091f4f..f76a7f82c 100644 --- a/tools/parity_hosts.json +++ b/tools/parity_hosts.json @@ -28,19 +28,7 @@ "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", - "shell": "sh -c", - "jobs": 2, - "nice": 19, - "environment": { - "PARITY_BUILD_JOBS": "2" - }, - "note": "hosts the Claude account pool: two harnesses at most, at the lowest priority", - "setup": "export PKG_CONFIG_PATH=$HOME/code/horizon-parity/alsa-dev/lib/pkgconfig" + "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 always-on Linux host since the ThinkPad stopped running harnesses (2026-10-26)" } }, "local_only": { diff --git a/tools/pr_ready.py b/tools/pr_ready.py index df75025ed..5b1622e2e 100755 --- a/tools/pr_ready.py +++ b/tools/pr_ready.py @@ -46,12 +46,10 @@ from tools import parity, release_train # noqa: E402 RBUILD = Path.home() / "fleet" / "rbuild" LINE_LIMIT = 500 -# What rbuild's login shell needs on each fleet machine before cargo (it adds sccache itself). The ThinkPad hosts -# the Claude account pool: three jobs at most. +# What rbuild's login shell needs on each fleet machine before cargo (it adds sccache itself). The ThinkPad no +# longer builds (2026-10-26: it keeps the AI pool and a few services; Linux work goes to playhorizon's runner). HOST_SETUP = { "macmini": "source ~/.cargo/env; export PATH=/opt/homebrew/bin:$PATH CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-10}", - "thinkpad": 'export CARGO_BUILD_JOBS=3 PKG_CONFIG_PATH="$(ls -d /nix/store/*-alsa-lib-*-dev/lib/pkgconfig | tail -1):' - '$(ls -d /nix/store/*-systemd-*-dev/lib/pkgconfig | tail -1)"', "local": "", } # Hosts that hold the vanilla data, and how a run there gets it: CI's own runner scripts on the parity runner's From 9f1784dc0c3e91c860a9c12b6f975f6a0f7f286f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:14:46 +0100 Subject: [PATCH 45/51] rust_changes: append the repository root to sys.path instead of prepending tools/ Prepending tools/ made unittest discovery import tools/test_decoration_parity.py in place of tests/test_decoration_parity.py. Co-Authored-By: Claude Opus 5.5 --- tools/ci/rust_changes.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tools/ci/rust_changes.py b/tools/ci/rust_changes.py index f856778e9..a22b86f12 100644 --- a/tools/ci/rust_changes.py +++ b/tools/ci/rust_changes.py @@ -9,8 +9,9 @@ import subprocess import sys from pathlib import Path -sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) -import release_train # noqa: E402 +# The repository root, appended so a script run finds `tools` without shadowing anything already importable. +sys.path.append(str(Path(__file__).resolve().parents[2])) +from tools import release_train # noqa: E402 # The root workspace's manifest and toolchain files: the launcher's path crates inherit from them. ROOT_RUST = {"Cargo.toml", "Cargo.lock", "rust-toolchain.toml", "rustfmt.toml", "clippy.toml"} From d8e68148beec68cb857537ebbf0f6ef5b2c46d18 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:18:47 +0100 Subject: [PATCH 46/51] /recipe gives and takes each target's own recipes cmd_recipe changed self.level.recipe_book for every target, so `/recipe give|take ` changed the book of whoever ran it (or the dedicated server's own) and the target's client heard nothing. Each target now runs with its state swapped in (for_player), as ServerPlayer.awardRecipes/resetRecipes do on the player's own ServerRecipeBook: the guest's book changes and its client gets ClientboundRecipeBookAdd/RemovePacket. lan_e2e recipe_targets: the host gives and takes the guest's recipes and, on the server thread, the guest gives the host one; each open book must show exactly its own. Co-Authored-By: Claude Opus 5.5 --- .../src/game/commands/world_cmds.rs | 47 ++++++++------- tools/lan_e2e.py | 58 +++++++++++++++++++ 2 files changed, 85 insertions(+), 20 deletions(-) diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 30f019997..687eb3f88 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -49,26 +49,12 @@ impl Game<'_> { let mut tracker = Tracker::default(); for &t in &targets { let h = holder(self.target_name(t)); - // ServerRecipeBook.addRecipes/removeRecipes count recipe book - // displays (a transmute recipe has one per material count). - let mut n = 0; - // ServerPlayer.awardRecipes / resetRecipes: the displays changed. - let index = &self.res.stations().recipe_index; - n += if give { - let (count, unlocked) = self.level.recipe_book.add_recipes(index, &recipes); - self.recipe_unlocked(&unlocked); - count as i32 - } else { - let removed = self.level.recipe_book.remove_recipes(index, &recipes); - let count = removed.len() as i32; - // A network player's client drops them from its book. - if self.lan_acting.is_some() && !removed.is_empty() { - self.guest_packets.push(C::RecipeBookRemove( - horizon_protocol::packets::recipes::RecipeBookRemove { ids: removed }, - )); - } - count - }; + // ServerPlayer.awardRecipes / resetRecipes on the target's own + // ServerRecipeBook: a guest's is swapped in for the call, and the + // packets go to its client. + let n = self + .for_player(t, |g| g.change_recipes(give, &recipes)) + .unwrap_or(0); tracker.track(&h, n); } let verb = if give { "give" } else { "take" }; @@ -92,6 +78,27 @@ impl Game<'_> { Ok(total) } + /// ServerRecipeBook.addRecipes/removeRecipes for the player in place: how + /// many recipe book displays changed (a transmute recipe has one per + /// material count). + fn change_recipes(&mut self, give: bool, recipes: &[String]) -> i32 { + let index = &self.res.stations().recipe_index; + if give { + let (count, unlocked) = self.level.recipe_book.add_recipes(index, recipes); + self.recipe_unlocked(&unlocked); + return count as i32; + } + let removed = self.level.recipe_book.remove_recipes(index, recipes); + let count = removed.len() as i32; + // A network player's client drops them from its book. + if self.lan_acting.is_some() && !removed.is_empty() { + self.guest_packets.push(C::RecipeBookRemove( + horizon_protocol::packets::recipes::RecipeBookRemove { ids: removed }, + )); + } + count + } + // ---- /damage ---------------------------------------------------------------- fn damage_kind(ty: &str) -> DamageKind { diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 246729d1f..b5c3e6c1f 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -91,6 +91,8 @@ address. The script then checks, from both sides, what a guest's game used to ge places a log in the inventory's crafting grid (the server places it). - recipe_removal: the host and guest each forget all and individual recipes while the book is open; it stays empty when reopened, and a later grant appears (#1495). +- recipe_targets: `/recipe give|take ` changes that player's book, the host's + for the guest and (server thread) the guest's for the host; their open book shows it. - feedback: the guest's command feedback names the guest and shows the numbers, and the host (an operator) is told of it as `[Guest: ...]`. - clicks: with real mouse presses (not click-slot, which skips the screen's press and drag @@ -6222,6 +6224,62 @@ CHECKS += ['recipe_removal'] CHECK_FNS.update(recipe_removal=check_recipe_removal) +def check_recipe_targets(host, guest, out): + """RecipeCommand gives and takes the recipes of each target's own ServerRecipeBook: a + `/recipe give|take ` changes that player's book and reaches their client, + not the book of the player who typed it. An in-frame host isn't one of the players a guest's + command can name (`command_players` lists the guests), so the guest gives the host a recipe + only when the host is a client of its server thread.""" + host_name = host.raw('lan', 'status').get('host', 'Player') + books = {} + for game in (host, guest): + back_to_game(game) + game('command', command='clear @s') + game('command', command='recipe take @s *') + host.wait(20) + for game in (host, guest): + game.raw('key', 'e', 'tap') + game.wait(5) + book = game('screen').get('recipe_book') + assert book, f'{game.name}: the inventory has no recipe book' + if len(book['targets']) == 1: + game.raw('click-at', *centre(book['targets'][0])) + game.wait(5) + + def known(): + return {game.name: game('screen')['recipe_book']['known'] for game in (host, guest)} + + try: + books['empty'] = known() + assert books['empty'] == {host.name: 0, guest.name: 0}, books + host('command', command=f'recipe give {GUEST_NAME} minecraft:oak_planks') + host('command', command=f'recipe give {GUEST_NAME} minecraft:stick') + host.wait(20) + books['host gives guest'] = known() + if SERVER_THREAD: + guest('command', command=f'recipe give {host_name} minecraft:stick') + guest.wait(20) + books['guest gives host'] = known() + host('command', command=f'recipe take {GUEST_NAME} minecraft:stick') + host.wait(20) + books['host takes from guest'] = known() + host.shot(out, 'recipe-targets-host') + guest.shot(out, 'recipe-targets-guest') + by_guest = int(SERVER_THREAD) + expected = {'empty': (0, 0), 'host gives guest': (0, 2), 'guest gives host': (by_guest, 2), + 'host takes from guest': (by_guest, 1)} + for step, (in_host, in_guest) in expected.items(): + assert books[step] == {host.name: in_host, guest.name: in_guest}, (step, books) + finally: + back_to_game(host) + back_to_game(guest) + return books + + +CHECKS += ['recipe_targets'] +CHECK_FNS.update(recipe_targets=check_recipe_targets) + + def check_shulker_bullets(host, guest, out): """ShulkerAttackGoal's bullets reach ClientPacketListener.handleAddEntity, then the existing projectile renderer and interpolation, with distinct ids from the server's entity counter.""" From 0f22a274fa302c60dd9667b101bd201fb79b7d1d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:44:05 +0100 Subject: [PATCH 47/51] test_remote_motion: stub what remote_motion reaches on main remote_motion now also hands motion to the dragon, its fireballs, thrown potions and eyes of ender; the extracted fixture needs those to compile. Co-Authored-By: Claude Opus 5.5 --- tests/test_remote_motion.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/test_remote_motion.py b/tests/test_remote_motion.py index da059c60b..b00e5f0a9 100644 --- a/tests/test_remote_motion.py +++ b/tests/test_remote_motion.py @@ -27,11 +27,19 @@ struct Remote { pending_items: HashMap } #[derive(Default)] struct Creatures { projectiles: Vec } #[derive(Default)] +struct Potions; +impl Potions { fn remote_thrown_motion(&mut self, _id: u32, _v: Vec3) -> bool { false } } +#[derive(Default)] +struct End; +impl End { fn remote_eye_motion(&mut self, _id: u32, _v: [f64; 3]) {} } +#[derive(Default)] struct Game { mobs: Vec, dropped: Vec, falling: Vec, tnts: Vec, - creatures: Creatures, remote: Option, + creatures: Creatures, dragon_fireballs: Vec, remote: Option, + potions: Potions, end: End, } impl Game { +fn remote_dragon_motion(&mut self, _id: i32, _velocity: [f64; 3]) {} METHOD } fn main() { From d01a621fec1f4ac79f9661cd9b741b0d5bc08719 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:46:06 +0100 Subject: [PATCH 48/51] tests: two parity-runner tests pass on macOS OracleReuseTests ran the shim through `#!/usr/bin/env python3` with a PATH whose Python folder is Homebrew's, which names it only python3.13: the shim wasn't found (127). The test now gives that PATH a python3 of its own. test_report_rejects_sources_changed_during_a_run compared a resolved source path with an unresolved temp root, and macOS's /var is /private/var. Co-Authored-By: Claude Opus 5.5 --- tests/test_parity_runner.py | 6 +++++- tests/test_rust_parity.py | 4 +++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/test_parity_runner.py b/tests/test_parity_runner.py index a85f1e969..518f23ba4 100644 --- a/tests/test_parity_runner.py +++ b/tests/test_parity_runner.py @@ -259,7 +259,11 @@ class OracleReuseTests(unittest.TestCase): self.input, self.output = root / "work" / "in.txt", root / "work" / "out.txt" self.input.parent.mkdir() self.input.write_text("a") - python = Path(sys.executable).parent + # The shim starts with `#!/usr/bin/env python3`, and a Python's own folder may name it only + # python3.13 (Homebrew's): a python3 of its own keeps the PATH below enough. + python = root / "python" + python.mkdir() + (python / "python3").symlink_to(sys.executable) self.env = dict(os.environ, PATH=f"{self.shim}:{self.bin}:{python}", PARITY_SHIM_REAL_PATH=str(self.bin), PARITY_SHIM_CACHE=str(root / "cache")) self.subprocess = subprocess diff --git a/tests/test_rust_parity.py b/tests/test_rust_parity.py index b14723c16..68a68d6e1 100644 --- a/tests/test_rust_parity.py +++ b/tests/test_rust_parity.py @@ -10,7 +10,9 @@ from tools import test_rust_parity as parity class ParityRunnerTests(unittest.TestCase): def test_report_rejects_sources_changed_during_a_run(self): with tempfile.TemporaryDirectory() as temp: - root = Path(temp) + # Resolved, as source_hashes resolves the sources: macOS's temp folder is a symlink + # (/var -> /private/var). + root = Path(temp).resolve() source = root / "source.rs" source.write_text("before") with mock.patch.object(parity.lab, "ROOT", root): From fbbed63f04094038e076f127c5995b72f2b85d31 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:02:34 +0100 Subject: [PATCH 49/51] setblock and data keep a container's loot table A command's tag went through decode_block_entity, which has nowhere to put LootTable, so `setblock ... chest{LootTable:...}` made an empty chest (`data get` showed `Items: []`). An empty container given a LootTable is now rolled as a loaded chunk's are, and the roll is kept with its chunk (RolledLoot), so it saves, and `data get` shows, LootTable and LootTableSeed until its items change (tryLoadLootTable / trySaveLootTable). `data merge` and `data modify` go through the same path. command_exec: setblock a seeded loot chest, then data get it whole and its LootTableSeed (870/870 match the 26.3 oracle). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/commands.rs | 78 ++++++++++++++++++- .../horizon-client/src/game/commands/data.rs | 4 +- tools/command_exec_corpus.py | 6 ++ 3 files changed, 85 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 38a5cddd3..8f934ad8a 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1885,11 +1885,12 @@ impl Game<'_> { } } } - let Some((_, new)) = horizon_client::save::decode_block_entity(&tag) else { + let Some((_, mut new)) = horizon_client::save::decode_block_entity(&tag) else { return false; }; + let rolled = self.take_loot_table(key, &tag, &mut new); let after = horizon_client::save::encode_block_entity(key, &new, &name); - if after == before { + if after == before && !rolled { return false; } self.world.block_entities.insert(key, new); @@ -1897,6 +1898,79 @@ impl Game<'_> { let _ = self.world.set(pos[0], pos[1], pos[2], state); true } + /// RandomizableContainer.tryLoadLootTable for a tag a command gives a + /// container (`setblock`, `data`): an empty container with a `LootTable` + /// is rolled now, as a loaded chunk's are (`save::roll_loaded_loot`), and + /// the roll is kept with its chunk, so that the container saves, and + /// `data get` shows, its table and seed until its items change. A tag + /// without one drops what the container had. True when it had a table. + pub(super) fn take_loot_table( + &mut self, + key: (i32, i32, i32), + tag: &horizon_world::nbt::Tag, + entity: &mut horizon_client::containers::BlockEntity, + ) -> bool { + use horizon_client::{containers::BlockEntity, save, structure_blocks}; + let table = save::text(tag.get("LootTable")); + let rolled = match (table, entity) { + (Some(table), BlockEntity::Chest(slots)) if slots.iter().all(Option::is_none) => { + let loot = structure_blocks::loot_data(&self.options.resources); + let at = Vec3::new(f64::from(key.0), f64::from(key.1), f64::from(key.2)); + let biome = self.biome_name_at(at).unwrap_or_default(); + Some(structure_blocks::roll_container( + slots, + loot.as_deref(), + table, + structure_blocks::loot_seed(tag), + key, + &biome, + )) + } + _ => None, + }; + let Some(chunk) = self.world.chunks.get_mut(&(key.0 >> 4, key.2 >> 4)) else { + return false; + }; + let held = |c: &horizon_client::chunk::Chunk| { + c.saved + .as_ref() + .is_some_and(|s| s.rolled_loot.iter().any(|r| r.pos == key)) + }; + if rolled.is_none() && !held(chunk) { + return false; + } + let chunk = std::sync::Arc::make_mut(chunk); + let mut extras = chunk + .saved + .take() + .map(std::sync::Arc::unwrap_or_clone) + .unwrap_or_default(); + extras.rolled_loot.retain(|r| r.pos != key); + let taken = rolled.is_some(); + extras.rolled_loot.extend(rolled); + chunk.saved = Some(std::sync::Arc::new(extras)); + taken + } + /// The loot table and seed a container still holding its roll saves + /// (`RolledLoot::restore`), in place of its items. + pub(super) fn restore_loot_table( + &self, + key: (i32, i32, i32), + tag: &mut horizon_world::nbt::Tag, + ) { + let horizon_world::nbt::Tag::Compound(map) = tag else { + return; + }; + let rolled = self + .world + .chunks + .get(&(key.0 >> 4, key.2 >> 4)) + .and_then(|c| c.saved.as_ref()) + .and_then(|s| s.rolled_loot.iter().find(|r| r.pos == key)); + if let Some(r) = rolled { + r.restore(map); + } + } fn cmd_fill(&mut self, ctx: &Context) -> R { let a = self.block_pos_arg(ctx, "from")?; let b = self.block_pos_arg(ctx, "to")?; diff --git a/crates/horizon-client/src/game/commands/data.rs b/crates/horizon-client/src/game/commands/data.rs index 18035ddd7..ac16c5e7c 100644 --- a/crates/horizon-client/src/game/commands/data.rs +++ b/crates/horizon-client/src/game/commands/data.rs @@ -286,6 +286,7 @@ impl Game<'_> { if let Tag::Compound(c) = &mut tag { c.remove(&"keepPacked".into()); } + self.restore_loot_table(key, &mut tag); Ok(tag) } DataRef::Storage(id) => Ok(self.score.storage.get(id)), @@ -296,7 +297,8 @@ impl Game<'_> { DataRef::Entity(t) => self.apply_entity_nbt(*t, tag), DataRef::Block(p) => { let key = (p[0], p[1], p[2]); - if let Some((_, new)) = save::decode_block_entity(&tag) { + if let Some((_, mut new)) = save::decode_block_entity(&tag) { + self.take_loot_table(key, &tag, &mut new); self.world.block_entities.insert(key, new); let state = self.world.block(p[0], p[1], p[2]); // Redraw what shows the block entity (signs, banners). diff --git a/tools/command_exec_corpus.py b/tools/command_exec_corpus.py index 0e3a7f92e..d8f925ef0 100644 --- a/tools/command_exec_corpus.py +++ b/tools/command_exec_corpus.py @@ -241,6 +241,12 @@ def world_blocks(): cmd('/clone 0 205 0 4 207 4 6 205 6 masked'), cmd('/execute if blocks 0 205 0 4 207 4 6 205 6 all'), cmd('/setblock 3 206 3 minecraft:air'), + # A container keeps its loot table and seed until its items change + # (RandomizableContainer.tryLoadLootTable / trySaveLootTable). + cmd('/setblock 7 206 7 minecraft:chest{LootTable:"minecraft:chests/simple_dungeon",LootTableSeed:42L}'), + cmd('/data get block 7 206 7'), + cmd('/data get block 7 206 7 LootTableSeed'), + cmd('/setblock 7 206 7 minecraft:air'), # A hopper placed into power turns `enabled=false` and keeps its block entity. cmd('/setblock 5 205 5 minecraft:redstone_block'), cmd('/setblock 5 206 5 minecraft:hopper'), From 64f4e9b6ff2fd59b64dcf5811604bdcd524fdca7 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:12:19 +0100 Subject: [PATCH 50/51] parity_hosts: playhorizon skips mob_ai, lan_integration, world_reopen (failed in its trial) Full trial (run 40341431094): 342/348 in 96.9 min; save_roundtrip, remote_fireball and server_player_sculk passed on a rerun with vscreen and fewer jobs; these three did not. Co-Authored-By: Claude Opus 5.5 --- tools/parity_hosts.json | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tools/parity_hosts.json b/tools/parity_hosts.json index f76a7f82c..b56106e4d 100644 --- a/tools/parity_hosts.json +++ b/tools/parity_hosts.json @@ -28,6 +28,11 @@ "python": "python3.13", "jobs": 6, "nice": 10, + "exclude": { + "mob_ai": "the vanilla oracle runs out of its 3 GB heap here (OutOfMemoryError in IO workers; passes on the desktop and the Mac) - 2026-10-26 trial", + "lan_integration": "two clients rendered on the CPU (lavapipe): different timing subtests fail on each run (elytra, consume-release, barter, critical-hits) - 2026-10-26 trial", + "world_reopen": "failed twice here (no Save and Quit button after reopening; the minecart-count flake), passes on the desktop - 2026-10-26 trial" + }, "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 always-on Linux host since the ThinkPad stopped running harnesses (2026-10-26)" } }, From 1825b3991cae222b6aac29951b5542abfb7c7f8a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:30:56 +0100 Subject: [PATCH 51/51] Campfires are no Container for droppers and hoppers Since campfires got their block entity (#2015), the container lookup took it for a zero-slot container: a dropper facing one kept its item instead of dropping it, as vanilla's HopperBlockEntity.getContainerAt finds no Container there. The dispense fixture also filled campfires through the generic slots, which a campfire doesn't have, so block_removal saw them empty. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/dispense_fixture.rs | 5 +++++ crates/horizon-client/src/game/machines.rs | 6 ++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index 267f323c3..43f41d201 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -725,6 +725,11 @@ impl Game<'_> { match self.world.block_entities.get_mut(&p) { Some(BlockEntity::Jukebox(j)) => j.record = stack, Some(BlockEntity::Lectern(l)) => l.book = stack, + Some(BlockEntity::Campfire(c)) => { + if let Some(cell) = c.items.get_mut(slot) { + *cell = stack; + } + } Some(e) => { if let Some(cell) = e.slots_mut().get_mut(slot) { *cell = stack; diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index 8742962e9..bb936744b 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -159,8 +159,10 @@ impl Containers<'_> { }); } let entity = self.world.block_entities.get(&pos)?; - // A beehive keeps bees, not items: it is no `Container`. - if matches!(entity, BlockEntity::Beehive(_)) { + // A beehive keeps bees, not items, and a campfire cooks its own: neither + // is a `Container` (HopperBlockEntity.getContainerAt), so a dropper drops + // in front of them and a hopper leaves them alone. + if matches!(entity, BlockEntity::Beehive(_) | BlockEntity::Campfire(_)) { return None; } let kind = match (entity, name) {