diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml index 79ea852fb..3346e1986 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/launcher.yml @@ -188,9 +188,6 @@ jobs: retry "$launcher" install latest "$launcher" versions --installed "$launcher" links --json - "$launcher" menu-style classic - grep -qx 'menuStyle:classic' "$HORIZON_HOME/horizon.txt" - "$launcher" menu-style horizon clients=("$HORIZON_LAUNCHER_HOME"/versions/v*/horizon-client*) client="${clients[0]}" echo "installed client: $client" diff --git a/README.md b/README.md index 72b6a3496..4abb52b86 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ The [documentation](https://playhorizon.dev/docs/) covers each of these. - **The game:** singleplayer with vanilla's world generation, mobs, villagers, raids, redstone, every command, the HUD and the recipe book, on saves in vanilla's format. Worlds from 1.8 to 26.2 are upgraded as vanilla does. [Status table](#project-status). - **Horizon's own extras:** new menus (vanilla's are one setting away), graphics presets, distant terrain up to 1024 chunks, controller support, optional zoom, minimap and more, all off by default where they would change the vanilla look. See [Settings](https://playhorizon.dev/docs/settings). - **Resource packs, shader packs and data packs:** resource packs work, Java shader packs run their full-screen effects (experimental), and data packs load functions, predicates and item modifiers. -- **Playing with others:** invite friends from the pause menu with a code, Open to LAN, and joining offline-mode servers. Horizon cannot sign in to a Microsoft account yet, so it cannot join servers that check accounts. See [Multiplayer](https://playhorizon.dev/docs/multiplayer). +- **Playing with others:** invite friends from the pause menu's Friends button with a code, Open to LAN, and joining offline-mode servers. Horizon cannot sign in to a Microsoft account yet, so it cannot join servers that check accounts. See [Multiplayer](https://playhorizon.dev/docs/multiplayer). - **Mods:** Horizon has its own mod system (Rust compiled to WebAssembly). Java mod jars do not run. See [Mods and data packs](https://playhorizon.dev/docs/mods). Screenshots, captured in the Rust client itself with vanilla assets and no mods or shaders: @@ -56,8 +56,8 @@ Screenshots, captured in the Rust client itself with vanilla assets and no mods Sunset over a savanna river valley and a plains village - Horizon's title screen over a veiled snowy landscape - The Video settings in their Simple view: a preset, render distance, field of view, framerate, VSync and GUI scale, each with what it costs + Survival at dusk: a zombie walks up, with the hotbar, health, hunger and experience + Vanilla's Video Settings screen with Horizon's own buttons at the top: Horizon Graphics, Advanced Graphics and Shader Packs A plains village among savanna hills, with farms, villagers and an iron golem diff --git a/crates/horizon-client/examples/firework_tooltip_fixture.rs b/crates/horizon-client/examples/firework_tooltip_fixture.rs index 196fa9955..7f10278b7 100644 --- a/crates/horizon-client/examples/firework_tooltip_fixture.rs +++ b/crates/horizon-client/examples/firework_tooltip_fixture.rs @@ -1,7 +1,7 @@ //! Firework tooltip companion for tools/test_firework_tooltip_parity.py: the //! lines `item_tooltip::firework_lines` gives each stack (SNBT, one per line; //! the `#resources` line names the prepared resources for en_us). -use horizon_client::{item_data::parse_stack, item_tooltip::firework_lines, lang::Language}; +use horizon_client::{enchant::Enchantments, item_data::parse_stack, item_tooltip::firework_lines}; use std::{error::Error, fmt::Write, path::PathBuf}; fn main() -> Result<(), Box> { @@ -12,8 +12,9 @@ fn main() -> Result<(), Box> { .find_map(|l| l.strip_prefix("#resources ")) .map(PathBuf::from) .ok_or("no #resources line")?; - let language = Language::load(&[&root], "en_us"); - let translate = |key: &str| language.get(key).map(str::to_owned); + // Use the inventory's filtered translations so missing tooltip keys are caught. + let enchantments = Enchantments::load(&root); + let translate = |key: &str| enchantments.translate(key).map(str::to_owned); let mut output = String::new(); for line in input.lines().filter(|l| !l.starts_with('#')) { let stack = parse_stack(line)?.ok_or("empty stack")?; diff --git a/crates/horizon-client/examples/held_drop_fixture.rs b/crates/horizon-client/examples/held_drop_fixture.rs index 87ca9870c..a0c5d92ba 100644 --- a/crates/horizon-client/examples/held_drop_fixture.rs +++ b/crates/horizon-client/examples/held_drop_fixture.rs @@ -14,13 +14,22 @@ fn main() { for count in [0, 1, 4, 64] { let mut slot = Some(ItemStack::new("minecraft:stone", count)); let mut dropped = 0; + let mut swings = 0; + let mut packets = 0; for _ in 0..2 { if let Some(stack) = take_held_drop(&mut slot, all, mode == GameMode::Spectator) { dropped += stack.count; + swings += 1; } - println!("{} {}", slot.as_ref().map_or(0, |s| s.count), dropped); + if mode != GameMode::Spectator { + packets += 1; + } + println!( + "{} {dropped} {swings} {packets}", + slot.as_ref().map_or(0, |s| s.count), + ); } } } diff --git a/crates/horizon-client/examples/load_bench.rs b/crates/horizon-client/examples/load_bench.rs new file mode 100644 index 000000000..5c30a71ff --- /dev/null +++ b/crates/horizon-client/examples/load_bench.rs @@ -0,0 +1,153 @@ +//! Read-only saved chunk benchmark. All timings exclude resource/corpus setup. +//! +//! load_bench RESOURCES DIMENSION_DIR [--rounds N] [--limit N] [--checksum] +//! Add --profile-worker when a sampling collector cannot sample the main thread. +//! Reports warm filesystem SaveDir::load (read, inflate, NBT, decode and light), +//! plus isolated inflate/NBT and native decode. No files in the save are changed. +use horizon_client::{ + assets::Assets, + biome::Biomes, + blocks::BlockFacts, + save::{SaveDir, SaveTables, decode_with}, +}; +use horizon_world::{nbt::Limits, region::RegionFile}; +use sha2::{Digest, Sha256}; +use std::{hint::black_box, path::PathBuf, sync::Arc, time::Instant}; + +type Result = std::result::Result>; + +fn main() -> Result<()> { + if std::env::args().any(|a| a == "--profile-worker") { + std::thread::spawn(|| run().map_err(|e| e.to_string())) + .join() + .expect("benchmark worker") + .map_err(Into::into) + } else { + run() + } +} + +fn run() -> Result<()> { + let args: Vec = std::env::args().skip(1).collect(); + let usage = "load_bench RESOURCES DIMENSION_DIR [--rounds N] [--limit N] [--checksum]"; + let root = PathBuf::from(args.first().ok_or(usage)?); + let dimension = PathBuf::from(args.get(1).ok_or(usage)?); + let flag = |name: &str, default: usize| -> Result { + Ok(match args.iter().position(|a| a == name) { + Some(i) => args.get(i + 1).ok_or(usage)?.parse()?, + None => default, + }) + }; + let rounds = flag("--rounds", 5)?; + let limit = flag("--limit", 256)?; + if rounds == 0 || limit == 0 { + return Err("rounds and limit must be positive".into()); + } + let assets = Assets::load(&root)?; + let facts = BlockFacts::load(&root, assets.registry)?; + let biomes = Biomes::load(&root)?; + let tables = Arc::new(SaveTables::new(&assets).with_block_entities(&facts)); + let source = SaveDir::new(dimension.clone()); + let _ = source.tables.set(tables.clone()); + let mut paths: Vec<_> = std::fs::read_dir(dimension.join("region"))? + .map(|e| e.map(|e| e.path())) + .collect::>()?; + paths.retain(|p| p.extension().is_some_and(|e| e == "mca")); + paths.sort(); + let mut corpus = Vec::new(); + 'regions: for path in paths { + let mut region = RegionFile::open(path)?; + let mut positions: Vec<_> = region.chunks().map(|(pos, _)| pos).collect(); + positions.sort_by_key(|p| (p.x, p.z)); + for pos in positions { + let record = region.read(pos)?.ok_or("missing record")?; + let tag = record.nbt(Limits::default())?; + if decode_with(&tag, assets.registry, &biomes, Some(&tables)).is_none() { + continue; + } + corpus.push((pos, record, tag)); + if corpus.len() == limit { + break 'regions; + } + } + } + if corpus.is_empty() { + return Err("no full chunks in corpus".into()); + } + let mut records_hash = Sha256::new(); + for (pos, record, _) in &corpus { + records_hash.update(pos.x.to_le_bytes()); + records_hash.update(pos.z.to_le_bytes()); + records_hash.update((record.compressed.len() as u64).to_le_bytes()); + records_hash.update(&record.compressed); + } + println!( + "{}", + serde_json::json!({"corpus": dimension, "chunks": corpus.len(), "rounds": rounds, + "compressed_records_sha256": format!("{:x}", records_hash.finalize()), + "compressed_bytes": corpus.iter().map(|(_, r, _)| r.compressed.len()).sum::()}) + ); + // Prime SaveDir's region handles and the filesystem cache before measurement. + for (pos, _, _) in &corpus { + black_box( + source + .load(pos.x, pos.z, assets.registry, &biomes) + .ok_or("load failed")?, + ); + } + for round in 0..rounds { + let started = Instant::now(); + for (pos, _, _) in &corpus { + black_box( + source + .load(pos.x, pos.z, assets.registry, &biomes) + .ok_or("load failed")?, + ); + } + let load_s = started.elapsed().as_secs_f64(); + let started = Instant::now(); + for (_, record, _) in &corpus { + black_box(record.nbt(Limits::default())?); + } + let nbt_s = started.elapsed().as_secs_f64(); + let started = Instant::now(); + for (_, _, tag) in &corpus { + black_box( + decode_with(tag, assets.registry, &biomes, Some(&tables)).ok_or("decode failed")?, + ); + } + let decode_s = started.elapsed().as_secs_f64(); + println!( + "{}", + serde_json::json!({"round": round, "load_s": load_s, + "inflate_nbt_s": nbt_s, "decode_s": decode_s}) + ); + } + if args.iter().any(|a| a == "--checksum") { + let mut hash = Sha256::new(); + let mut light_loaded = 0; + for (pos, _, _) in &corpus { + let chunk = source + .load(pos.x, pos.z, assets.registry, &biomes) + .ok_or("load failed")?; + hash.update(pos.x.to_le_bytes()); + hash.update(pos.z.to_le_bytes()); + light_loaded += usize::from(chunk.light_loaded); + for section in &chunk.sections { + for i in 0..4096 { + hash.update(section.get(i).to_le_bytes()); + hash.update([section.light(i)]); + } + for i in 0..64 { + hash.update(section.biomes.get(i).to_le_bytes()); + } + } + } + println!( + "{}", + serde_json::json!({"blocks_biomes_light_sha256": format!("{:x}", hash.finalize()), + "light_loaded": light_loaded}) + ); + } + Ok(()) +} diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 2a4969221..a3abb54d9 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -1027,6 +1027,7 @@ fn main() -> horizon_client::Result<()> { nearest_player: player.as_ref().filter(|p| !p.spectator).map(|p| p.position), others: $snapshot, others_grid: $grid, + others_index: None, daylight: (world.day_time.rem_euclid(24000)) < 12000, game_time: world.game_time, day_time: world.day_time, @@ -1132,7 +1133,7 @@ fn main() -> horizon_client::Result<()> { } #[allow(unused_mut)] // filled only with the rng-trace feature let mut traces: Vec = Vec::new(); - let mut pushes = Vec::new(); + let mut pushes = horizon_client::mobs::PendingPushes::default(); let mut born = Vec::new(); for i in 0..mobs.len() { if mobs[i].removed { diff --git a/crates/horizon-client/examples/streaming_bench.rs b/crates/horizon-client/examples/streaming_bench.rs index 9f8e99899..b8c56b28c 100644 --- a/crates/horizon-client/examples/streaming_bench.rs +++ b/crates/horizon-client/examples/streaming_bench.rs @@ -3,6 +3,7 @@ //! what the render thread pays for it in `Streaming::update`. //! //! streaming_bench RESOURCES [--threads N] [--radius R] [--seed S] [--fly CHUNKS_PER_S] [--seconds T] [--hz F] +//! [--dimension overworld|the_nether|the_end] [--center-x X] [--center-z Z] //! //! First the area around (0, 0) fills; then, with `--fly`, the centre moves along +x //! at that speed for T seconds while frames run at F per second. Each phase reports @@ -72,14 +73,33 @@ static ALLOCATOR: CountingAllocator = CountingAllocator; type Result = std::result::Result>; +fn cpu_seconds() -> f64 { + std::fs::read_to_string("/proc/self/stat") + .ok() + .and_then(|stat| { + let fields = stat + .rsplit_once(')')? + .1 + .split_whitespace() + .collect::>(); + Some((fields[11].parse::().ok()? + fields[12].parse::().ok()?) / 100.0) + }) + .unwrap_or(0.0) +} + #[derive(Default)] struct Phase { updates: Vec, local: (u64, u64), uploads: usize, + stage_samples: [u64; 7], + cpu_start: f64, } impl Phase { fn update(&mut self, streaming: &mut Streaming, world: &mut World) { + if self.updates.is_empty() { + self.cpu_start = cpu_seconds(); + } let before = LOCAL.with(Cell::get); let started = Instant::now(); let (uploads, _) = streaming.update(world); @@ -89,6 +109,9 @@ impl Phase { self.local.1 += after.1 - before.1; self.uploads += uploads.len(); drop(uploads); + for (sum, (_, count)) in self.stage_samples.iter_mut().zip(streaming.stages()) { + *sum += count as u64; + } } fn report(&self, name: &str, wall: Duration, streaming: &Streaming, generated: u64) { let mut sorted = self.updates.clone(); @@ -106,6 +129,16 @@ impl Phase { at(0.99), sorted.last().copied().unwrap_or(0.0), ); + println!( + "BENCH {}", + serde_json::json!({ + "phase": name, "wall_s": wall.as_secs_f64(), + "cpu_s": cpu_seconds() - self.cpu_start, + "chunks": streaming.generated_total - generated, "sections": self.uploads, + "updates": self.updates.len(), "update_ms": total, + "mean_stages": self.stage_samples.map(|n| n as f64 / self.updates.len() as f64), + }) + ); if TRACK { println!( " update allocations: {} ({:.1} MiB)", @@ -142,6 +175,22 @@ fn main() -> Result<()> { let fly = flag("--fly", 0.0); let seconds = flag("--seconds", 10.0); let hz = flag("--hz", 240.0); + let dimension = args + .iter() + .position(|a| a == "--dimension") + .and_then(|i| args.get(i + 1)) + .map(|d| { + if d.contains(':') { + d.clone() + } else { + format!("minecraft:{d}") + } + }) + .unwrap_or_else(|| "minecraft:overworld".into()); + let center = ( + flag("--center-x", 0.0) as i32, + flag("--center-z", 0.0) as i32, + ); let assets = Arc::new(Assets::load(&root)?); let render = Arc::new(assets.reload(&root)?); @@ -154,11 +203,12 @@ fn main() -> Result<()> { models::load_visibility(&root, assets.registry)?, )?); let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?); - let terrain = Arc::new(VanillaTerrain::new( + let terrain = Arc::new(VanillaTerrain::for_dimension( &root.join("worldgen"), assets.registry, &biomes, seed, + &dimension, )?); let context = Arc::new(WorkerContext { assets, @@ -170,8 +220,12 @@ fn main() -> Result<()> { let mut world = World::new(facts.air, seed); let mut streaming = Streaming::new(terrain, context, threads); streaming.radius = radius; - streaming.center = (0, 0); - println!("{threads} workers, radius {radius}, seed {seed}"); + streaming.center = center; + streaming.nether_shading = dimension == "minecraft:the_nether"; + streaming.sky_light = dimension != "minecraft:the_nether"; + println!( + "{threads} workers, radius {radius}, seed {seed}, dimension {dimension}, center {center:?}" + ); let (allocations, bytes) = (ALLOCATIONS.load(Relaxed), BYTES.load(Relaxed)); // Fill: update as often as the game would uncapped, until settled. @@ -198,12 +252,12 @@ fn main() -> Result<()> { let mut behind = Vec::new(); while started.elapsed().as_secs_f64() < seconds { let next = Instant::now() + frame; - let x = (started.elapsed().as_secs_f64() * fly) as i32; - streaming.center = (x, 0); + let x = center.0 + (started.elapsed().as_secs_f64() * fly) as i32; + streaming.center = (x, center.1); phase.update(&mut streaming, &mut world); // Columns within 2 chunks of the player still missing their meshes. let near = (-2..=2) - .flat_map(|dz| (-2..=2).map(move |dx| (x + dx, dz))) + .flat_map(|dz| (-2..=2).map(move |dx| (x + dx, center.1 + dz))) .filter(|&(cx, cz)| !streaming.is_lit(cx, cz)) .count(); behind.push(near); diff --git a/crates/horizon-client/examples/weather_fixture.rs b/crates/horizon-client/examples/weather_fixture.rs index 15aab6bdb..3cf6c31be 100644 --- a/crates/horizon-client/examples/weather_fixture.rs +++ b/crates/horizon-client/examples/weather_fixture.rs @@ -11,6 +11,7 @@ fn bits(value: f32) -> String { fn main() -> Result<(), Box> { let args: Vec<_> = std::env::args().collect(); let mut output = String::new(); + let mut parameters = weather::ParameterCache::default(); for (case, line) in fs::read_to_string(&args[1])?.lines().enumerate() { let p: Vec<&str> = line.split_whitespace().collect(); let int = |i: usize| p[i].parse::().unwrap(); @@ -38,6 +39,13 @@ fn main() -> Result<(), Box> { bits(column.v_offset), column.light_coords )?; + assert_eq!( + parameters + .get(x, z) + .column(kind != 0, ticks, x, bottom, top, z, light, partial), + column, + "cached parameters differ from original random source at case {case}" + ); let max_alpha = if kind == 0 { 1.0 } else { 0.8 }; for v in weather::column_quad(&column, camera, max_alpha, radius, intensity) { write!( diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 6a135799c..854332815 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -528,7 +528,7 @@ impl Furnace { let has_fuel = self.items[1].is_some(); if lit || has_fuel && has_ingredient { if let Some(ingredient) = self.items[0].clone() { - if let Some(recipe) = recipes.cook(self.kind.recipe_type(), &ingredient).cloned() { + if let Some(recipe) = recipes.cook(self.kind.recipe_type(), &ingredient) { if self.cooking_timer == 0 { self.cooking_total = total_time(recipe.time, self.speed); } diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index e96ca0067..d0b8906ee 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -1102,7 +1102,11 @@ pub struct Recipes { facts: HashMap, Facts>, /// The `#minecraft:curse` enchantments. curses: HashSet, + /// The first cooking recipe of each kind taking each item, built at the + /// first lookup (furnaces look theirs up every tick). + cook_index: std::sync::OnceLock, } +type CookIndex = HashMap>; /// `MinMaxBounds.Ints` as (min, max) with the given defaults. fn bounds(v: Option<&Value>, default: (i64, i64), open: (i64, i64)) -> (i64, i64) { match v { @@ -1421,6 +1425,7 @@ impl Recipes { meta, facts, curses, + cook_index: Default::default(), }) } /// Match a `size`x`size` grid (row-major) against the crafting recipes. @@ -1606,6 +1611,22 @@ impl Recipes { out } pub fn cook(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> { + let index = self.cook_index.get_or_init(|| { + let mut index = CookIndex::new(); + for (i, c) in self.cooking.iter().enumerate() { + let of_kind = index.entry(c.kind.clone()).or_default(); + for item in &c.ingredient.0 { + of_kind.entry(item.clone()).or_insert(i); + } + } + index + }); + let i = *index.get(kind)?.get(&*input.item)?; + self.cooking.get(i) + } + /// `cook` by scanning every recipe, as it was before the index. + #[cfg(test)] + fn cook_scan(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> { self.cooking .iter() .find(|c| c.kind == kind && c.ingredient.test(input)) @@ -1625,6 +1646,80 @@ mod tests { s.data_mut().banner_patterns = vec![BannerLayer::new("minecraft:cross", "red")]; s } + /// About vanilla's count of cooking recipes: four kinds, ingredients of + /// one to twelve items, overlapping (several recipes take some items). + fn cooking_book() -> Recipes { + let kinds = ["smelting", "blasting", "smoking", "campfire_cooking"]; + let cooking = (0..320usize) + .map(|i| Cooking { + id: format!("r{i}"), + category: "misc".into(), + group: String::new(), + kind: kinds[i % 4].into(), + ingredient: ingredient( + &(0..1 + i % 12) + .map(|k| format!("minecraft:item_{}", (i * 7 + k * 13) % 400)) + .collect::>() + .iter() + .map(String::as_str) + .collect::>(), + ), + result: ItemStack::new("minecraft:stone", 1), + experience: 0.1, + time: 200, + }) + .collect(); + Recipes { + crafting: Vec::new(), + cooking, + meta: HashMap::new(), + facts: HashMap::new(), + curses: HashSet::new(), + cook_index: Default::default(), + } + } + #[test] + fn cook_finds_the_first_recipe_the_scan_finds() { + let recipes = cooking_book(); + for kind in [ + "smelting", + "blasting", + "smoking", + "campfire_cooking", + "other", + ] { + for n in 0..420 { + let stack = ItemStack::new(&format!("minecraft:item_{n}"), 1); + let a = recipes.cook(kind, &stack).map(|c| &c.id); + let b = recipes.cook_scan(kind, &stack).map(|c| &c.id); + assert_eq!(a, b, "{kind} item_{n}"); + } + } + } + /// A furnace's recipe lookup, once per lit furnace per tick. + #[test] + #[ignore] + fn cook_cost() { + let recipes = cooking_book(); + let stacks: Vec = (0..1000) + .map(|n| ItemStack::new(&format!("minecraft:item_{}", n % 400), 1)) + .collect(); + let t = std::time::Instant::now(); + let a = stacks + .iter() + .filter(|s| recipes.cook_scan("smelting", s).cloned().is_some()) + .count(); + let before = t.elapsed().as_secs_f64() * 1e3; + recipes.cook("smelting", &stacks[0]); + let t = std::time::Instant::now(); + let b = stacks + .iter() + .filter(|s| recipes.cook("smelting", s).is_some()) + .count(); + let after = t.elapsed().as_secs_f64() * 1e3; + assert_eq!(a, b); + println!("1000 furnace lookups (scan and clone -> index): {before:.3} ms -> {after:.3} ms"); + } fn run(special: &Special, cells: &[ItemStack]) -> Option { let recipes = Recipes { crafting: Vec::new(), @@ -1632,6 +1727,7 @@ mod tests { meta: HashMap::new(), facts: HashMap::new(), curses: HashSet::new(), + cook_index: Default::default(), }; let ctx = Context { recipes: &recipes, diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs index 039ea658f..ca2ea6f5c 100644 --- a/crates/horizon-client/src/enchant.rs +++ b/crates/horizon-client/src/enchant.rs @@ -193,6 +193,8 @@ impl Enchantments { || k.starts_with("item.minecraft.splash_potion") || k.starts_with("item.minecraft.lingering_potion") || k.starts_with("item.minecraft.tipped_arrow") + || k.starts_with("item.minecraft.firework_rocket.") + || k.starts_with("item.minecraft.firework_star.") || k.starts_with("trim_") || k.starts_with("potion.") || k.starts_with("container.") diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index ed8fe4dec..cfbdb0636 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -583,6 +583,10 @@ pub struct ArmorStand { pub no_base_plate: bool, pub invisible: bool, pub marker: bool, + /// `CustomName`: the text of a hologram. + pub custom_name: Option, + /// `CustomNameVisible`. + pub name_visible: bool, /// Game time of the last hit (the wobble and the second-hit window). pub last_hit: i64, } @@ -603,6 +607,8 @@ impl ArmorStand { no_base_plate: false, invisible: false, marker: false, + custom_name: None, + name_visible: false, last_hit: i64::MIN / 2, } } diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index 2c6af26f9..2e865dfb1 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -43,6 +43,7 @@ struct Out { @location(8) back_color: vec4, // entity.vsh's lightMapColor, multiplied in after the overlay. @location(9) light_color: vec4, + @location(10) @interpolate(flat) weather_rect: vec4, } // Shipped light.glsl; normals are already transformed and RGBA8_SNORM packed. fn entity_light(normal: vec3, nether: bool) -> f32 { @@ -109,6 +110,13 @@ fn entity_vertex(position: vec3, uv: vec2, @location(2) overlay: u32, @location(3) color: vec4, @location(4) light: vec4, @location(5) normal: vec4) -> Out { return entity_vertex(position, uv, overlay, color, light, normal); } +// Retained bolt-local geometry, translated using the same f64 camera +// subtraction as the former CPU path before adding each local f32 position. +@vertex fn vs_lightning(@location(0) position: vec3, @location(1) uv: vec2, + @location(2) overlay: u32, @location(3) color: vec4, @location(4) light: vec4, @location(5) normal: vec4, + @location(6) offset: vec3) -> Out { + return entity_vertex(offset + position, uv, overlay, color, light, normal); +} struct CloudInfo { offset: vec4, colors: array, 4>, @@ -209,3 +217,135 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { @fragment fn fs_water_mask() -> @location(0) vec4 { return vec4(0.0); } + +// WEATHER_MATH_BEGIN +// Unsigned 64-bit helpers (low word first). Snow adds a random double to a +// float drift before casting to float. Retaining the 53-bit base avoids early +// rounding, including ties, without requiring optional GPU float64 support. +fn weather_shr_jam(v: vec2, n: u32) -> vec2 { + if n == 0u { return v; } + if n < 32u { + return vec2((v.x >> n) | (v.y << (32u - n)) | select(0u, 1u, (v.x << (32u - n)) != 0u), v.y >> n); + } + if n == 32u { return vec2(v.y | select(0u, 1u, v.x != 0u), 0u); } + if n < 64u { + return vec2((v.y >> (n - 32u)) | select(0u, 1u, v.x != 0u || (v.y << (64u - n)) != 0u), 0u); + } + return vec2(select(0u, 1u, any(v != vec2(0u))), 0u); +} +fn weather_add64(a: vec2, b: vec2) -> vec2 { + let lo = a.x + b.x; + return vec2(lo, a.y + b.y + select(0u, 1u, lo < a.x)); +} +fn weather_sub64(a: vec2, b: vec2) -> vec2 { + return vec2(a.x - b.x, a.y - b.y - select(0u, 1u, a.x < b.x)); +} +fn weather_double_plus_float(base: vec2, delta: f32) -> f32 { + // The random base is nonnegative and either zero or >= 2^-53. + if all(base == vec2(0u)) { return select(delta, 0.0, delta == 0.0); } + let db = bitcast(delta); + let mag = db & 0x7fffffffu; + let be = i32((base.y >> 20u) & 2047u) - 1023; + var de = i32(mag >> 23u) - 127; + var dm = (mag & 0x7fffffu) | 0x800000u; + if mag < 0x800000u { + dm = mag; + if dm == 0u { de = -200; } + else { + let shift = countLeadingZeros(dm) - 8u; + dm <<= shift; + de = -126 - i32(shift); + } + } + let e = max(be, de); + // Leading significand bit at 61, with room for addition and guard bits. + var a = vec2(base.x << 9u, ((base.y & 0xfffffu) | 0x100000u) << 9u | (base.x >> 23u)); + var b = vec2(0u, dm << 6u); + a = weather_shr_jam(a, u32(e - be)); + b = weather_shr_jam(b, u32(e - de)); + var sign = 0u; + var value: vec2; + if (db >> 31u) == 0u { value = weather_add64(a, b); } + else if a.y > b.y || (a.y == b.y && a.x >= b.x) { value = weather_sub64(a, b); } + else { value = weather_sub64(b, a); sign = 0x80000000u; } + if all(value == vec2(0u)) { return 0.0; } + let leading = select(31u - countLeadingZeros(value.x), 63u - countLeadingZeros(value.y), value.y != 0u); + var exponent = e + i32(leading) - 61; + // Normalize the leading bit to 62. After jamming, bit 38 is the guard + // bit and bits 0..37 distinguish a tie from a value above the midpoint. + let shift = 62u - leading; + if shift >= 32u { value = vec2(0u, value.x << (shift - 32u)); } + else if shift != 0u { value = vec2(value.x << shift, (value.y << shift) | (value.x >> (32u - shift))); } + // Vanilla first rounds the addition to double, then casts to float. + // Round at bit 10 (53 retained bits) before the 24-bit rounding below; + // otherwise a double-rounding midpoint can select the wrong float. + let double_guard = (value.x & 512u) != 0u; + let double_sticky = (value.x & 511u) != 0u; + let double_odd = (value.x & 1024u) != 0u; + value.x &= 0xfffffc00u; + if double_guard && (double_sticky || double_odd) { + value = weather_add64(value, vec2(1024u, 0u)); + } + if (value.y & 0x80000000u) != 0u { + value = weather_shr_jam(value, 1u); + exponent += 1; + } + var mantissa = value.y >> 7u; + let guard = (value.y & 64u) != 0u; + let sticky = (value.y & 63u) != 0u || value.x != 0u; + if guard && (sticky || (mantissa & 1u) != 0u) { mantissa += 1u; } + if mantissa >= 0x1000000u { mantissa >>= 1u; exponent += 1; } + return bitcast(sign | (u32(exponent + 127) << 23u) | (mantissa & 0x7fffffu)); +} +fn weather_phase(animation: vec4, bases: vec4, snow: u32, time: vec4) -> vec2 { + if snow == 0u { + let ticks = time.x + animation.y; + let t = ticks + time.z; + let step = -t / 32.0; + let offset = step * animation.x; + return vec2(0.0, offset % 32.0); + } + let t = time.x + time.z; + let u_time = t * 0.01; + let du = u_time * animation.z; + let v_time = t * animation.w; + let dv = v_time * 0.001; + let u = weather_double_plus_float(bases.xy, du); + let v = weather_double_plus_float(bases.zw, dv); + let fall_time = time.y + time.z; + let fall = -fall_time / 512.0; + return vec2(u, fall + v); +} +// Atlas sampler is nearest with no mipmaps. Clamp the integer texel inside +// the sprite even when a fractional coordinate rounds up at its far edge. +fn weather_texel(uv: vec2, rect: vec4, dimensions: vec2) -> vec2 { + let size = vec2(dimensions); + let origin = vec2(round(rect.xy * size)); + let extent = max(vec2(round(rect.zw * size)), vec2(1)); + let local = min(vec2(floor(fract(uv) * vec2(extent))), extent - vec2(1)); + return origin + local; +} +// WEATHER_MATH_END + +struct WeatherTime { values: vec4 } +@group(1) @binding(1) var weather_time: WeatherTime; +@vertex fn vs_weather(@location(0) position: vec3, @location(1) uv: vec2, + @location(2) rect: vec4, @location(3) animation: vec4, + @location(4) bases: vec4, @location(5) color: vec4, + @location(6) light: vec4, @location(7) snow: u32) -> Out { + let phase = weather_phase(animation, bases, snow, weather_time.values); + var out = entity_vertex(position, uv + phase, 0u, color, light, vec4(0.0)); + out.weather_rect = rect; + return out; +} +@fragment fn fs_weather(in: Out) -> @location(0) vec4 { + // Repeat within this sprite, never across the atlas. The atlas uses nearest + // filtering and no mipmaps, so fractional UVs have no seam derivatives. + let texel = weather_texel(in.uv, in.weather_rect, textureDimensions(atlas)); + var color = textureLoad(atlas, texel, 0) * in.color; + if color.a < 0.1 { discard; } + color *= in.light_color; + let f = max(linear_fog(in.spherical, globals.fog.x, globals.fog.y), + linear_fog(in.cylindrical, globals.fog.z, globals.fog.w)); + return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a); +} diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index d9cf20db5..aaccdd844 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -13,6 +13,7 @@ use crate::{ doubles, float, floats, item_from_nbt, item_to_nbt, number, put, read_doubles, text, uuid_from_tag, }, + text::Text, }; use horizon_core::geometry::Vec3; use horizon_world::nbt::{Compound, Tag}; @@ -555,6 +556,14 @@ fn custom_name(tag: &Tag) -> Option { _ => None, } } +/// `CustomName` as text: a string keeps its legacy formatting codes, anything +/// else is a component (`ComponentSerialization`). +pub fn name_text(tag: &Tag) -> Text { + match tag { + Tag::String(s) => Text::legacy(&s.to_string_lossy()), + t => crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t)), + } +} pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) -> Option { let kind = types.get(&self::kind(tag)?)?.clone(); let position = position(tag)?; @@ -606,6 +615,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.persistent = flag(tag, "PersistenceRequired"); m.extra.pick_up_loot = flag(tag, "CanPickUpLoot"); m.custom_name = custom_name(tag); + m.custom_name_text = tag.get("CustomName").map(name_text); if m.kind.category == "creature" { m.extra.age = number(tag.get("Age")).unwrap_or(0) as i32; m.extra.forced_age = number(tag.get("ForcedAge")).unwrap_or(0) as i32; @@ -1266,6 +1276,21 @@ pub fn armor_stand_to_nbt(a: &ArmorStand, uuid: [i32; 4], raw: Option<&Tag>) -> } else if let Tag::Compound(map) = &mut tag { map.remove(&"Marker".into()); } + if a.name_visible { + put(&mut tag, "CustomNameVisible", Tag::Byte(1)); + } else if let Tag::Compound(map) = &mut tag { + map.remove(&"CustomNameVisible".into()); + } + // A name from the save keeps its own shape unless it changed. + if let Some(name) = &a.custom_name + && !tag.get("CustomName").is_some_and(|t| name_text(t) == *name) + { + put( + &mut tag, + "CustomName", + crate::scoreboard::json_to_tag(&name.component()), + ); + } put(&mut tag, "Health", Tag::Float(a.health.to_bits())); put(&mut tag, "Fire", Tag::Short(a.fire_ticks as i16)); // LivingEntity.addAdditionalSaveData and ArmorStand's own fields. @@ -1294,6 +1319,8 @@ pub fn armor_stand_from_nbt(tag: &Tag, id: u32) -> Option { a.velocity = motion(tag); a.health = float(tag.get("Health")).unwrap_or(20.0) as f32; a.fire_ticks = number(tag.get("Fire")).unwrap_or(0) as i32; + a.custom_name = tag.get("CustomName").map(name_text); + a.name_visible = flag(tag, "CustomNameVisible"); if let Some(eq) = tag.get("equipment") { for (i, slot) in ArmorStand::SLOTS.iter().enumerate() { a.equipment[i] = eq.get(slot).and_then(item_from_nbt); @@ -1574,6 +1601,31 @@ mod tests { assert!(ominous_item_spawner_from_nbt(&raw).is_none()); } + #[test] + fn armor_stand_names_keep_their_formatting_across_a_save() { + let tag = Tag::compound([ + ( + "Pos", + Tag::List(vec![ + Tag::Double(0.0f64.to_bits()), + Tag::Double(64.0f64.to_bits()), + Tag::Double(0.0f64.to_bits()), + ]), + ), + ("CustomName", string("§6Hello")), + ("CustomNameVisible", Tag::Byte(1)), + ]); + let a = armor_stand_from_nbt(&tag, 7).unwrap(); + let name = a.custom_name.as_ref().unwrap(); + assert_eq!(name.plain(), "Hello"); + assert!(name.spans[0].style.color.is_some()); + assert!(a.name_visible); + let saved = armor_stand_to_nbt(&a, [0; 4], Some(&tag)); + let restored = armor_stand_from_nbt(&saved, 7).unwrap(); + assert_eq!(restored.custom_name, a.custom_name); + assert!(restored.name_visible); + } + #[test] fn falling_block_round_trip_keeps_impact_distance_and_settings() { let state = Tag::compound([("Name", string("minecraft:damaged_anvil"))]); diff --git a/crates/horizon-client/src/friends_screen.rs b/crates/horizon-client/src/friends_screen.rs new file mode 100644 index 000000000..7577e2add --- /dev/null +++ b/crates/horizon-client/src/friends_screen.rs @@ -0,0 +1,303 @@ +//! Play with Friends: Horizon's own sharing of the open world behind an +//! invite code (`game/friends.rs`). The pause menu's Friends button, the icon +//! vanilla's PauseScreen already has, opens it. It is drawn the way a mod adds +//! a screen to vanilla: the menu background, a centred title and text, +//! vanilla's buttons and Done in the footer. +use crate::{ + hud::{HudAtlas, HudBatch, rgba}, + multiplayer::wrap, + text::Text, + ui, +}; + +pub const TITLE: &str = "Play with Friends"; +/// What the screen shows (game/friends.rs fills it). +#[derive(Clone, Debug, Default)] +pub struct FriendsView { + /// A singleplayer world (not a server): sharing is offered. + pub shown: bool, + pub sharing: bool, + pub code: Option, + /// Who can join and what to do when friends on the internet can't (or, + /// before the code, what the game is doing). + pub status: String, + /// Friends on the internet can reach the host. + pub reachable: bool, + /// Where the troubleshooting is, when they can't. + pub help: Option, + /// The players in the world besides the host. + pub guests: Vec, + pub notice: Option, + /// The code was just copied. + pub copied: bool, +} + +/// A button's action. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Action { + Share, + Copy, + Stop, + /// Open the troubleshooting page. + Help, + Done, +} + +fn grey() -> u32 { + rgba(160, 160, 160, 255) +} +const WHITE: u32 = u32::MAX; +const HINT: &str = "Friends paste the code after the title screen's Friends button, in Direct Connection, or on the launcher's Play page."; + +struct Button { + x: f32, + y: f32, + w: f32, + label: &'static str, + action: Action, + active: bool, +} + +/// The centred lines (text, colour, y) and the buttons. +fn layout( + atlas: &HudAtlas, + (w, h): (f32, f32), + view: &FriendsView, +) -> (Vec<(String, u32, f32)>, Vec - - -
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
-
Horizon's title screen: the mark and the pages on the left, the Horizon title, Singleplayer and Multiplayer, the last world played and the faint wordmark, over a veiled snowy landscape
-
The Singleplayer page: the worlds as a numbered list with their dates and game modes, and Create world and Play
-
The Video settings in their Simple view: a preset, render distance, field of view, framerate, VSync and GUI scale, each with what it costs
-
The pause screen of a world, with Back to game, Open to LAN and Save and quit
+
Vanilla's Video Settings screen with Horizon's own buttons at the top: Horizon Graphics, Advanced Graphics and Shader Packs
-

The launcher, and Horizon's own menus in the game. The launcher opens them, or vanilla's.

+

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