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/cargo-horizon-mod/src/check.rs b/crates/cargo-horizon-mod/src/check.rs index f42674da8..33095a115 100644 --- a/crates/cargo-horizon-mod/src/check.rs +++ b/crates/cargo-horizon-mod/src/check.rs @@ -262,6 +262,9 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> { format!("{}: {text}", if error { "error" } else { "feedback" }) } Output::Command { line } => format!("command: /{line}"), + Output::QuietCommands { lines, .. } => { + format!("{} quiet command(s)", lines.len()) + } Output::Stopped { reason, .. } => return Err(format!("it stopped: {reason}")), Output::OpenScreen { .. } => "opened a screen".to_string(), Output::CloseScreen { .. } => "closed its screen".to_string(), 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 1e1bc04d9..281be5608 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 cushion_placement_probe; mod emitter_particles_probe; @@ -108,6 +109,7 @@ probes! { block_transform_fixture, breaking_fixture, camera_probe, + creative_mining_probe, cushion_placement_probe, cauldron_fixture, chat_screen_fixture, diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index 48e8f16f4..b3a587114 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 with ignite odds above zero (none waterlogged). + burnable: Vec, /// Biome id -> ambient particles and probabilities (`minecraft:visual/ambient_particles`). ambient: Vec>, } @@ -220,6 +226,21 @@ 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| { + // FireBlock.getIgniteOdds: a waterlogged state never burns. + registry.state(BlockStateId(id)).is_some_and(|s| { + 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(); let mut ambient = vec![Vec::new(); biomes.list.len()]; for (name, &id) in &biomes.index { let path = root.join(format!( @@ -248,6 +269,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 +1125,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 +1137,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/block_entity_nbt.rs b/crates/horizon-client/src/block_entity_nbt.rs index 54d230eb4..a4c02ba3b 100644 --- a/crates/horizon-client/src/block_entity_nbt.rs +++ b/crates/horizon-client/src/block_entity_nbt.rs @@ -664,7 +664,9 @@ pub fn canonical(tag: &Tag) -> Option { } "minecraft:trial_spawner" => { // `TrialSpawnerStateData.Packed` and `FullConfig`: every key is optional - // and defaulted by vanilla; they are kept as loaded. + // and defaulted by vanilla; they are kept as loaded. No `spawn_data` is + // added: an absent one loads as Optional.empty and is not stored, and + // an empty entity would keep the spawner from ever picking a mob. if let Tag::Compound(c) = tag { for (k, v) in c { let key = k.to_string_lossy(); @@ -676,12 +678,6 @@ pub fn canonical(tag: &Tag) -> Option { } } } - if !f.out.contains_key(&"spawn_data".into()) { - f.put( - "spawn_data", - Tag::compound([("entity", Tag::Compound(Compound::new()))]), - ); - } } "minecraft:vault" => { // `VaultConfig.DEFAULT` (when the config is absent): the trial key and the @@ -827,6 +823,21 @@ mod tests { canonical(&snbt(s)).expect("known type") } + #[test] + fn a_trial_spawner_without_spawn_data_saves_none() { + let fresh = canon( + r#"{id:"minecraft:trial_spawner",x:1,y:2,z:3,normal_config:"minecraft:trial_chamber/ranged/skeleton/normal"}"#, + ); + assert_eq!(fresh.get("spawn_data"), None); + let picked = canon( + r#"{id:"minecraft:trial_spawner",x:1,y:2,z:3,spawn_data:{entity:{id:"minecraft:skeleton"}}}"#, + ); + assert_eq!( + picked.get("spawn_data"), + Some(&snbt(r#"{entity:{id:"minecraft:skeleton"}}"#)) + ); + } + #[test] fn every_type_has_defaults() { for id in TYPES.iter().chain(NEWEST.iter()) { diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs index c0bec476b..7cd375343 100644 --- a/crates/horizon-client/src/chunk.rs +++ b/crates/horizon-client/src/chunk.rs @@ -161,6 +161,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 { @@ -178,6 +181,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/containers.rs b/crates/horizon-client/src/containers.rs index 00e3f05b8..6aba0970e 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -94,9 +94,66 @@ pub enum BlockEntity { Beehive(Box), /// `CommandBlockEntity` of the three command blocks (`crate::command_block`). CommandBlock(Box), + /// `CampfireBlockEntity` of campfires and soul campfires. + Campfire(Box), /// `SkullBlockEntity` of every skull and head block. Skull(Skull), } +/// `CampfireBlockEntity`: four cooking slots, each with its +/// `cookingProgress` and `cookingTime` (the recipe's). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Campfire { + pub items: [Option; 4], + pub progress: [i32; 4], + pub total: [i32; 4], +} +impl Campfire { + /// `placeFood`'s slot: the first empty one, given the item's + /// `campfire_cooking` time; it takes one item of `held`. + pub fn place_food(&mut self, held: &mut ItemStack, cooking_time: i32) -> bool { + let Some(slot) = self.items.iter().position(Option::is_none) else { + return false; + }; + self.total[slot] = cooking_time; + self.progress[slot] = 0; + self.items[slot] = Some(ItemStack { + count: 1, + ..held.clone() + }); + held.count = held.count.saturating_sub(1); + true + } + /// `cookTick` (lit): each item's progress rises by one; the slots whose + /// progress reached their cooking time give up their item (the caller + /// drops its result). + pub fn cook_tick(&mut self) -> Vec<(usize, ItemStack)> { + let mut done = Vec::new(); + for i in 0..4 { + if self.items[i].is_none() { + continue; + } + self.progress[i] += 1; + if self.progress[i] >= self.total[i] + && let Some(item) = self.items[i].take() + { + done.push((i, item)); + } + } + done + } + /// `cooldownTick` (unlit): the progress falls by two, no lower than 0. + /// Whether anything changed (`setChanged`). + pub fn cooldown_tick(&mut self) -> bool { + let mut changed = false; + for i in 0..4 { + if self.progress[i] > 0 { + changed = true; + self.progress[i] = (self.progress[i] - 2).clamp(0, self.total[i]); + } + } + changed + } +} /// `SkullBlockEntity`: the player profile the head shows (kept as loaded: /// a compound, or a string when it names a player only), the note block /// sound and `custom_name`. @@ -315,6 +372,9 @@ impl BlockEntity { if name == "minecraft:brewing_stand" { return Some(Self::Brewing(Box::new(crate::brewing::BrewingStand::new()))); } + if name == "minecraft:campfire" || name == "minecraft:soul_campfire" { + return Some(Self::Campfire(Box::default())); + } let size = match name { "minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" => 27, n if n.ends_with("copper_chest") => 27, @@ -352,6 +412,7 @@ impl BlockEntity { Self::Beehive(_) => "minecraft:beehive", Self::CommandBlock(_) => "minecraft:command_block", Self::Skull(_) => "minecraft:skull", + Self::Campfire(_) => "minecraft:campfire", } } pub fn contents(&self) -> Vec { @@ -373,6 +434,7 @@ impl BlockEntity { Self::Sculk(_) => Vec::new(), Self::Banner(_) => Vec::new(), Self::Crafter(c) => c.items.iter().flatten().cloned().collect(), + Self::Campfire(c) => c.items.iter().flatten().cloned().collect(), } } pub fn slots(&self) -> &[Option] { @@ -393,7 +455,9 @@ impl BlockEntity { | Self::TrialSpawner(_) | Self::Vault(_) | Self::Beehive(_) - | Self::CommandBlock(_) => &[], + | Self::CommandBlock(_) + // Not a Container (only Clearable): hoppers don't reach in. + | Self::Campfire(_) => &[], } } pub fn slots_mut(&mut self) -> &mut [Option] { @@ -414,7 +478,8 @@ impl BlockEntity { | Self::TrialSpawner(_) | Self::Vault(_) | Self::Beehive(_) - | Self::CommandBlock(_) => &mut [], + | Self::CommandBlock(_) + | Self::Campfire(_) => &mut [], } } } @@ -706,6 +771,41 @@ mod tests { use super::*; use horizon_core::random::{LegacyRandom, RandomSource}; + #[test] + fn campfire_slots_take_food_cook_it_and_cool_down() { + let mut c = Campfire::default(); + let mut beef = ItemStack::new("minecraft:beef", 2); + // placeFood: the first free slot, one item, its recipe's time. + assert!(c.place_food(&mut beef, 600)); + assert_eq!(beef.count, 1); + assert_eq!(c.items[0].as_ref().map(|s| s.count), Some(1)); + assert_eq!((c.progress[0], c.total[0]), (0, 600)); + let mut fish = ItemStack::new("minecraft:cod", 1); + assert!(c.place_food(&mut fish, 3)); + assert_eq!(c.items[1].as_ref().map(|s| &*s.item), Some("minecraft:cod")); + // cookTick: the cod is done on its third tick, the beef keeps cooking. + assert!(c.cook_tick().is_empty()); + assert!(c.cook_tick().is_empty()); + let done = c.cook_tick(); + assert_eq!(done.len(), 1); + assert_eq!((done[0].0, &*done[0].1.item), (1, "minecraft:cod")); + assert!(c.items[1].is_none()); + assert_eq!(c.progress[0], 3); + // cooldownTick: two a tick, never below zero. + assert!(c.cooldown_tick()); + assert_eq!(c.progress[0], 1); + assert!(c.cooldown_tick()); + assert_eq!(c.progress[0], 0); + // Full: four slots, no fifth. + for _ in 0..3 { + let mut more = ItemStack::new("minecraft:potato", 1); + assert!(c.place_food(&mut more, 600)); + } + let mut fifth = ItemStack::new("minecraft:potato", 1); + assert!(!c.place_food(&mut fifth, 600)); + assert_eq!(fifth.count, 1); + } + /// A whole amount pays itself without a draw; a fraction is a chance of one more. #[test] fn create_experience_rounds_the_fraction_by_chance() { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a8ede43a4..88ca4795a 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; mod cartography; mod chat; mod client_ambient; @@ -3345,6 +3346,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]); @@ -3970,7 +3978,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(()); } @@ -5302,7 +5315,8 @@ impl Game<'_> { | BlockEntity::Vault(_) | BlockEntity::Beehive(_) | BlockEntity::CommandBlock(_) - | BlockEntity::Skull(_), + | BlockEntity::Skull(_) + | BlockEntity::Campfire(_), ) => {} None => { v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i)); @@ -5572,7 +5586,8 @@ impl Game<'_> { | BlockEntity::Vault(_) | BlockEntity::Beehive(_) | BlockEntity::CommandBlock(_) - | BlockEntity::Skull(_), + | BlockEntity::Skull(_) + | BlockEntity::Campfire(_), ) => {} None if self.mount_active() => self.draw_mount_background(batch, ox, oy), None => { @@ -7037,6 +7052,9 @@ impl Game<'_> { // `VaultRenderer`. self.mark_entity(out.len(), ""); self.vault_geometry(camera, alpha, &mut out); + // `CampfireRenderer`. + self.mark_entity(out.len(), ""); + self.campfire_geometry(camera, &mut out); self.mark_entity(out.len(), "minecraft:ominous_item_spawner"); self.ominous_item_spawner_geometry(camera, alpha, &mut out); // Mobs and their projectiles (a span each). @@ -8740,6 +8758,13 @@ impl Game<'_> { { return Ok(UseResult::Success { swing: true }); } + if allow_block_actions + && let Some(hit) = self.pick() + && let Some(placed) = self.use_on_campfire(hit.pos)? + { + // SUCCESS_SERVER swings; a full campfire's CONSUME does not. + return Ok(UseResult::Success { swing: placed }); + } // BucketItem has no useOn: a guest's UseItemOn leaves it to UseItem. let bucket = horizon_client::items::bucket_contents(&stack.item); if matches!(self.guest_use, Some(GuestUse::OnBlock(_))) diff --git a/crates/horizon-client/src/game/block_entity_ticks.rs b/crates/horizon-client/src/game/block_entity_ticks.rs index e48c8f398..e0798b4cb 100644 --- a/crates/horizon-client/src/game/block_entity_ticks.rs +++ b/crates/horizon-client/src/game/block_entity_ticks.rs @@ -56,6 +56,7 @@ impl Game<'_> { Some(BlockEntity::Beehive(_)) => self.tick_beehive(pos), Some(BlockEntity::Furnace(_)) => self.tick_furnace(pos)?, Some(BlockEntity::Brewing(_)) => self.tick_brewing_stand(pos)?, + Some(BlockEntity::Campfire(_)) => self.tick_campfire(pos)?, _ => {} } } @@ -92,7 +93,10 @@ impl Game<'_> { | "minecraft:vault" | "minecraft:beehive" | "minecraft:bee_nest" - | "minecraft:brewing_stand" => Ticking::Yes, + | "minecraft:brewing_stand" + // Lit, cookTick; unlit, cooldownTick. + | "minecraft:campfire" + | "minecraft:soul_campfire" => Ticking::Yes, "minecraft:jukebox" => { let record = registry .state(state) diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index 40dd1b7eb..06dfab22d 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/campfire.rs b/crates/horizon-client/src/game/campfire.rs new file mode 100644 index 000000000..c388b7561 --- /dev/null +++ b/crates/horizon-client/src/game/campfire.rs @@ -0,0 +1,190 @@ +//! Campfires' cooking: `CampfireBlock.useItemOn` (`CampfireBlockEntity.placeFood`) +//! and the block entity's `cookTick` (lit) and `cooldownTick` (unlit). The +//! items drawn on the fire are `campfire_geometry`'s; a server's clients get +//! them through the block entity's update tag (`lan::chunks::entity_tag`). +use super::Game; +use horizon_assets::item_model::DisplayContext; +use horizon_client::{ + Result, block_entities::Pos, block_entity_render::vertex_light, containers::BlockEntity, + items::ItemStack, mesher::Vertex, mobs::Who, +}; +use horizon_core::position::BlockPos; + +/// The `campfire_cooking` recipe kind (`RecipeType.CAMPFIRE_COOKING`). +const KIND: &str = "minecraft:campfire_cooking"; + +fn is_campfire(name: &str) -> bool { + name == "minecraft:campfire" || name == "minecraft:soul_campfire" +} + +impl Game<'_> { + /// `CampfireBlock.useItemOn` with a held item that is a campfire recipe's + /// input (`RecipePropertySet.CAMPFIRE_INPUT`): on a server level the food + /// goes into the first free slot (`placeFood`), and the use is consumed + /// whether or not there was room. A client of a server leaves the placing + /// to the server. Whether the food went in; None when this isn't a + /// campfire use, so the item's own use runs. + pub(super) fn use_on_campfire(&mut self, pos: [i32; 3]) -> Result> { + let state = self.world.block(pos[0], pos[1], pos[2]); + if !is_campfire(&self.res.facts().get(state).name) { + return Ok(None); + } + let Some(held) = self.held().cloned() else { + return Ok(None); + }; + let Some(time) = self.res.recipes().cook(KIND, &held).map(|r| r.time as i32) else { + return Ok(None); + }; + // A client of a server predicts the placing; the server decides. + if self.remote.is_some() { + return Ok(Some(true)); + } + let key = (pos[0], pos[1], pos[2]); + let placed = match self.world.block_entities.get_mut(&key) { + Some(BlockEntity::Campfire(c)) => { + let mut one = held.clone(); + c.place_food(&mut one, time) + } + _ => false, + }; + if placed { + // ItemStack.consumeAndReturn: creative keeps the item. + self.consume_held(); + self.stats.custom("interact_with_campfire", 1); + self.post_block_game_event( + "minecraft:block_change", + pos, + Some(Who::Player), + Some(state), + ); + self.mark_block_entity_updated(key); + } + Ok(Some(placed)) + } + + /// `CampfireBlockEntity.cookTick` of a lit campfire, `cooldownTick` of an + /// unlit one. A finished item's result (the recipe's, or the item itself + /// when no recipe takes it any more) drops at the block's corner + /// (`Containers.dropItemStack` at its integer position), then the clients + /// see the slot empty and a `block_change` goes out. + pub(super) fn tick_campfire(&mut self, pos: Pos) -> Result<()> { + let state = self.world.block(pos.0, pos.1, pos.2); + let lit = self + .pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("lit")) + .is_some_and(|v| v == "true"); + let Some(BlockEntity::Campfire(c)) = self.world.block_entities.get_mut(&pos) else { + return Ok(()); + }; + // BlockEntity.setChanged: a timer that moved is saved with the + // chunk (no update to the clients, who don't see the timers). + let changed = if lit { + c.items.iter().any(Option::is_some) + } else { + c.cooldown_tick() + }; + if changed { + self.world.modified.insert((pos.0 >> 4, pos.2 >> 4)); + } + if !lit { + return Ok(()); + } + let Some(BlockEntity::Campfire(c)) = self.world.block_entities.get_mut(&pos) else { + return Ok(()); + }; + let done = c.cook_tick(); + for (_, item) in done { + let result = self + .res + .recipes() + .cook(KIND, &item) + .map_or_else(|| item.clone(), |r| r.result.clone()); + self.campfire_drop(pos, result); + self.mark_block_entity_updated(pos); + self.post_block_game_event( + "minecraft:block_change", + [pos.0, pos.1, pos.2], + None, + Some(state), + ); + } + Ok(()) + } + + /// `CampfireRenderer`: each cooking item lies on the fire, slot `i` + /// turned to `Direction.from2DDataValue((i + facing) % 4)`, laid flat + /// (90° about X), at a corner and three eighths of its size, drawn as a + /// FIXED item seeded by the block's position plus the slot. + pub(super) fn campfire_geometry(&self, camera: glam::DVec3, out: &mut Vec) { + for (key, entity) in &self.world.block_entities { + let BlockEntity::Campfire(c) = entity else { + continue; + }; + if c.items.iter().all(Option::is_none) { + continue; + } + let at = glam::DVec3::new(f64::from(key.0), f64::from(key.1), f64::from(key.2)); + if at.distance_squared(camera) >= 64.0 * 64.0 { + continue; + } + // Direction.get2DDataValue: south 0, west 1, north 2, east 3. + let state = self.world.block(key.0, key.1, key.2); + let facing = match self + .pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("facing")) + .map(String::as_str) + { + Some("west") => 1, + Some("north") => 2, + Some("east") => 3, + _ => 0, + }; + let light = vertex_light(self.world.light(key.0, key.1, key.2)); + let packed = BlockPos::new(key.0, key.1, key.2).pack(); + for (i, stack) in c.items.iter().enumerate() { + let Some(stack) = stack else { + continue; + }; + let seed = (packed as i32).wrapping_add(i as i32); + let item = self.resolve_item(stack, DisplayContext::Fixed, None, seed); + if item.is_empty() { + continue; + } + // Direction.toYRot: 90° per 2D step from south. + let yaw = -(((i + facing) % 4) as f32 * 90.0); + let pose = glam::Mat4::from_translation( + (at - camera).as_vec3() + glam::Vec3::new(0.5, 0.449_218_75, 0.5), + ) * glam::Mat4::from_rotation_y(yaw.to_radians()) + * glam::Mat4::from_rotation_x(90f32.to_radians()) + * glam::Mat4::from_translation(glam::Vec3::new(-0.3125, -0.3125, 0.0)) + * glam::Mat4::from_scale(glam::Vec3::splat(0.375)); + self.submit_item_world(&item, pose, light, out); + } + } + } + + /// `Containers.dropItemStack(level, x, y, z, stack)` at the block's + /// integer position. + fn campfire_drop(&mut self, pos: Pos, stack: ItemStack) { + let at = BlockPos::new(pos.0, pos.1, pos.2); + for piece in + horizon_world::level::removal::drop_item_stack(&mut self.world.random, at, stack.count) + { + self.spawn_item( + ItemStack { + count: piece.count, + ..stack.clone() + }, + piece.pos, + piece.motion, + 0, + ); + } + } +} diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index ce97fcd52..6602055ea 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -373,6 +373,7 @@ impl Game<'_> { // Drawn seated (Entity.isPassenger); set apart because the // json! above is at the macro recursion limit. state["passenger"] = m.extra.passenger.into(); + state["guardian_beam"] = serde_json::json!(horizon_client::mobs::guardian::beam(m, 0.0)); state }) .collect(); @@ -1065,7 +1066,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, diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index e33064531..c75c2c762 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -1560,6 +1560,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, @@ -2022,6 +2023,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, @@ -2068,6 +2070,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, @@ -2197,15 +2200,58 @@ 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: `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, + ); + } +} 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/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, ); } } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 9f468db9f..63aea7e9f 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -14,7 +14,7 @@ use horizon_client::{ hub::{HostEvent, HostState, Hub, HubConfig, TickCtx}, playerdata, }, - mobs::{Mob, leash::Holder}, + mobs::{Mob, Who, leash::Holder}, text::Text, }; use horizon_core::geometry::Vec3; @@ -147,6 +147,7 @@ pub(super) fn baby_index(kind: &str) -> Option { fn mob_meta( m: &Mob, hub: &Hub, + player_entity: Option, meta: &mut Vec<(u8, i32, Value)>, defaults: &mut Vec<(u8, i32, Value)>, ) { @@ -196,6 +197,25 @@ fn mob_meta( let e = &m.extra; let id = |registry: &str, name: &str| hub.registry_id(registry, &format!("minecraft:{name}")); match kind { + "minecraft:guardian" | "minecraft:elder_guardian" => { + // Guardian.DATA_ID_MOVING and DATA_ID_ATTACK_TARGET. + if e.flag2 { + meta.push((16, serializer::BOOLEAN, Value::Bool(true))); + } + let target = if e.flag { + m.ai.target.and_then(|who| match who { + Who::Player => player_entity, + Who::Mob(id) => Some(id as i32), + }) + } else { + None + }; + if let Some(target) = target { + meta.push((17, serializer::INT, Value::Int(target))); + } + defaults.push((16, serializer::BOOLEAN, Value::Bool(false))); + defaults.push((17, serializer::INT, Value::Int(0))); + } // Bat.DATA_ID_FLAGS: resting in bit 0, flying by default. "minecraft:bat" => { if e.flag { @@ -831,12 +851,13 @@ impl Game<'_> { for m in self.mobs.iter().filter(|m| !m.removed) { // The lead's holder: the player the mob sees (a guest, else the // host) or another mob. A fence knot isn't an entity here. + let player_entity = mob_players + .get(&m.id) + .and_then(|conn| hub.guest(*conn)) + .map(|g| g.entity_id) + .or(host_entity); let leash = m.extra.leash.and_then(|h| match h { - Holder::Player => mob_players - .get(&m.id) - .and_then(|conn| hub.guest(*conn)) - .map(|g| g.entity_id) - .or(host_entity), + Holder::Player => player_entity, Holder::Mob(id) => Some(id as i32), Holder::Knot(_) => None, }); @@ -846,7 +867,7 @@ impl Game<'_> { e.on_ground = m.on_ground; e.velocity = [m.velocity.x, m.velocity.y, m.velocity.z]; e.needs_sync = m.needs_sync; - mob_meta(m, hub, &mut e.meta, &mut e.defaults); + mob_meta(m, hub, player_entity, &mut e.meta, &mut e.defaults); mob_equipment(m, hub, &mut e.equipment); self.mob_attributes(m, &mut e.attributes); e.leash = leash; diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index e1a13881c..43bb573dc 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. @@ -875,7 +879,11 @@ impl Game<'_> { .filter(|g| host.hub.here(g)) .filter(|g| { g.menu.as_ref().is_some_and(|m| { - m.slots.valid(&self.world) && !m.slots.still_valid(&self.world, g, m.pos) + (m.slots.valid(&self.world) && !m.slots.still_valid(&self.world, g, m.pos)) + || m.pos.is_some_and(|k| { + k.1 == super::minecarts::CART_KEY_Y + && !self.chest_vehicle_still_valid(k.2, g) + }) }) }) .map(|g| g.conn) @@ -889,6 +897,35 @@ impl Game<'_> { } } + /// `ContainerEntity.isChestVehicleStillValid`: the chest minecart or chest + /// boat is still there and within the guest's entity interaction range + /// plus 4 of its box. + fn chest_vehicle_still_valid(&self, id: i32, g: &horizon_client::lan::guest::Guest) -> bool { + let bounds = self + .carts + .iter() + .find(|c| c.id as i32 == id) + .map(|c| c.bounds()) + .or_else(|| { + self.boats + .iter() + .find(|b| b.id as i32 == id) + .map(|b| b.bounds()) + }); + let Some(b) = bounds else { + return false; + }; + let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]]; + let (lo, hi) = (b.min_position(), b.max_position()); + let d = [ + eye[0] - eye[0].clamp(lo.x, hi.x), + eye[1] - eye[1].clamp(lo.y, hi.y), + eye[2] - eye[2].clamp(lo.z, hi.z), + ]; + let range = if g.creative() { 5.0 } else { 3.0 } + 4.0; + d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < range * range + } + /// A packet from a guest that the hub does not handle itself. pub(super) fn lan_guest_packet(&mut self, host: &mut LanHost, conn: u32, packet: S) { let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { @@ -1314,6 +1351,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/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 776466c25..529666590 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -289,6 +289,10 @@ 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)); + self.dragon_fireballs + .iter_mut() + .for_each(|b| give(&mut b.id)); } /// Primed TNT, falling blocks, projectiles, tridents, firework rockets and @@ -445,6 +449,35 @@ 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.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))); + 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 719fe79ab..c41fdf1ad 100644 --- a/crates/horizon-client/src/game/lan_particles.rs +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -95,7 +95,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/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index 1bec9809d..7beeeba2f 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -144,15 +144,16 @@ impl Game<'_> { .offers .iter() .filter_map(|o| { - let cost = - |st: &ItemStack, hub: &mut horizon_client::lan::hub::Hub| play::NetCost { - item: hub.item_id(&st.item), - count: st.count as i32, - }; + let cost = |st: &ItemStack, hub: &mut horizon_client::lan::hub::Hub| { + hub.stack(&Some(st.clone())).map(play::NetCost::from) + }; Some(play::NetOffer { - cost_a: cost(&o.base_cost_a.stack, &mut host.hub), + cost_a: cost(&o.base_cost_a.stack, &mut host.hub)?, result: host.hub.stack(&Some(o.result.clone()))?, - cost_b: o.cost_b.as_ref().map(|b| cost(&b.stack, &mut host.hub)), + cost_b: match &o.cost_b { + Some(b) => Some(cost(&b.stack, &mut host.hub)?), + None => None, + }, out_of_stock: o.out_of_stock(), uses: o.uses, max_uses: o.max_uses, diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index a19b6df73..f5f748a49 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 } @@ -97,7 +97,7 @@ fn display_offset(kind: CartKind) -> f64 { /// The minecart's passenger attachment minus Player.DEFAULT_VEHICLE_ATTACHMENT. pub(super) const SEAT: f64 = 0.1875 - 0.6; /// The placeholder container key under which an open cart's items live. -pub(super) const CART_KEY_Y: i32 = -100_000; +pub(super) const CART_KEY_Y: i32 = horizon_client::lan::menu::VEHICLE_KEY_Y; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(super) enum Shape { diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index e2df267f4..d6e38dbbf 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -68,6 +68,10 @@ pub(super) struct ModsState { /// is still being shown, and a mod answering its own lines would recurse. #[cfg(feature = "mods")] commands: Vec, + /// `command.run-quiet` batches for this window's own world, by mod id, + /// run on the next tick as `commands` are. + #[cfg(feature = "mods")] + quiet: Vec<(String, Vec)>, /// The server's command tree with the running mods' commands added. #[cfg(feature = "mods")] remote_tree: Option, @@ -505,6 +509,51 @@ impl Game<'_> { } None } + /// A mod's `command.run-quiet` lines (vanilla's commands only, as + /// `command.run`): to a server that runs them quietly as one payload + /// (`horizon_protocol::quiet`), to any other as chat commands, or for this + /// window's own world next tick. + fn mod_quiet_commands(&mut self, mod_id: String, lines: Vec) { + let lines: Vec = lines + .into_iter() + .filter(|l| vanilla_command(l.split(' ').next().unwrap_or_default())) + .collect(); + match self.remote.as_ref().map(|r| r.quiet_commands) { + Some(true) => { + for data in horizon_protocol::quiet::encode(&mod_id, &lines) { + self.send(horizon_protocol::packets::play::Serverbound::CustomPayload( + horizon_protocol::packets::configuration::CustomPayload { + channel: horizon_protocol::quiet::CHANNEL.into(), + data, + }, + )); + } + } + // The server checks the player's permissions; its feedback shows. + Some(false) => { + for line in lines { + self.send_chat(&format!("/{line}")); + } + } + None => self.mods.quiet.push((mod_id, lines)), + } + } + /// A quiet batch in this window's own world, as a server runs one + /// (game/lan_quiet.rs): each line as the player typing it, no chat, a + /// chat message refused; one line in the log. + fn run_quiet_batch(&mut self, mod_id: &str, lines: &[String]) { + let permission = self.ui.registries.permission; + let mut failed = 0; + for line in lines { + let ok = self.signable_arguments(permission, line).is_empty() + && self.run_command_quietly(line); + failed += usize::from(!ok); + } + log::info!( + "[mod {mod_id}] ran {} quiet command(s): {failed} failed", + lines.len() + ); + } /// A game tick. pub(super) fn tick_mods(&mut self) { // Here, at the player's level: shown inside a console call (a control @@ -512,6 +561,9 @@ impl Game<'_> { for line in std::mem::take(&mut self.mods.commands) { self.run_command(&line); } + for (mod_id, lines) in std::mem::take(&mut self.mods.quiet) { + self.run_quiet_batch(&mod_id, &lines); + } if !self.mods.mods.is_running() { return; } @@ -606,6 +658,10 @@ impl Game<'_> { } continue; } + Output::QuietCommands { mod_id, lines } => { + self.mod_quiet_commands(mod_id, lines); + continue; + } Output::Stopped { name, reason } => { // Its screen goes with it: the entry's run is gone, so // `mod_ui_view` finds no widgets and the screen closes. 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: diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 0b14db314..13eae7d3e 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.rs b/crates/horizon-client/src/game/remote.rs index 309fd38bb..3ef87c201 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -109,6 +109,8 @@ enum Received { pub(super) struct Remote { pub session: Session, pub brand: String, + /// The server announced it runs mods' quiet commands. + pub quiet_commands: bool, pub(super) builtin: Arc, lang: Arc, pub(super) registries: Arc, @@ -419,6 +421,7 @@ impl Game<'_> { self.remote = Some(Remote { session, brand: "unknown".into(), + quiet_commands: false, builtin: Arc::new(builtin), lang, registries: Arc::new(Dynamic::default()), @@ -839,6 +842,11 @@ impl Game<'_> { remote.brand = brand; } } + Event::QuietCommands => { + if let Some(remote) = &mut self.remote { + remote.quiet_commands = true; + } + } Event::Reconfigured(registries) => { self.boss_overlay.reset(); self.set_registries(registries); @@ -1398,6 +1406,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; } @@ -2979,6 +2995,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() @@ -3462,6 +3480,13 @@ impl Game<'_> { if m.species() == horizon_client::mobs::Species::Creeper { horizon_client::mobs::hostile::creeper_client_tick(m); } + if matches!( + m.species(), + horizon_client::mobs::Species::Guardian + | horizon_client::mobs::Species::ElderGuardian + ) { + horizon_client::mobs::guardian::client_tick(m); + } if m.hurt_time > 0 { m.hurt_time -= 1; } @@ -3734,6 +3759,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; }; @@ -4868,16 +4902,20 @@ impl Game<'_> { if self.open_menu_name(p.container) != "minecraft:merchant" { return; } - let cost = |g: &Self, c: &play::NetCost| horizon_client::merchant::ItemCost { - stack: ItemStack::new(&g.item_name(c.item), c.count.max(0) as u32), + let cost = |g: &Self, c: &play::NetCost| { + g.to_stack(&Some(c.clone().into())) + .map(|stack| horizon_client::merchant::ItemCost { stack }) }; let offers: Vec<_> = p .offers .iter() .filter_map(|o| { let mut offer = horizon_client::merchant::MerchantOffer { - base_cost_a: cost(self, &o.cost_a), - cost_b: o.cost_b.as_ref().map(|b| cost(self, b)), + base_cost_a: cost(self, &o.cost_a)?, + cost_b: match &o.cost_b { + Some(b) => Some(cost(self, b)?), + None => None, + }, result: self.to_stack(&Some(o.result.clone()))?, uses: o.uses, max_uses: o.max_uses, diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index 5ea772307..c6702dfb6 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -4,14 +4,14 @@ //! own simulation, which a client of a server doesn't run. use super::Game; use horizon_client::mobs::render::{PROFESSIONS, VILLAGER_TYPES}; -use horizon_client::mobs::{Mob, Species, bat, tame}; +use horizon_client::mobs::{Mob, Species, Who, bat, tame}; use horizon_protocol::entity_data::Value; use horizon_protocol::registry::Builtin; /// The values `apply` takes from one SetEntityData packet, by vanilla's entry /// indices (Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses). /// `builtin` names the ids of built-in registries. -fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin) { +fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_entity: i32) { let species = m.species(); let baby = super::lan::baby_index(&m.kind.id); for (index, _, value) in values { @@ -46,6 +46,19 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin) { _ => {} } match (species, *index, value) { + (Species::Guardian | Species::ElderGuardian, 16, Value::Bool(moving)) => { + m.extra.flag2 = *moving; + } + (Species::Guardian | Species::ElderGuardian, 17, Value::Int(target)) => { + // Guardian.onSyncedDataUpdated resets the visual charge clock. + m.extra.counter2 = 0; + m.extra.flag = *target != 0; + m.ai.target = (*target != 0).then_some(if *target == local_entity { + Who::Player + } else { + Who::Mob(*target as u32) + }); + } // Bat.DATA_ID_FLAGS: resting in bit 0. (Species::Bat, 16, Value::Byte(flags)) => bat::set_resting(m, flags & 1 != 0), // Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 sheared. @@ -116,7 +129,7 @@ impl Game<'_> { return; }; if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) { - apply(m, values, &r.builtin); + apply(m, values, &r.builtin, r.entity_id); } } } @@ -153,7 +166,7 @@ mod tests { } fn apply(m: &mut Mob, values: &[(u8, i32, Value)]) { - super::apply(m, values, &builtin()); + super::apply(m, values, &builtin(), 99); } fn mob(kind: &str) -> Option { @@ -164,6 +177,49 @@ mod tests { Some(m) } + #[test] + fn guardian_charge_follows_target_updates_and_caps_at_its_duration() { + use horizon_client::mobs::guardian::{beam, client_tick}; + for (kind, duration) in [("guardian", 80), ("elder_guardian", 60)] { + let Some(mut m) = mob(&format!("minecraft:{kind}")) else { + return; + }; + assert!(beam(&m, 0.0).is_none()); + apply( + &mut m, + &[ + (16, s::BOOLEAN, Value::Bool(true)), + (17, s::INT, Value::Int(99)), + ], + ); + assert!(m.extra.flag2); + assert_eq!(m.ai.target, Some(Who::Player)); + assert_eq!(beam(&m, 0.0), Some((0.0, 0.0))); + for _ in 0..duration + 10 { + client_tick(&mut m); + } + assert_eq!(beam(&m, 0.0), Some((duration as f32, 1.0))); + // Another player or a mob retains its network entity id. + apply(&mut m, &[(17, s::INT, Value::Int(42))]); + assert_eq!(m.ai.target, Some(Who::Mob(42))); + assert_eq!(m.extra.counter2, 0); + client_tick(&mut m); + assert_eq!(m.extra.counter2, 1); + apply( + &mut m, + &[ + (16, s::BOOLEAN, Value::Bool(false)), + (17, s::INT, Value::Int(0)), + ], + ); + client_tick(&mut m); + assert!(!m.extra.flag2); + assert_eq!(m.ai.target, None); + assert_eq!(m.extra.counter2, 0); + assert!(beam(&m, 0.0).is_none()); + } + } + #[test] fn a_sheep_takes_its_wool_and_a_calf_its_size() { let Some(mut m) = mob("minecraft:sheep") else { diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index ac0413cc6..897999c6b 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::{Hit, Projectile, ProjectileKind, ProjectileWorld}; -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 { @@ -118,6 +133,16 @@ 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, + 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]) @@ -151,6 +176,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) { @@ -336,6 +386,75 @@ impl Game<'_> { self.step_remote_thrown(); self.step_remote_hooks(&mut step); self.end.step_remote_eyes(); + 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 + /// 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) { @@ -346,6 +465,8 @@ 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.dragon_fireballs.retain(|b| b.id != id); self.end.remove_remote_eye(id); self.remove_remote_hook(id); } @@ -361,6 +482,8 @@ impl Game<'_> { // The dragon a server sent goes with its crystals. self.dragon = None; self.potions.clear_thrown(); + self.potions.clouds.clear(); + self.dragon_fireballs.clear(); self.end.clear_remote_eyes(); self.clear_remote_hooks(); } 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/game/spill.rs b/crates/horizon-client/src/game/spill.rs index b7283c57b..7f370507f 100644 --- a/crates/horizon-client/src/game/spill.rs +++ b/crates/horizon-client/src/game/spill.rs @@ -398,8 +398,12 @@ impl GameLevel<'_> { } } PreRemove::Campfire => { - for _ in 0..4 { - self.drop_item_stack(pos, None); + let items = match &entity { + Some(BlockEntity::Campfire(c)) => c.items.clone(), + _ => Default::default(), + }; + for stack in items { + self.drop_item_stack(pos, stack); } } PreRemove::Jukebox => { diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 2b51a81a1..56b19e393 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -1703,6 +1703,8 @@ impl Game<'_> { }; let name = if let Some(n) = stack.custom_name() { n.to_owned() + } else if let Some(n) = stack.item_name() { + n } else if stack.data().is_some_and(|d| d.ominous_banner) { self.translate("block.minecraft.ominous_banner", "Ominous Banner") } else if stack.data().and_then(|d| d.potion.as_ref()).is_some() @@ -1729,7 +1731,9 @@ impl Game<'_> { // ItemContainerContents.addToTooltip. let hover_name = |s: &ItemStack| { s.custom_name() - .map_or_else(|| self.pack.names.display_item(&s.item), str::to_owned) + .map(str::to_owned) + .or_else(|| s.item_name()) + .unwrap_or_else(|| self.pack.names.display_item(&s.item)) }; if display.shows("minecraft:container") { for text in diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index c07e2f352..ac624e85b 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -204,6 +204,14 @@ impl ItemStack { pub fn custom_name(&self) -> Option<&str> { self.data().and_then(|d| d.custom_name.as_deref()) } + /// `minecraft:item_name` in the current language (`getItemName`'s + /// component). It stays in the patch as loaded, so a translatable name + /// saves and reaches clients unchanged; the ominous banner's is modelled + /// by `ominous_banner` instead. + pub fn item_name(&self) -> Option { + let name = self.data()?.other("minecraft:item_name")?; + Some(crate::entity_nbt::name_text(name).plain()) + } pub fn potion(&self) -> Option<&str> { self.data().and_then(|d| d.potion.as_deref()) } diff --git a/crates/horizon-client/src/item_sync.rs b/crates/horizon-client/src/item_sync.rs index d18ed3af5..fc35e15e7 100644 --- a/crates/horizon-client/src/item_sync.rs +++ b/crates/horizon-client/src/item_sync.rs @@ -238,6 +238,85 @@ mod tests { use super::*; use horizon_protocol::registry::Ids; + #[test] + fn merchant_water_cost_survives_the_offer_packet() { + use horizon_protocol::{ + buf::{Codec, Reader, Writer}, + packets::play::{NetOffer, Offers}, + }; + let mut components = vec![String::new(); component::POTION_CONTENTS as usize + 1]; + components[component::POTION_CONTENTS as usize] = "minecraft:potion_contents".into(); + let builtin = Builtin { + registries: [ + ( + "minecraft:item".into(), + Ids::from_names(vec!["minecraft:potion".into(), "minecraft:emerald".into()]), + ), + ( + "minecraft:potion".into(), + Ids::from_names(vec!["minecraft:water".into()]), + ), + ( + "minecraft:data_component_type".into(), + Ids::from_names(components), + ), + ] + .into(), + }; + let dynamic = Dynamic::default(); + let water = ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"); + let wire = crate::lan::guest::stack_to_network( + |name| builtin.get("minecraft:item").unwrap().id(name).unwrap(), + |registry, name| builtin.get(registry)?.id(name), + &Some(water.clone()), + ) + .unwrap(); + let offers = vec![NetOffer { + cost_a: wire.into(), + result: Stack::new(1, 1), + cost_b: Some(Stack::new(1, 2).into()), + out_of_stock: false, + uses: 0, + max_uses: 2, + xp: 0, + special_price: 0, + price_multiplier: 0.05, + demand: 0, + }]; + let mut w = Writer::new(); + Offers::write(&offers, &mut w); + let mut r = Reader::new(&w.data); + let decoded = Offers::read(&mut r).unwrap(); + assert_eq!(r.remaining(), 0); + let cost = crate::merchant::ItemCost { + stack: from_network(&decoded[0].cost_a.clone().into(), &builtin, &dynamic), + }; + assert_eq!(cost.stack, water); + assert_eq!(cost.stack.potion(), Some("minecraft:water")); + let authoritative = crate::merchant::ItemCost { + stack: water.clone(), + }; + for payment in [ + water, + ItemStack::new("minecraft:potion", 1).with_potion("minecraft:swiftness"), + ItemStack::new("minecraft:potion", 1), + ] { + assert_eq!(cost.test(&payment), authoritative.test(&payment)); + } + assert!(cost.test(&ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"))); + assert!( + !cost.test(&ItemStack::new("minecraft:potion", 1).with_potion("minecraft:swiftness")) + ); + let emerald = crate::merchant::ItemCost { + stack: from_network( + &decoded[0].cost_b.clone().unwrap().into(), + &builtin, + &dynamic, + ), + }; + assert!(emerald.test(&ItemStack::new("minecraft:emerald", 2))); + } + /// A bundle's contents cross the wire, so a server's client can draw /// its tooltip (BundleContents' stream codec: a list of templates). #[test] @@ -286,6 +365,7 @@ mod tests { for (id, name) in [ (component::DAMAGE, "minecraft:damage"), (component::CUSTOM_NAME, "minecraft:custom_name"), + (component::ITEM_NAME, "minecraft:item_name"), (component::ENCHANTMENTS, "minecraft:enchantments"), (component::POTION_CONTENTS, "minecraft:potion_contents"), (component::REPAIR_COST, "minecraft:repair_cost"), @@ -345,6 +425,10 @@ mod tests { .push((Arc::from("minecraft:sharpness"), 2)); d.repair_cost = 9; d.custom_name = Some("Keeper".to_owned()); + // A translatable item name reaches the client as the same component. + let item_name = Tag::compound([("translate", Tag::String("filled_map.monument".into()))]); + d.other + .push(("minecraft:item_name".into(), item_name.clone())); d.trim = Some((Arc::from("minecraft:gold"), Arc::from("minecraft:sentry"))); let id = |registry: &str, name: &str| { builtin @@ -374,6 +458,7 @@ mod tests { ); assert_eq!(d.repair_cost, 9); assert_eq!(d.custom_name.as_deref(), Some("Keeper")); + assert_eq!(d.other("minecraft:item_name"), Some(&item_name)); assert_eq!( d.trim, Some((Arc::from("minecraft:gold"), Arc::from("minecraft:sentry"))) diff --git a/crates/horizon-client/src/item_tooltip.rs b/crates/horizon-client/src/item_tooltip.rs index cb52965a0..88f01439e 100644 --- a/crates/horizon-client/src/item_tooltip.rs +++ b/crates/horizon-client/src/item_tooltip.rs @@ -188,6 +188,9 @@ pub fn name_line(stack: &ItemStack, translate: &dyn Fn(&str) -> Option) if let Some(name) = stack.custom_name() { return name.to_owned(); } + if let Some(name) = stack.item_name() { + return name; + } if stack.data().is_some_and(|d| d.ominous_banner) { return translate("block.minecraft.ominous_banner") .unwrap_or_else(|| "Ominous Banner".to_owned()); @@ -611,6 +614,14 @@ mod tests { assert_eq!(rarity(&banner, "common"), "uncommon"); banner.data_mut().custom_name = Some("Captain's Standard".into()); assert_eq!(name_line(&banner, &translate), "Captain's Standard"); + let mut custom_item = ItemStack::new("minecraft:diamond_sword", 1); + custom_item.data_mut().other.push(( + "minecraft:item_name".into(), + Tag::String("Excalibur".into()), + )); + assert_eq!(name_line(&custom_item, &translate), "Excalibur"); + custom_item.data_mut().custom_name = Some("Custom Blade".into()); + assert_eq!(name_line(&custom_item, &translate), "Custom Blade"); banner.enchant("minecraft:unbreaking", 1); assert_eq!(rarity(&banner, "common"), "rare"); let plain = ItemStack::new("minecraft:white_banner", 1); diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index e34471966..b4092a201 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`. @@ -558,6 +560,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. @@ -758,6 +764,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/crates/horizon-client/src/lan/chunks.rs b/crates/horizon-client/src/lan/chunks.rs index d7dcc6cd8..122d37bcd 100644 --- a/crates/horizon-client/src/lan/chunks.rs +++ b/crates/horizon-client/src/lan/chunks.rs @@ -952,6 +952,11 @@ pub fn entity_tag(entity: &BlockEntity) -> Option { Some(Tag::compound(entries)) } BlockEntity::Jukebox(_) | BlockEntity::Lectern(_) => None, + // CampfireBlockEntity.getUpdateTag: the items alone. + BlockEntity::Campfire(c) => Some(Tag::compound([( + "Items", + crate::save::encode_items(&c.items), + )])), _ => None, } } diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 9224d3711..7e43cf04e 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, @@ -645,6 +648,13 @@ fn network_stack( horizon_protocol::item::Component::Text(horizon_protocol::text::literal(name)), )); } + // The component as loaded, so a translatable name stays one. + if let Some(name) = s.data().and_then(|d| d.other("minecraft:item_name")) { + stack.added.push(( + horizon_protocol::item::component::ITEM_NAME, + horizon_protocol::item::Component::Text(name.clone()), + )); + } Some(stack) } diff --git a/crates/horizon-client/src/lan/menu.rs b/crates/horizon-client/src/lan/menu.rs index 4185dadc4..859bafa23 100644 --- a/crates/horizon-client/src/lan/menu.rs +++ b/crates/horizon-client/src/lan/menu.rs @@ -37,6 +37,10 @@ pub struct Menu { pub sent_data: Vec, } +/// The y of the key a chest minecart's or chest boat's items are kept under +/// while a menu shows them. +pub const VEHICLE_KEY_Y: i32 = -100_000; + /// Where the slots of a container menu live. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Slots { @@ -72,10 +76,12 @@ impl Slots { Slots::Ender => at.into_iter().collect(), _ => self.halves(), }; + // A vehicle's container is kept under a key, not a block: the game + // checks its reach to the vehicle (`isChestVehicleStillValid`). self.valid(world) && blocks .iter() - .all(|k| guest.within_block_range([k.0, k.1, k.2], 4.0)) + .all(|k| k.1 == VEHICLE_KEY_Y || guest.within_block_range([k.0, k.1, k.2], 4.0)) } /// Container slot `n`. pub fn get(self, world: &World, guest: &Guest, mut n: usize) -> Option { 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. diff --git a/crates/horizon-client/src/mobs/guardian.rs b/crates/horizon-client/src/mobs/guardian.rs index d6219794d..9704de044 100644 --- a/crates/horizon-client/src/mobs/guardian.rs +++ b/crates/horizon-client/src/mobs/guardian.rs @@ -241,9 +241,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } else { a.v[SPIKES] += (1.0 - a.v[SPIKES]) * 0.06; } - if m.extra.flag && m.extra.counter2 < attack_duration(m) { - m.extra.counter2 += 1; - } + client_tick(m); if in_water { m.air = 300; } else if m.on_ground { @@ -332,6 +330,13 @@ pub fn elder_server_ai_step(m: &mut Mob, cx: &mut Cx) { ]); } } +/// Guardian.aiStep's visual attack clock, also used by server clients. +/// Does not run attack goals, movement, damage or random draws. +pub fn client_tick(m: &mut Mob) { + if m.extra.flag && m.extra.counter2 < attack_duration(m) { + m.extra.counter2 += 1; + } +} /// The beam's clock for rendering: (attack time with the partial tick, /// attack scale), while a target is locked. pub fn beam(m: &Mob, partial: f32) -> Option<(f32, f32)> { diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs index 0eb260477..34daaf85c 100644 --- a/crates/horizon-client/src/net.rs +++ b/crates/horizon-client/src/net.rs @@ -40,6 +40,8 @@ pub enum Event { Status(String), /// The server's `minecraft:brand` custom payload. Brand(String), + /// The server runs mods' quiet commands (`horizon_protocol::quiet`). + QuietCommands, /// Configuration finished: the play state begins with these registries. Joined { registries: Arc, @@ -668,6 +670,8 @@ fn receive_brand(payload: &cfg::CustomPayload, send: &Sender) { && let Ok(brand) = horizon_protocol::buf::Reader::new(&payload.data).string(32767) { let _ = send.send(Event::Brand(brand)); + } else if payload.channel == horizon_protocol::quiet::CHANNEL { + let _ = send.send(Event::QuietCommands); } } diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 830198174..075534c09 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -526,6 +526,12 @@ pub fn encode_block_entity( } } BlockEntity::Sculk(s) => entries.extend(s.to_nbt()), + // CampfireBlockEntity.saveAdditional. + BlockEntity::Campfire(c) => { + entries.push(("Items", encode_items(&c.items))); + entries.push(("CookingTimes", Tag::IntArray(c.progress.to_vec()))); + entries.push(("CookingTotalTimes", Tag::IntArray(c.total.to_vec()))); + } BlockEntity::Crafter(c) => { entries.push(("Items", encode_items(&c.items))); entries.push(( @@ -706,6 +712,18 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain } BlockEntity::Sign(sign) => sign.decode(tag), BlockEntity::Sculk(s) => s.load(tag), + // CampfireBlockEntity.loadAdditional: missing time arrays stay zeros. + BlockEntity::Campfire(c) => { + for (slot, item) in decode_items(tag.get("Items"), 4).into_iter().enumerate() { + c.items[slot] = item; + } + let ints = |key: &str| match tag.get(key) { + Some(Tag::IntArray(v)) => std::array::from_fn(|i| v.get(i).copied().unwrap_or(0)), + _ => [0; 4], + }; + c.progress = ints("CookingTimes"); + c.total = ints("CookingTotalTimes"); + } BlockEntity::Crafter(c) => { for (slot, item) in decode_items(tag.get("Items"), 9).into_iter().enumerate() { c.items[slot] = item; @@ -736,18 +754,67 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain Some((pos, entity)) } +/// What a dimension's saved chunks depend on: skylight and the build height +/// (`DimensionType.minY` and `height`). `Chunk` always holds the Overworld's +/// sections; a level saves only the ones inside its own height. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct LevelShape { + pub sky_light: bool, + pub min_y: i32, + pub height: i32, +} +impl LevelShape { + pub const OVERWORLD: Self = Self { + sky_light: true, + min_y: MIN_Y, + height: SECTIONS as i32 * 16, + }; + pub const NETHER: Self = Self { + sky_light: false, + min_y: 0, + height: 256, + }; + pub const END: Self = Self { + sky_light: true, + min_y: 0, + height: 256, + }; + /// The shape of a dimension folder (`dimensions/minecraft/`, or the + /// old `DIM-1` and `DIM1`). + pub fn for_dir(root: &Path) -> Self { + if root.ends_with("the_nether") || root.ends_with("DIM-1") { + Self::NETHER + } else if root.ends_with("the_end") || root.ends_with("DIM1") { + Self::END + } else { + Self::OVERWORLD + } + } + fn min_section(self) -> i32 { + self.min_y >> 4 + } + fn section_count(self) -> usize { + (self.height >> 4) as usize + } + fn has_section(self, y: i32) -> bool { + (self.min_section()..self.min_section() + self.section_count() as i32).contains(&y) + } +} + /// A column's sections as `Heightmap.primeHeightmaps` reads them. struct HeightmapView<'a> { sections: &'a [Arc
], tables: &'a SaveTables, + min_y: i32, + height: i32, } impl HeightmapChunk for HeightmapView<'_> { type State = crate::assets::StateFacts; fn min_y(&self) -> i32 { - MIN_Y + self.min_y } fn height(&self) -> i32 { - SECTIONS as i32 * 16 + self.height } fn highest_section_y(&self) -> i32 { let top = self @@ -767,7 +834,7 @@ impl HeightmapChunk for HeightmapView<'_> { } } /// Heightmaps kept after world generation (`ChunkStatus.FULL.heightmapsAfter`). -fn heightmaps(chunk: &Chunk, tables: &SaveTables) -> Tag { +fn heightmaps(chunk: &Chunk, tables: &SaveTables, shape: LevelShape) -> Tag { let kinds = [ HeightmapType::WorldSurface, HeightmapType::OceanFloor, @@ -776,11 +843,13 @@ fn heightmaps(chunk: &Chunk, tables: &SaveTables) -> Tag { ]; let mut maps: Vec = kinds .iter() - .filter_map(|k| Heightmap::new(*k, MIN_Y, SECTIONS as i32 * 16).ok()) + .filter_map(|k| Heightmap::new(*k, shape.min_y, shape.height).ok()) .collect(); let view = HeightmapView { sections: &chunk.sections, tables, + min_y: shape.min_y, + height: shape.height, }; let mut refs: Vec<&mut Heightmap> = maps.iter_mut().collect(); if Heightmap::prime(&view, &mut refs).is_err() { @@ -810,7 +879,12 @@ pub fn client_heightmaps_in( .iter() .filter_map(|(id, k)| Heightmap::new(*k, min_y, height).ok().map(|m| (*id, m))) .collect(); - let view = HeightmapView { sections, tables }; + let view = HeightmapView { + sections, + tables, + min_y, + height, + }; let mut refs: Vec<&mut Heightmap> = maps.iter_mut().map(|(_, m)| m).collect(); if Heightmap::prime(&view, &mut refs).is_err() { return Vec::new(); @@ -836,17 +910,18 @@ fn nibbles(light: &Light, sky: bool) -> Vec { } pub fn encode(chunk: &Chunk, registry: &BlockRegistry, biomes: &Biomes) -> NamedTag { - encode_with(chunk, registry, biomes, None, true) + encode_with(chunk, registry, biomes, None, LevelShape::OVERWORLD) } /// The chunk NBT vanilla's `SerializableChunkData.write` produces for a full -/// chunk. `sky_light` is false in dimensions without skylight. +/// chunk in a level of `shape`. pub fn encode_with( chunk: &Chunk, registry: &BlockRegistry, biomes: &Biomes, tables: Option<&SaveTables>, - sky_light: bool, + shape: LevelShape, ) -> NamedTag { + let sky_light = shape.sky_light; let mut sections = Vec::new(); let air = tables.map_or(0, |t| t.air); // Sky layers below the highest section with light other than 15 are @@ -858,6 +933,9 @@ pub fn encode_with( }); for (si, section) in chunk.sections.iter().enumerate() { let y = (MIN_Y >> 4) + si as i32; + if !shape.has_section(y) { + continue; + } // PalettedContainer.pack: distinct states in index order, indices at // the saved width. let packed = section.blocks.pack(); @@ -987,7 +1065,7 @@ pub fn encode_with( ("DataVersion", Tag::Int(DATA_VERSION)), ("xPos", Tag::Int(chunk.x)), ("zPos", Tag::Int(chunk.z)), - ("yPos", Tag::Int(MIN_Y >> 4)), + ("yPos", Tag::Int(shape.min_section())), ("Status", string("minecraft:full")), ("LastUpdate", Tag::Long(extras.map_or(0, |e| e.last_update))), ("isLightOn", Tag::Byte(i8::from(chunk.lit))), @@ -1019,11 +1097,30 @@ 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])); + .or_insert_with(|| Tag::List(vec![Tag::List(Vec::new()); shape.section_count()])); } if let Some(t) = tables { - put(&mut root, "Heightmaps", heightmaps(chunk, t)); + put(&mut root, "Heightmaps", heightmaps(chunk, t, shape)); let names = |k: u32| t.block_names.get(k as usize).cloned(); let (blocks, fluids) = extras.map_or((&[][..], &[][..]), |e| { (&e.block_ticks[..], &e.fluid_ticks[..]) @@ -1239,18 +1336,19 @@ pub fn encode_proto( registry: &BlockRegistry, biomes: &Biomes, tables: Option<&SaveTables>, - sky_light: bool, + shape: LevelShape, ) -> NamedTag { - let mut root = encode_with(&proto.column, registry, biomes, tables, sky_light); + let mut root = encode_with(&proto.column, registry, biomes, tables, shape); let status = if proto.decorated { ChunkStatus::Features } else { ChunkStatus::Terrain }; // ProtoChunk.postProcessing: one list per section, packed section offsets. - let mut marks = vec![Vec::new(); SECTIONS]; + let mut marks = vec![Vec::new(); shape.section_count()]; for &[x, y, z] in &proto.column.postprocess { - if let Some(list) = marks.get_mut(((y - MIN_Y) >> 4) as usize) { + let section = usize::try_from((y - shape.min_y) >> 4).ok(); + if let Some(list) = section.and_then(|s| marks.get_mut(s)) { list.push(Tag::Short( ((x & 15) | (y & 15) << 4 | (z & 15) << 8) as i16, )); @@ -1564,7 +1662,7 @@ struct Encoding { registry: &'static BlockRegistry, biomes: Arc, tables: Option>, - sky_light: bool, + shape: LevelShape, } impl Record { fn tag(&self) -> Option> { @@ -1575,7 +1673,7 @@ impl Record { e.registry, &e.biomes, e.tables.as_deref(), - e.sky_light, + e.shape, ))), Record::Delete => None, } @@ -1612,12 +1710,12 @@ pub struct SaveDir { outstanding: Arc, /// Set by `Persistent` before the first load. pub tables: OnceLock>, - /// False in dimensions without skylight (no SkyLight layers are written). - pub sky_light: bool, + /// The dimension's skylight and height, from its folder name. + pub shape: LevelShape, } impl SaveDir { pub fn new(root: PathBuf) -> Self { - let sky_light = !root.ends_with("the_nether") && !root.ends_with("DIM-1"); + let shape = LevelShape::for_dir(&root); Self { root, regions: Default::default(), @@ -1627,7 +1725,7 @@ impl SaveDir { writer: Mutex::new(None), outstanding: Default::default(), tables: OnceLock::new(), - sky_light, + shape, } } fn region_path(&self, folder: &str, rx: i32, rz: i32) -> PathBuf { @@ -1658,7 +1756,7 @@ impl SaveDir { let root = self.read_record("region", x, z)?; let tables = self.tables.get().map(|t| &**t); let mut chunk = decode_with(&root, registry, biomes, tables)?; - load_light(&root.tag, &mut chunk, self.sky_light); + load_light(&root.tag, &mut chunk, self.shape.sky_light); Some(chunk) } /// A proto chunk saved before it became final (`decode_proto`). @@ -1683,7 +1781,7 @@ impl SaveDir { let records = protos .iter() .map(|p| { - let tag = encode_proto(p, registry, biomes, tables, self.sky_light); + let tag = encode_proto(p, registry, biomes, tables, self.shape); ((p.column.x, p.column.z), Some(tag)) }) .collect(); @@ -1858,7 +1956,7 @@ impl SaveDir { .map(|c| { ( (c.x, c.z), - Some(encode_with(c, registry, biomes, tables, self.sky_light)), + Some(encode_with(c, registry, biomes, tables, self.shape)), ) }) .collect(); @@ -1877,7 +1975,7 @@ impl SaveDir { registry, biomes: biomes.clone(), tables: self.tables.get().cloned(), - sky_light: self.sky_light, + shape: self.shape, }); let records = chunks .iter() @@ -3347,7 +3445,7 @@ impl SaveDir { { return None; } - decode_lod_surfaces(&root, assets, biomes, self.sky_light) + decode_lod_surfaces(&root, assets, biomes, self.shape.sky_light) } } @@ -3438,6 +3536,71 @@ impl ChunkGenerator for Persistent { #[cfg(test)] mod tests { + #[test] + fn nether_and_end_chunks_save_with_their_own_height() { + 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 rack = assets + .registry + .default_state("minecraft:netherrack") + .unwrap(); + let mut chunk = Chunk::empty(0, 0); + for y in 0..128 { + chunk.set(0, y, 0, rack.0); + } + let saved = encode_with( + &chunk, + assets.registry, + &biomes, + Some(&tables), + LevelShape::NETHER, + ); + assert_eq!(number(saved.tag.get("yPos")), Some(0)); + let Some(Tag::List(sections)) = saved.tag.get("sections") else { + panic!("no sections"); + }; + let ys: Vec = sections + .iter() + .filter_map(|s| number(s.get("Y")).map(|y| y as i32)) + .collect(); + assert_eq!(ys, (0..16).collect::>()); + let Some(Tag::List(post)) = saved.tag.get("PostProcessing") else { + panic!("no PostProcessing"); + }; + assert_eq!(post.len(), 16); + // Heightmap values count from the level's minimum: the column's top + // block at y=127 reads 128 (vanilla), not 192 (from the Overworld's -64). + let Some(Tag::LongArray(surface)) = saved + .tag + .get("Heightmaps") + .and_then(|h| h.get("WORLD_SURFACE")) + else { + panic!("no WORLD_SURFACE"); + }; + assert_eq!(surface[0] & 0x1ff, 128); + let overworld = encode_with( + &chunk, + assets.registry, + &biomes, + Some(&tables), + LevelShape::OVERWORLD, + ); + assert_eq!(number(overworld.tag.get("yPos")), Some(-4)); + assert_eq!( + LevelShape::for_dir(Path::new("w/dimensions/minecraft/the_end")), + LevelShape::END + ); + assert_eq!( + LevelShape::for_dir(Path::new("w/DIM-1")), + LevelShape::NETHER + ); + } + #[test] fn saved_far_surface_reads_builds_and_water_without_gameplay_chunks() { let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES") else { @@ -3556,7 +3719,7 @@ mod tests { "unfinished proto saves must not suppress complete decoration" ); let mut nether = SaveDir::new(dir.clone()); - nether.sky_light = false; + nether.shape = LevelShape::NETHER; let dark = nether.lod_surfaces(-2, 3, &assets, &biomes).unwrap(); assert!( dark.iter() @@ -3875,6 +4038,31 @@ mod tests { assert_eq!(back.redstone_signal(), 2); } #[test] + fn campfire_block_entity_round_trips() { + let mut c = crate::containers::Campfire::default(); + c.items[1] = Some(crate::items::ItemStack::new("minecraft:beef", 1)); + c.progress[1] = 120; + c.total[1] = 600; + let tag = encode_block_entity( + (3, 64, -2), + &crate::containers::BlockEntity::Campfire(Box::new(c.clone())), + "minecraft:soul_campfire", + ); + // One block entity type for both campfires. + assert_eq!(text(tag.get("id")).as_deref(), Some("minecraft:campfire")); + let (pos, back) = decode_block_entity(&tag).expect("campfire"); + assert_eq!(pos, (3, 64, -2)); + let crate::containers::BlockEntity::Campfire(back) = back else { + panic!("not a campfire"); + }; + assert_eq!(*back, c); + // The update tag a server's clients get: the items alone. + let update = + crate::lan::chunks::entity_tag(&crate::containers::BlockEntity::Campfire(Box::new(c))) + .expect("update tag"); + assert!(update.get("Items").is_some() && update.get("CookingTimes").is_none()); + } + #[test] fn spawner_block_entity_round_trips() { // A dungeon spawner as vanilla saves it (`id` is mob_spawner, not the block). let saved = horizon_world::nbt::parse_snbt( diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index c24d8b39f..a307b35cf 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -175,7 +175,9 @@ pub fn increased_repair_cost(cost: u32) -> u32 { pub fn hover_name(names: &dyn Fn(&str) -> String, stack: &ItemStack) -> String { stack .custom_name() - .map_or_else(|| names(&stack.item), str::to_owned) + .map(str::to_owned) + .or_else(|| stack.item_name()) + .unwrap_or_else(|| names(&stack.item)) } /// `AnvilMenu.createResult`. `name` is the rename box text (None = untouched). pub fn anvil_result( diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index 517b14f44..9c8edf6ad 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; @@ -436,6 +442,14 @@ impl ChunkGenerator for VanillaTerrain { .iter() .map(|(pos, nbt)| { let mut nbt = nbt.clone(); + // Placed data can lack its type (a brushable block's loot table + // alone); vanilla saves every pending block entity with its id, + // and skips one without when the chunk finishes. + if let Some(id) = + crate::lan::chunks::block_entity_type(chunk.block_name(pos[0], pos[1], pos[2])) + { + nbt.insert("id".into(), Tag::String(id.into())); + } for (key, v) in ["x", "y", "z"].into_iter().zip(pos) { nbt.insert(key.into(), Tag::Int(*v)); } @@ -566,11 +580,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-client/tests/generation_saves.rs b/crates/horizon-client/tests/generation_saves.rs index 30b971e05..2f8c2ab6b 100644 --- a/crates/horizon-client/tests/generation_saves.rs +++ b/crates/horizon-client/tests/generation_saves.rs @@ -315,3 +315,70 @@ fn saved_proto_chunks_restore_exactly() { drop(save); let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn saved_proto_block_entities_keep_their_id() { + use horizon_client::{ + save::{Persistent, SaveDir}, + vanillagen::VanillaTerrain, + }; + use horizon_world::{ + nbt::{Limits, Tag}, + region::RegionFile, + }; + let Some(root) = resources() else { + return; + }; + let assets = Arc::new(Assets::load(&root).unwrap()); + let biomes = Arc::new(Biomes::load(&root).unwrap()); + let terrain = VanillaTerrain::for_dimension( + &root.join("worldgen"), + assets.registry, + &biomes, + 12345, + "minecraft:overworld", + ) + .unwrap(); + let dir = std::env::temp_dir().join(format!("horizon-proto-ids-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let save = Arc::new(SaveDir::new(dir.clone())); + let generator = Persistent { + inner: Arc::new(terrain), + save: save.clone(), + registry: assets.clone(), + biomes, + }; + let mut worker = generator.worker(); + // A cold ocean ruin of seed 12345: its suspicious gravel is placed with a + // loot table and no type. + let keys: Vec<(i32, i32)> = (0..9).map(|i| (43 + i % 3 - 1, 21 + i / 3 - 1)).collect(); + let mut region: [Proto; 9] = + std::array::from_fn(|i| generator.proto(&mut worker, keys[i].0, keys[i].1)); + generator.decorate(&mut worker, &mut region); + generator.save_protos(®ion.iter().collect::>()); + save.flush().unwrap(); + let mut file = RegionFile::open(dir.join("region/r.1.0.mca")).unwrap(); + let mut suspicious = 0; + for &(x, z) in &keys { + let Some(record) = file + .read(horizon_core::position::ChunkPos::new(x, z)) + .unwrap() + else { + continue; + }; + let root = record.nbt(Limits::default()).unwrap(); + let Some(Tag::List(entities)) = root.tag.get("block_entities") else { + continue; + }; + for e in entities { + assert!(e.get("id").is_some(), "chunk {x} {z}: {e:?}"); + if let Some(Tag::String(table)) = e.get("LootTable") { + suspicious += usize::from(table.to_string_lossy().contains("archaeology/")); + } + } + } + assert!(suspicious > 0, "the ruin placed no suspicious blocks"); + drop(generator); + drop(save); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index 7f8245c48..d9bb9f5c2 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -111,6 +111,14 @@ interface storage { interface command { /// `line` without its slash; its feedback goes to the chat as if typed. run: func(line: string); + /// `lines` (each without its slash, at most 256 a call) as `run` does, + /// but with nothing in the chat: no feedback and no failure. In single + /// player and on Horizon's servers, each runs exactly as the player + /// typing it would (the same rights), in order, 64 a tick, and the + /// server logs one line a batch; one that carries a chat message (`say`, + /// `msg`) is refused. On any other server they go as chat commands, and + /// there their feedback shows: a mod running many should say so. + run-quiet: func(lines: list); } /// Capability `ui`: widgets the game draws with its own menus' widgets, for diff --git a/crates/horizon-mods/src/api_level.rs b/crates/horizon-mods/src/api_level.rs index 785f0e573..bf87d0cfa 100644 --- a/crates/horizon-mods/src/api_level.rs +++ b/crates/horizon-mods/src/api_level.rs @@ -7,13 +7,13 @@ //! version's level so the launcher can tell before it installs. /// The newest level this Horizon serves. -pub const LEVEL: u32 = 2; +pub const LEVEL: u32 = 3; /// Every function the game offers mods, as `interface.function`, with its /// level. Level 0 is the contract of Horizon 0.2.67 to 0.2.69. A new /// function takes the next level and raises [`LEVEL`] (the `api_reference` /// test fails until it is listed here). -pub const FUNCTIONS: [(&str, u32); 33] = [ +pub const FUNCTIONS: [(&str, u32); 34] = [ ("log.write", 0), ("game.get-player", 0), ("game.get-clock", 0), @@ -47,6 +47,7 @@ pub const FUNCTIONS: [(&str, u32); 33] = [ ("players.tell", 1), ("players.broadcast", 1), ("game.raycast", 2), + ("command.run-quiet", 3), ]; /// What the game's program carries so the launcher can read its level diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index ea603ee31..ce48f2317 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -89,6 +89,9 @@ const FUEL_FRAME: u64 = 10_000_000; const FUEL_EVENT: u64 = 100_000_000; /// Chat lines a mod may show per call, HUD lines and their length. const CHAT_PER_CALL: usize = 8; +/// `command.run-quiet` lines one call of a mod may queue (a quiet payload's +/// cap, `horizon_protocol::quiet::MAX_LINES`). +const QUIET_PER_CALL: usize = 256; /// How far `game.raycast` sees, in blocks. pub const RAYCAST_MAX: f32 = 1024.0; const HUD_LINES: usize = 16; @@ -160,6 +163,9 @@ pub enum Output { /// `command.run`: a vanilla command line, without its slash, to run as /// the player. Command { line: String }, + /// `command.run-quiet`: vanilla command lines to run as the player with + /// nothing in the chat (`horizon_protocol::quiet` on a server). + QuietCommands { mod_id: String, lines: Vec }, /// The mod was turned off: it trapped, overran or failed to start. Stopped { name: String, reason: String }, /// `players.tell`: a line after the mod's name, to the player with this id. @@ -1408,6 +1414,23 @@ impl command::Host for State { self.out.push(Output::Command { line: clip(line) }); } } + fn run_quiet(&mut self, lines: Vec) { + let queued: usize = self + .out + .iter() + .map(|o| match o { + Output::QuietCommands { lines, .. } => lines.len(), + _ => 0, + }) + .sum(); + let room = QUIET_PER_CALL.saturating_sub(queued); + if room > 0 && !lines.is_empty() { + self.out.push(Output::QuietCommands { + mod_id: self.id.clone(), + lines: lines.into_iter().take(room).map(clip).collect(), + }); + } + } } impl hud::Host for State { fn set_panel(&mut self, corner: Corner, lines: Vec) { diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index 5b673583d..c6b835f10 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -26,7 +26,7 @@ id = "test_ui_guest" name = "Test UI Guest" version = "0.1.0" api = "0.1" -capabilities = ["game-read", "chat", "ui", "render", "input"] +capabilities = ["game-read", "chat", "command", "ui", "render", "input"] experimental = ["ui", "render", "input"] "#; @@ -763,6 +763,32 @@ fn game_raycast_sees_the_view_hit_within_its_distance() { assert_eq!(said(&mut mods, "1e9"), [hit]); } +#[test] +fn quiet_commands_come_out_as_one_batch_capped() { + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + let quiet = |mods: &mut Mods, command: &str| -> Vec<(String, Vec)> { + assert!(mods.command(command)); + mods.drain() + .into_iter() + .filter_map(|o| match o { + Output::QuietCommands { mod_id, lines } => Some((mod_id, lines)), + _ => None, + }) + .collect() + }; + assert_eq!( + quiet(&mut mods, "quiet setblock 0 0 0 stone;say hi"), + [( + "test_ui_guest".to_string(), + vec!["setblock 0 0 0 stone".to_string(), "say hi".to_string()] + )] + ); + let batches = quiet(&mut mods, "quiet_many 300"); + assert_eq!(batches.len(), 1); + assert_eq!(batches[0].1.len(), 256); + assert_eq!(batches[0].1[255], "setblock 255 300 0 stone"); +} + #[test] fn corner_panels_text_width_and_readings() { let mut mods = load("horizon_mods_test_ui_guest.hmod"); diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index 32e811fc7..74fb64350 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -5,9 +5,10 @@ //! `/input_claim`, `/input_poll`, `/input_held` and `/input_wheel` test //! `input`; `/zoom FACTOR SMOOTH TURN` tests `render.set-zoom`; //! `/corner` and `/readings` the calls the official extras mods use; -//! `/raycast DISTANCE` says what `game.raycast` sees. +//! `/raycast DISTANCE` says what `game.raycast` sees; `/quiet A;B` runs +//! lines with `command.run-quiet` (`/quiet_many N`: N of them). use horizon_mod_sdk::{ - Mod, Registration, chat, game, + Mod, Registration, chat, command, game, input::{self, Event}, render::{self, FillShape, ItemShape, Point, QuadShape, Rect, Shape, SpriteShape, TextShape}, ui::{self, ItemWidget, ListWidget, Screen, TextWidget, Widget}, @@ -99,6 +100,8 @@ impl Mod for Guest { "zoom", "minimap", "raycast", + "quiet", + "quiet_many", "corner", "readings", ] @@ -219,6 +222,15 @@ impl Mod for Guest { }); render::set_minimap(map); } + "quiet" => command::run_quiet(&args.split(';').map(str::to_owned).collect::>()), + "quiet_many" => { + let n: usize = args.parse().unwrap_or(0); + command::run_quiet( + &(0..n) + .map(|i| format!("setblock {i} 300 0 stone")) + .collect::>(), + ); + } "raycast" => { let distance = args.parse().unwrap_or(f32::NAN); chat::show(&match game::raycast(distance) { diff --git a/crates/horizon-port-pack/src/net.rs b/crates/horizon-port-pack/src/net.rs index d829d1357..a441fb13a 100644 --- a/crates/horizon-port-pack/src/net.rs +++ b/crates/horizon-port-pack/src/net.rs @@ -91,8 +91,9 @@ pub fn keep( pub fn parse(spec: &str) -> Option { if socks(spec) { say(&format!( - "{spec} is a SOCKS proxy; downloads go without one. Write the http:// address your \ - proxy app listens on as well." + "{} is a SOCKS proxy; downloads go without one. Write the http:// address your \ + proxy app listens on as well.", + redacted(spec) )); return None; } @@ -100,13 +101,29 @@ pub fn parse(spec: &str) -> Option { Ok(proxy) => Some(proxy), Err(e) => { say(&format!( - "The proxy address {spec} can't be used ({e}); downloads go without one." + "The proxy address {} can't be used ({e}); downloads go without one.", + redacted(spec) )); None } } } +/// `spec` as it may be shown: a user name and password in it become `***`. An address that can't +/// be used is printed to stderr and shown in the launcher, and a proxy's credentials don't belong in +/// either. Everything up to the last `@` is the credentials, so a password with an unescaped `/` or +/// `@` is hidden too. +pub fn redacted(spec: &str) -> String { + let (scheme, rest) = match spec.split_once("://") { + Some((scheme, rest)) => (format!("{scheme}://"), rest), + None => (String::new(), spec), + }; + match rest.rfind('@') { + Some(at) => format!("{scheme}***@{}", &rest[at + 1..]), + None => spec.to_owned(), + } +} + /// Whether `spec` names a SOCKS proxy, which these downloads don't go through: `ureq` reads a /// SOCKS address happily and only fails when it connects through it. pub fn socks(spec: &str) -> bool { @@ -227,6 +244,26 @@ mod tests { lock(&TURN) } + #[test] + fn credentials_are_not_shown() { + assert_eq!(redacted("http://127.0.0.1:7890"), "http://127.0.0.1:7890"); + assert_eq!(redacted("proxy.local:3128"), "proxy.local:3128"); + assert_eq!( + redacted("http://user:pass@proxy.local:3128"), + "http://***@proxy.local:3128" + ); + assert_eq!( + redacted("socks5://u:p@10.0.0.1:1080"), + "socks5://***@10.0.0.1:1080" + ); + assert_eq!( + redacted("user:pass@proxy.local:3128"), + "***@proxy.local:3128" + ); + assert_eq!(redacted("http://u:p/a@ss@proxy:1"), "http://***@proxy:1"); + assert_eq!(redacted("http://user:pass@"), "http://***@"); + } + #[test] fn a_proxy_the_launcher_sets_is_trimmed_and_kept() { let _turn = alone(); diff --git a/crates/horizon-protocol/src/item.rs b/crates/horizon-protocol/src/item.rs index 259aeb2d1..3d5bacfe9 100644 --- a/crates/horizon-protocol/src/item.rs +++ b/crates/horizon-protocol/src/item.rs @@ -164,7 +164,7 @@ pub struct Profile { pub properties: Vec<(String, String, Option)>, } impl Component { - fn read(kind: i32, r: &mut Reader) -> Result { + pub(crate) fn read(kind: i32, r: &mut Reader) -> Result { use component::*; Ok(match kind { MAX_STACK_SIZE | MAX_DAMAGE | DAMAGE | RARITY | REPAIR_COST | MAP_ID @@ -338,7 +338,7 @@ impl Component { } }) } - fn write(&self, kind: i32, w: &mut Writer) { + pub(crate) fn write(&self, kind: i32, w: &mut Writer) { match self { Self::Raw(bytes) => w.bytes(bytes), Self::Trim { material, pattern } => { diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 1bdf43b08..26bc09a84 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -8,7 +8,7 @@ use crate::{ }, chunk::{ChunkData, LightData}, entity_data::{EntityData, Particle, Value}, - item::{Hashed, HashedSlot, Slot, Stack}, + item::{Component, Hashed, HashedSlot, Slot, Stack}, packet, packet_enum, packets::{ Empty, @@ -88,11 +88,31 @@ packet!(ContainerSetContent { carried: Option => Slot, }); /// ItemCost.STREAM_CODEC: item, count, then the exact component predicate -/// (Horizon sends and reads it as a component patch without removals). +/// (a list of typed component values, with no patch removal count). #[derive(Clone, Debug, PartialEq)] pub struct NetCost { pub item: i32, pub count: i32, + pub components: Vec<(i32, Component)>, +} +impl From for NetCost { + fn from(stack: Stack) -> Self { + Self { + item: stack.item, + count: stack.count, + components: stack.added, + } + } +} +impl From for Stack { + fn from(cost: NetCost) -> Self { + Self { + item: cost.item, + count: cost.count, + added: cost.components, + removed: Vec::new(), + } + } } /// MerchantOffer.STREAM_CODEC. #[derive(Clone, Debug, PartialEq)] @@ -114,10 +134,17 @@ impl Codec> for Offers { fn cost(r: &mut Reader) -> Result { let item = r.varint()?; let count = r.varint()?; - if r.varint()? != 0 { - return Err(Error::new("item cost components are not supported")); + let n = r.count(r.remaining())?; + let mut components = Vec::with_capacity(n.min(64)); + for _ in 0..n { + let kind = r.varint()?; + components.push((kind, Component::read(kind, r)?)); } - Ok(NetCost { item, count }) + Ok(NetCost { + item, + count, + components, + }) } let n = r.count(r.remaining())?; let mut out = Vec::with_capacity(n.min(64)); @@ -144,7 +171,11 @@ impl Codec> for Offers { fn cost(c: &NetCost, w: &mut Writer) { w.varint(c.item); w.varint(c.count); - w.varint(0); + w.varint(c.components.len() as i32); + for (kind, value) in &c.components { + w.varint(*kind); + value.write(*kind, w); + } } w.varint(v.len() as i32); for o in v { @@ -2300,6 +2331,39 @@ mod tests { use super::*; use crate::{chunk::BlockEntityInfo, packets::round_trip, text::literal}; + #[test] + fn merchant_cost_predicate_is_a_typed_list_without_patch_counts() { + // ItemCost.STREAM_CODEC: item=7, count=1, one typed component, + // potion_contents=53, potion present (water=0), no color/effects/name. + // Result: count=1, item=8, empty component patch. Secondary cost: + // item=9, count=2, empty predicate, followed by the offer fields. + let mut bytes = vec![1, 7, 1, 1, 53, 1, 0, 0, 0, 0, 1, 8, 0, 0, 1, 9, 2, 0, 0]; + bytes.extend_from_slice(&[0; 4]); // uses + bytes.extend_from_slice(&2i32.to_be_bytes()); // max uses + bytes.extend_from_slice(&[0; 16]); // xp, special price, multiplier, demand + let mut r = Reader::new(&bytes); + let offers = Offers::read(&mut r).unwrap(); + assert_eq!(r.remaining(), 0); + assert_eq!( + offers[0].cost_a.components, + vec![( + 53, + Component::Potion { + potion: Some(0), + color: None, + rest: Vec::new() + } + )] + ); + assert!(offers[0].cost_b.as_ref().unwrap().components.is_empty()); + let mut w = Writer::new(); + Offers::write(&offers, &mut w); + assert_eq!(w.data, bytes); + for len in 0..bytes.len() { + assert!(Offers::read(&mut Reader::new(&bytes[..len])).is_err()); + } + } + #[test] fn serverbound_abilities_carry_only_flying() { // ServerboundPlayerAbilitiesPacket.write: one byte, 2 when flying. @@ -2576,9 +2640,9 @@ mod tests { Clientbound::MerchantOffers(MerchantOffers { container: 3, offers: vec![NetOffer { - cost_a: NetCost { item: 5, count: 24 }, + cost_a: Stack::new(5, 24).into(), result: Stack::new(7, 1), - cost_b: Some(NetCost { item: 9, count: 1 }), + cost_b: Some(Stack::new(9, 1).into()), out_of_stock: false, uses: 2, max_uses: 16, 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/crates/horizon-world/examples/probe/main.rs b/crates/horizon-world/examples/probe/main.rs index 479a3ed23..b87e5620a 100644 --- a/crates/horizon-world/examples/probe/main.rs +++ b/crates/horizon-world/examples/probe/main.rs @@ -169,6 +169,7 @@ mod stored_effect_attributes_fixture; mod stored_effect_notifications_fixture; mod structure_density_fixture; mod structure_pieces; +mod structure_start_nbt; mod suffocation_fixture; mod swimming_fixture; mod synced_bytes_fixture; @@ -340,6 +341,7 @@ probes! { stored_effect_notifications_fixture, structure_density_fixture, structure_pieces, + structure_start_nbt, suffocation_fixture, swimming_fixture, synced_bytes_fixture, diff --git a/crates/horizon-world/examples/probe/structure_pieces.rs b/crates/horizon-world/examples/probe/structure_pieces.rs index ebbad9c7a..3b1415da5 100644 --- a/crates/horizon-world/examples/probe/structure_pieces.rs +++ b/crates/horizon-world/examples/probe/structure_pieces.rs @@ -21,7 +21,7 @@ use std::{fs, path::Path}; type Error = Box; -fn registry(resources: &Path) -> Result<&'static BlockRegistry, Error> { +pub fn registry(resources: &Path) -> Result<&'static BlockRegistry, Error> { let facts: Value = serde_json::from_str(&fs::read_to_string(resources.join("facts.json"))?)?; let states = facts["states"].as_array().ok_or("facts states")?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/probe/structure_start_nbt.rs b/crates/horizon-world/examples/probe/structure_start_nbt.rs new file mode 100644 index 000000000..daea17314 --- /dev/null +++ b/crates/horizon-world/examples/probe/structure_start_nbt.rs @@ -0,0 +1,74 @@ +//! The structure starts a chunk owns, as `StructureStart.createTag` saves them. +//! +//! structure_start_nbt ... +//! prints `nbt CX CZ TAG` for every start whose chunk is a target, the tag +//! with sorted keys and typed numbers (VanillaStructureStartOracle's +//! `canonical`), or `unsaved CX CZ ID` when Horizon cannot save it yet. +use horizon_core::position::ChunkPos; +use horizon_world::{ + nbt::Tag, + worldgen::generator::{GeneratorData, OverworldGenerator}, +}; + +type Error = Box; + +/// `VanillaStructureStartOracle.canonical`. +fn canonical(tag: &Tag) -> String { + let join = |parts: Vec| parts.join(","); + match tag { + Tag::Compound(c) => { + let mut keys: Vec<_> = c.keys().map(|k| (k.to_string_lossy(), k)).collect(); + keys.sort_by(|a, b| a.0.encode_utf16().cmp(b.0.encode_utf16())); + let parts = keys + .into_iter() + .map(|(name, key)| format!("{name}:{}", canonical(&c[key]))) + .collect(); + format!("{{{}}}", join(parts)) + } + Tag::List(l) => format!("[{}]", join(l.iter().map(canonical).collect())), + Tag::Byte(v) => format!("{v}b"), + Tag::Short(v) => format!("{v}s"), + Tag::Int(v) => v.to_string(), + Tag::Long(v) => format!("{v}L"), + Tag::Float(bits) => format!("{}f", *bits as i32), + Tag::Double(bits) => format!("{}d", *bits as i64), + Tag::String(s) => format!( + "\"{}\"", + s.to_string_lossy() + .replace('\\', "\\\\") + .replace('"', "\\\"") + ), + Tag::IntArray(a) => format!("[I;{}]", join(a.iter().map(i32::to_string).collect())), + Tag::LongArray(a) => format!("[L;{}]", join(a.iter().map(i64::to_string).collect())), + Tag::ByteArray(a) => format!( + "[B;{}]", + join(a.iter().map(|b| (*b as i8).to_string()).collect()) + ), + Tag::End => "END".into(), + } +} + +pub fn main() -> Result<(), Error> { + let mut args = crate::args().skip(1); + let resources = std::path::PathBuf::from(args.next().ok_or("client resource directory")?); + let seed: i64 = args.next().ok_or("seed")?.parse()?; + let dimension = format!("minecraft:{}", args.next().ok_or("dimension")?); + let registry = crate::structure_pieces::registry(&resources)?; + let data = GeneratorData::load(&resources.join("worldgen"), registry)?; + let generator = OverworldGenerator::for_dimension(data, seed, "minecraft:normal", &dimension)?; + let mut worker = generator.worker(); + for target in args { + let (x, z) = target.split_once(',').ok_or("target cx,cz")?; + let chunk = ChunkPos::new(x.parse()?, z.parse()?); + for start in worker.structure_starts(chunk) { + if start.chunk != chunk { + continue; + } + match start.save() { + Some(tag) => println!("nbt {} {} {}", chunk.x, chunk.z, canonical(&tag)), + None => println!("unsaved {} {} {}", chunk.x, chunk.z, start.name), + } + } + } + Ok(()) +} diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 3831efbd6..41b325768 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -114,6 +114,7 @@ mod place; mod portal; pub mod portal_travel; mod query; +pub(crate) use query::data_2d; mod rails; mod redstone; pub mod removal; diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index b554da9e3..7a38608be 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -618,6 +618,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; diff --git a/crates/horizon-world/src/worldgen/structure.rs b/crates/horizon-world/src/worldgen/structure.rs index e0ac4d9e8..c998cc3be 100644 --- a/crates/horizon-world/src/worldgen/structure.rs +++ b/crates/horizon-world/src/worldgen/structure.rs @@ -79,6 +79,15 @@ impl Rotation { pub fn get_rotated(self, other: Self) -> Self { Self::ALL[(self as usize + other as usize) % 4] } + /// `Rotation.name()`, as structure pieces save it. + pub fn saved_name(self) -> &'static str { + match self { + Self::None => "NONE", + Self::Clockwise90 => "CLOCKWISE_90", + Self::Clockwise180 => "CLOCKWISE_180", + Self::Counterclockwise90 => "COUNTERCLOCKWISE_90", + } + } } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Mirror { @@ -86,6 +95,16 @@ pub enum Mirror { LeftRight, FrontBack, } +impl Mirror { + /// `Mirror.name()`, as structure pieces save it. + pub fn saved_name(self) -> &'static str { + match self { + Self::None => "NONE", + Self::LeftRight => "LEFT_RIGHT", + Self::FrontBack => "FRONT_BACK", + } + } +} /// Inclusive integer box (vanilla BoundingBox). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] diff --git a/crates/horizon-world/src/worldgen/structure/end_city.rs b/crates/horizon-world/src/worldgen/structure/end_city.rs index 225f810f5..b440fc832 100644 --- a/crates/horizon-world/src/worldgen/structure/end_city.rs +++ b/crates/horizon-world/src/worldgen/structure/end_city.rs @@ -381,19 +381,22 @@ pub fn pieces( } else { vec!["minecraft:structure_block".into(), "minecraft:air".into()] }; - EndCityPiece(TemplatePiece::new( - "minecraft:ecp", - &format!("minecraft:end_city/{}", d.name), - d.template, - d.position, - d.rotation, - Mirror::None, - [0; 3], - Arc::new(ProcessorList::default()), - true, - ignore, - TemplateHandler::Plain, - )) + EndCityPiece( + TemplatePiece::new( + "minecraft:ecp", + &format!("minecraft:end_city/{}", d.name), + d.template, + d.position, + d.rotation, + Mirror::None, + [0; 3], + Arc::new(ProcessorList::default()), + true, + ignore, + TemplateHandler::Plain, + ), + d.depth, + ) }) .collect(), ) @@ -401,11 +404,21 @@ pub fn pieces( /// EndCityPieces.EndCityPiece. #[derive(Debug)] -pub struct EndCityPiece(TemplatePiece); +/// The template piece and its genDepth (the collision tag of its batch). +pub struct EndCityPiece(TemplatePiece, i32); impl LegacyPiece for EndCityPiece { fn bounding_box(&self) -> BoundingBox { self.0.bounding_box } + /// `EndCityPiece`: the template piece's tag, `OW` for the pieces that + /// overwrite air (only structure blocks ignored). + fn save(&self) -> Option { + let mut tag = self.0.saved(); + tag.insert("GD".into(), crate::nbt::Tag::Int(self.1)); + let overwrite = self.0.ignore.len() == 1; + tag.insert("OW".into(), crate::nbt::Tag::Byte(i8::from(overwrite))); + Some(tag) + } fn type_name(&self) -> &'static str { "minecraft:ecp" } diff --git a/crates/horizon-world/src/worldgen/structure/enhanced_terrain.rs b/crates/horizon-world/src/worldgen/structure/enhanced_terrain.rs index 24c3b9a82..04f14e969 100644 --- a/crates/horizon-world/src/worldgen/structure/enhanced_terrain.rs +++ b/crates/horizon-world/src/worldgen/structure/enhanced_terrain.rs @@ -294,6 +294,8 @@ mod tests { source_x: junction[0], source_ground_y: junction[1], source_z: junction[2], + delta_y: 0, + dest_projection: Projection::Rigid, }], waterlogging: false, }) @@ -303,6 +305,7 @@ mod tests { Arc::new(PoolElement::Single { template: Arc::new(StructureTemplate::empty()), processors: Default::default(), + processors_source: serde_json::Value::Null, legacy: false, projection, waterlogging: None, 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/jigsaw.rs b/crates/horizon-world/src/worldgen/structure/jigsaw.rs index a6cf7a22a..6fd935024 100644 --- a/crates/horizon-world/src/worldgen/structure/jigsaw.rs +++ b/crates/horizon-world/src/worldgen/structure/jigsaw.rs @@ -5,6 +5,7 @@ use super::{ }; use crate::{ heightmap::HeightmapType, + nbt::{Compound, Tag}, worldgen::{ DecodeError, block_feature::FeatureBlockBindings, @@ -30,12 +31,24 @@ pub enum Projection { Rigid, TerrainMatching, } +impl Projection { + /// `StructureTemplatePool.Projection.getSerializedName`. + pub fn saved_name(self) -> &'static str { + match self { + Self::Rigid => "rigid", + Self::TerrainMatching => "terrain_matching", + } + } +} #[derive(Clone, Debug)] pub enum PoolElement { Empty, Single { template: Arc, processors: ProcessorList, + /// The element's `processors` as written: a list id or an inline list, + /// saved back as it was. + processors_source: Value, legacy: bool, projection: Projection, waterlogging: Option, @@ -136,6 +149,7 @@ impl PoolElement { resources, bindings, )?, + processors_source: value["processors"].clone(), legacy: kind == "minecraft:legacy_single_pool_element", projection: projection()?, waterlogging: match value @@ -178,6 +192,64 @@ impl PoolElement { _ => return Err(DecodeError::Field("pool element type")), }) } + /// `StructurePoolElement.CODEC`'s encoding, as a jigsaw piece saves it. + pub fn save(&self) -> Tag { + let text = |s: &str| Tag::String(s.into()); + match self { + Self::Empty => Tag::compound([("element_type", text("minecraft:empty_pool_element"))]), + Self::Single { + template, + processors_source, + legacy, + projection, + waterlogging, + .. + } => { + let kind = if *legacy { + "minecraft:legacy_single_pool_element" + } else { + "minecraft:single_pool_element" + }; + let mut entries = vec![ + ("element_type", text(kind)), + ("location", text(&template.location)), + ( + "processors", + super::processor::json_to_nbt(processors_source), + ), + ("projection", text(projection.saved_name())), + ]; + if let Some(apply) = waterlogging { + let settings = if *apply { + "apply_waterlogging" + } else { + "ignore_waterlogging" + }; + entries.push(("override_liquid_settings", text(settings))); + } + Tag::compound(entries) + } + Self::Feature { + feature, + projection, + } => Tag::compound([ + ("element_type", text("minecraft:feature_pool_element")), + ("feature", text(feature)), + ("projection", text(projection.saved_name())), + ]), + Self::List { + elements, + projection, + } => Tag::compound([ + ("element_type", text("minecraft:list_pool_element")), + ( + "elements", + Tag::List(elements.iter().map(Self::save).collect()), + ), + ("projection", text(projection.saved_name())), + ]), + } + } pub fn projection(&self) -> Projection { match self { Self::Empty => Projection::TerrainMatching, @@ -466,6 +538,9 @@ pub struct Junction { pub source_x: i32, pub source_ground_y: i32, pub source_z: i32, + /// Saved only (`JigsawJunction.deltaY`, `destProjection`). + pub delta_y: i32, + pub dest_projection: Projection, } #[derive(Debug)] pub struct PoolPiece { @@ -517,6 +592,12 @@ impl PoolPiece { source_x: int(j, "source_x")?, source_ground_y: int(j, "source_ground_y")?, source_z: int(j, "source_z")?, + delta_y: int(j, "delta_y")?, + dest_projection: match j["dest_proj"].as_str() { + Some("rigid") => Projection::Rigid, + Some("terrain_matching") => Projection::TerrainMatching, + _ => return Err(DecodeError::Field("dest_proj")), + }, }) }) .collect::>()?; @@ -535,6 +616,45 @@ impl PoolPiece { waterlogging: v["liquid_settings"].as_str() != Some("ignore_waterlogging"), }) } + /// `PoolElementStructurePiece`'s tag (always genDepth 0, no orientation). + pub fn save(&self) -> Compound { + let mut tag = super::legacy::piece_tag("minecraft:jigsaw", self.bounding_box, None, 0); + let junctions = self + .junctions + .iter() + .map(|j| { + Tag::compound([ + ("source_x", Tag::Int(j.source_x)), + ("source_ground_y", Tag::Int(j.source_ground_y)), + ("source_z", Tag::Int(j.source_z)), + ("delta_y", Tag::Int(j.delta_y)), + ( + "dest_proj", + Tag::String(j.dest_projection.saved_name().into()), + ), + ]) + }) + .collect(); + for (key, value) in [ + ("PosX", Tag::Int(self.position[0])), + ("PosY", Tag::Int(self.position[1])), + ("PosZ", Tag::Int(self.position[2])), + ("ground_level_delta", Tag::Int(self.ground_level_delta)), + ("pool_element", self.element.save()), + ("rotation", Tag::String(self.rotation.saved_name().into())), + ("junctions", Tag::List(junctions)), + ] { + tag.insert(key.into(), value); + } + // LiquidSettings.APPLY_WATERLOGGING, the default, is not written. + if !self.waterlogging { + tag.insert( + "liquid_settings".into(), + Tag::String("ignore_waterlogging".into()), + ); + } + tag + } pub(super) fn moved(&mut self, dy: i32) { self.position[1] += dy; self.bounding_box = self.bounding_box.moved([0, dy, 0]); @@ -1204,6 +1324,8 @@ impl Placer<'_, '_> { source_x: target_pos[0], source_ground_y: junction_y - local_y + source_ground, source_z: target_pos[2], + delta_y, + dest_projection: target.projection(), }); self.pieces.push(PoolPiece { element: target.clone(), @@ -1215,6 +1337,12 @@ impl Placer<'_, '_> { source_x: jigsaw.pos[0], source_ground_y: junction_y - target_local_y + target_ground, source_z: jigsaw.pos[2], + delta_y: -delta_y, + dest_projection: if source_rigid { + Projection::Rigid + } else { + Projection::TerrainMatching + }, }], waterlogging: self.config.waterlogging, }); diff --git a/crates/horizon-world/src/worldgen/structure/legacy.rs b/crates/horizon-world/src/worldgen/structure/legacy.rs index f558081ee..785b5fb2e 100644 --- a/crates/horizon-world/src/worldgen/structure/legacy.rs +++ b/crates/horizon-world/src/worldgen/structure/legacy.rs @@ -282,6 +282,11 @@ pub trait LegacyPiece: std::fmt::Debug + Send + Sync { fn bounding_box(&self) -> BoundingBox; /// The vanilla StructurePieceType id, for diagnostics and comparisons. fn type_name(&self) -> &'static str; + /// `StructurePiece.createTag`; None while Horizon cannot save this type, + /// and then its start is not saved. + fn save(&self) -> Option { + None + } fn post_process(&self, context: &mut PieceContext<'_>) -> Result<()>; /// Structure.afterPlace, run on the first piece once per chunk after all /// pieces were placed, with every piece's current box. @@ -290,6 +295,31 @@ pub trait LegacyPiece: std::fmt::Debug + Send + Sync { } } +/// `StructurePiece.createTag`'s own fields: the type, `BB`, `O` (the +/// orientation's 2D data value, -1 for none) and `GD` (genDepth). +pub fn piece_tag( + id: &str, + b: BoundingBox, + orientation: Option, + gen_depth: i32, +) -> Compound { + let o = orientation.map_or(-1, crate::level::data_2d); + [ + ("id", Tag::String(id.into())), + ( + "BB", + Tag::IntArray(vec![ + b.min[0], b.min[1], b.min[2], b.max[0], b.max[1], b.max[2], + ]), + ), + ("O", Tag::Int(o)), + ("GD", Tag::Int(gen_depth)), + ] + .into_iter() + .map(|(k, v)| (JavaString::from(k), v)) + .collect() +} + /// StructurePiece's orientation transform and block helpers. #[derive(Clone, Copy, Debug)] pub struct PieceFrame { 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/nether_fossil.rs b/crates/horizon-world/src/worldgen/structure/nether_fossil.rs index 48e4de58a..b80b8c1a8 100644 --- a/crates/horizon-world/src/worldgen/structure/nether_fossil.rs +++ b/crates/horizon-world/src/worldgen/structure/nether_fossil.rs @@ -73,6 +73,9 @@ impl LegacyPiece for NetherFossilPiece { fn bounding_box(&self) -> BoundingBox { self.0.bounding_box } + fn save(&self) -> Option { + Some(self.0.saved()) + } fn type_name(&self) -> &'static str { "minecraft:nefos" } diff --git a/crates/horizon-world/src/worldgen/structure/ocean_ruin.rs b/crates/horizon-world/src/worldgen/structure/ocean_ruin.rs index 9d0ce8923..bf15dc372 100644 --- a/crates/horizon-world/src/worldgen/structure/ocean_ruin.rs +++ b/crates/horizon-world/src/worldgen/structure/ocean_ruin.rs @@ -325,6 +325,8 @@ pub fn post_process(piece: &TemplatePiece, c: &mut PieceContext<'_>) -> Result<( new_y = min_y + 1; } position[1] = new_y; + // OceanRuinPiece.postProcess keeps the height in templatePosition. + *piece.state.lock().unwrap() = Some(new_y); if let Some(markers) = piece.place_at(c, position, &[])? { for (marker, pos) in markers { if marker == "chest" { diff --git a/crates/horizon-world/src/worldgen/structure/piece_limited.rs b/crates/horizon-world/src/worldgen/structure/piece_limited.rs index 6977ebc88..8b3a6d7de 100644 --- a/crates/horizon-world/src/worldgen/structure/piece_limited.rs +++ b/crates/horizon-world/src/worldgen/structure/piece_limited.rs @@ -910,6 +910,8 @@ impl Assembler<'_> { source_x: slot.target_pos[0], source_ground_y: junction_y - local_y + source_ground, source_z: slot.target_pos[2], + delta_y, + dest_projection: target.projection(), }); slot.free.borrow_mut().removed.push(target_box); self.pieces.push(PoolPiece { @@ -922,6 +924,12 @@ impl Assembler<'_> { source_x: jigsaw.pos[0], source_ground_y: junction_y - target_local[1] + target_ground, source_z: jigsaw.pos[2], + delta_y: -delta_y, + dest_projection: if source_rigid { + Projection::Rigid + } else { + Projection::TerrainMatching + }, }], waterlogging: self.config.waterlogging, }); @@ -1022,6 +1030,7 @@ mod tests { let element = Arc::new(PoolElement::Single { template, processors: Default::default(), + processors_source: serde_json::Value::Null, legacy: false, projection: Projection::Rigid, waterlogging: None, @@ -1038,6 +1047,8 @@ mod tests { source_x: 1, source_ground_y: 2, source_z: 3, + delta_y: 0, + dest_projection: Projection::Rigid, }], waterlogging: true, }; diff --git a/crates/horizon-world/src/worldgen/structure/processor.rs b/crates/horizon-world/src/worldgen/structure/processor.rs index b0a0622b7..0665f785d 100644 --- a/crates/horizon-world/src/worldgen/structure/processor.rs +++ b/crates/horizon-world/src/worldgen/structure/processor.rs @@ -706,7 +706,7 @@ fn holder_set( } Ok(Arc::new(out)) } -fn json_to_nbt(value: &Value) -> Tag { +pub(super) fn json_to_nbt(value: &Value) -> Tag { match value { Value::Bool(b) => Tag::Byte(i8::from(*b)), Value::Number(n) => match n.as_i64() { diff --git a/crates/horizon-world/src/worldgen/structure/ruined_portal.rs b/crates/horizon-world/src/worldgen/structure/ruined_portal.rs index 76010aa86..4f87cdd10 100644 --- a/crates/horizon-world/src/worldgen/structure/ruined_portal.rs +++ b/crates/horizon-world/src/worldgen/structure/ruined_portal.rs @@ -25,6 +25,17 @@ pub enum Vertical { InNether, } impl Vertical { + /// `RuinedPortalPiece.VerticalPlacement.getSerializedName`. + fn saved_name(self) -> &'static str { + match self { + Self::OnLandSurface => "on_land_surface", + Self::PartlyBuried => "partly_buried", + Self::OnOceanFloor => "on_ocean_floor", + Self::InMountain => "in_mountain", + Self::Underground => "underground", + Self::InNether => "in_nether", + } + } fn heightmap(self) -> HeightmapType { if self == Self::OnOceanFloor { HeightmapType::OceanFloorWg @@ -70,6 +81,9 @@ impl Setup { #[derive(Clone, Copy, Debug)] pub struct PortalProps { placement: Vertical, + mossiness: f32, + air_pocket: bool, + blackstone: bool, cold: bool, overgrown: bool, vines: bool, @@ -182,6 +196,9 @@ pub fn start( }; let props = PortalProps { placement: setup.placement, + mossiness: setup.mossiness, + air_pocket, + blackstone: setup.blackstone, cold, overgrown: setup.overgrown, vines: setup.vines, @@ -379,3 +396,28 @@ pub fn post_process(piece: &TemplatePiece, c: &mut PieceContext<'_>) -> Result<( } Ok(()) } + +impl PortalProps { + /// `RuinedPortalPiece`'s `VerticalPlacement` and `Properties` tags. + pub fn save(&self) -> [(&'static str, crate::nbt::Tag); 2] { + use crate::nbt::Tag; + let flag = |b: bool| Tag::Byte(i8::from(b)); + [ + ( + "VerticalPlacement", + Tag::String(self.placement.saved_name().into()), + ), + ( + "Properties", + Tag::compound([ + ("cold", flag(self.cold)), + ("mossiness", Tag::Float(self.mossiness.to_bits())), + ("air_pocket", flag(self.air_pocket)), + ("overgrown", flag(self.overgrown)), + ("vines", flag(self.vines)), + ("replace_with_blackstone", flag(self.blackstone)), + ]), + ), + ] + } +} diff --git a/crates/horizon-world/src/worldgen/structure/simple.rs b/crates/horizon-world/src/worldgen/structure/simple.rs index 72aab4710..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(()); } @@ -193,10 +205,87 @@ pub fn shipwreck_too_big(template: &StructureTemplate) -> bool { template.size[0] > 32 || template.size[1] > 32 } +impl TemplatePiece { + /// `TemplateStructurePiece.addAdditionalSaveData` and its subclasses', + /// with the height a shipwreck settled on once placed. + pub fn saved(&self) -> crate::nbt::Compound { + use crate::nbt::Tag; + let flag = |b: bool| Tag::Byte(i8::from(b)); + let adjusted = match self.handler { + TemplateHandler::Shipwreck { .. } + | TemplateHandler::OceanRuin { .. } + | TemplateHandler::Igloo => *self.state.lock().unwrap(), + _ => None, + }; + let dy = adjusted.map_or(0, |y| y - self.position[1]); + let template_dy = if matches!(self.handler, TemplateHandler::Igloo) { + 0 + } else { + dy + }; + let mut tag = super::legacy::piece_tag( + self.type_name, + self.bounding_box.moved([0, dy, 0]), + Some(Direction::North), + 0, + ); + // Mansion and End City pieces keep the name inside their folder. + let name = self + .template_name + .strip_prefix("minecraft:woodland_mansion/") + .or_else(|| self.template_name.strip_prefix("minecraft:end_city/")) + .unwrap_or(&self.template_name); + let rotation = || Tag::String(self.rotation.saved_name().into()); + let mut entries = vec![ + ("TPX", Tag::Int(self.position[0])), + ("TPY", Tag::Int(self.position[1] + template_dy)), + ("TPZ", Tag::Int(self.position[2])), + ("Template", Tag::String(name.into())), + ]; + match self.handler { + TemplateHandler::Igloo => entries.push(("Rot", rotation())), + TemplateHandler::Shipwreck { beached } => entries.extend([ + ("isBeached", flag(beached)), + ("Rot", rotation()), + ("height_adjusted", flag(adjusted.is_some())), + ]), + TemplateHandler::OceanRuin { + warm, + large, + integrity, + } => entries.extend([ + ("Rot", rotation()), + ("Integrity", Tag::Float(integrity.to_bits())), + ( + "BiomeType", + Tag::String(if warm { "WARM" } else { "COLD" }.into()), + ), + ("IsLarge", flag(large)), + ]), + TemplateHandler::RuinedPortal(props) => { + entries.push(("Rotation", rotation())); + entries.push(("Mirror", Tag::String(self.mirror.saved_name().into()))); + entries.extend(props.save()); + } + TemplateHandler::Mansion => entries.extend([ + ("Rot", rotation()), + ("Mi", Tag::String(self.mirror.saved_name().into())), + ]), + TemplateHandler::Plain => entries.push(("Rot", rotation())), + } + for (key, value) in entries { + tag.insert(key.into(), value); + } + tag + } +} impl LegacyPiece for TemplatePiece { fn bounding_box(&self) -> BoundingBox { self.bounding_box } + fn save(&self) -> Option { + Some(self.saved()) + } fn after_place(&self, c: &mut PieceContext<'_>, pieces: &[BoundingBox]) -> Result<()> { match self.handler { TemplateHandler::Mansion => super::mansion::after_place(c, pieces), @@ -232,6 +321,8 @@ impl LegacyPiece for TemplatePiece { self.position[1] + height - 90 - 1, self.position[2], ]; + // The box stays moved; templatePosition goes back after placing. + *self.state.lock().unwrap() = Some(position[1]); if let Some(markers) = self.place_at(c, position, &[])? { for (marker, pos) in markers { if marker == "chest" { @@ -362,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 { @@ -419,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), } } } @@ -432,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" } @@ -500,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 ea4549131..810332c61 100644 --- a/crates/horizon-world/src/worldgen/structure/start.rs +++ b/crates/horizon-world/src/worldgen/structure/start.rs @@ -694,6 +694,13 @@ impl Piece { Self::Legacy(p) => p.type_name(), } } + /// `StructurePiece.createTag`; None for a type Horizon cannot save yet. + pub fn save(&self) -> Option { + match self { + Self::Pool(p) => Some(p.save()), + Self::Legacy(p) => p.save(), + } + } } fn legacy(pieces: Vec) -> Vec { pieces @@ -735,6 +742,26 @@ pub struct StructureStart { /// Piece union, inflated by 12 for terrain-adapting structures. pub bounding_box: BoundingBox, } +impl StructureStart { + /// `StructureStart.createTag` in its own chunk; None while one of its + /// pieces cannot be saved. `references` counts `addReference` calls, + /// which only locating structures makes: 0 in a freshly made world. + pub fn save(&self) -> Option { + use crate::nbt::Tag; + let children: Option> = self + .pieces + .iter() + .map(|p| p.save().map(Tag::Compound)) + .collect(); + Some(Tag::compound([ + ("id", Tag::String(self.name.as_str().into())), + ("ChunkX", Tag::Int(self.chunk.x)), + ("ChunkZ", Tag::Int(self.chunk.z)), + ("references", Tag::Int(0)), + ("Children", Tag::List(children?)), + ])) + } +} /// A block of a noise column (ChunkGenerator.getBaseColumn), by what /// structures ask of it. @@ -935,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/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/api/mods-reference.md b/docs/api/mods-reference.md index a197b2c04..c44f27576 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -176,6 +176,7 @@ Capability `command`: vanilla commands run as the player, with the player's perm | Function | Signature | What it does | | --- | --- | --- | | `run` | `func(line: string)` | `line` without its slash; its feedback goes to the chat as if typed. | +| `run-quiet` | `func(lines: list)` | `lines` (each without its slash, at most 256 a call) as `run` does, but with nothing in the chat: no feedback and no failure. In single player and on Horizon's servers, each runs exactly as the player typing it would (the same rights), in order, 64 a tick, and the server logs one line a batch; one that carries a chat message (`say`, `msg`) is refused. On any other server they go as chat commands, and there their feedback shows: a mod running many should say so. | ## `ui` diff --git a/docs/api/stability.md b/docs/api/stability.md index f6b40fabe..df2c1aeb3 100644 --- a/docs/api/stability.md +++ b/docs/api/stability.md @@ -38,7 +38,7 @@ don't import it); faster, or fixing behaviour to what the reference already says A new WIT function doesn't break older mods, but a mod that calls it can't run on a Horizon from before it. So every function the game offers mods has an **API level**, the one it arrived at (`crates/horizon-mods/src/api_level.rs`): -level 0 is the contract of Horizon 0.2.67 to 0.2.69, level 1 adds `render.set-minimap` and server mods' `players`, level 2 `game.raycast`. A mod needs the level of +level 0 is the contract of Horizon 0.2.67 to 0.2.69, level 1 adds `render.set-minimap` and server mods' `players`, level 2 `game.raycast`, level 3 `command.run-quiet`. A mod needs the level of the newest function it imports (a component imports only the functions it calls). The level is read from the file, never declared: 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 1b9f270e7..000000000 Binary files a/website/public/og.png and /dev/null differ diff --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}} -
    -
    -
    - -
    -
    -

    06Community

    -

    Built in the open

    - -
    -

    Contributors

    -

    Everyone who has committed to Horizon on GitHub, with how many commits.

    -
      {{CONTRIBUTORS}}
    -
    -
    -
    -
    - -
    -
    - - - -
    - -
    - - -
    - - -
    - - - - 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");