diff --git a/.github/workflows/promote.yml b/.github/workflows/promote.yml index 389d99712..3966f571b 100644 --- a/.github/workflows/promote.yml +++ b/.github/workflows/promote.yml @@ -1,7 +1,7 @@ name: promote # Beta game releases become stable once a day (docs/release-flow.md, "Channels"): at 20:00 UTC (21:00 in Paris in # winter time, 22:00 in summer) tools/release_channels.py promotes the newest beta that had been out 6 hours by then, -# passed its release smoke test and isn't covered by an issue labelled release-blocker. Launchers on the Nightly +# passed its release smoke test and isn't covered by an issue labelled release-blocker. Launchers on the Alpha # channel install every beta when it is published; Stable gets the day's promotion. The later runs of the evening are # retries for a run GitHub starts late or skips: they promote the same beta, so stable still moves once. # By hand, from GitHub's app too (Actions > promote > Run workflow): diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6c1ecf422..b19ba9ce5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -349,7 +349,7 @@ jobs: run: | signature=(); [[ -f dist/SHA256SUMS.sig ]] && signature=(dist/SHA256SUMS.sig) smoke=(); [[ -f dist/smoke-test.json ]] && smoke=(dist/smoke-test.json) - # A beta (pre-release), the Nightly channel's: promote.yml makes it stable and latest in its daily promotion + # A beta (pre-release), the Alpha channel's: promote.yml makes it stable and latest in its daily promotion # (docs/release-flow.md). gh release create "$TAG" --target "${{ needs.decide.outputs.head }}" --title "$(cat notes/title.txt)" \ --notes-file notes/body.md --prerelease --latest=false dist/horizon-linux-x86_64.tar.gz \ 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/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..3b5dd9dcc 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -109,6 +109,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>, 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/game.rs b/crates/horizon-client/src/game.rs index 04c8d5ed1..dfe1a714e 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -214,6 +214,7 @@ use horizon_world::{ registry::BlockStateId, }; use std::{ + cell::RefCell, collections::{HashMap, HashSet}, path::PathBuf, sync::{ @@ -272,9 +273,10 @@ struct Options { benchmark: Option, /// `--dev-mod PATH` (repeatable): mods always on and reloaded when rebuilt. dev_mods: Vec, - /// Single player runs on an integrated server thread (game/integrated.rs), - /// as vanilla's does: the default. `--no-server-thread` or - /// `HORIZON_SERVER_THREAD=0` runs the world in the frame instead. + /// `--server-thread` or `HORIZON_SERVER_THREAD=1`: single player runs on an + /// integrated server thread (game/integrated.rs), as vanilla's does. Off by + /// default again until a server's players can board, ride and hit + /// vehicles (#1222); `--no-server-thread` keeps it off. server_thread: bool, /// Set on the integrated server's own options: it draws nothing, so it skips meshing. integrated: bool, @@ -331,7 +333,7 @@ impl Options { dev_mods: Vec::new(), // The command harness (HORIZON_COMMAND_SCRIPT) drives the world // itself, without the event loop: it stays in the frame. - server_thread: std::env::var("HORIZON_SERVER_THREAD").map_or(true, |v| v != "0") + server_thread: std::env::var("HORIZON_SERVER_THREAD").is_ok_and(|v| v == "1") && std::env::var_os("HORIZON_COMMAND_SCRIPT").is_none(), integrated: false, }; @@ -341,7 +343,7 @@ impl Options { match arg.as_str() { "--help" | "-h" => { println!( - "Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --no-server-thread Run single player's world in the frame, not on its server thread\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.", + "Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --server-thread Run single player's world on its server thread (no vehicles yet)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.", horizon_core::VANILLA_VERSION ); return Ok(None); @@ -1387,7 +1389,7 @@ struct Game<'a> { map_patches: Vec, /// Player skin downloads, and which skin each atlas skin slot holds /// (least recently shown first). - skin_downloads: horizon_client::skins::Downloader, + skin_downloads: RefCell, skin_slots: Vec<(String, usize)>, cart_models: minecarts::CartModels, /// The boat the player rides. @@ -1417,6 +1419,8 @@ struct Game<'a> { arrow_model: Option, tnts: Vec, hoppers: HashMap<(i32, i32, i32), machines::HopperState>, + /// Where item entities are, while the block entities tick (hoppers). + item_columns: Option, creative_screen: Creative, control: Option, frame_stats: horizon_client::control::FrameStats, @@ -4485,10 +4489,17 @@ impl Game<'_> { }; if capture { self.mouse.set_ignore_first_move(); + // macOS warps by re-associating the mouse with the pointer, + // which undoes a Locked grab and leaves the pointer free: warp + // first there. Wayland moves a pointer only while it is locked, + // so everywhere else warp after grabbing. + #[cfg(target_os = "macos")] + warp(window); self.captured = window .set_cursor_grab(CursorGrabMode::Locked) .or_else(|_| window.set_cursor_grab(CursorGrabMode::Confined)) .is_ok(); + #[cfg(not(target_os = "macos"))] if self.captured && self.focused { warp(window); } @@ -4838,6 +4849,9 @@ impl Game<'_> { self.draw_chat(&mut batch); self.draw_tab_list(&mut batch); } + // Screen.extractBlurredBackground blurs the world and HUD, while the + // screen's background, widgets, toasts and debug overlay stay sharp. + batch.blur_at = batch.vertices.len() as u32; match self.screen { Screen::Paused if self.pause_menu => self.draw_pause_menu(&mut batch), // PauseScreen(false): only its title, at the top. @@ -9775,15 +9789,17 @@ impl Game<'_> { self.entity_geometry(camera, alpha, entities) }); } + let bolts = if title { + Vec::new() + } else { + self.bolt_instances() + }; let mut additive = Vec::new(); - if !title { - self.bolt_geometry(camera, &mut additive); - if self.dim == Dim::End { - let mut dragon = Vec::new(); - self.dragon_geometry(camera, alpha, &mut dragon, &mut additive); - self.dragon_fireball_geometry(camera, alpha, &mut dragon); - entities.extend(dragon); - } + if !title && self.dim == Dim::End { + let mut dragon = Vec::new(); + self.dragon_geometry(camera, alpha, &mut dragon, &mut additive); + self.dragon_fireball_geometry(camera, alpha, &mut dragon); + entities.extend(dragon); } // A Java pack's `clouds` replaces the cloud option (`renderClouds`: // "false", "fast", "true"), as Iris overrides `getCloudsType`. @@ -9805,8 +9821,8 @@ impl Game<'_> { { // Camera.doesMobEffectBlockSky: no sun, moon or stars. self.celestial_geometry(&sky) - } else if self.dim == Dim::End { - (self.end_sky_geometry(), None) + } else if self.dim == Dim::End && self.settings.horizon.sky { + (self.end_flash_geometry(), None) } else { (Vec::new(), None) }; @@ -9853,6 +9869,12 @@ impl Game<'_> { title: title && !live, skybox: self.dim == Dim::Overworld && self.settings.horizon.sky, end_sky: self.dim == Dim::End && self.settings.horizon.sky, + end_sky_sprite: self + .gui + .atlas + .sprites + .get("environment/end_sky") + .map(|r| [r.u0, r.v0, r.u1, r.v1]), environment_fog: (self.dim == Dim::Nether).then_some((sky.fog_start, sky.fog_end)), cave_culling, water_fog, @@ -9895,6 +9917,13 @@ impl Game<'_> { }), entities: &entities, dynamic_lights: &self.dynamic_lights, + lightning: horizon_client::gfx::lightning::Input { + bolts: &bolts, + uv: [ + self.gui.atlas.font.white().u0, + self.gui.atlas.font.white().v0, + ], + }, additive: &additive, see_through: &see_through, celestial: if self.settings.horizon.sky || title { @@ -10000,9 +10029,8 @@ impl Game<'_> { }; level_loading::draw(batch, atlas, Some(&status), Some(self.loading_progress)); } - /// `Screen.extractBlurredBackground` over the panorama: every classic - /// screen of the title menus but the title itself (`TitleScreen` - /// doesn't blur), when `menuBackgroundBlurriness` is at least 1. + /// `Screen.extractBlurredBackground` over the panorama or the world and + /// HUD, when `menuBackgroundBlurriness` is at least 1. fn menu_blur(&self) -> Option { let loading = self.loading_reason() == Some(horizon_client::level_loading::Reason::Other); let blurred = !horizon_client::ui_theme::horizon() @@ -10010,7 +10038,10 @@ impl Game<'_> { || self.title.as_ref().is_some_and(|t| { self.screen == Screen::Options || !matches!(t.mode, horizon_client::title::Mode::Main) - })); + }) + || (self.title.is_none() + && self.player.is_some() + && self.screen.blurs_background(self.pause_menu))); let radius = self.settings.menu_blur as f32; (blurred && radius >= 1.0).then_some(radius) } @@ -11620,11 +11651,11 @@ impl<'a> Game<'a> { breath_clouds: Vec::new(), dragon_model: prepared.dragon_model, map_patches: Vec::new(), - skin_downloads: horizon_client::skins::Downloader::new( + skin_downloads: RefCell::new(horizon_client::skins::Downloader::new( std::env::current_dir() .unwrap_or_default() .join("assets/skins"), - ), + )), skin_slots: Vec::new(), cart_models: prepared.cart_models, riding: None, @@ -11644,6 +11675,7 @@ impl<'a> Game<'a> { arrow_model: prepared.arrow_model, tnts: Vec::new(), hoppers: HashMap::new(), + item_columns: None, creative_screen: prepared.creative_screen, control: None, frame_stats: Default::default(), @@ -12356,6 +12388,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> { title: true, skybox: false, end_sky: false, + end_sky_sprite: None, environment_fog: None, water_fog: [0.0; 3], fog: None, @@ -12370,6 +12403,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> { entities: &[], dynamic_lights: &[], clouds: None, + lightning: Default::default(), additive: &[], see_through: &[], celestial: &[], diff --git a/crates/horizon-client/src/game/allays.rs b/crates/horizon-client/src/game/allays.rs index 52dfa7e1c..bed835663 100644 --- a/crates/horizon-client/src/game/allays.rs +++ b/crates/horizon-client/src/game/allays.rs @@ -9,18 +9,28 @@ impl Game<'_> { pub(super) fn tick_allays(&mut self) { let griefing = self.ui.rules.bool("mob_griefing"); let player = self.player.as_ref().map(|p| p.position); + // The playing jukeboxes, found at the first allay: no allay starts + // or stops one, and the block entities run into the thousands. + let mut jukeboxes: Option> = None; for i in 0..self.mobs.len() { if self.mobs[i].species() != Species::Allay || !self.mobs[i].alive() { continue; } let pos = self.mobs[i].position; // Dancing: a playing jukebox within 10 blocks. - let dancing = self.world.block_entities.iter().any(|(k, e)| { - matches!(e, BlockEntity::Jukebox(j) if j.playing) - && (f64::from(k.0) + 0.5 - pos.x).powi(2) - + (f64::from(k.1) + 0.5 - pos.y).powi(2) - + (f64::from(k.2) + 0.5 - pos.z).powi(2) - <= 100.0 + let jukeboxes = jukeboxes.get_or_insert_with(|| { + self.world + .block_entities + .iter() + .filter(|(_, e)| matches!(e, BlockEntity::Jukebox(j) if j.playing)) + .map(|(k, _)| *k) + .collect() + }); + let dancing = jukeboxes.iter().any(|k| { + (f64::from(k.0) + 0.5 - pos.x).powi(2) + + (f64::from(k.1) + 0.5 - pos.y).powi(2) + + (f64::from(k.2) + 0.5 - pos.z).powi(2) + <= 100.0 }); self.mobs[i].extra.flag = dancing && !horizon_client::mobs::goals::should_panic(&self.mobs[i]); diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index 9f174c5ef..9fd41bb55 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -432,6 +432,10 @@ impl Game<'_> { (false, false) => (0.5, 1.975), }; let edge = (width + height + width) / 3.0 * 4.0; + // 26.3 compares the size with RenderSystem.DEFAULT_DEPTH_CLEAR_VALUE, + // which is 0.0 (reverse Z; the bytecode is `dconst_0`): an empty + // marker box falls back to 4, so a visible marker stand draws. + // Holograms stay hidden through the invisible flag instead. let range = if edge == 0.0 { 4.0 } else { edge } * 64.0; let dragon = a.equipment[5] .as_ref() @@ -700,9 +704,15 @@ impl Game<'_> { self.dim == super::Dim::Nether, )), }; + let profile = stack + .extra + .as_deref() + .and_then(|d| d.other.iter().find(|(k, _)| k == "minecraft:profile")) + .map(|(_, t)| horizon_client::scoreboard::tag_to_json(t)) + .unwrap_or(serde_json::Value::Null); self.pack.item_renderer.submit_special( &special, - &serde_json::Value::Null, + &profile, false, pose, &self.gui.atlas.sprites, diff --git a/crates/horizon-client/src/game/block_entity_ticks.rs b/crates/horizon-client/src/game/block_entity_ticks.rs index bb1cadd15..094aed6ef 100644 --- a/crates/horizon-client/src/game/block_entity_ticks.rs +++ b/crates/horizon-client/src/game/block_entity_ticks.rs @@ -24,6 +24,7 @@ impl Game<'_> { let ticking = self.block_ticking_area(); let mut spawners = Vec::new(); let mut trial_spawners = Vec::new(); + self.item_columns = Some(Default::default()); for slot in self.world.block_entity_tickers() { let pos = slot.0; // Ticks before this one can remove it (`TickingBlockEntity.isRemoved`). @@ -56,6 +57,8 @@ impl Game<'_> { _ => {} } } + // Items move between passes: the columns hold for this one only. + self.item_columns = None; self.update_song_volumes(); self.scan_for_hearts(); // The client ticks (particles, sounds, the turning mob) are for a diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index d36e0adec..dd8c5335a 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -390,6 +390,7 @@ impl Game<'_> { player, others, others_grid: None, + others_index: None, daylight: self.dim != Dim::Nether && self.sky_darken() < 4, game_time: self.world.game_time, day_time: self.world.day_time, @@ -402,7 +403,7 @@ impl Game<'_> { end: self.dim == Dim::End, world_seed: self.level.seed, sea_level: if self.dim == Dim::Nether { 32 } else { 63 }, - teams: self.mob_teams(), + teams: std::sync::Arc::new(self.mob_teams()), items: Some(self.res.items()), difficulty: self.local_difficulty( self.player @@ -499,13 +500,26 @@ impl Game<'_> { // The level random, lent to the mobs (brain behaviours draw from // it) and taken back after their ticks. let mut scratch = self.world.random.clone(); - let mut pushes = Vec::new(); + let mut pushes = horizon_client::mobs::PendingPushes::default(); let mut keep = Vec::with_capacity(mobs.len()); let mut grid = horizon_client::mobs::seen_grid::SeenGrid::new(snapshot.iter().map(|s| s.bounds)); + // All but the snapshot is the same for every mob of the tick, so + // build it once: the player view and the teams scan every UUID. + let base = self.mob_world_base(&[]); + // Each mob keeps its snapshot slot all tick; the first slot of an + // id answers, as a scan would. + let mut index = horizon_client::fast_hash::FxHashMap::::default(); + for (i, s) in snapshot.iter().enumerate() { + index.entry(s.id).or_insert(i as u32); + } for i in 0..mobs.len() { - let mut w = self.mob_world_base(&snapshot); - w.others_grid = Some(&grid); + let mut w = MobWorld { + others: &snapshot, + others_grid: Some(&grid), + others_index: Some(&index), + ..base.clone() + }; let m = &mut mobs[i]; w.nearest_player = super::natural_spawning::nearest_player( &players, @@ -589,7 +603,11 @@ impl Game<'_> { if let Some(host) = self.lan.as_mut() && !guests.is_empty() { - bindings.retain(|id, _| mobs.iter().any(|m| m.id == *id)); + // A set: a scan of every mob for each binding is quadratic, and a + // server's loaded mobs run into the thousands. + let live: horizon_client::fast_hash::FxHashSet = + mobs.iter().map(|m| m.id).collect(); + bindings.retain(|id, _| live.contains(id)); host.mob_players = bindings; } self.mobs.append(&mut mobs); @@ -2929,6 +2947,10 @@ impl Game<'_> { let scale = f64::from(self.settings.entity_distance); for mob in &self.mobs { let entity_start = out.len(); + // Entity.DATA_SHARED_FLAGS_ID invisible: only the name tag draws. + if mob.invisible { + continue; + } let d = glam::DVec3::new(mob.position.x, mob.position.y, mob.position.z) - camera; // Entity.shouldRenderAtSqrDistance: 64 times the bounding box's // mean edge, scaled by the entity distance option. diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index a2e1b0ce6..553cd0d96 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -753,7 +753,7 @@ impl Game<'_> { let lerp = |a: f64, b: f64| a + f64::from(alpha) * (b - a); let lerpf = |a: f32, b: f32| a + alpha * (b - a); for m in &self.mobs { - if m.removed || m.has_effect("minecraft:invisibility") { + if m.removed || m.invisible || m.has_effect("minecraft:invisibility") { continue; } let pos = [ diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index b4e358d50..61725c6ab 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -1736,7 +1736,9 @@ impl Game<'_> { mob.head_pitch = old.head_pitch; mob.persistent = old.persistent; mob.custom_name = old.custom_name.clone(); + mob.custom_name_text = old.custom_name_text.clone(); mob.name_visible = old.name_visible; + mob.invisible = old.invisible; mob.no_ai = old.no_ai; mob.silent = old.silent; mob.no_gravity = old.no_gravity; diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index 08eb8ad33..279f583f6 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -138,47 +138,12 @@ impl Game<'_> { } } - /// SkyRenderer.buildEndSky: six faces of end_sky.png tiled 16 times, - /// tinted 0x282828. The atlas does not wrap, so each face is 16×16 quads. - pub(super) fn end_sky_geometry(&self) -> Vec { - let mut out = Vec::with_capacity(6 * 256 * 4); - let Some(r) = self.gui.atlas.sprites.get("environment/end_sky").copied() else { + /// SkyRenderer.renderEndFlash, drawn after the renderer's resident sky mesh. + pub(super) fn end_flash_geometry(&self) -> Vec { + let mut out = Vec::new(); + // The old combined sky/flash draw also skipped the flash without a sky sprite. + if !self.gui.atlas.sprites.contains_key("environment/end_sky") { return out; - }; - use std::f32::consts::FRAC_PI_2; - let faces = [ - glam::Mat4::IDENTITY, - glam::Mat4::from_rotation_x(FRAC_PI_2), - glam::Mat4::from_rotation_x(-FRAC_PI_2), - glam::Mat4::from_rotation_x(std::f32::consts::PI), - glam::Mat4::from_rotation_z(FRAC_PI_2), - glam::Mat4::from_rotation_z(-FRAC_PI_2), - ]; - let step = 200.0 / 16.0; - for pose in faces { - for a in 0..16 { - for b in 0..16 { - let (x0, z0) = (-100.0 + step * a as f32, -100.0 + step * b as f32); - let (x1, z1) = (x0 + step, z0 + step); - let corners = [ - (x0, z0, [r.u0, r.v0]), - (x0, z1, [r.u0, r.v1]), - (x1, z1, [r.u1, r.v1]), - (x1, z0, [r.u1, r.v0]), - ]; - for (x, z, uv) in corners { - let p = pose.transform_point3(glam::Vec3::new(x, -100.0, z)); - out.push(Vertex { - normal: [0; 4], - pos: p.to_array(), - uv, - layer: 2, - color: 0xFF28_2828, - light: 0, - }); - } - } - } } // SkyRenderer.renderEndFlash: the end_flash sprite at height 100, scale 60. let intensity = self.end.flash.intensity(self.clock.fraction() as f32); diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index ef5775174..1bd3c7696 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -6,9 +6,10 @@ //! the world's options) with [`Integrated::call`], as vanilla's client calls //! into its `IntegratedServer`. //! -//! On by default. `--no-server-thread` or `HORIZON_SERVER_THREAD=0` runs -//! the world in the frame instead (the escape hatch while the network -//! player's side catches up with the in-frame one). +//! Opt-in again (`--server-thread` or `HORIZON_SERVER_THREAD=1`): it was the +//! default for one day, but a server's players can't board, ride or hit +//! boats and minecarts yet (#1222), and single player's window is one of +//! them here. use super::{ Game, Options, PackResources, Resources, UiResources, lan::{LanSettings, Owner}, diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index 8e7176a70..1d79f077d 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -9,12 +9,13 @@ use horizon_assets::item_model::{ }; use horizon_client::{ block_entity_render::{diffuse_lights, vertex_light}, - hud::HudBatch, + hud::{HudBatch, Rect}, item_render::{self, ItemRenderState, SpecialHost, WorldSink}, items::ItemStack, mesher::Vertex, }; use serde_json::Value; +use std::{cell::RefCell, collections::HashMap}; /// The game's answers to what the resolver cannot read from the stack. pub(super) struct Env<'a, 'g> { @@ -126,6 +127,8 @@ pub(super) fn local_time(pattern: &str) -> String { /// Banner and shield pattern textures from the banner pattern registry. pub(super) struct Host<'a> { banners: &'a horizon_client::banner::Banners, + sprites: &'a HashMap, + skins: &'a RefCell, } impl SpecialHost for Host<'_> { fn banner_texture(&self, pattern: &str) -> Option { @@ -138,6 +141,18 @@ impl SpecialHost for Host<'_> { .pattern(pattern) .map(|_| self.banners.shield_texture(pattern)) } + fn player_skin(&self, profile: &Value) -> Option { + // SkullBlockRenderer.getPlayerSkin: SkinManager.getInsecureSkinInformation + // accepts a texture property without a signature, unlike the tab list. + let url = horizon_client::skins::profile_skin_url(profile)?; + let location = + horizon_client::skins::skin_location(&horizon_client::skins::texture_hash(&url)?); + let _ = self + .skins + .borrow_mut() + .state(horizon_client::skins::Kind::Skin, &url); + self.sprites.contains_key(&location).then_some(location) + } } /// `ItemOwner` of an entity holding or showing an item. @@ -177,6 +192,8 @@ impl Game<'_> { pub(super) fn item_host(&self) -> Host<'_> { Host { banners: &self.res.stations().banners, + sprites: &self.gui.atlas.sprites, + skins: &self.skin_downloads, } } /// The client level as item models read it. diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 60a403871..4cb840b6b 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1751,6 +1751,13 @@ impl Game<'_> { break; } } + // A ServerPlayer travels on the server too + // (MoveSimulationType.AUTHORITATIVE_SIDE_AND_SERVER), so every tick + // on a ladder or vine LivingEntity.handleOnClimbable resets its fall + // distance: climbing down doesn't hurt where it lands (#1255). + if w.climbable().unwrap_or(false) { + w.player.fall_distance = 0.0; + } let _ = w.tick_environment_damage(); let _ = w.apply_fire_contact(); let _ = w.server_hazards_tick(in_wall); diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 6c4dd933f..0f43c4c54 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -5,14 +5,8 @@ //! witches, mooshroom colours, turtles, burnt items), lightning rods, the sky //! flash, the sounds and the branching additive bolt. use super::Game; -use horizon_client::{ - mesher::Vertex, - mobs::{Damage, DamageKind, MobEvent, SpawnSetup, Species}, -}; -use horizon_core::{ - position::BlockPos, - random::{LegacyRandom, RandomSource}, -}; +use horizon_client::mobs::{Damage, DamageKind, MobEvent, SpawnSetup, Species}; +use horizon_core::{position::BlockPos, random::RandomSource}; pub(super) struct Bolt { at: [f64; 3], @@ -349,71 +343,14 @@ impl Game<'_> { || e.stack.item.contains("netherite") }); } - /// `LightningBoltRenderer`: 4 layers of a trunk and two branches, 8 - /// segments of 16 blocks, from the bolt's seed. - pub(super) fn bolt_geometry(&self, camera: glam::DVec3, out: &mut Vec) { - let white = self.gui.atlas.font.white(); - let uv = [white.u0, white.v0]; - // ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA. - let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114; - for b in &self.bolts { - let o = (glam::DVec3::from_array(b.at) - camera).as_vec3(); - let mut random = LegacyRandom::new(b.seed); - let (mut xs, mut zs) = ([0f32; 8], [0f32; 8]); - let (mut x_off, mut z_off) = (0f32, 0f32); - for i in (0..8).rev() { - xs[i] = x_off; - zs[i] = z_off; - x_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32; - z_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32; - } - for layer in 0..4 { - let mut random = LegacyRandom::new(b.seed); - for branch in 0..3 { - let trunk = branch == 0; - let start = 7 - branch; - let end = if trunk { 0 } else { start - 3 + 1 }; - let mut sx = xs[start] - x_off; - let mut sz = zs[start] - z_off; - for segment in (end..=start).rev() { - let (ex, ez) = (sx, sz); - let spread = if trunk { 11 } else { 31 }; - sx += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32; - sz += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32; - let mut top = 0.1 + layer as f32 * 0.2; - let mut bottom = top; - if trunk { - top *= segment as f32 * 0.1 + 1.0; - bottom *= (segment as f32 - 1.0) * 0.1 + 1.0; - } - for (rx, rz, lx, lz) in [ - (false, false, true, false), - (true, false, true, true), - (true, true, false, true), - (false, true, false, false), - ] { - let s = |p: bool, r: f32| if p { r } else { -r }; - let y0 = segment as f32 * 16.0; - let corners = [ - [sx + s(rx, bottom), y0, sz + s(rz, bottom)], - [ex + s(rx, top), y0 + 16.0, ez + s(rz, top)], - [ex + s(lx, top), y0 + 16.0, ez + s(lz, top)], - [sx + s(lx, bottom), y0, sz + s(lz, bottom)], - ]; - for c in corners { - out.push(Vertex { - normal: [0; 4], - pos: (o + glam::Vec3::from_array(c)).to_array(), - uv, - layer: 2, - color, - light: 240 | 240 << 8, - }); - } - } - } - } - } - } + /// Simulation-order render inputs; seeded geometry lives in the renderer. + pub(super) fn bolt_instances(&self) -> Vec { + self.bolts + .iter() + .map(|b| horizon_client::gfx::lightning::Bolt { + at: b.at, + seed: b.seed, + }) + .collect() } } diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index c05c7295f..8ce1940c9 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -327,6 +327,46 @@ impl Containers<'_> { } } +/// The block columns any item entity's box reaches, so that a hopper with +/// no item over it skips the scan of every item. Kept for one block-entity +/// pass, in which items do not move: removing one leaves a superset, still +/// right, and adding one (always pushed at the end, under a new id) or +/// removing the last rebuilds the columns. +#[derive(Default)] +pub(super) struct ItemColumns { + /// The item count and last item id when last asked, if built. + seen: Option<(usize, Option)>, + cells: horizon_client::fast_hash::FxHashSet<(i32, i32)>, +} +impl ItemColumns { + /// Whether an item's box may reach into column (x, z). + fn may_reach( + &mut self, + items: &[horizon_client::entities::ItemEntity], + x: i32, + z: i32, + ) -> bool { + let (len, last) = (items.len(), items.last().map(|i| i.id)); + let stale = self + .seen + .is_none_or(|(seen_len, seen_last)| len > seen_len || last != seen_last); + self.seen = Some((len, last)); + if stale { + self.cells.clear(); + for item in items { + let b = item.bounds(); + let (lo, hi) = (b.min_position(), b.max_position()); + for cx in lo.x.floor() as i32..=hi.x.floor() as i32 { + for cz in lo.z.floor() as i32..=hi.z.floor() as i32 { + self.cells.insert((cx, cz)); + } + } + } + } + self.cells.contains(&(x, z)) + } +} + fn bone_meal() -> ItemStack { ItemStack { item: "minecraft:bone_meal".into(), @@ -648,6 +688,11 @@ impl Game<'_> { f64::from(pos.2) + 1.0, ], ); + if let Some(columns) = self.item_columns.as_mut() + && !columns.may_reach(&self.dropped, pos.0, pos.2) + { + return false; + } let mut i = 0; while i < self.dropped.len() { let b = self.dropped[i].bounds(); @@ -880,3 +925,122 @@ impl Game<'_> { true } } + +#[cfg(test)] +mod item_column_tests { + use super::ItemColumns; + use horizon_client::{entities::ItemEntity, items::ItemStack}; + use horizon_core::geometry::Vec3; + + fn item(id: u32, x: f64, y: f64, z: f64) -> ItemEntity { + let at = Vec3::new(x, y, z); + ItemEntity { + health: 5, + fire_ticks: 0, + id, + stack: ItemStack::new("minecraft:stone", 1), + thrower: None, + position: at, + previous: at, + velocity: Vec3::ZERO, + on_ground: true, + age: 0, + pickup_delay: 0, + bob_offset: 0.0, + ticks: 0, + } + } + /// `hopper_suck`'s test: some item box meets the hopper's SUCK_AABB. + fn scan(items: &[ItemEntity], (x, y, z): (i32, i32, i32)) -> bool { + let (min, max) = ( + Vec3::new(f64::from(x), f64::from(y) + 11.0 / 16.0, f64::from(z)), + Vec3::new(f64::from(x) + 1.0, f64::from(y) + 2.0, f64::from(z) + 1.0), + ); + items.iter().any(|i| { + let b = i.bounds(); + let (lo, hi) = (b.min_position(), b.max_position()); + lo.x < max.x + && hi.x > min.x + && lo.y < max.y + && hi.y > min.y + && lo.z < max.z + && hi.z > min.z + }) + } + + /// One tick of empty hoppers looking for items: each scans every item + /// (before) or asks the columns first (after, build included). + #[test] + #[ignore] + fn hopper_suck_cost() { + for (hoppers, count) in [(500i32, 200u32), (2000, 500), (2000, 2000)] { + let mut seed = 99u64; + let mut next = |range: f64| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); + (seed >> 11) as f64 / (1u64 << 53) as f64 * range + }; + let items: Vec = (0..count) + .map(|id| item(id, next(160.0), 64.0, next(160.0))) + .collect(); + let at: Vec<(i32, i32, i32)> = (0..hoppers) + .map(|_| (next(160.0) as i32, 63, next(160.0) as i32)) + .collect(); + let t = std::time::Instant::now(); + let a: Vec = at.iter().map(|&h| scan(&items, h)).collect(); + let before = t.elapsed().as_secs_f64() * 1e3; + let t = std::time::Instant::now(); + let mut columns = ItemColumns::default(); + let b: Vec = at + .iter() + .map(|&h| columns.may_reach(&items, h.0, h.2) && scan(&items, h)) + .collect(); + let after = t.elapsed().as_secs_f64() * 1e3; + assert_eq!(a, b); + println!("{hoppers} hoppers, {count} items: {before:.3} ms -> {after:.3} ms"); + } + } + + #[test] + fn no_hopper_with_an_item_over_it_is_skipped() { + let mut seed = 0x1234_5678_9abc_def1u64; + let mut next = |range: f64| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); + (seed >> 11) as f64 / (1u64 << 53) as f64 * range + }; + let mut items: Vec = Vec::new(); + let mut columns = ItemColumns::default(); + let mut next_id = 0; + let mut skipped = 0; + for round in 0..3000 { + // Items come and go as hoppers take them and crafters drop them. + match round % 5 { + 0 | 1 => { + next_id += 1; + // On edges too: a quarter of them sit on a block line. + let snap = |v: f64, edge: bool| if edge { v.floor() + 0.125 } else { v }; + let edge = round % 4 == 0; + items.push(item( + next_id, + snap(next(24.0) - 12.0, edge), + 64.0, + snap(next(24.0) - 12.0, edge), + )); + } + 2 if !items.is_empty() => { + let i = next(items.len() as f64) as usize; + items.remove(i); + } + _ => {} + } + let hopper = (next(26.0) as i32 - 13, 63, next(26.0) as i32 - 13); + let reach = columns.may_reach(&items, hopper.0, hopper.2); + let found = scan(&items, hopper); + assert!( + reach || !found, + "round {round}: skipped a hopper with an item over it" + ); + skipped += usize::from(!reach); + } + assert!(skipped > 1000, "skipped only {skipped}"); + } +} diff --git a/crates/horizon-client/src/game/maps.rs b/crates/horizon-client/src/game/maps.rs index 855ef941a..bc2534659 100644 --- a/crates/horizon-client/src/game/maps.rs +++ b/crates/horizon-client/src/game/maps.rs @@ -275,6 +275,37 @@ impl Game<'_> { } self.maps.data.get_mut(&id) } + /// `ClientboundMapItemDataPacket.handle`: the server's colours for a map + /// this client does not own (lobby map art, a framed map on a wall). + pub(super) fn remote_map_item_data( + &mut self, + p: &horizon_protocol::packets::play::MapItemData, + ) { + let dimension = self.dimension_id(); + let map = self + .maps + .data + .entry(p.map_id) + .or_insert_with(|| MapData::fresh(0.0, 0.0, p.scale.max(0) as u8, dimension)); + map.locked = p.locked; + let Some(patch) = &p.patch else { + map.dirty = false; + return; + }; + for x in 0..patch.width { + for y in 0..patch.height { + let Some(&color) = patch.colors.get((x + y * patch.width) as usize) else { + continue; + }; + let (px, py) = (patch.start_x + x, patch.start_y + y); + if (0..128).contains(&px) && (0..128).contains(&py) { + map.update_color(px, py, color); + } + } + } + // The server owns a remote map: only the texture has to change. + map.dirty = false; + } fn next_map_id(&mut self) -> i32 { let last = *self.maps.last_id.get_or_insert_with(|| { horizon_client::save::read_dat(&self.world_root.join("data/minecraft/maps/last_id.dat")) diff --git a/crates/horizon-client/src/game/names.rs b/crates/horizon-client/src/game/names.rs index 707b9df96..be829f1bb 100644 --- a/crates/horizon-client/src/game/names.rs +++ b/crates/horizon-client/src/game/names.rs @@ -124,7 +124,7 @@ impl Game<'_> { team, viewer, self.spectator(), - m.has_effect("minecraft:invisibility"), + m.invisible || m.has_effect("minecraft:invisibility"), ); // Entity.isDiscrete: a crouching player. let discrete = player && m.extra.crouching; @@ -144,9 +144,16 @@ impl Game<'_> { continue; } // getDisplayName: the name in the team's prefix, suffix and colour. + let member = if player { + Text::literal(&name) + } else { + m.custom_name_text + .clone() + .unwrap_or_else(|| Text::literal(&name)) + }; let shown = match team { - Some(t) => t.formatted_name(Text::literal(&name)), - None => Text::literal(&name), + Some(t) => t.formatted_name(member), + None => member, }; let mut lines = Vec::new(); // EntityRenderer.extractNameTags: the score shows within the @@ -171,6 +178,64 @@ impl Game<'_> { discrete, }); } + // Armor stands name themselves: an invisible one with a visible name + // is a hologram (its model is skipped, its name tag is not). + for a in &self.armor_stands { + let Some(name) = &a.custom_name else { + continue; + }; + if !a.name_visible { + continue; + } + let height = match (a.marker, a.small) { + (true, _) => 0.0, + (false, true) => 0.9875, + (false, false) => 1.975, + }; + let distance_sqr = + glam::DVec3::new(a.position.x, a.position.y, a.position.z).distance_squared(camera); + if distance_sqr >= 64.0 * 64.0 { + continue; + } + let team = self.mob_team(a.id); + let invisible = sb::invisible_to(team, viewer, self.spectator(), false); + let view = sb::NameView { + discrete: false, + distance_sqr, + invisible_to_viewer: invisible, + hud_hidden: self.ui.hide_gui, + is_camera: false, + is_vehicle: false, + }; + if !sb::name_shown(team, viewer, view) { + continue; + } + let shown = match team { + Some(t) => t.formatted_name(name.clone()), + None => name.clone(), + }; + let mut lines = Vec::new(); + let mut lift = 0.0; + let holder = self.persist.uuids.get(&a.id).map(|u| uuid_text(*u)); + if distance_sqr < 10.0 * 10.0 + && let Some(score) = holder.and_then(|h| self.below_name_text(&h)) + { + lines.push((score, 0.0)); + lift = f64::from(9.0f32 * 1.15 * 0.025); + } + lines.push((shown, lift)); + let l = self.world.light( + a.position.x.floor() as i32, + (a.position.y + height).floor() as i32, + a.position.z.floor() as i32, + ); + tags.push(NameTag { + at: glam::DVec3::new(a.position.x, a.position.y + height + 0.5, a.position.z), + lines, + light: l, + discrete: false, + }); + } tags } /// `SubmitNodeCollection.submitNameTag`: a discrete name is drawn once, diff --git a/crates/horizon-client/src/game/natural_spawning.rs b/crates/horizon-client/src/game/natural_spawning.rs index 68aabbbc6..6dda8e0ac 100644 --- a/crates/horizon-client/src/game/natural_spawning.rs +++ b/crates/horizon-client/src/game/natural_spawning.rs @@ -9,6 +9,7 @@ use horizon_client::{ mobs::{ Mob, MobWorld, Species, data::{self, MobData}, + seen_grid::SeenGrid, spawn_rules::{Dimension, SpawnLevel}, spawn_selection::{ self, Category, Counted, Heightmap, NaturalLevel, SpawnCost, SpawnPlayer, SpawnRequest, @@ -75,8 +76,72 @@ pub(super) struct GameLevel<'g, 'a> { pub(super) pending: std::cell::RefCell>, /// The types and boxes of what a spawner created this tick. pub(super) pending_ids: std::cell::RefCell>, + /// The game's mobs by box, built once a pass has asked more than + /// [`SCANNED_QUERIES`] box queries (the mobs do not change while it + /// holds the game); the first ones scan, as the build costs a few scans. + pub(super) boxes: std::cell::OnceCell, + pub(super) box_queries: std::cell::Cell, +} +const SCANNED_QUERIES: u32 = 8; +/// A mob not removed: its index in `Game::mobs`, box, alive, and whether +/// it is a living shulker. +type MobBox = (usize, Aabb, bool, bool); +fn mob_box(i: usize, m: &Mob) -> MobBox { + let alive = m.alive(); + ( + i, + m.bounds(), + alive, + alive && m.species() == Species::Shulker, + ) +} +/// The boxes of the game's mobs not removed, and a grid over them. +pub(super) struct MobBoxes { + entries: Vec, + grid: SeenGrid, +} +impl MobBoxes { + fn new(mobs: &[Mob]) -> Self { + let entries: Vec<_> = mobs + .iter() + .enumerate() + .filter(|(_, m)| !m.removed) + .map(|(i, m)| mob_box(i, m)) + .collect(); + let grid = SeenGrid::new(entries.iter().map(|e| e.1)); + Self { entries, grid } + } + /// The entries whose boxes meet `area` (and possibly a few more). + fn near(&self, area: Aabb) -> impl Iterator + '_ { + let mut near = Vec::new(); + let indexed = self.grid.candidates(area, &mut near); + let all = (!indexed).then(|| self.entries.iter()); + near.into_iter() + .map(|i| self.entries[i as usize]) + .chain(all.into_iter().flatten().copied()) + } } impl GameLevel<'_, '_> { + /// The mobs not removed whose boxes may meet `area` (callers test them). + fn mobs_near(&self, area: Aabb) -> Box + '_> { + let asked = self.box_queries.get() + 1; + self.box_queries.set(asked); + if asked <= SCANNED_QUERIES && self.boxes.get().is_none() { + return Box::new( + self.game + .mobs + .iter() + .enumerate() + .filter(|(_, m)| !m.removed) + .map(|(i, m)| mob_box(i, m)), + ); + } + Box::new( + self.boxes + .get_or_init(|| MobBoxes::new(&self.game.mobs)) + .near(area), + ) + } fn biome(&self, x: i32, y: i32, z: i32) -> Option<&BiomeInfo> { let chunk = self.game.world.chunks.get(&(x >> 4, z >> 4))?; Some(self.game.res.biomes().get(chunk.biome(x, y, z))) @@ -224,12 +289,9 @@ impl NaturalLevel for GameLevel<'_, '_> { // getEntityCollisions(null, box): living shulkers are solid. let grown = bounds.inflate(Vec3::new(1e-7, 1e-7, 1e-7)); no_collision_empty(&mut scene, bounds) - && !self.game.mobs.iter().any(|m| { - m.species() == Species::Shulker - && m.alive() - && !m.removed - && m.bounds().intersects(grown) - }) + && !self + .mobs_near(grown) + .any(|(_, b, _, shulker)| shulker && b.intersects(grown)) && !self .pending_ids .borrow() @@ -244,10 +306,8 @@ impl NaturalLevel for GameLevel<'_, '_> { !player && !self.pending.borrow().iter().any(|b| b.intersects(bounds)) && !self - .game - .mobs - .iter() - .any(|m| m.alive() && !m.removed && m.bounds().intersects(bounds)) + .mobs_near(bounds) + .any(|(_, b, alive, _)| alive && b.intersects(bounds)) } fn spawn_mobs(&self) -> bool { self.game.ui.rules.bool("spawn_mobs") @@ -289,10 +349,8 @@ impl horizon_client::mobs::spawner::SpawnerLevel for GameLevel<'_, '_> { } fn count_entities(&self, id: &str, bounds: Aabb) -> usize { let mobs = self - .game - .mobs - .iter() - .filter(|m| !m.removed && m.kind.id == id && m.bounds().intersects(bounds)) + .mobs_near(bounds) + .filter(|&(i, b, ..)| self.game.mobs[i].kind.id == id && b.intersects(bounds)) .count(); let pending = self .pending_ids @@ -311,6 +369,8 @@ impl<'a> Game<'a> { players: self.level_players(), pending: Default::default(), pending_ids: Default::default(), + boxes: Default::default(), + box_queries: Default::default(), } } /// Creates a mob the spawner accepted, finalized the game's way; the diff --git a/crates/horizon-client/src/game/piglins.rs b/crates/horizon-client/src/game/piglins.rs index 6280959d8..bcf9e6ab5 100644 --- a/crates/horizon-client/src/game/piglins.rs +++ b/crates/horizon-client/src/game/piglins.rs @@ -34,6 +34,9 @@ impl Game<'_> { if !self.ui.rules.bool("mob_griefing") { return; } + // Whether each item is piglin-loved, kept until an item is added or + // removed (added ones are pushed at the end under a new id). + let mut loved: (Option<(usize, Option)>, Vec) = (None, Vec::new()); for i in 0..self.mobs.len() { let m = &self.mobs[i]; if m.species() != Species::Piglin @@ -46,11 +49,20 @@ impl Game<'_> { continue; } let pos = m.position; + let key = (self.dropped.len(), self.dropped.last().map(|e| e.id)); + if loved.0 != Some(key) { + loved.0 = Some(key); + loved.1 = self + .dropped + .iter() + .map(|e| self.piglin_loved(&e.stack.item)) + .collect(); + } let best = self .dropped .iter() .enumerate() - .filter(|(_, e)| self.piglin_loved(&e.stack.item)) + .filter(|&(j, _)| loved.1[j]) .map(|(j, e)| (j, e.position.distance_squared(pos))) .filter(|(_, d)| *d <= 81.0) .min_by(|a, b| a.1.total_cmp(&b.1)); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 7c96e7bad..9d1e82e56 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -7,7 +7,7 @@ //! client predicts its own movement; the server stays authoritative for //! everything else. use super::{Dim, Game, Mining, Screen}; -use horizon_client::first_person::Hand; +use horizon_client::first_person::{Hand, SwingAnimation}; use horizon_client::{ Result, chunk::{BIOME_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, Section, block_strategy}, @@ -140,6 +140,8 @@ pub(super) struct Remote { tab_players: HashMap, /// Each listed profile's unpacked `textures` property. skin_textures: HashMap, + /// The skin texture each profile's players show, once its download is ready. + skins: HashMap, listed: std::collections::HashSet, /// `ClientboundLoginPacket.onlineMode`: the player list shows heads. online_mode: bool, @@ -194,6 +196,30 @@ fn face_direction(face: [i32; 3]) -> u8 { } } +/// A `minecraft:profile` component as the item data JSON the model reads. +fn profile_tag(p: &horizon_protocol::item::Profile) -> Tag { + let properties = p + .properties + .iter() + .map(|(name, value, signature)| { + let mut entries: Vec<(&'static str, Tag)> = vec![ + ("name", Tag::String(name.as_str().into())), + ("value", Tag::String(value.as_str().into())), + ]; + if let Some(signature) = signature { + entries.push(("signature", Tag::String(signature.as_str().into()))); + } + Tag::compound(entries) + }) + .collect::>(); + let mut entries: Vec<(&'static str, Tag)> = Vec::new(); + if let Some(name) = &p.name { + entries.push(("name", Tag::String(name.as_str().into()))); + } + entries.push(("properties", Tag::List(properties))); + Tag::compound(entries) +} + /// A protocol number format as the scoreboard's. fn number_format(f: &play::NumberFormat) -> horizon_client::scoreboard::NumberFormat { use horizon_client::scoreboard::{NumberFormat, tag_to_json}; @@ -306,6 +332,11 @@ impl Game<'_> { progress: 0.0, total: 0, }; + // The connected client never opens a server world (single player also + // joins here), so load the registries its argument parsers and local + // suggestions need before receiving the server's command tree. + self.ui.registries = Default::default(); + self.build_registries(); self.ui.registries.permission = 0; self.ui.chat.clear(); self.screen = Screen::Playing; @@ -355,6 +386,7 @@ impl Game<'_> { players: HashMap::new(), tab_players: HashMap::new(), skin_textures: HashMap::new(), + skins: HashMap::new(), listed: Default::default(), online_mode: false, level_players: HashMap::new(), @@ -515,66 +547,118 @@ impl Game<'_> { let mut out = ItemStack { item: self.item_name(s.item), count: s.count.max(0) as u32, - damage: s.damage().max(0) as u32, + damage: 0, extra: None, }; - use horizon_protocol::item::{Component, component}; - if let Some(Component::Int(rgb)) = s.component(component::DYED_COLOR) { - out.data_mut().dyed_color = Some(*rgb); - } - if let Some(Component::Int(id)) = s.component(component::MAP_ID) { - out.data_mut().map_id = Some(*id); - } - if let Some(Component::Int(cost)) = s.component(component::REPAIR_COST) { - out.data_mut().repair_cost = (*cost).max(0) as u32; - } - if let Some(Component::Int(mode)) = s.component(component::MAP_POST_PROCESSING) { - out.data_mut().map_post_processing = Some((*mode).clamp(0, 1) as u8); - } - if let Some(Component::WritableBook(pages)) = s.component(component::WRITABLE_BOOK_CONTENT) - { - out.data_mut().writable_pages = pages.clone(); - } - if let Some(Component::WrittenBook(b)) = s.component(component::WRITTEN_BOOK_CONTENT) { - let lang = self - .remote - .as_ref() - .map(|r| r.lang.clone()) - .unwrap_or_default(); - out.data_mut().written = Some(horizon_client::item_data::WrittenBook { - title: b.title.clone(), - author: b.author.clone(), - generation: b.generation.clamp(0, 3) as u8, - pages: b.pages.iter().map(|p| plain(p, &lang)).collect(), - }); - } - if let Some(Component::Text(name)) = s.component(component::CUSTOM_NAME) { - let lang = self - .remote - .as_ref() - .map(|r| r.lang.clone()) - .unwrap_or_default(); - out.data_mut().custom_name = Some(plain(name, &lang)); - } - // The enchantments by the server's registry ids. - let levels = |list: &[(i32, i32)]| -> Vec<(Arc, u32)> { - let names = self.remote.as_ref().map(|r| &r.registries); - list.iter() - .filter_map(|(id, level)| { - let name = names?.name("minecraft:enchantment", *id)?; - Some((Arc::from(name), (*level).max(0) as u32)) - }) - .collect() - }; - if let Some(Component::Enchantments(list)) = s.component(component::ENCHANTMENTS) { - out.data_mut().enchantments = levels(list); - } - if let Some(Component::Enchantments(list)) = s.component(component::STORED_ENCHANTMENTS) { - out.data_mut().stored_enchantments = levels(list); + // A vanilla `components` compound, then the same decoder the saved + // and command item NBT use, so tooltips and models see every field. + let components = self.protocol_components(s); + let (damage, data) = horizon_client::item_data::decode_components(components.as_ref()); + out.damage = damage; + if let Some(data) = data { + *out.data_mut() = *data; } out.tidy(); Some(out) } + /// The item's patched components as vanilla's `components` compound. + fn protocol_components(&self, s: &Stack) -> Option { + use horizon_protocol::item::{Component, component}; + let r = self.remote.as_ref()?; + let name = |id: i32| r.builtin.get("minecraft:data_component_type")?.name(id); + let mut entries: Vec<(&str, Tag)> = Vec::new(); + for (kind, c) in &s.added { + let Some(key) = name(*kind) else { + continue; + }; + let value = match c { + Component::Int(v) if *kind == component::RARITY => { + let rarity = ["common", "uncommon", "rare", "epic"]; + Tag::String(rarity.get(*v as usize).copied().unwrap_or("common").into()) + } + Component::Int(v) => Tag::Int(*v), + Component::Unit => Tag::Compound(Default::default()), + Component::Bool(v) => Tag::Byte(i8::from(*v)), + Component::Text(t) | Component::Nbt(t) => t.clone(), + Component::Ident(v) => Tag::String(v.as_str().into()), + Component::Lore(lines) => Tag::List(lines.clone()), + Component::WritableBook(pages) => Tag::compound([( + "pages", + Tag::List( + pages + .iter() + .map(|p| Tag::String(p.as_str().into())) + .collect(), + ), + )]), + Component::WrittenBook(b) => Tag::compound([ + ("title", Tag::String(b.title.as_str().into())), + ("author", Tag::String(b.author.as_str().into())), + ("generation", Tag::Int(b.generation)), + ("pages", Tag::List(b.pages.clone())), + ("resolved", Tag::Byte(i8::from(b.resolved))), + ]), + Component::Enchantments(list) => { + // Enchantments are a synced (data-driven) registry: the + // ids index the server's RegistryData, not the builtin + // report, so a datapack enchantment names correctly. + let levels = list.iter().filter_map(|(id, level)| { + let name = r.registries.name("minecraft:enchantment", *id)?; + Some((name, Tag::Int(*level))) + }); + Tag::compound(levels) + } + Component::AttackRange(v) => Tag::compound([ + ("min_reach", Tag::Float(v[0].to_bits())), + ("max_reach", Tag::Float(v[1].to_bits())), + ("min_attack_momentum", Tag::Float(v[2].to_bits())), + ("max_attack_momentum", Tag::Float(v[3].to_bits())), + ("hitbox_margin", Tag::Float(v[4].to_bits())), + ("mob_factor", Tag::Float(v[5].to_bits())), + ]), + Component::Profile(p) => profile_tag(p), + Component::CustomModelData { + floats, + flags, + strings, + colors, + } => Tag::compound([ + ( + "floats", + Tag::List(floats.iter().map(|f| Tag::Float(f.to_bits())).collect()), + ), + ( + "flags", + Tag::List(flags.iter().map(|b| Tag::Byte(i8::from(*b))).collect()), + ), + ( + "strings", + Tag::List( + strings + .iter() + .map(|s| Tag::String(s.as_str().into())) + .collect(), + ), + ), + ( + "colors", + Tag::List(colors.iter().map(|c| Tag::Int(*c)).collect()), + ), + ]), + Component::TooltipDisplay { hide, hidden } => { + let hidden = hidden + .iter() + .filter_map(|id| Some(Tag::String(name(*id)?.into()))); + Tag::compound([ + ("hide_tooltip", Tag::Byte(i8::from(*hide))), + ("hidden_components", Tag::List(hidden.collect())), + ]) + } + }; + entries.push((key, value)); + } + Some(Tag::compound(entries)) + } fn to_network(&self, s: &Option) -> Option { let s = s.as_ref()?; let mut stack = Stack::new(self.item_id(&s.item), s.count as i32); @@ -1677,6 +1761,29 @@ impl Game<'_> { } } C::SetEntityData(p) => { + // Entity.DATA_SHARED_FLAGS_ID, DATA_CUSTOM_NAME and + // DATA_CUSTOM_NAME_VISIBLE: server NPCs and holograms rely on + // these instead of saved NBT. + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { + for (index, _, value) in &p.values { + match (index, value) { + (0, Value::Byte(flags)) => m.invisible = flags & 0x20 != 0, + (2, Value::OptText(name)) => { + let text = name.as_ref().map(horizon_client::entity_nbt::name_text); + m.custom_name = + text.as_ref().map(horizon_client::text::Text::plain); + m.custom_name_text = text; + } + (2, Value::Text(name)) => { + let text = horizon_client::entity_nbt::name_text(name); + m.custom_name = Some(text.plain()); + m.custom_name_text = Some(text); + } + (3, Value::Bool(visible)) => m.name_visible = *visible, + _ => {} + } + } + } if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) && m.species() == horizon_client::mobs::Species::Rabbit { @@ -2314,6 +2421,7 @@ impl Game<'_> { .then(|| Vec3::new(f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5)); } C::ServerData(p) => self.remote_server_data(p.icon.as_deref()), + C::MapItemData(p) => self.remote_map_item_data(&p), // handleTickingState / handleTickingStep: the level's TickRateManager. C::TickingState(p) => { self.clock.set_rate(p.rate); @@ -2459,33 +2567,20 @@ impl Game<'_> { pub(super) fn remote_tab_players( &mut self, ) -> Option<(Vec, bool, Vec)> { - let r = self.remote.as_ref()?; - let mut players: Vec<_> = r - .listed - .iter() - .filter_map(|u| r.tab_players.get(u).cloned()) - .collect(); + self.update_remote_skins(); + let mut players: Vec<_> = { + let r = self.remote.as_ref()?; + r.listed + .iter() + .filter_map(|u| r.tab_players.get(u).cloned()) + .collect() + }; for p in &mut players { - let Some(textures) = r.skin_textures.get(&p.uuid) else { - continue; - }; - // PlayerInfo.createSkinLookup: only the local player's own skin - // may be unsigned. - let downloads = &mut self.skin_downloads; - let skin = horizon_client::skins::lookup(textures, p.uuid != r.profile, |kind, url| { - downloads.state(kind, url) - }); - if let Some(skin) = skin { - p.skin = skin; - } - } - for (location, rgba) in self.skin_downloads.take_ready() { - self.store_skin(location, rgba); - } - for p in &mut players { - if p.skin.starts_with("skins/") && !self.show_skin(&p.skin) { - p.skin = horizon_client::tab_list::default_skin(p.uuid).to_owned(); - } + p.skin = self + .remote + .as_ref() + .and_then(|r| r.skins.get(&p.uuid).cloned()) + .unwrap_or_else(|| horizon_client::tab_list::default_skin(p.uuid).to_owned()); } let r = self.remote.as_ref()?; let upside_down = players @@ -2498,9 +2593,68 @@ impl Game<'_> { .collect(); Some((players, r.online_mode, upside_down)) } + /// `PlayerInfo.getSkin` for every player entity, including NPCs that are + /// never in the tab list: resolve each profile's textures and give the + /// level's player models their skin. + fn update_remote_skins(&mut self) { + let Some(r) = self.remote.as_ref() else { + return; + }; + let local = r.profile; + let entries: Vec<(u128, horizon_client::skins::Textures)> = r + .skin_textures + .iter() + .map(|(uuid, textures)| (*uuid, textures.clone())) + .collect(); + let mut resolved: Vec<(u128, String)> = Vec::new(); + for (uuid, textures) in entries { + // PlayerInfo.createSkinLookup: only the local player's own skin + // may be unsigned. + let skin = { + let mut downloads = self.skin_downloads.borrow_mut(); + horizon_client::skins::lookup(&textures, uuid != local, |kind, url| { + downloads.state(kind, url) + }) + }; + if let Some(skin) = skin { + resolved.push((uuid, skin)); + } + } + resolved.retain(|(_, skin)| !skin.starts_with("skins/") || self.show_skin(skin)); + let Some((level, skins, own)) = self.remote.as_mut().map(|r| { + r.skins = resolved.into_iter().collect(); + ( + r.level_players + .iter() + .map(|(id, uuid)| (*id as u32, *uuid)) + .collect::>(), + r.skins.clone(), + r.skins.get(&r.profile).cloned(), + ) + }) else { + return; + }; + for (id, uuid) in level { + let Some(skin) = skins.get(&uuid) else { + continue; + }; + if let Some(mob) = self + .mobs + .iter_mut() + .find(|m| m.id == id && &*m.kind.id == "minecraft:player") + { + mob.skin = Some(skin.clone()); + } + } + if let Some(skin) = own + && let Some(mob) = self.player_model.as_mut() + { + mob.skin = Some(skin); + } + } /// Puts a downloaded skin in an atlas skin slot: a free one, else the /// least recently shown. - fn store_skin(&mut self, location: String, rgba: Vec) { + pub(super) fn store_skin(&mut self, location: String, rgba: Vec) { use horizon_client::hud::SKIN_SLOTS; let slot = if self.skin_slots.len() < SKIN_SLOTS { self.skin_slots.len() @@ -3309,10 +3463,8 @@ impl Game<'_> { sequence: seq, })); if progress >= 1.0 { + // startDestroyBlock: instant survival breaks have no destroy delay. self.predict_break(hit.pos, state, seq); - if let Some(r) = self.remote.as_mut() { - r.destroy_delay = 5; - } return; } if let Some(r) = self.remote.as_mut() { @@ -3489,7 +3641,15 @@ impl Game<'_> { self.predict_use(&changes, seq); } if held_block { - self.with_hand(hand, Game::swing_arm); + if reacts + || held + .as_ref() + .is_some_and(|stack| self.remote_can_place(&hit, stack)) + { + self.with_hand(hand, Game::swing_arm); + } + // BlockItem.place returns FAIL when placement is rejected: + // stop this click without trying the item or the other hand. return true; } return reacts; @@ -3547,7 +3707,11 @@ impl Game<'_> { /// container, and the blocks it changed. Vanilla's client runs it on its /// own level first; this runs it on a copy, and `predict_use` keeps the /// changes it predicts. - fn remote_block_reacts(&self, hit: &super::Hit, held: Option<&ItemStack>) -> (bool, DryUse) { + fn remote_block_reacts( + &mut self, + hit: &super::Hit, + held: Option<&ItemStack>, + ) -> (bool, DryUse) { // Player.isSecondaryUseActive with something in either hand. let hands_full = self.stack_in(self.selected).is_some() || self.offhand.is_some(); if self.keys.contains(&KeyCode::ShiftLeft) && hands_full { @@ -3562,26 +3726,53 @@ impl Game<'_> { [-1, 0, 0] => Direction::West, _ => Direction::East, }; - let mut level = DryLevel { - world: &self.world, - changed: HashMap::new(), - random: horizon_core::random::LegacyRandom::new(0), - sounds: Vec::new(), + let player = self.use_context(); + self.with_level(|b, level, _| { + let mut level = DryLevel::new(level); + let reacts = b + .use_item_on( + &mut level, + &mut horizon_world::level::Ticks::default(), + horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]), + face, + horizon_core::geometry::Vec3::new(hit.point[0], hit.point[1], hit.point[2]), + player, + held.map(|s| &*s.item), + ) + .consumes_action(); + (reacts, (level.changed.into_iter().collect(), level.sounds)) + }) + } + + /// Run BlockItem.place on a disposable level before predicting its swing. + /// The real level supplies collision shapes and building-blocking entities; + /// block writes, random draws, scheduled ticks and events stay in the preview. + fn remote_can_place(&mut self, hit: &super::Hit, stack: &ItemStack) -> bool { + if !self.may_build() { + return false; + } + let ctx = horizon_world::level::PlaceContext { + clicked_pos: horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]), + face: horizon_core::geometry::Direction::ALL[face_direction(hit.face) as usize], + hit: Vec3::new(hit.point[0], hit.point[1], hit.point[2]), + inside: hit.face == [0; 3], + yaw: self.yaw, + pitch: self.pitch, + sneaking: self.keys.contains(&KeyCode::ShiftLeft), + item: stack.item.to_string(), + can_use_game_master_blocks: self.can_use_game_master_blocks(), }; - let reacts = self - .res - .behaviours() - .use_item_on( - &mut level, - &mut horizon_world::level::Ticks::default(), - horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]), - face, - horizon_core::geometry::Vec3::new(hit.point[0], hit.point[1], hit.point[2]), - self.use_context(), - held.map(|s| &*s.item), + self.with_level(|b, level, _| { + let mut level = DryLevel::new(level); + matches!( + b.place_block( + &mut level, + &mut horizon_world::level::Ticks::default(), + &ctx + ), + horizon_world::level::PlaceOutcome::Placed { .. } ) - .consumes_action(); - (reacts, (level.changed.into_iter().collect(), level.sounds)) + }) } /// MultiPlayerGameMode.useItem for `hand`, if it holds something: whether @@ -3836,23 +4027,26 @@ impl Game<'_> { Ok(true) } KeyCode::KeyQ => { + if self.spectator() { + return Ok(true); + } let all = self.keys.contains(&KeyCode::ControlLeft); + // MultiPlayerGameMode.dropItem: predict removal before sending + // the action, then swing only if a nonempty stack was removed. + let dropped = horizon_client::items::take_held_drop( + &mut self.inventory[self.selected], + all, + false, + ); self.send(S::PlayerAction(play::PlayerAction { action: if all { 4 } else { 5 }, pos: [0; 3], direction: 0, sequence: 0, })); - // Inventory.removeFromSelected (prediction). - let slot = &mut self.inventory[self.selected]; - if let Some(s) = slot { - if all || s.count <= 1 { - *slot = None; - } else { - s.count -= 1; - } + if dropped.is_some() { + self.swing_hand(Hand::Main, SwingAnimation::DEFAULT); } - self.swing_arm(); Ok(true) } KeyCode::KeyE => { @@ -4529,7 +4723,7 @@ pub(super) fn input_ordinal(input: Input) -> i32 { /// The client's world for a guess at what a click does: reads go to the /// world, writes stay here and are dropped. struct DryLevel<'w> { - world: &'w horizon_client::world::World, + base: &'w dyn horizon_world::level::LevelAccess, changed: HashMap, random: horizon_core::random::LegacyRandom, /// The sounds the use plays (a door's creak). @@ -4559,6 +4753,17 @@ pub(super) fn hand_operated(name: &str) -> bool { || name == "lever" } +impl<'w> DryLevel<'w> { + fn new(base: &'w dyn horizon_world::level::LevelAccess) -> Self { + Self { + base, + changed: HashMap::new(), + random: horizon_core::random::LegacyRandom::new(0), + sounds: Vec::new(), + } + } +} + impl horizon_world::level::LevelAccess for DryLevel<'_> { fn emit(&mut self, event: horizon_world::level::LevelEvent) { if let horizon_world::level::LevelEvent::Sound { @@ -4575,7 +4780,7 @@ impl horizon_world::level::LevelAccess for DryLevel<'_> { self.changed .get(&pos) .copied() - .unwrap_or_else(|| self.world.block(pos.x, pos.y, pos.z)) + .unwrap_or_else(|| self.base.block_state(pos)) } fn set_raw( &mut self, @@ -4587,13 +4792,31 @@ impl horizon_world::level::LevelAccess for DryLevel<'_> { Some(previous) } fn is_loaded(&self, pos: horizon_core::position::BlockPos) -> bool { - self.world.loaded(pos.x, pos.z) + self.base.is_loaded(pos) + } + fn min_y(&self) -> i32 { + self.base.min_y() + } + fn max_y(&self) -> i32 { + self.base.max_y() + } + fn block_light(&self, pos: horizon_core::position::BlockPos) -> i32 { + self.base.block_light(pos) + } + fn sky_light(&self, pos: horizon_core::position::BlockPos) -> i32 { + self.base.sky_light(pos) + } + fn sky_darken(&self) -> i32 { + self.base.sky_darken() + } + fn is_unobstructed(&self, pos: horizon_core::position::BlockPos, state: BlockStateId) -> bool { + self.base.is_unobstructed(pos, state) } fn random(&mut self) -> &mut horizon_core::random::LegacyRandom { &mut self.random } fn game_time(&self) -> i64 { - self.world.game_time + self.base.game_time() } } @@ -4709,6 +4932,110 @@ impl horizon_client::interaction_input::InteractionWorld for RemoteInputWorld<'_ mod tests { use super::Game; + #[test] + fn placement_preview_checks_obstruction_without_changing_the_level() { + use super::DryLevel; + use horizon_core::{position::BlockPos, random::LegacyRandom}; + use horizon_world::{ + level::{ + Behaviours, LevelAccess, PlaceContext, PlaceOutcome, Ticks, data::load_registry, + }, + registry::BlockStateId, + }; + + struct Level { + air: BlockStateId, + stone: BlockStateId, + obstructed: bool, + loaded: bool, + ceiling: i32, + } + impl LevelAccess for Level { + fn block_state(&self, pos: BlockPos) -> BlockStateId { + if pos == BlockPos::new(0, 0, 0) { + self.stone + } else { + self.air + } + } + fn set_raw(&mut self, _: BlockPos, _: BlockStateId) -> Option { + panic!("preview must not write to the live level"); + } + fn is_loaded(&self, _: BlockPos) -> bool { + self.loaded + } + fn max_y(&self) -> i32 { + self.ceiling + } + fn is_unobstructed(&self, pos: BlockPos, _: BlockStateId) -> bool { + assert_eq!(pos, BlockPos::new(0, 1, 0)); + !self.obstructed + } + fn random(&mut self) -> &mut LegacyRandom { + panic!("preview must not advance the live level's random source"); + } + fn game_time(&self) -> i64 { + 0 + } + } + + // As with the LAN tests, prepared game resources are optional locally. + let resources = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !resources.join("block-behaviours.json").exists() { + return; + } + let registry = load_registry(&resources).unwrap(); + let behaviours = Behaviours::load(®istry, &resources).unwrap(); + let mut base = Level { + air: registry.default_state("minecraft:air").unwrap(), + stone: registry.default_state("minecraft:stone").unwrap(), + obstructed: false, + loaded: true, + ceiling: 320, + }; + for item in [ + "minecraft:stone", + "minecraft:oak_slab", + "minecraft:oak_door", + // GrowingPlantHeadBlock.getStateForPlacement draws a random age. + "minecraft:twisting_vines", + ] { + let ctx = PlaceContext { + clicked_pos: BlockPos::new(0, 0, 0), + face: horizon_core::geometry::Direction::Up, + hit: horizon_core::geometry::Vec3::new(0.5, 1.0, 0.5), + inside: false, + yaw: 0.0, + pitch: 45.0, + sneaking: false, + item: item.into(), + can_use_game_master_blocks: false, + }; + for (obstructed, loaded, ceiling) in [ + (false, true, 320), + (true, true, 320), + (false, false, 320), + (false, true, 1), + ] { + base.obstructed = obstructed; + base.loaded = loaded; + base.ceiling = ceiling; + let valid = !obstructed && loaded && ceiling > 1; + let mut preview = DryLevel::new(&base); + let outcome = behaviours.place_block(&mut preview, &mut Ticks::default(), &ctx); + assert_eq!( + matches!(outcome, PlaceOutcome::Placed { .. }), + valid, + "{item}, obstructed={obstructed}, loaded={loaded}, ceiling={ceiling}" + ); + assert_eq!(preview.changed.is_empty(), !valid); + assert_eq!(base.block_state(BlockPos::new(0, 1, 0)), base.air); + } + } + } + #[test] fn every_inventory_menu_slot_is_a_game_slot_and_45_is_the_off_hand() { // InventoryMenu: result, 2x2 grid, armour, 27 + 9 inventory slots, then the off hand. diff --git a/crates/horizon-client/src/game/remote_objects.rs b/crates/horizon-client/src/game/remote_objects.rs index 12a15bc34..4cf9cb1a8 100644 --- a/crates/horizon-client/src/game/remote_objects.rs +++ b/crates/horizon-client/src/game/remote_objects.rs @@ -123,6 +123,14 @@ impl Game<'_> { } else if let Some(a) = self.armor_stands.iter_mut().find(|a| a.id == id) { match (index, value) { (0, Value::Byte(flags)) => a.invisible = flags & 0x20 != 0, + // Entity.DATA_CUSTOM_NAME and DATA_CUSTOM_NAME_VISIBLE. + (2, Value::OptText(name)) => { + a.custom_name = name.as_ref().map(horizon_client::entity_nbt::name_text); + } + (2, Value::Text(name)) => { + a.custom_name = Some(horizon_client::entity_nbt::name_text(name)); + } + (3, Value::Bool(visible)) => a.name_visible = *visible, (9, Value::Float(health)) => a.health = *health, // ArmorStand.DATA_CLIENT_FLAGS. (15, Value::Byte(flags)) => { diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 99dae39a5..4d60c2df7 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -431,20 +431,18 @@ impl Game<'_> { self.score.board.players_team(self.acting_player_name()) } /// The teams of the player and of the mobs on one (empty without teams). - pub(super) fn mob_teams(&self) -> horizon_client::mobs::Teams { + pub(super) fn mob_teams(&self) -> horizon_client::mobs::Teams<'_> { let board = &self.score.board; if board.teams.is_empty() { return Default::default(); } horizon_client::mobs::Teams { - player: self.player_team().cloned(), + player: self.player_team(), mobs: self .persist .uuids .iter() - .filter_map(|(id, uuid)| { - Some((*id, board.players_team(&uuid_text(*uuid))?.clone())) - }) + .filter_map(|(id, uuid)| Some((*id, board.players_team(&uuid_text(*uuid))?))) .collect(), } } @@ -599,6 +597,11 @@ impl Game<'_> { /// objective. pub(super) fn draw_tab_list(&mut self, batch: &mut HudBatch) { use horizon_client::tab_list::{self, TabInputs}; + // Player heads and the player list both draw from the same skin slots. + let ready: Vec<_> = self.skin_downloads.borrow_mut().take_ready(); + for (location, rgba) in ready { + self.store_skin(location, rgba); + } let key = self.screen == super::Screen::Playing && self.keys.contains(&winit::keyboard::KeyCode::Tab); let (players, online_mode, upside_down) = match self.remote_tab_players() { diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index cecd8d46f..07eacfb49 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -7,6 +7,24 @@ use horizon_client::{ ui, }; +impl Screen { + /// Screen.extractBackground for non-isInGameUi screens, and + /// PauseScreen.extractBackground only when showPauseMenu is true. + pub(super) fn blurs_background(self, pause_menu: bool) -> bool { + match self { + Self::Paused => pause_menu, + Self::Options | Self::Stats | Self::Advancements | Self::WorldOptions => true, + Self::Playing + | Self::GameModeSwitcher + | Self::Chat + | Self::Creative + | Self::Inventory + | Self::Dead + | Self::CommandBlock => false, + } + } +} + /// PauseScreen buttons: (x, y, width, label key, action id, active). /// https://mcsrc.dev/2/26.3/net/minecraft/client/gui/screens/PauseScreen fn pause_buttons(w: f32, h: f32, remote: bool) -> Vec<(f32, f32, f32, &'static str, u8, bool)> { @@ -334,7 +352,34 @@ impl Game<'_> { #[cfg(test)] mod tests { - use super::pause_buttons; + use super::{Screen, pause_buttons}; + + #[test] + fn menu_blur_matches_vanilla_screen_backgrounds() { + for screen in [ + Screen::Options, + Screen::Stats, + Screen::Advancements, + Screen::WorldOptions, + ] { + assert!(screen.blurs_background(false)); + assert!(screen.blurs_background(true)); + } + assert!(Screen::Paused.blurs_background(true)); + assert!(!Screen::Paused.blurs_background(false)); + for screen in [ + Screen::Playing, + Screen::GameModeSwitcher, + Screen::Chat, + Screen::Creative, + Screen::Inventory, + Screen::Dead, + Screen::CommandBlock, + ] { + assert!(!screen.blurs_background(true)); + assert!(!screen.blurs_background(false)); + } + } #[test] fn pause_menu_uses_disconnect_for_servers_and_keeps_world_options() { diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index 096562608..8667f305f 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -71,6 +71,8 @@ pub(super) struct SculkState { /// The sculk block entities in the order they were added. index: Index, pub known: HashSet<(i32, i32)>, + /// The chunk map's membership revision `known` was taken at. + pub known_revision: Option, // Keyed by mob ids the server gives out: the fast hasher is safe. steps: FxHashMap, damaged: FxHashMap, @@ -336,7 +338,10 @@ impl Game<'_> { /// the block writes recorded since the last tick. pub(super) fn sculk_sync_index(&mut self) { // Chunks that arrived or left (every half second is plenty). - if self.sculk.ticks.is_multiple_of(10) { + // Nothing to do while no chunk came or went. + let revision = self.world.chunks.membership_revision(); + if self.sculk.ticks.is_multiple_of(10) && self.sculk.known_revision != Some(revision) { + self.sculk.known_revision = Some(revision); let loaded: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect(); let arrived: Vec<(i32, i32)> = loaded.difference(&self.sculk.known).copied().collect(); for key in arrived { diff --git a/crates/horizon-client/src/game/sculk_fixture.rs b/crates/horizon-client/src/game/sculk_fixture.rs index d71cd5431..b02dfe998 100644 --- a/crates/horizon-client/src/game/sculk_fixture.rs +++ b/crates/horizon-client/src/game/sculk_fixture.rs @@ -433,6 +433,7 @@ impl Game<'_> { }); self.level_events.clear(); self.sculk.known = self.world.chunks.keys().copied().collect(); + self.sculk.known_revision = Some(self.world.chunks.membership_revision()); self.sculk_sync_index(); let mut names: HashMap = HashMap::new(); let mut sources: Vec = Vec::new(); diff --git a/crates/horizon-client/src/game/zombie_villagers.rs b/crates/horizon-client/src/game/zombie_villagers.rs index c68c0f1c1..b47e2460c 100644 --- a/crates/horizon-client/src/game/zombie_villagers.rs +++ b/crates/horizon-client/src/game/zombie_villagers.rs @@ -194,7 +194,9 @@ fn carry_over(from: &Mob, to: &mut Mob) { to.fire_ticks = from.fire_ticks; to.persistent = from.persistent; to.custom_name = from.custom_name.clone(); + to.custom_name_text = from.custom_name_text.clone(); to.name_visible = from.name_visible; + to.invisible = from.invisible; to.extra.pick_up_loot = from.extra.pick_up_loot; to.extra.main_hand = from.extra.main_hand.clone(); to.extra.off_hand = from.extra.off_hand.clone(); diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 14c040c5c..8e36ee3bf 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -61,8 +61,10 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6] mod arena; mod cull; +mod end_sky; mod flat; mod java_stages; +pub mod lightning; mod lod; mod occlusion; mod pack_stages; @@ -163,8 +165,10 @@ pub struct Frame<'a> { pub title: bool, /// Dimensions without a skybox (the Nether) clear to the fog colour. pub skybox: bool, - /// The End: clear to black and draw `celestial` (the End sky box) behind the world. + /// The End: clear to black and draw the resident sky box behind the world. pub end_sky: bool, + /// End sky atlas bounds (u0, v0, u1, v1); absent when the sprite is missing. + pub end_sky_sprite: Option<[f32; 4]>, /// Environmental fog start/end (Nether 10..96), if any. pub environment_fog: Option<(f32, f32)>, pub water_fog: [f32; 3], @@ -193,12 +197,14 @@ pub struct Frame<'a> { pub dynamic_lights: &'a [[f32; 4]], /// Cloud mesh inputs; geometry and GPU storage are retained by the renderer. pub clouds: Option>, - /// Additive translucent geometry after the entities (lightning, dragon rays). + /// Retained lightning bolts, drawn before the other additive entities. + pub lightning: lightning::Input<'a>, + /// Additive translucent geometry after lightning (dragon rays). pub additive: &'a [Vertex], /// Name tags over everything, without depth (`TEXT_SEE_THROUGH`). pub see_through: &'a [Vertex], - /// Camera-relative sun and moon, or the End sky box (drawn behind - /// everything, additive). + /// Camera-relative sun and moon, or the animated End flash (additive, + /// behind everything and after the resident End sky box). pub celestial: &'a [Vertex], /// The stars, drawn from their static buffer after the sun and moon: /// the sky's rotation (camera-relative world from star space) and the @@ -334,9 +340,12 @@ pub struct Renderer { cloud_uniform: wgpu::Buffer, cloud_group: wgpu::BindGroup, additive_pipeline: wgpu::RenderPipeline, + lightning_pipeline: wgpu::RenderPipeline, + lightning: lightning::Renderer, see_through_pipeline: wgpu::RenderPipeline, celestial_pipeline: wgpu::RenderPipeline, celestial_buffer: wgpu::Buffer, + end_sky: end_sky::EndSky, stars: stars::Stars, panorama: panorama::Panorama, /// `RenderPipelines.WORLD_BORDER` and its buffers. @@ -1664,8 +1673,17 @@ impl Renderer { alpha_blend, false, ); + let lightning_attributes = wgpu::vertex_attr_array![6=>Float32x3]; + let lightning_vertex = [ + entity_vertex[0].clone(), + Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::<[f32; 3]>() as u64, + step_mode: wgpu::VertexStepMode::Instance, + attributes: &lightning_attributes, + }), + ]; // BlendFunction.LIGHTNING: src alpha, one; no depth writes. - let additive_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + let additive_descriptor = wgpu::RenderPipelineDescriptor { label: Some("Additive entities"), layout: Some(&entity_layout), vertex: wgpu::VertexState { @@ -1709,6 +1727,16 @@ impl Renderer { }), multiview_mask: None, cache: None, + }; + let additive_pipeline = device.create_render_pipeline(&additive_descriptor); + let lightning_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Lightning"), + vertex: wgpu::VertexState { + entry_point: Some("vs_lightning"), + buffers: &lightning_vertex, + ..additive_descriptor.vertex.clone() + }, + ..additive_descriptor }); let celestial_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("Celestial bodies"), @@ -2110,9 +2138,12 @@ impl Renderer { cloud_uniform, cloud_group, additive_pipeline, + lightning_pipeline, + lightning: lightning::Renderer::new(), see_through_pipeline, celestial_pipeline, celestial_buffer, + end_sky: end_sky::EndSky::default(), stars, panorama, border_pipeline, @@ -3279,6 +3310,13 @@ impl Renderer { } else { 0 }; + self.lightning.prepare( + &self.device, + &mut self.uploads, + &mut encoder, + &frame.lightning, + camera, + ); let all_entities = &self.entity_batch.combined; let hand_quads = (frame.hand.len() / 4) as u32; let additive_quads = (frame.additive.len() / 4) as u32; @@ -3310,6 +3348,9 @@ impl Renderer { ); } let celestial_vertices = frame.celestial.len().min(2048 * 4); + if frame.end_sky && !frame.title { + self.end_sky.prepare(&self.device, frame.end_sky_sprite); + } if celestial_vertices > 0 { self.uploads.buffer( &mut encoder, @@ -3318,8 +3359,13 @@ impl Renderer { bytemuck::cast_slice(&frame.celestial[..celestial_vertices]), ); } - let max_quads = - (world_quads + additive_quads + hand_quads + see_through_quads).max(cloud_quads); + let max_quads = (world_quads + additive_quads + hand_quads + see_through_quads) + .max(cloud_quads) + .max(if frame.lightning.bolts.is_empty() { + 0 + } else { + lightning::QUADS + }); if max_quads > self.index_quads { self.index_quads = max_quads.next_power_of_two(); self.indices = Self::quad_indices(&self.device, self.index_quads); @@ -3510,12 +3556,17 @@ impl Renderer { if frame.title { self.panorama.draw(&mut pass); pass.set_bind_group(0, &self.group, &[]); - } else if celestial_vertices > 0 { + } else if celestial_vertices > 0 || frame.end_sky { pass.set_pipeline(&self.celestial_pipeline); pass.set_bind_group(0, &self.entity_group, &[]); pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); - pass.set_vertex_buffer(0, self.celestial_buffer.slice(..)); - pass.draw_indexed(0..(celestial_vertices as u32 / 4) * 6, 0, 0..1); + if frame.end_sky { + self.end_sky.draw(&mut pass); + } + if celestial_vertices > 0 { + pass.set_vertex_buffer(0, self.celestial_buffer.slice(..)); + pass.draw_indexed(0..(celestial_vertices as u32 / 4) * 6, 0, 0..1); + } pass.set_bind_group(0, &self.group, &[]); } if !frame.title && frame.stars.is_some() { @@ -3622,6 +3673,12 @@ impl Renderer { ); pass.set_bind_group(0, &self.group, &[]); } + if !frame.lightning.bolts.is_empty() { + pass.set_pipeline(&self.lightning_pipeline); + pass.set_bind_group(0, &self.entity_group, &[]); + self.lightning.draw(&mut pass, &frame.lightning); + pass.set_bind_group(0, &self.group, &[]); + } if additive_quads > 0 { pass.set_pipeline(&self.additive_pipeline); pass.set_bind_group(0, &self.entity_group, &[]); @@ -3841,9 +3898,19 @@ impl Renderer { let first = debug_depth + debug_top; pass.draw(0..4, first..first + crosshair); } - if let Some(radius) = frame.menu_blur - && self.config.usage.contains(wgpu::TextureUsages::COPY_SRC) - { + let menu_blur = frame + .menu_blur + .filter(|_| self.config.usage.contains(wgpu::TextureUsages::COPY_SRC)); + let blur_at = menu_blur.map_or(0, |_| frame.hud.blur_at); + self.hud.draw_range( + &mut encoder, + &view_target, + &self.depth, + frame.hud, + [self.config.width, self.config.height], + 0..blur_at, + ); + if let Some(radius) = menu_blur { let format = self.config.format; let device = &self.device; self.menu_blur @@ -3875,12 +3942,13 @@ impl Renderer { grade, ); } - self.hud.draw( + self.hud.draw_range( &mut encoder, &view_target, &self.depth, frame.hud, [self.config.width, self.config.height], + blur_at..frame.hud.vertices.len() as u32, ); if culling && let Some(cull) = &mut self.cull { cull.end(&self.device, &mut encoder); diff --git a/crates/horizon-client/src/gfx/end_sky.rs b/crates/horizon-client/src/gfx/end_sky.rs new file mode 100644 index 000000000..15e9001fc --- /dev/null +++ b/crates/horizon-client/src/gfx/end_sky.rs @@ -0,0 +1,84 @@ +//! The End sky's six tiled faces, retained for the lifetime of the renderer's atlas. +use crate::mesher::Vertex; +use wgpu::util::DeviceExt; + +const VERTICES: u32 = 6 * 16 * 16 * 4; + +#[derive(Default)] +pub(super) struct EndSky { + mesh: Option<([f32; 4], wgpu::Buffer)>, +} + +impl EndSky { + /// Called only when the End sky is enabled. Rebuild on atlas UV changes; + /// resource reload and device recreation also replace the owning renderer. + pub(super) fn prepare(&mut self, device: &wgpu::Device, uv: Option<[f32; 4]>) { + let Some(uv) = uv else { + self.mesh = None; + return; + }; + if self.mesh.as_ref().is_some_and(|(old, _)| *old == uv) { + return; + } + let vertices = vertices(uv); + let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("End sky vertices"), + contents: bytemuck::cast_slice(&vertices), + usage: wgpu::BufferUsages::VERTEX, + }); + self.mesh = Some((uv, buffer)); + } + + /// The celestial pipeline, atlas bind group and quad indices are already bound. + pub(super) fn draw(&self, pass: &mut wgpu::RenderPass<'_>) { + if let Some((_, buffer)) = &self.mesh { + pass.set_vertex_buffer(0, buffer.slice(..)); + pass.draw_indexed(0..VERTICES / 4 * 6, 0, 0..1); + } + } +} + +/// SkyRenderer.buildEndSky: six faces of end_sky.png tiled 16 times, +/// tinted 0x282828. The atlas does not wrap, so each face is 16×16 quads. +fn vertices(uv: [f32; 4]) -> Vec { + let mut out = Vec::with_capacity(VERTICES as usize); + use std::f32::consts::FRAC_PI_2; + let faces = [ + glam::Mat4::IDENTITY, + glam::Mat4::from_rotation_x(FRAC_PI_2), + glam::Mat4::from_rotation_x(-FRAC_PI_2), + glam::Mat4::from_rotation_x(std::f32::consts::PI), + glam::Mat4::from_rotation_z(FRAC_PI_2), + glam::Mat4::from_rotation_z(-FRAC_PI_2), + ]; + let step = 200.0 / 16.0; + for pose in faces { + for a in 0..16 { + for b in 0..16 { + let (x0, z0) = (-100.0 + step * a as f32, -100.0 + step * b as f32); + let (x1, z1) = (x0 + step, z0 + step); + let corners = [ + (x0, z0, [uv[0], uv[1]]), + (x0, z1, [uv[0], uv[3]]), + (x1, z1, [uv[2], uv[3]]), + (x1, z0, [uv[2], uv[1]]), + ]; + for (x, z, uv) in corners { + let p = pose.transform_point3(glam::Vec3::new(x, -100.0, z)); + out.push(Vertex { + normal: [0; 4], + pos: p.to_array(), + uv, + layer: 2, + color: 0xFF28_2828, + light: 0, + }); + } + } + } + } + out +} + +#[cfg(test)] +mod tests; diff --git a/crates/horizon-client/src/gfx/end_sky/tests.rs b/crates/horizon-client/src/gfx/end_sky/tests.rs new file mode 100644 index 000000000..61266003d --- /dev/null +++ b/crates/horizon-client/src/gfx/end_sky/tests.rs @@ -0,0 +1,330 @@ +use super::*; +use crate::gfx::{Globals, Renderer}; +use bytemuck::Zeroable; +use glam::Mat4; + +#[test] +fn geometry_matches_pre_residency_vertex_snapshots() { + use sha2::{Digest, Sha256}; + // Captured from game/end.rs at 34c3c1cf for full, tiled and non-binary UVs. + // Quantize positions only, avoiding platform sin/cos rounding differences; + // quad order, UVs, tint, material and light retain their exact byte values. + for (uv, expected) in [ + ( + [0.0, 0.0, 1.0, 1.0], + "f7ee23457fc557b33ecf09c9afaf858f3d8907e108abf06055f627523f733536", + ), + ( + [0.125, 0.25, 0.375, 0.5], + "f74c4b8d23ec2b7c11b5752821d0733851bf11358f1b26f9448226ff62a6a318", + ), + ( + [0.13, 0.27, 0.41, 0.59], + "f0aaa39c5b22168bdc7c6c329acb4d3598a2feb61ff7b6f2850b644682749b39", + ), + ] { + let mut mesh = vertices(uv); + assert_eq!(mesh.len(), VERTICES as usize); + for vertex in &mut mesh { + vertex.pos = vertex.pos.map(|x| { + let n = (x * 1024.0).round() / 1024.0; + if n == 0.0 { 0.0 } else { n } + }); + } + assert_eq!( + format!("{:x}", Sha256::digest(bytemuck::cast_slice(&mesh))), + expected + ); + } +} + +fn device() -> Option<(wgpu::Device, wgpu::Queue)> { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let adapter = pollster::block_on(instance.request_adapter(&Default::default())).ok()?; + eprintln!("End sky test adapter: {:?}", adapter.get_info()); + pollster::block_on(adapter.request_device(&Default::default())).ok() +} + +#[test] +fn resident_buffer_survives_frames_and_refreshes_with_the_atlas() { + let Some((device, _)) = device() else { + eprintln!("no GPU adapter: skipped"); + return; + }; + let mut sky = EndSky::default(); + let uv = [0.125, 0.25, 0.375, 0.5]; + sky.prepare(&device, Some(uv)); + let first = sky.mesh.as_ref().unwrap().1.clone(); + assert_eq!( + first.size(), + u64::from(VERTICES) * size_of::() as u64 + ); + // Immutable: steady-state frames cannot upload into this buffer. + assert_eq!(first.usage(), wgpu::BufferUsages::VERTEX); + for _ in 0..600 { + sky.prepare(&device, Some(uv)); + assert_eq!(sky.mesh.as_ref().unwrap().1, first); + } + let moved = [0.5, 0.5, 0.75, 0.75]; + sky.prepare(&device, Some(moved)); + assert_ne!(sky.mesh.as_ref().unwrap().1, first); + assert_eq!(sky.mesh.as_ref().unwrap().0, moved); + sky.prepare(&device, None); + assert!(sky.mesh.is_none()); + sky.prepare(&device, Some(uv)); + assert_ne!(sky.mesh.as_ref().unwrap().1, first); + // A resource reload/device recreation starts a new renderer-owned cache, + // even if the replacement atlas happens to use exactly the same UVs. + let mut replacement = EndSky::default(); + replacement.prepare(&device, Some(uv)); + assert_ne!( + replacement.mesh.as_ref().unwrap().1, + sky.mesh.as_ref().unwrap().1 + ); +} + +/// The actual entity shader and celestial blend, comparing the old combined +/// vertex stream with a resident sky draw followed by a separate flash draw. +#[test] +fn separate_draws_match_combined_celestial_pixels() { + let Some((device, queue)) = device() else { + eprintln!("no GPU adapter: skipped"); + return; + }; + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("End sky differential shader"), + source: wgpu::ShaderSource::Wgsl(crate::gfx::entity_shader().into()), + }); + let attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4,5=>Snorm8x4]; + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("End sky differential pipeline"), + layout: None, + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_entity"), + compilation_options: Default::default(), + buffers: &[Some(wgpu::VertexBufferLayout { + array_stride: size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &attributes, + })], + }, + primitive: wgpu::PrimitiveState { + cull_mode: None, + ..Default::default() + }, + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_celestial"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: wgpu::TextureFormat::Rgba8Unorm, + blend: Some(wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::SrcAlpha, + dst_factor: wgpu::BlendFactor::One, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent::OVER, + }), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }); + let texture = |pixels: &[u8], width, height| { + device.create_texture_with_data( + &queue, + &wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { + width, + height, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }, + wgpu::util::TextureDataOrder::LayerMajor, + pixels, + ) + }; + // Asymmetric, translucent texels expose UV/winding and blend-order errors. + let pixels: Vec = (0..16 * 16) + .flat_map(|i| { + [ + (i * 17) as u8, + (i * 31) as u8, + (i * 7) as u8, + (80 + i % 176) as u8, + ] + }) + .collect(); + let atlas = texture(&pixels, 16, 16).create_view(&Default::default()); + let lightmap = texture(&[255; 4], 1, 1).create_view(&Default::default()); + let sampler = device.create_sampler(&Default::default()); + let uniform = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &pipeline.get_bind_group_layout(0), + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: uniform.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&atlas), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::Sampler(&sampler), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: wgpu::BindingResource::TextureView(&lightmap), + }, + wgpu::BindGroupEntry { + binding: 4, + resource: wgpu::BindingResource::Sampler(&sampler), + }, + ], + }); + let indices = Renderer::quad_indices(&device, VERTICES / 4 + 1); + let mut resident = EndSky::default(); + let uv = [0.125, 0.25, 0.375, 0.5]; + resident.prepare(&device, Some(uv)); + let first = resident.mesh.as_ref().unwrap().1.clone(); + let render = |sky: &EndSky, flash: &[Vertex], combined: bool| { + let target = device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { + width: 64, + height: 64, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let view = target.create_view(&Default::default()); + let mut vertices = if combined { vertices(uv) } else { Vec::new() }; + vertices.extend_from_slice(flash); + let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: None, + contents: bytemuck::cast_slice(&vertices), + usage: wgpu::BufferUsages::VERTEX, + }); + let readback = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 64 * 64 * 4, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut encoder = device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), + store: wgpu::StoreOp::Store, + }, + })], + ..Default::default() + }); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &group, &[]); + pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); + if !combined { + sky.draw(&mut pass); + } + if !vertices.is_empty() { + pass.set_vertex_buffer(0, buffer.slice(..)); + pass.draw_indexed(0..vertices.len() as u32 / 4 * 6, 0, 0..1); + } + } + encoder.copy_texture_to_buffer( + target.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &readback, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(256), + rows_per_image: Some(64), + }, + }, + target.size(), + ); + queue.submit([encoder.finish()]); + readback + .slice(..) + .map_async(wgpu::MapMode::Read, |r| r.unwrap()); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + readback.slice(..).get_mapped_range().unwrap().to_vec() + }; + let mut cases = 0; + let mut visible_flash_cases = 0; + for yaw in [0.0_f32, 45.0, 90.0, 180.0, 270.0] { + for pitch in [-85.0_f32, -30.0, 0.0, 45.0, 85.0] { + let mut globals = Globals::zeroed(); + globals.view_proj = (Mat4::perspective_rh(90_f32.to_radians(), 1.0, 0.05, 1024.0) + * Mat4::from_rotation_x(pitch.to_radians()) + * Mat4::from_rotation_y(yaw.to_radians())) + .to_cols_array_2d(); + queue.write_buffer(&uniform, 0, bytemuck::bytes_of(&globals)); + let no_flash = render(&resident, &[], true); + for level in [0_u32, 1, 127, 255] { + let flash: Vec<_> = if level == 0 { + Vec::new() + } else { + // Same flash size/height, with an arbitrary EndFlashState pose. + let pose = Mat4::from_rotation_y(1.3) * Mat4::from_rotation_x(-1.6); + [(-60.0, -60.0), (60.0, -60.0), (60.0, 60.0), (-60.0, 60.0)] + .map(|(x, z)| Vertex { + pos: pose.transform_point3(glam::vec3(x, 100.0, z)).to_array(), + uv: [0.75 + x / 480.0, 0.75 + z / 480.0], + layer: 2, + color: level * 0x01010101, + light: 0, + normal: [0; 4], + }) + .to_vec() + }; + resident.prepare(&device, Some(uv)); + let expected = render(&resident, &flash, true); + let actual = render(&resident, &flash, false); + visible_flash_cases += usize::from(expected != no_flash); + assert_eq!(actual, expected, "yaw={yaw} pitch={pitch} flash={level}"); + assert!( + actual.as_chunks::<4>().0.iter().any(|p| p[..3] != [0; 3]), + "empty frame" + ); + assert_eq!(resident.mesh.as_ref().unwrap().1, first); + cases += 1; + } + } + } + assert!( + visible_flash_cases > 0, + "the flash must affect the comparison" + ); + eprintln!("{cases} combined/resident framebuffer cases matched exactly"); +} diff --git a/crates/horizon-client/src/gfx/lightning.rs b/crates/horizon-client/src/gfx/lightning.rs new file mode 100644 index 000000000..251dbf00e --- /dev/null +++ b/crates/horizon-client/src/gfx/lightning.rs @@ -0,0 +1,211 @@ +//! Seeded, bolt-local lightning meshes retained until their last active bolt disappears. +use crate::{gfx::upload::Uploads, mesher::Vertex}; +use glam::DVec3; +use horizon_core::random::{LegacyRandom, RandomSource}; +use std::collections::HashMap; +use wgpu::util::DeviceExt; + +/// A bolt's render state. Simulation lifetime and flashes stay in the game. +#[derive(Clone, Copy)] +pub struct Bolt { + pub at: [f64; 3], + pub seed: i64, +} + +#[derive(Default)] +pub struct Input<'a> { + pub bolts: &'a [Bolt], + /// Current atlas white texel; a changed rect invalidates retained vertices. + pub uv: [f32; 2], +} + +// Four layers, fourteen segments (eight trunk, two branches of three), four quads. +pub(super) const QUADS: u32 = 4 * 14 * 4; + +/// `LightningBoltRenderer.submit`: keep random draws, layers and quad order unchanged. +fn geometry(seed: i64, uv: [f32; 2]) -> Vec { + let mut out = Vec::with_capacity(QUADS as usize * 4); + // ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA. + let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114; + let mut random = LegacyRandom::new(seed); + let (mut xs, mut zs) = ([0f32; 8], [0f32; 8]); + let (mut x_off, mut z_off) = (0f32, 0f32); + for i in (0..8).rev() { + xs[i] = x_off; + zs[i] = z_off; + x_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32; + z_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32; + } + for layer in 0..4 { + let mut random = LegacyRandom::new(seed); + for branch in 0..3 { + let trunk = branch == 0; + let start = 7 - branch; + let end = if trunk { 0 } else { start - 3 + 1 }; + let mut sx = xs[start] - x_off; + let mut sz = zs[start] - z_off; + for segment in (end..=start).rev() { + let (ex, ez) = (sx, sz); + let spread = if trunk { 11 } else { 31 }; + sx += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32; + sz += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32; + let mut top = 0.1 + layer as f32 * 0.2; + let mut bottom = top; + if trunk { + top *= segment as f32 * 0.1 + 1.0; + bottom *= (segment as f32 - 1.0) * 0.1 + 1.0; + } + for (rx, rz, lx, lz) in [ + (false, false, true, false), + (true, false, true, true), + (true, true, false, true), + (false, true, false, false), + ] { + let s = |p: bool, r: f32| if p { r } else { -r }; + let y0 = segment as f32 * 16.0; + let corners = [ + [sx + s(rx, bottom), y0, sz + s(rz, bottom)], + [ex + s(rx, top), y0 + 16.0, ez + s(rz, top)], + [ex + s(lx, top), y0 + 16.0, ez + s(lz, top)], + [sx + s(lx, bottom), y0, sz + s(lz, bottom)], + ]; + for c in corners { + out.push(Vertex { + normal: [0; 4], + pos: c, + uv, + layer: 2, + color, + light: 240 | 240 << 8, + }); + } + } + } + } + } + out +} + +struct Cached { + mesh: T, + used: bool, +} + +/// Shared seeds use the same mesh; storage is bounded by active unique seeds, +/// including after seed changes, removals, dimension switches and disconnects. +struct Cache { + uv: Option<[f32; 2]>, + meshes: HashMap>, +} +impl Cache { + fn new() -> Self { + Self { + uv: None, + meshes: HashMap::new(), + } + } + + fn prepare(&mut self, input: &Input<'_>, mut build: impl FnMut(i64, [f32; 2]) -> T) { + if self.uv != Some(input.uv) { + self.meshes.clear(); + self.uv = Some(input.uv); + } + for cached in self.meshes.values_mut() { + cached.used = false; + } + for bolt in input.bolts { + self.meshes + .entry(bolt.seed) + .or_insert_with(|| Cached { + mesh: build(bolt.seed, input.uv), + used: true, + }) + .used = true; + } + self.meshes.retain(|_, cached| cached.used); + // HashMap::retain keeps its allocation. Release historical peak capacity + // as well as meshes once the storm (or connection) is gone. + if self.meshes.is_empty() { + self.meshes = HashMap::new(); + } else if self.meshes.capacity() > self.meshes.len() * 4 { + self.meshes.shrink_to_fit(); + } + } +} + +fn offset(bolt: &Bolt, camera: DVec3) -> [f32; 3] { + (DVec3::from_array(bolt.at) - camera).as_vec3().to_array() +} + +pub(super) struct Renderer { + cache: Cache, + instances: Option, + capacity: usize, +} +impl Renderer { + pub(super) fn new() -> Self { + Self { + cache: Cache::new(), + instances: None, + capacity: 0, + } + } + + pub(super) fn prepare( + &mut self, + device: &wgpu::Device, + uploads: &mut Uploads, + encoder: &mut wgpu::CommandEncoder, + input: &Input<'_>, + camera: DVec3, + ) { + self.cache.prepare(input, |seed, uv| { + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("Lightning vertices"), + contents: bytemuck::cast_slice(&geometry(seed, uv)), + usage: wgpu::BufferUsages::VERTEX, + }) + }); + if input.bolts.is_empty() { + self.instances = None; + self.capacity = 0; + return; + } + if input.bolts.len() > self.capacity || input.bolts.len() < self.capacity / 4 { + self.capacity = input.bolts.len().next_power_of_two(); + self.instances = Some(device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Lightning offsets"), + size: (self.capacity * std::mem::size_of::<[f32; 3]>()) as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + })); + } + let offsets: Vec<_> = input + .bolts + .iter() + .map(|bolt| offset(bolt, camera)) + .collect(); + uploads.buffer( + encoder, + self.instances.as_ref().unwrap(), + 0, + bytemuck::cast_slice(&offsets), + ); + } + + pub(super) fn draw(&self, pass: &mut wgpu::RenderPass<'_>, input: &Input<'_>) { + let Some(instances) = &self.instances else { + return; + }; + pass.set_vertex_buffer(1, instances.slice(..)); + // Follow simulation order, including repeated seeds; HashMap order must + // never change additive accumulation or the order before dragon rays. + for (i, bolt) in input.bolts.iter().enumerate() { + pass.set_vertex_buffer(0, self.cache.meshes[&bolt.seed].mesh.slice(..)); + pass.draw_indexed(0..QUADS * 6, 0, i as u32..i as u32 + 1); + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/horizon-client/src/gfx/lightning/tests/mod.rs b/crates/horizon-client/src/gfx/lightning/tests/mod.rs new file mode 100644 index 000000000..f89f402de --- /dev/null +++ b/crates/horizon-client/src/gfx/lightning/tests/mod.rs @@ -0,0 +1,495 @@ +use super::*; +use std::cell::Cell; + +// Frozen pre-cache generator: compare every Vertex byte, including primitive +// order and the original camera-relative rounding, without game resources. +fn reference(seed: i64, at: [f64; 3], camera: DVec3, uv: [f32; 2]) -> Vec { + let mut out = Vec::new(); + // ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA. + let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114; + let b = Bolt { seed, at }; + { + let o = (glam::DVec3::from_array(b.at) - camera).as_vec3(); + let mut random = LegacyRandom::new(b.seed); + let (mut xs, mut zs) = ([0f32; 8], [0f32; 8]); + let (mut x_off, mut z_off) = (0f32, 0f32); + for i in (0..8).rev() { + xs[i] = x_off; + zs[i] = z_off; + x_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32; + z_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32; + } + for layer in 0..4 { + let mut random = LegacyRandom::new(b.seed); + for branch in 0..3 { + let trunk = branch == 0; + let start = 7 - branch; + let end = if trunk { 0 } else { start - 3 + 1 }; + let mut sx = xs[start] - x_off; + let mut sz = zs[start] - z_off; + for segment in (end..=start).rev() { + let (ex, ez) = (sx, sz); + let spread = if trunk { 11 } else { 31 }; + sx += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32; + sz += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32; + let mut top = 0.1 + layer as f32 * 0.2; + let mut bottom = top; + if trunk { + top *= segment as f32 * 0.1 + 1.0; + bottom *= (segment as f32 - 1.0) * 0.1 + 1.0; + } + for (rx, rz, lx, lz) in [ + (false, false, true, false), + (true, false, true, true), + (true, true, false, true), + (false, true, false, false), + ] { + let s = |p: bool, r: f32| if p { r } else { -r }; + let y0 = segment as f32 * 16.0; + let corners = [ + [sx + s(rx, bottom), y0, sz + s(rz, bottom)], + [ex + s(rx, top), y0 + 16.0, ez + s(rz, top)], + [ex + s(lx, top), y0 + 16.0, ez + s(lz, top)], + [sx + s(lx, bottom), y0, sz + s(lz, bottom)], + ]; + for c in corners { + out.push(Vertex { + normal: [0; 4], + pos: (o + glam::Vec3::from_array(c)).to_array(), + uv, + layer: 2, + color, + light: 240 | 240 << 8, + }); + } + } + } + } + } + } + out +} + +fn seeds() -> Vec { + let mut seeds = vec![0, 1, -1, i64::MIN, i64::MAX, 0x123456789abcdef]; + let mut random = LegacyRandom::new(42); + seeds.extend((0..256).map(|_| random.next_long())); + seeds +} + +/// Pinned 26.3 LightningBoltRenderer.lambda$submit$0, captured with an +/// identity PoseStack and a VertexConsumer recording big-endian xyz floats. +#[test] +fn geometry_matches_pinned_vanilla_vertex_digest() { + use sha2::{Digest, Sha256}; + let mut digest = Sha256::new(); + for seed in seeds() { + for vertex in geometry(seed, [0.0; 2]) { + for value in vertex.pos { + digest.update(value.to_be_bytes()); + } + } + } + assert_eq!( + format!("{:x}", digest.finalize()), + "a9ed25caa50b9aa340faa4bb417b3d533b061f0dce66514e4bb212931444dee6" + ); +} + +#[test] +fn retained_geometry_matches_original_generator() { + let uv = [0.8125, 0.03125]; + for seed in seeds() { + let local = geometry(seed, uv); + assert_eq!(local.len(), QUADS as usize * 4); + for (at, camera) in [ + ([0.0; 3], DVec3::ZERO), + ([12.5, 64.0, -12.5], DVec3::new(-4.25, 71.125, 32.5)), + ( + [29_999_999.5, -64.0, -29_999_999.5], + DVec3::new(29_999_987.125, 67.75, -29_999_983.875), + ), + ] { + let offset = offset(&Bolt { seed, at }, camera); + let translated: Vec<_> = local + .iter() + .map(|v| Vertex { + pos: (glam::Vec3::from_array(offset) + glam::Vec3::from_array(v.pos)) + .to_array(), + ..*v + }) + .collect(); + let expected = reference(seed, at, camera, uv); + assert_eq!( + bytemuck::cast_slice::<_, u8>(&translated), + bytemuck::cast_slice::<_, u8>(&expected), + "seed {seed}" + ); + } + } +} + +#[test] +fn cache_tracks_seed_lifecycle_movement_and_atlas_reload() { + let mut cache = Cache::new(); + let builds = Cell::new(0); + let build = |seed, uv| { + builds.set(builds.get() + 1); + geometry(seed, uv) + }; + let mut bolts = [ + Bolt { + seed: 123, + at: [0.0; 3], + }, + Bolt { + seed: 456, + at: [1.0; 3], + }, + ]; + fn input(bolts: &[Bolt]) -> Input<'_> { + Input { + bolts, + uv: [0.25, 0.5], + } + } + cache.prepare(&input(&bolts), build); + assert_eq!(builds.get(), 2); + assert_eq!(cache.meshes.len(), 2); + // Any number of rendered frames or multiplayer position updates reuse meshes. + for i in 0..100 { + bolts[0].at = [i as f64; 3]; + cache.prepare(&input(&bolts), build); + } + assert_eq!(builds.get(), 2); + // A flash changes the seed; retire its previous mesh immediately. + bolts[0].seed = 789; + cache.prepare(&input(&bolts), build); + assert_eq!(builds.get(), 3); + assert!(!cache.meshes.contains_key(&123)); + // Removal retains other bolts, and repeated seeds still share geometry. + bolts[0].seed = 456; + cache.prepare(&input(&bolts), build); + assert_eq!(builds.get(), 3); + assert_eq!(cache.meshes.len(), 1); + // Atlas replacement must update white texel UVs without changing the seed. + cache.prepare( + &Input { + bolts: &bolts, + uv: [0.75, 0.25], + }, + build, + ); + assert_eq!(builds.get(), 4); + assert_eq!(cache.meshes[&456].mesh[0].uv, [0.75, 0.25]); + // Disconnect/dimension switch/expiry drops every retained resource. + cache.prepare(&Input::default(), build); + assert!(cache.meshes.is_empty()); + assert_eq!(cache.meshes.capacity(), 0); + cache.prepare(&input(&bolts), build); + assert_eq!(builds.get(), 5); +} + +#[test] +fn long_flash_sequence_keeps_only_active_seeds() { + let mut cache = Cache::new(); + for seed in 0..10_000 { + cache.prepare( + &Input { + bolts: &[Bolt { seed, at: [0.0; 3] }], + uv: [0.0; 2], + }, + |seed, _| seed, + ); + assert_eq!(cache.meshes.len(), 1); + assert_eq!(cache.meshes[&seed].mesh, seed); + assert!(cache.meshes.capacity() < 16); + } +} + +/// Exercise the actual entity shader and retained draw path offscreen. Run +/// explicitly, separately from other headless device tests (some GPU drivers +/// fail during concurrent device teardown). Machines without an adapter skip it. +#[test] +#[ignore = "requires GPU; run separately with --ignored --exact"] +fn retained_gpu_draw_matches_transient_additive_draw() { + use bytemuck::Zeroable; + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { + eprintln!("no GPU adapter: skipped"); + return; + }; + eprintln!("lightning differential GPU: {}", adapter.get_info().name); + let (device, queue) = pollster::block_on(adapter.request_device(&Default::default())).unwrap(); + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Lightning differential shader"), + source: wgpu::ShaderSource::Wgsl(crate::gfx::entity_shader().into()), + }); + let attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4,5=>Snorm8x4]; + let offsets = wgpu::vertex_attr_array![6=>Float32x3]; + let vertices = [Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &attributes, + })]; + let retained_vertices = [ + vertices[0].clone(), + Some(wgpu::VertexBufferLayout { + array_stride: 12, + step_mode: wgpu::VertexStepMode::Instance, + attributes: &offsets, + }), + ]; + let pipelines: Vec<_> = [false, true] + .into_iter() + .map(|retained| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Lightning differential pipeline"), + layout: None, + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some(if retained { + "vs_lightning" + } else { + "vs_entity" + }), + compilation_options: Default::default(), + buffers: if retained { + &retained_vertices + } else { + &vertices + }, + }, + primitive: wgpu::PrimitiveState { + cull_mode: None, + ..Default::default() + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(false), + depth_compare: Some(wgpu::CompareFunction::GreaterEqual), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_celestial"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: wgpu::TextureFormat::Rgba8Unorm, + blend: Some(wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::SrcAlpha, + dst_factor: wgpu::BlendFactor::One, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::SrcAlpha, + dst_factor: wgpu::BlendFactor::One, + operation: wgpu::BlendOperation::Add, + }, + }), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }) + }) + .collect(); + let globals = crate::gfx::Globals { + view_proj: (glam::Mat4::orthographic_rh(-100.0, 100.0, -10.0, 150.0, 0.1, 400.0) + * glam::Mat4::look_at_rh( + glam::Vec3::new(80.0, 30.0, 160.0), + glam::Vec3::new(0.0, 60.0, 0.0), + glam::Vec3::Y, + )) + .to_cols_array_2d(), + ..crate::gfx::Globals::zeroed() + }; + let globals = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: None, + contents: bytemuck::bytes_of(&globals), + usage: wgpu::BufferUsages::UNIFORM, + }); + let size = wgpu::Extent3d { + width: 256, + height: 256, + depth_or_array_layers: 1, + }; + let texture = |format, usage| { + device.create_texture(&wgpu::TextureDescriptor { + label: None, + size, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }) + }; + let white = device + .create_texture_with_data( + &queue, + &wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { + width: 1, + height: 1, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }, + wgpu::util::TextureDataOrder::LayerMajor, + &[255; 4], + ) + .create_view(&Default::default()); + let sampler = device.create_sampler(&Default::default()); + let groups: Vec<_> = pipelines + .iter() + .map(|pipeline| { + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &pipeline.get_bind_group_layout(0), + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: globals.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&white), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::Sampler(&sampler), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: wgpu::BindingResource::TextureView(&white), + }, + wgpu::BindGroupEntry { + binding: 4, + resource: wgpu::BindingResource::Sampler(&sampler), + }, + ], + }) + }) + .collect(); + let mut renderer = Renderer::new(); + let mut uploads = Uploads::new(&device); + let mut bolts = [Bolt { + seed: 123, + at: [29_999_999.5, 64.0, -29_999_999.5], + }; 3]; + bolts[1].seed = -456; + bolts[1].at[0] -= 32.0; + bolts[2].at[2] += 20.0; + let indices = crate::gfx::Renderer::quad_indices(&device, QUADS * 3); + for frame in 0..4 { + let camera = DVec3::new(29_999_997.125 + frame as f64, 62.75, -29_999_998.875); + if frame == 2 { + bolts[0].seed = 789; + } + let input = Input { + bolts: &bolts[..if frame == 3 { 1 } else { 3 }], + uv: if frame == 3 { [0.75; 2] } else { [0.5; 2] }, + }; + let expected: Vec<_> = input + .bolts + .iter() + .flat_map(|bolt| reference(bolt.seed, bolt.at, camera, input.uv)) + .collect(); + let transient = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: None, + contents: bytemuck::cast_slice(&expected), + usage: wgpu::BufferUsages::VERTEX, + }); + let mut encoder = device.create_command_encoder(&Default::default()); + renderer.prepare(&device, &mut uploads, &mut encoder, &input, camera); + let mut readbacks = Vec::new(); + for mode in 0..2 { + let color = texture( + wgpu::TextureFormat::Rgba8Unorm, + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + ); + let view = color.create_view(&Default::default()); + let depth = texture( + wgpu::TextureFormat::Depth32Float, + wgpu::TextureUsages::RENDER_ATTACHMENT, + ) + .create_view(&Default::default()); + { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: None, + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &depth, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(0.0), + store: wgpu::StoreOp::Discard, + }), + stencil_ops: None, + }), + ..Default::default() + }); + pass.set_pipeline(&pipelines[mode]); + pass.set_bind_group(0, &groups[mode], &[]); + pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); + if mode == 0 { + pass.set_vertex_buffer(0, transient.slice(..)); + pass.draw_indexed(0..expected.len() as u32 / 4 * 6, 0, 0..1); + } else { + renderer.draw(&mut pass, &input); + } + } + let read = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 256 * 256 * 4, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + encoder.copy_texture_to_buffer( + color.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &read, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(1024), + rows_per_image: None, + }, + }, + size, + ); + readbacks.push(read); + } + uploads.finish(&encoder); + queue.submit([encoder.finish()]); + for read in &readbacks { + read.slice(..) + .map_async(wgpu::MapMode::Read, |r| r.unwrap()); + } + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let pixels: Vec> = readbacks + .iter() + .map(|read| read.slice(..).get_mapped_range().unwrap().to_vec()) + .collect(); + assert!(pixels[0].iter().any(|&b| b != 0), "empty reference frame"); + assert_eq!(pixels[0], pixels[1], "frame {frame}: GPU output differs"); + } +} diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 0cc99b07b..b4bfe72ac 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -30,8 +30,10 @@ pub struct HudAtlas { } /// Atlas rows reserved for glyphs rasterized at run time. pub const GLYPH_ROWS: u32 = 512; -/// 128x128 atlas slots for map textures. -pub const MAP_SLOTS: usize = 16; +/// 128x128 atlas slots for map textures. A lobby paints its signs as walls of +/// framed maps, so the pool holds a wall; too few slots re-upload every map +/// every frame. 26.3's `MapTextureManager` keeps a texture per map instead. +pub const MAP_SLOTS: usize = 256; /// The atlas slot the minimap extra draws into. pub const MINIMAP_SPRITE: &str = "horizon/minimap"; /// Atlas slots for downloaded player skins (`skins/`), 64x64 each. @@ -363,6 +365,8 @@ pub struct HudBatch { pub patches: Vec, /// Vertex ranges with another blend or depth/scissor state, in order. pub blends: Vec<(std::ops::Range, Blend)>, + /// Screen's first vertex: the preceding HUD is part of its blurred background. + pub blur_at: u32, } /// How a run of HUD vertices blends and tests depth. #[derive(Clone, Copy, PartialEq, Eq, Debug)] @@ -398,6 +402,7 @@ impl HudBatch { height: (window[1] as f32 / scale as f32).ceil(), patches: Vec::new(), blends: Vec::new(), + blur_at: 0, } } /// Draw the vertices added since `start` with the inverting blend. @@ -450,6 +455,14 @@ impl HudBatch { } out } + fn runs_in(&self, vertices: std::ops::Range) -> Vec<(std::ops::Range, Blend)> { + let mut runs = self.runs(); + for (range, _) in &mut runs { + *range = range.start.max(vertices.start)..range.end.min(vertices.end); + } + runs.retain(|(range, _)| !range.is_empty()); + runs + } /// `AbstractContainerScreen.init`: center in integer GUI coordinates. pub fn centered_origin(&self, width: f32, height: f32) -> (f32, f32) { ( @@ -1078,7 +1091,26 @@ impl HudRenderer { batch: &HudBatch, size: [u32; 2], ) { - if batch.vertices.is_empty() || size.contains(&0) { + self.draw_range( + encoder, + target, + depth, + batch, + size, + 0..batch.vertices.len() as u32, + ); + } + /// Draw part of the prepared batch, preserving its blend/depth runs. + pub fn draw_range( + &self, + encoder: &mut wgpu::CommandEncoder, + target: &wgpu::TextureView, + depth: &wgpu::TextureView, + batch: &HudBatch, + size: [u32; 2], + vertices: std::ops::Range, + ) { + if vertices.is_empty() || size.contains(&0) { return; } let attachments = [Some(wgpu::RenderPassColorAttachment { @@ -1090,7 +1122,7 @@ impl HudRenderer { store: wgpu::StoreOp::Store, }, })]; - let runs = batch.runs(); + let runs = batch.runs_in(vertices); let mut at = 0; while at < runs.len() { let clip = match runs[at].1 { @@ -1329,6 +1361,33 @@ mod tests { ] ); } + + #[test] + fn blur_boundary_splits_blend_runs_without_losing_or_repeating_vertices() { + let mut batch = HudBatch::new([854, 480]); + for _ in 0..5 { + batch.quad([[0.0; 2]; 4], [[0.0; 2]; 4], 0); + } + batch.blends = vec![ + (6..18, Blend::Invert), + (18..24, Blend::Depth([0, 0, 10, 10])), + ]; + for split in [0, 6, 12, 18, 24, 30] { + let before = batch.runs_in(0..split); + let after = batch.runs_in(split..30); + let actual: Vec<_> = before + .into_iter() + .chain(after) + .flat_map(|(range, blend)| range.map(move |v| (v, blend))) + .collect(); + let expected: Vec<_> = batch + .runs() + .into_iter() + .flat_map(|(range, blend)| range.map(move |v| (v, blend))) + .collect(); + assert_eq!(actual, expected, "blur at {split}"); + } + } #[test] fn container_origins_use_java_integer_division() { // Odd scaled dimensions, odd image sizes and an oversized panel. @@ -1340,6 +1399,7 @@ mod tests { height: height as f32, patches: Vec::new(), blends: Vec::new(), + blur_at: 0, }; for (image_width, image_height) in [(195, 136), (176, 166), (176, 222)] { assert_eq!( diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index 2ba8d39a9..1376dde98 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -302,7 +302,10 @@ fn filterable_text(t: &Tag) -> Option { fn read_text(t: &Tag) -> Option { match t { Tag::String(s) => Some(s.to_string_lossy()), - Tag::Compound(_) => t.get("text").and_then(string), + // A component's root `text` may be empty with the visible words in + // `extra` (every legacy display name ViaVersion produces looks like + // this), so flatten the whole component instead of reading one key. + Tag::Compound(_) => Some(crate::entity_nbt::name_text(t).plain()), _ => None, } } @@ -860,6 +863,26 @@ mod tests { assert_eq!(back.custom_name(), Some("Blade")); } + #[test] + fn custom_name_reads_the_extra_spans() { + let name = Tag::compound([ + ( + "extra", + Tag::List(vec![ + Tag::compound([("text", Tag::String("Games ".into()))]), + Tag::compound([("text", Tag::String("Right click".into()))]), + ]), + ), + ("text", Tag::String("".into())), + ]); + let components = Tag::compound([("minecraft:custom_name", name)]); + let (_, extra) = decode_components(Some(&components)); + assert_eq!( + extra.and_then(|d| d.custom_name.clone()).as_deref(), + Some("Games Right click") + ); + } + #[test] fn banner_layers_and_shield_base_round_trip() { let mut stack = ItemStack::new("minecraft:shield", 1); diff --git a/crates/horizon-client/src/item_tooltip.rs b/crates/horizon-client/src/item_tooltip.rs index 0fc9910d1..ca6ff481b 100644 --- a/crates/horizon-client/src/item_tooltip.rs +++ b/crates/horizon-client/src/item_tooltip.rs @@ -486,10 +486,28 @@ pub fn lines( translate: &dyn Fn(&str) -> Option, ) -> Vec { let mut lines = vec![name_line(stack, translate)]; + if TooltipDisplay::for_stack(stack).shows("minecraft:lore") { + lines.extend(lore_lines(stack)); + } lines.extend(detail_lines(stack, info, translate)); lines } +/// `LoreComponent.addToTooltip`: the saved component lines, as plain text. +fn lore_lines(stack: &ItemStack) -> Vec { + let Some(Tag::List(entries)) = stack.data().and_then(|d| d.other("minecraft:lore")) else { + return Vec::new(); + }; + entries + .iter() + .map(|entry| { + let json = crate::scoreboard::tag_to_json(entry); + let text = crate::component::to_text(&json, &mut |s| crate::text::Text::literal(s)); + text.plain() + }) + .collect() +} + #[cfg(test)] mod tests { use super::*; @@ -591,6 +609,65 @@ mod tests { assert!(container_lines(&ItemStack::new("minecraft:chest", 1), &name, &lang).is_empty()); } + #[test] + fn fireworks_use_loaded_tooltip_translations() { + let root = std::env::temp_dir().join(format!( + "horizon-firework-tooltip-language-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(), + )); + let dir = root.join("assets/minecraft/lang"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join("en_us.json"), + serde_json::to_vec(&serde_json::json!({ + "item.minecraft.firework_rocket.flight_duration": "Flight Duration: %s", + "item.minecraft.firework_rocket.multiple_stars": "%s x %s", + "item.minecraft.firework_star.shape.small_ball": "Small Ball", + "item.minecraft.firework_star.red": "Red", + "item.minecraft.firework_star.custom_color": "Custom", + "item.minecraft.firework_star.fade_to": "Fade to", + "item.minecraft.firework_star.trail": "Trail", + "item.minecraft.firework_star.flicker": "Twinkle", + })) + .unwrap(), + ) + .unwrap(); + let enchantments = crate::enchant::Enchantments::load(&root); + std::fs::remove_dir_all(&root).unwrap(); + let translate = |key: &str| enchantments.translate(key).map(str::to_owned); + let mut rocket = ItemStack::new("minecraft:firework_rocket", 1); + assert_eq!(firework_lines(&rocket, &translate), ["Flight Duration: 1"]); + let explosion = crate::particles::FireworkExplosion { + colors: vec![0xB3312C], + fade: vec![0x123456], + trail: true, + twinkle: true, + ..Default::default() + }; + rocket.data_mut().fireworks = Some((3, vec![explosion.clone(), explosion.clone()])); + assert_eq!( + firework_lines(&rocket, &translate), + [ + "Flight Duration: 3", + "2 x Small Ball", + " Red", + " Fade to Custom", + " Trail", + " Twinkle", + ] + ); + let mut star = ItemStack::new("minecraft:firework_star", 1); + star.data_mut().firework_explosion = Some(explosion); + assert_eq!( + firework_lines(&star, &translate), + ["Small Ball", "Red", "Fade to Custom", "Trail", "Twinkle"] + ); + } + #[test] fn amounts_use_two_decimals_at_most() { assert_eq!(format_amount(8.0), "8"); diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 5be044e5d..ab0b8b6ad 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -242,6 +242,30 @@ fn tracked(cx: i32, cz: i32, r: i32, x: i32, z: i32) -> bool { dx * dx + dz * dz < i64::from(r) * i64::from(r) } +/// The view's queue around a new centre: the queued chunks still tracked, then +/// the tracked ones neither sent nor queued, closest first (a stable sort, so +/// equally close chunks keep their order). +fn requeue( + queue: &mut Vec<(i32, i32)>, + sent: &crate::fast_hash::FxHashSet<(i32, i32)>, + (cx, cz): (i32, i32), + r: i32, +) { + queue.retain(|&(x, z)| tracked(cx, cz, r, x, z)); + // A walking player changes chunk every few ticks with hundreds of chunks + // queued: a set, not a scan of the queue for each of the view's chunks. + let mut queued: crate::fast_hash::FxHashSet<(i32, i32)> = queue.iter().copied().collect(); + for dz in -r - 2..=r + 2 { + for dx in -r - 2..=r + 2 { + let key = (cx + dx, cz + dz); + if tracked(cx, cz, r, key.0, key.1) && !sent.contains(&key) && queued.insert(key) { + queue.push(key); + } + } + } + queue.sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2)); +} + /// What a level's players were last told of its clock and weather. #[derive(Clone, Copy)] struct LevelSync { @@ -1310,20 +1334,7 @@ impl Hub { g.sent_chunks.remove(&(x, z)); g.send(&C::ForgetLevelChunk(play::ForgetLevelChunk { pos: [x, z] })); } - g.chunk_queue.retain(|&(x, z)| tracked(cx, cz, r, x, z)); - for dz in -r - 2..=r + 2 { - for dx in -r - 2..=r + 2 { - let key = (cx + dx, cz + dz); - if tracked(cx, cz, r, key.0, key.1) - && !g.sent_chunks.contains(&key) - && !g.chunk_queue.contains(&key) - { - g.chunk_queue.push(key); - } - } - } - g.chunk_queue - .sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2)); + requeue(&mut g.chunk_queue, &g.sent_chunks, (cx, cz), r); } /// PlayerChunkSender.sendNextChunks' choice: ready chunks, closest first, @@ -2500,3 +2511,76 @@ fn ticking_state(rate: f32, frozen: bool) -> C { w.bool(frozen); raw(ids::TICKING_STATE, w.data) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::fast_hash::FxHashSet; + + /// `requeue` as it was, scanning the queue for each chunk of the view. + fn requeue_scan( + queue: &mut Vec<(i32, i32)>, + sent: &FxHashSet<(i32, i32)>, + (cx, cz): (i32, i32), + r: i32, + ) { + queue.retain(|&(x, z)| tracked(cx, cz, r, x, z)); + for dz in -r - 2..=r + 2 { + for dx in -r - 2..=r + 2 { + let key = (cx + dx, cz + dz); + if tracked(cx, cz, r, key.0, key.1) && !sent.contains(&key) && !queue.contains(&key) + { + queue.push(key); + } + } + } + queue.sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2)); + } + + /// A player walking a loop, sending a few chunks a tick: the queue + /// after every move is the one the scan built. + #[test] + fn requeue_matches_the_scan() { + for r in [2, 5, 10, 12, 32] { + let (mut a, mut b) = (Vec::new(), Vec::new()); + let mut sent = FxHashSet::default(); + for step in 0..60i32 { + let center = ((step % 17) - 8, (step * 3 % 11) - 5); + requeue(&mut a, &sent, center, r); + requeue_scan(&mut b, &sent, center, r); + assert_eq!(a, b, "radius {r}, step {step}"); + for key in a.drain(..a.len().min(7)) { + sent.insert(key); + } + b.drain(..b.len().min(7)); + sent.retain(|&(x, z)| tracked(center.0, center.1, r, x, z)); + } + } + } + + /// cargo test --release -p horizon-client --lib lan::hub::tests::requeue_cost -- --ignored --nocapture + #[test] + #[ignore] + fn requeue_cost() { + for r in [10, 16, 32] { + for (name, f) in [ + ("scan", requeue_scan as fn(&mut _, &_, _, _)), + ("set", requeue as fn(&mut _, &_, _, _)), + ] { + let sent = FxHashSet::default(); + let mut queue = Vec::new(); + let start = std::time::Instant::now(); + let moves = 200; + for step in 0..moves { + // Nothing sent yet (an explorer waiting on generation). + f(&mut queue, &sent, (step, 0), r); + } + let per = start.elapsed().as_secs_f64() * 1e6 / f64::from(moves); + println!( + "view {r}: {name} {per:.1} us per chunk crossed, {} queued", + queue.len() + ); + } + } + } +} diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index e87032f07..db2ebeb60 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -807,7 +807,11 @@ pub struct Mob { pub persistent: bool, /// `CustomName` (plain text) and `CustomNameVisible`. pub custom_name: Option, + /// The styled `CustomName`, when it came from a component. + pub custom_name_text: Option, pub name_visible: bool, + /// `Entity.DATA_SHARED_FLAGS_ID` bit 0x20: the model is hidden. + pub invisible: bool, pub random: LegacyRandom, pub ai: Box, pub extra: Extra, @@ -846,6 +850,9 @@ pub struct Mob { /// from the game), handed over with the next tick's events or drained /// by the game. pub outbox: Vec, + /// The skin texture of a player mob (`PlayerInfo.getSkin`), which + /// replaces the type's default when its download is ready. + pub skin: Option, } /// Events a mob tick asks the game to act on. #[derive(Clone, Debug)] @@ -1310,31 +1317,67 @@ impl Mob { /// `Entity.push` on other mobs acts at once in vanilla: a mob ticking later /// moves with it this tick. Takes the `Push` events aimed at mobs out of /// `events[from..]` into `pending`, which the caller adds to each mob's -/// velocity before its tick (and to every mob once all have ticked). -pub fn take_mob_pushes(events: &mut Vec, from: usize, pending: &mut Vec<(u32, Vec3)>) { - let mut i = from; - while i < events.len() { +/// velocity before its tick (and to every mob once all have ticked). The +/// other events keep their order. +pub fn take_mob_pushes(events: &mut Vec, from: usize, pending: &mut PendingPushes) { + // One pass: a crowd's tick holds a push per neighbour, and removing each + // in place would shift the rest every time. + let mut kept = from; + for i in from..events.len() { if let MobEvent::Push { target: Who::Mob(id), velocity, } = events[i] { - pending.push((id, Vec3::new(velocity[0], velocity[1], velocity[2]))); - events.remove(i); + pending.push(id, Vec3::new(velocity[0], velocity[1], velocity[2])); } else { - i += 1; + events.swap(kept, i); + kept += 1; } } + events.truncate(kept); +} +/// Pushes waiting for their mob's tick, in push order. A list while short; +/// past [`PendingPushes::LIST_MAX`] (a crowd pushing each other) one list +/// per mob, as scanning the whole list for each mob grows with its square. +#[derive(Default)] +pub struct PendingPushes { + list: Vec<(u32, Vec3)>, + by_mob: crate::fast_hash::FxHashMap>, +} +impl PendingPushes { + const LIST_MAX: usize = 64; + pub fn push(&mut self, id: u32, v: Vec3) { + if self.by_mob.is_empty() && self.list.len() < Self::LIST_MAX { + self.list.push((id, v)); + return; + } + // Older pushes first, so each mob's stay in order. + for (id, v) in self.list.drain(..) { + self.by_mob.entry(id).or_default().push(v); + } + self.by_mob.entry(id).or_default().push(v); + } } /// Adds the pending pushes aimed at `m` to its velocity, in push order. -pub fn apply_mob_pushes(m: &mut Mob, pending: &mut Vec<(u32, Vec3)>) { - pending.retain(|(id, v)| { - if *id != m.id { - return true; - } +pub fn apply_mob_pushes(m: &mut Mob, pending: &mut PendingPushes) { + let mut add = |v: Vec3| { m.velocity = Vec3::new(m.velocity.x + v.x, m.velocity.y + v.y, m.velocity.z + v.z); - false - }); + }; + if !pending.list.is_empty() { + pending.list.retain(|(id, v)| { + if *id != m.id { + return true; + } + add(*v); + false + }); + } + if !pending.by_mob.is_empty() + && let Some(pushes) = pending.by_mob.remove(&m.id) + { + pushes.into_iter().for_each(add); + } } /// Applies the brain memories a mob's tick set on other mobs (from event /// index `from` on), at once: vanilla sets them on the other entity during @@ -1406,6 +1449,7 @@ pub struct PlayerView { /// (`EntitySelector.pushableBy` on the client). pub remote: bool, } +#[derive(Clone)] pub struct MobWorld<'a> { pub world: &'a World, pub registry: &'a horizon_world::registry::BlockRegistry, @@ -1420,6 +1464,8 @@ pub struct MobWorld<'a> { pub others: &'a [Seen], /// `others` by position, when the caller keeps one (the mob ticks). pub others_grid: Option<&'a seen_grid::SeenGrid>, + /// Where each id stands in `others`, when the caller keeps one. + pub others_index: Option<&'a crate::fast_hash::FxHashMap>, pub daylight: bool, pub game_time: i64, pub day_time: i64, @@ -1438,22 +1484,23 @@ pub struct MobWorld<'a> { pub world_seed: i64, /// `Level.getSeaLevel` (63 in the overworld, -63 in a flat world). pub sea_level: i32, - /// The scoreboard teams of the player and the mobs (collision rules). - pub teams: Teams, + /// The scoreboard teams of the player and the mobs (collision rules), + /// shared: the mob ticks build them once a tick, not once a mob. + pub teams: std::sync::Arc>, /// Item data (max stack sizes), when the host has it. pub items: Option<&'a crate::items::Items>, } /// `Entity.getTeam` of the player and of the mobs on a team. #[derive(Clone, Debug, Default)] -pub struct Teams { - pub player: Option, - pub mobs: HashMap, +pub struct Teams<'a> { + pub player: Option<&'a crate::scoreboard::Team>, + pub mobs: HashMap, } -impl Teams { - pub fn of(&self, who: Who) -> Option<&crate::scoreboard::Team> { +impl<'a> Teams<'a> { + pub fn of(&self, who: Who) -> Option<&'a crate::scoreboard::Team> { match who { - Who::Player => self.player.as_ref(), - Who::Mob(id) => self.mobs.get(&id), + Who::Player => self.player, + Who::Mob(id) => self.mobs.get(&id).copied(), } } } @@ -1515,10 +1562,13 @@ impl Mob { last_damage: None, removed: false, custom_name: None, + custom_name_text: None, name_visible: false, + invisible: false, anim: anim::AnimState::default(), rider: None, outbox: Vec::new(), + skin: None, attrs: Attrs { speed: kind.speed, attack_damage: kind.attack_damage, @@ -2139,3 +2189,504 @@ mod elytra_tests { assert!((wings.angles[1] - 0.08726646).abs() < 0.00001); } } +#[cfg(test)] +mod teams_tests { + use super::*; + use crate::save::uuid_text; + use crate::scoreboard::{Scoreboard, Team}; + + /// A board where every other mob is on the player's team, as with a + /// datapack that colours its mobs' names. + fn board(mobs: u32) -> (Scoreboard, HashMap) { + let mut board = Scoreboard::default(); + board.add_team("red"); + board.add_to_team("Steve", "red"); + let uuids: HashMap = (0..mobs) + .map(|id| (id, [id as i32, 7, -(id as i32), 11])) + .collect(); + for (id, uuid) in &uuids { + if id % 2 == 0 { + board.add_to_team(&uuid_text(*uuid), "red"); + } + } + (board, uuids) + } + /// `Game::mob_teams` as built for each mob before: owned clones of the teams. + fn owned(board: &Scoreboard, uuids: &HashMap) -> HashMap { + uuids + .iter() + .filter_map(|(id, u)| Some((*id, board.players_team(&uuid_text(*u))?.clone()))) + .collect() + } + fn borrowed<'a>(board: &'a Scoreboard, uuids: &HashMap) -> Teams<'a> { + Teams { + player: board.players_team("Steve"), + mobs: uuids + .iter() + .filter_map(|(id, u)| Some((*id, board.players_team(&uuid_text(*u))?))) + .collect(), + } + } + + #[test] + fn borrowed_teams_answer_as_the_clones() { + let (board, uuids) = board(40); + let teams = borrowed(&board, &uuids); + let old = owned(&board, &uuids); + for id in 0..41 { + assert_eq!(teams.of(Who::Mob(id)), old.get(&id), "mob {id}"); + } + assert_eq!(teams.of(Who::Player).map(|t| t.name.as_str()), Some("red")); + } + + /// One tick's worth of team building: once per mob (before) against once. + #[test] + #[ignore] + fn teams_cost() { + for mobs in [100u32, 250, 500] { + let (board, uuids) = board(mobs); + let t = std::time::Instant::now(); + for _ in 0..mobs { + std::hint::black_box(owned(&board, &uuids)); + } + let before = t.elapsed(); + let t = std::time::Instant::now(); + let reps = 20; + for _ in 0..reps { + std::hint::black_box(borrowed(&board, &uuids)); + } + let after = t.elapsed() / reps; + println!( + "{mobs} mobs, half on a team: per tick {:.3} ms -> {:.3} ms", + before.as_secs_f64() * 1e3, + after.as_secs_f64() * 1e3 + ); + } + } +} +#[cfg(test)] +mod sensor_scan_tests { + use super::*; + use horizon_core::geometry::Vec3; + use serde_json::json; + + fn kind() -> Arc { + Arc::new(MobType { + id: "minecraft:cow".into(), + species: Species::Cow, + width: 0.9, + height: 1.4, + eye_height: 1.3, + category: "creature".into(), + max_health: 10.0, + speed: 0.2, + flying_speed: 0.4, + attack_damage: 0.0, + attack_knockback: 0.0, + follow_range: 16.0, + step_height: 0.6, + armor: 0.0, + armor_toughness: 0.0, + knockback_resistance: 0.0, + jump_strength: 0.42, + attributes: Arc::default(), + gravity: 0.08, + safe_fall_distance: 3.0, + fall_damage_multiplier: 1.0, + water_efficiency: 0.0, + water_slowdown: 0.8, + air_speed: 0.02, + baby_scale: 0.5, + head_rot_speed: 10.0, + max_head_x_rot: 40.0, + max_head_y_rot: 75.0, + ambient_interval: 120, + flags: Flags { + animal: true, + ..Default::default() + }, + model: Arc::new(Part::parse("root", &json!({}))), + layers: HashMap::new(), + texture: String::new(), + brain: Brain::Passive, + anim: Anim::Rabbit, + sounds: [""; 3], + step_sound: None, + food: Arc::default(), + tempt: Arc::default(), + }) + } + /// `n` mobs in pens of 20 spread over a square of `side` blocks, as on a + /// server's farms; their snapshot and its grid. + fn herd(n: u32, side: f64) -> (Vec, seen_grid::SeenGrid) { + let kind = kind(); + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = |range: f64| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); + (seed >> 11) as f64 / (1u64 << 53) as f64 * range + }; + let mut pen = Vec3::ZERO; + let seen: Vec = (0..n) + .map(|id| { + if id % 20 == 0 { + pen = Vec3::new(next(side), 64.0, next(side)); + } + let at = Vec3::new(pen.x + next(8.0), 64.0, pen.z + next(8.0)); + Mob::new(id, kind.clone(), at, 0.0).seen(None) + }) + .collect(); + let grid = seen_grid::SeenGrid::new(seen.iter().map(|s| s.bounds)); + (seen, grid) + } + /// `NearestLivingEntitySensor` over every mob, as the brains ran it. + fn scan(seen: &[Seen], me: &Seen, area: Aabb) -> Vec { + seen.iter() + .filter(|o| o.id != me.id && o.alive && o.bounds.intersects(area)) + .map(|o| o.id) + .collect() + } + fn indexed(seen: &[Seen], grid: &seen_grid::SeenGrid, me: &Seen, area: Aabb) -> Vec { + let mut near = Vec::new(); + assert!(grid.candidates(area, &mut near)); + near.iter() + .map(|&i| &seen[i as usize]) + .filter(|o| o.id != me.id && o.alive && o.bounds.intersects(area)) + .map(|o| o.id) + .collect() + } + + #[test] + fn the_grid_finds_what_the_scan_finds() { + let (seen, grid) = herd(600, 160.0); + for me in &seen { + let area = me.bounds.inflate(Vec3::new(16.0, 16.0, 16.0)); + assert_eq!(indexed(&seen, &grid, me, area), scan(&seen, me, area)); + } + } + + /// `MobWorld::seen` once per mob (a target, a breeding partner...), by + /// scan as before and by the tick's id index. + #[test] + #[ignore] + fn lookup_cost() { + for n in [500u32, 1000, 2000] { + let (seen, _) = herd(n, 256.0); + let index: crate::fast_hash::FxHashMap = seen + .iter() + .enumerate() + .map(|(i, s)| (s.id, i as u32)) + .collect(); + let wanted: Vec = (0..n).map(|i| (i * 7919) % n).collect(); + let t = std::time::Instant::now(); + let a: usize = wanted + .iter() + .filter_map(|&id| seen.iter().find(|s| s.id == id)) + .map(|s| s.id as usize) + .sum(); + let before = t.elapsed().as_secs_f64() * 1e3; + let t = std::time::Instant::now(); + let b: usize = wanted + .iter() + .filter_map(|&id| index.get(&id).map(|&i| &seen[i as usize])) + .map(|s| s.id as usize) + .sum(); + let after = t.elapsed().as_secs_f64() * 1e3; + assert_eq!(a, b); + println!( + "{n} lookups over {n} mobs ({} B each): {before:.3} ms -> {after:.3} ms", + std::mem::size_of::() + ); + } + } + + /// Natural spawning's `isUnobstructed` box test against every mob (real + /// `Mob`s), by scan and by a grid built once for the pass. + #[test] + #[ignore] + fn spawn_box_cost() { + let kind = kind(); + for n in [500u32, 1000, 2000] { + let (seen, _) = herd(n, 384.0); + let mobs: Vec = seen + .iter() + .map(|s| Mob::new(s.id, kind.clone(), s.position, 0.0)) + .collect(); + let mut seed = 7u64; + let mut next = |range: f64| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); + (seed >> 11) as f64 / (1u64 << 53) as f64 * range + }; + let queries: Vec = (0..100) + .map(|_| { + let (x, z) = (next(384.0), next(384.0)); + Aabb::new(Vec3::new(x, 64.0, z), Vec3::new(x + 0.9, 65.4, z + 0.9)) + }) + .collect(); + let t = std::time::Instant::now(); + let a: Vec = queries + .iter() + .map(|&q| { + mobs.iter() + .any(|m| m.alive() && !m.removed && m.bounds().intersects(q)) + }) + .collect(); + let before = t.elapsed().as_secs_f64() * 1e3; + let t = std::time::Instant::now(); + let boxes: Vec = mobs.iter().map(|m| m.bounds()).collect(); + let grid = seen_grid::SeenGrid::new(boxes.iter().copied()); + let build = t.elapsed().as_secs_f64() * 1e3; + let mut near = Vec::new(); + let b: Vec = queries + .iter() + .map(|&q| { + assert!(grid.candidates(q, &mut near)); + near.iter().any(|&i| boxes[i as usize].intersects(q)) + }) + .collect(); + let after = t.elapsed().as_secs_f64() * 1e3; + assert_eq!(a, b); + println!( + "{n} mobs, 100 spawn box tests: {before:.3} ms -> {after:.3} ms (grid build {build:.3} ms included)" + ); + } + } + + /// One tick of sensing: a twentieth of the mobs fire their sensor. + #[test] + #[ignore] + fn sensor_cost() { + for (n, side) in [(500u32, 256.0), (1000, 384.0), (2000, 512.0)] { + let (seen, grid) = herd(n, side); + let time = |f: &dyn Fn(&Seen, Aabb) -> usize| { + let t = std::time::Instant::now(); + let mut found = 0; + for me in &seen { + found += f(me, me.bounds.inflate(Vec3::new(16.0, 16.0, 16.0))); + } + (t.elapsed().as_secs_f64() * 1e3 / 20.0, found) + }; + let (before, a) = time(&|me, area| scan(&seen, me, area).len()); + let (after, b) = time(&|me, area| indexed(&seen, &grid, me, area).len()); + assert_eq!(a, b); + println!("{n} mobs: per tick {before:.3} ms -> {after:.3} ms"); + } + } +} +#[cfg(test)] +mod push_tests { + use super::*; + use horizon_core::geometry::Vec3; + use serde_json::json; + + fn kind() -> Arc { + Arc::new(MobType { + id: "minecraft:cow".into(), + species: Species::Cow, + width: 0.9, + height: 1.4, + eye_height: 1.3, + category: "creature".into(), + max_health: 10.0, + speed: 0.2, + flying_speed: 0.4, + attack_damage: 0.0, + attack_knockback: 0.0, + follow_range: 16.0, + step_height: 0.6, + armor: 0.0, + armor_toughness: 0.0, + knockback_resistance: 0.0, + jump_strength: 0.42, + attributes: Arc::default(), + gravity: 0.08, + safe_fall_distance: 3.0, + fall_damage_multiplier: 1.0, + water_efficiency: 0.0, + water_slowdown: 0.8, + air_speed: 0.02, + baby_scale: 0.5, + head_rot_speed: 10.0, + max_head_x_rot: 40.0, + max_head_y_rot: 75.0, + ambient_interval: 120, + flags: Flags { + animal: true, + ..Default::default() + }, + model: Arc::new(Part::parse("root", &json!({}))), + layers: HashMap::new(), + texture: String::new(), + brain: Brain::Passive, + anim: Anim::Rabbit, + sounds: [""; 3], + step_sound: None, + food: Arc::default(), + tempt: Arc::default(), + }) + } + + /// The pending pushes as one list, scanned for each mob, as before. + fn take_old(events: &mut Vec, from: usize, pending: &mut Vec<(u32, Vec3)>) { + let mut i = from; + while i < events.len() { + if let MobEvent::Push { + target: Who::Mob(id), + velocity, + } = events[i] + { + pending.push((id, Vec3::new(velocity[0], velocity[1], velocity[2]))); + events.remove(i); + } else { + i += 1; + } + } + } + fn apply_old(velocity: &mut Vec3, id: u32, pending: &mut Vec<(u32, Vec3)>) { + pending.retain(|(to, v)| { + if *to != id { + return true; + } + *velocity = Vec3::new(velocity.x + v.x, velocity.y + v.y, velocity.z + v.z); + false + }); + } + fn mobs(n: u32) -> Vec { + let kind = kind(); + (0..n) + .map(|id| Mob::new(id, kind.clone(), Vec3::ZERO, 0.0)) + .collect() + } + /// A crowd tick: each mob takes its pushes, then pushes every other + /// mob (and the player, and hisses now and then); then all take theirs. + fn crowd_tick( + n: u32, + tick: u32, + mut on_push: impl FnMut(&mut Vec, usize), + mut on_apply: impl FnMut(u32), + ) -> Vec { + let mut events = Vec::new(); + for i in 0..n { + on_apply(i); + let from = events.len(); + for j in 0..n { + if j != i && !(i * 31 + j * 17 + tick).is_multiple_of(5) { + let f = f64::from(i * 7 + j + tick) * 0.001; + events.push(MobEvent::Push { + target: Who::Mob(j), + velocity: [f, -f * 0.5, f * 0.25], + }); + } + if j.is_multiple_of(9) { + events.push(MobEvent::Hiss { mob: j }); + } + } + events.push(MobEvent::Push { + target: Who::Player, + velocity: [0.1, 0.0, 0.1], + }); + on_push(&mut events, from); + } + for i in 0..n { + on_apply(i); + } + events + } + + #[test] + fn pushes_land_as_with_the_list() { + for n in [1u32, 3, 8, 20, 60] { + let mut new_mobs = mobs(n); + let mut old_v = vec![Vec3::ZERO; n as usize]; + let mut pending = PendingPushes::default(); + let mut old_pending = Vec::new(); + for tick in 0..4 { + let new_events = { + let pending = std::cell::RefCell::new(&mut pending); + let mobs = std::cell::RefCell::new(&mut new_mobs); + crowd_tick( + n, + tick, + |e, from| take_mob_pushes(e, from, &mut pending.borrow_mut()), + |i| { + apply_mob_pushes( + &mut mobs.borrow_mut()[i as usize], + &mut pending.borrow_mut(), + ) + }, + ) + }; + let old_events = { + let pending = std::cell::RefCell::new(&mut old_pending); + let v = std::cell::RefCell::new(&mut old_v); + crowd_tick( + n, + tick, + |e, from| take_old(e, from, &mut pending.borrow_mut()), + |i| { + apply_old( + &mut v.borrow_mut()[i as usize], + i, + &mut pending.borrow_mut(), + ) + }, + ) + }; + assert_eq!(format!("{new_events:?}"), format!("{old_events:?}")); + for i in 0..n as usize { + let (a, b) = (new_mobs[i].velocity, old_v[i]); + assert_eq!( + (a.x.to_bits(), a.y.to_bits(), a.z.to_bits()), + (b.x.to_bits(), b.y.to_bits(), b.z.to_bits()), + "{n} mobs, tick {tick}, mob {i}" + ); + } + } + } + } + + /// One tick of a pen of `n` mobs pushing each other. + #[test] + #[ignore] + fn push_cost() { + for n in [10u32, 30, 100, 200] { + let mut ms = mobs(n); + let mut v = vec![Vec3::ZERO; n as usize]; + let t = std::time::Instant::now(); + { + let pending = std::cell::RefCell::new(Vec::new()); + let v = std::cell::RefCell::new(&mut v); + crowd_tick( + n, + 0, + |e, from| take_old(e, from, &mut pending.borrow_mut()), + |i| { + apply_old( + &mut v.borrow_mut()[i as usize], + i, + &mut pending.borrow_mut(), + ) + }, + ); + } + let before = t.elapsed().as_secs_f64() * 1e3; + let t = std::time::Instant::now(); + { + let pending = std::cell::RefCell::new(PendingPushes::default()); + let ms = std::cell::RefCell::new(&mut ms); + crowd_tick( + n, + 0, + |e, from| take_mob_pushes(e, from, &mut pending.borrow_mut()), + |i| { + apply_mob_pushes( + &mut ms.borrow_mut()[i as usize], + &mut pending.borrow_mut(), + ) + }, + ); + } + let after = t.elapsed().as_secs_f64() * 1e3; + println!("{n} mobs pushing each other: {before:.3} ms -> {after:.3} ms"); + } + } +} diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs index 9920235a9..331870b4a 100644 --- a/crates/horizon-client/src/mobs/animal_brain.rs +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -606,7 +606,7 @@ fn sense_living(m: &mut Mob, w: &MobWorld) { let r = m.attrs.follow_range; let area = m.bounds().inflate(Vec3::new(r, r, r)); let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others { + for o in w.others_near(area) { if o.id != m.id && o.alive && o.bounds.intersects(area) { found.push((Who::Mob(o.id), m.distance_sqr(o.position))); } diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index 6afacb53a..dc80c6ea4 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -441,7 +441,7 @@ impl Goal for PufferfishPuff { .as_ref() .is_some_and(|p| p.alive && !p.creative && area.intersects(p.bounds)); // TARGETING_CONDITIONS: not other fish (not_scary_for_pufferfish) and alive. - let mob = cx.w.others.iter().any(|s| { + let mob = cx.w.others_near(area).any(|s| { s.id != m.id && s.alive && !matches!( diff --git a/crates/horizon-client/src/mobs/enderman.rs b/crates/horizon-client/src/mobs/enderman.rs index 13e6c8a44..fcfba832e 100644 --- a/crates/horizon-client/src/mobs/enderman.rs +++ b/crates/horizon-client/src/mobs/enderman.rs @@ -391,12 +391,11 @@ impl Goal for LeaveBlock { let target = cx.w.world.block(x, y, z); let below = cx.w.world.block(x, y - 1, z); let bf = cx.w.facts.get(below); - let free = !cx.w.others.iter().any(|s| { - s.bounds.intersects(Aabb::new( - Vec3::new(f64::from(x), f64::from(y), f64::from(z)), - Vec3::new(f64::from(x + 1), f64::from(y + 1), f64::from(z + 1)), - )) - }); + let block = Aabb::new( + Vec3::new(f64::from(x), f64::from(y), f64::from(z)), + Vec3::new(f64::from(x + 1), f64::from(y + 1), f64::from(z + 1)), + ); + let free = !cx.w.others_near(block).any(|s| s.bounds.intersects(block)); if cx.w.facts.is_air(target) && !cx.w.facts.is_air(below) && &*bf.name != "minecraft:bedrock" diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 9419a23ba..c12f9e7ee 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -1,7 +1,11 @@ //! Vanilla's `GoalSelector` (priorities, MOVE/LOOK/JUMP/TARGET control flags, //! interruption) and the shared goals of `net.minecraft.world.entity.ai.goal`. use super::{Mob, MobEvent, MobWorld, Seen, Species, Who, world::TargetInfo}; -use horizon_core::{geometry::Vec3, jmath, random::RandomSource}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + jmath, + random::RandomSource, +}; use std::sync::Arc; pub const MOVE: u8 = 1; @@ -970,8 +974,7 @@ impl Goal for LookAtPlayer { let (id, only) = (m.id, self.only); let at = Vec3::new(m.position.x, m.eye_y(), m.position.z); let candidates: Vec<(u32, Vec3)> = - cx.w.others - .iter() + cx.w.others_near(area) .filter(|s| s.id != id && s.alive && s.bounds.intersects(area)) .filter(|s| only.is_none_or(|o| s.species == o)) .map(|s| (s.id, s.position)) @@ -1902,7 +1905,12 @@ impl Goal for FollowParent { let species = m.species(); let pos = m.position; let mut best: Option<(u32, f64)> = None; - for s in cx.w.others.iter().filter(|s| { + // Every position in range puts the box's bottom face in this area. + let area = Aabb::new( + Vec3::new(pos.x - 9.0, pos.y - 5.0, pos.z - 9.0), + Vec3::new(pos.x + 9.0, pos.y + 5.0, pos.z + 9.0), + ); + for s in cx.w.others_near(area).filter(|s| { s.alive && s.species == species && !s.baby diff --git a/crates/horizon-client/src/mobs/golem.rs b/crates/horizon-client/src/mobs/golem.rs index d4d67660b..c41c34f11 100644 --- a/crates/horizon-client/src/mobs/golem.rs +++ b/crates/horizon-client/src/mobs/golem.rs @@ -68,7 +68,10 @@ impl Goal for DefendVillage { if !b.intersects(p.bounds) || m.position.distance_squared(p.position) > 64.0 * 64.0 { return false; } - let bad = cx.w.others.iter().any(|s| { + // A position inside `b` puts the box's bottom face there (one block + // wider, as the box test is strict). + let near = b.inflate(Vec3::new(1.0, 1.0, 1.0)); + let bad = cx.w.others_near(near).any(|s| { s.species == Species::Villager && s.alive && s.player_rep <= -100 diff --git a/crates/horizon-client/src/mobs/monster_brain.rs b/crates/horizon-client/src/mobs/monster_brain.rs index 238653dad..eeb2c42f2 100644 --- a/crates/horizon-client/src/mobs/monster_brain.rs +++ b/crates/horizon-client/src/mobs/monster_brain.rs @@ -299,7 +299,7 @@ fn sense_living(m: &mut Mob, w: &MobWorld) { let r = m.attrs.follow_range; let area = m.bounds().inflate(Vec3::new(r, r, r)); let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others { + for o in w.others_near(area) { if o.id != m.id && o.alive && o.bounds.intersects(area) { found.push((Who::Mob(o.id), m.distance_sqr(o.position))); } diff --git a/crates/horizon-client/src/mobs/ravager.rs b/crates/horizon-client/src/mobs/ravager.rs index ef71b8f77..49bac4d9f 100644 --- a/crates/horizon-client/src/mobs/ravager.rs +++ b/crates/horizon-client/src/mobs/ravager.rs @@ -177,7 +177,7 @@ fn roar(m: &mut Mob, w: &MobWorld, events: &mut Vec) { velocity: fling(p.position), }); } - for s in w.others.iter() { + for s in w.others_near(area) { if s.id == m.id || !s.alive || s.species == Species::Ravager || !s.bounds.intersects(area) { continue; } diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 4248f22c6..b8098a45a 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -104,7 +104,10 @@ pub fn body(m: &Mob) -> (String, String) { } }; if &*m.kind.id == "minecraft:player" { - return ("main".into(), m.kind.texture.to_string()); + return ( + "main".into(), + m.skin.clone().unwrap_or_else(|| m.kind.texture.clone()), + ); } match m.species() { S::Llama | S::TraderLlama => { diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index 5b8500c0d..e02cfa176 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -568,7 +568,7 @@ fn sense_living(m: &mut Mob, w: &MobWorld) { let r = m.attrs.follow_range; let area = m.bounds().inflate(Vec3::new(r, r, r)); let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others { + for o in w.others_near(area) { if o.id != m.id && o.alive && o.bounds.intersects(area) { found.push((Who::Mob(o.id), m.distance_sqr(o.position))); } @@ -898,8 +898,9 @@ fn poi_matches(m: &Mob, f: PoiFilter, p: Poi) -> bool { _ => false, } } -/// Tickets taken on a POI: by this villager's memories and by others'. -fn tickets(m: &Mob, w: &MobWorld, p: [i32; 3]) -> usize { +/// Tickets taken on a POI: by this villager's memories and by others' +/// (counted once per search by [`others_tickets`]). +fn tickets(m: &Mob, others: &crate::fast_hash::FxHashMap<[i32; 3], usize>, p: [i32; 3]) -> usize { let mut n = 0; if let Some(mm) = mem_ref(m) { for s in [ @@ -913,16 +914,22 @@ fn tickets(m: &Mob, w: &MobWorld, p: [i32; 3]) -> usize { } } } + n + others.get(&p).copied().unwrap_or(0) +} +/// The tickets the other living villagers' POIs take, by POI. +fn others_tickets(m: &Mob, w: &MobWorld) -> crate::fast_hash::FxHashMap<[i32; 3], usize> { + let mut taken = crate::fast_hash::FxHashMap::default(); for o in w.others { if o.id != m.id && o.alive && o.species == Species::Villager { - for q in [o.job, o.bed, o.potential_job, o.meeting] { - if q == Some(p) { - n += 1; - } + for q in [o.job, o.bed, o.potential_job, o.meeting] + .into_iter() + .flatten() + { + *taken.entry(q).or_insert(0) += 1; } } } - n + taken } /// The POIs of chunk `(qx, qz)` from `y0` to `y1` (within the world), in /// scan order: y, then z, then x. Only the indexed POI blocks of the sections @@ -962,6 +969,8 @@ fn pois_in_range( ) -> Vec<(Poi, [i32; 3])> { let c = block_of(m.position); let mut found = Vec::new(); + // Every candidate asks how taken it is: count the others' once. + let mut taken = None; let r2 = i64::from(radius) * i64::from(radius); let (cx, cz) = (c[0] >> 4, c[2] >> 4); let chunks = radius.div_euclid(16) + 1; @@ -974,7 +983,8 @@ fn pois_in_range( || (p[2] - c[2]).abs() > radius || dist_sqr(p, c) > r2 || !poi_matches(m, f, poi) - || tickets(m, w, p) >= poi.max_tickets() + || tickets(m, taken.get_or_insert_with(|| others_tickets(m, w)), p) + >= poi.max_tickets() { return; } diff --git a/crates/horizon-client/src/mobs/warden_brain.rs b/crates/horizon-client/src/mobs/warden_brain.rs index 41353fc83..518347e77 100644 --- a/crates/horizon-client/src/mobs/warden_brain.rs +++ b/crates/horizon-client/src/mobs/warden_brain.rs @@ -492,7 +492,7 @@ fn sense_entities(m: &mut Mob, w: &MobWorld) { let r = m.attrs.follow_range; let area = m.bounds().inflate(Vec3::new(r, r, r)); let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others { + for o in w.others_near(area) { if o.id != m.id && o.alive && o.bounds.intersects(area) { found.push((Who::Mob(o.id), m.distance_sqr(o.position))); } diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs index cc4110dd7..79bbaa30c 100644 --- a/crates/horizon-client/src/mobs/world.rs +++ b/crates/horizon-client/src/mobs/world.rs @@ -226,7 +226,13 @@ impl MobWorld<'_> { .chain(all.into_iter().flatten()) } pub fn seen(&self, id: u32) -> Option<&Seen> { - self.others.iter().find(|s| s.id == id) + match self.others_index { + Some(index) => index + .get(&id) + .and_then(|&i| self.others.get(i as usize)) + .filter(|s| s.id == id), + None => self.others.iter().find(|s| s.id == id), + } } /// Living mobs of the given species within `range` of `from`, nearest first. pub fn nearby<'s>( @@ -235,9 +241,15 @@ impl MobWorld<'_> { range: f64, pred: impl Fn(&Seen) -> bool + 's, ) -> impl Iterator + 's { + // A position within `range` puts the box's bottom face in this area + // (one block wider, as the box test is strict). + let r = range + 1.0; + let area = Aabb::new( + Vec3::new(from.x - r, from.y - r, from.z - r), + Vec3::new(from.x + r, from.y + r, from.z + r), + ); let mut v: Vec<&Seen> = self - .others - .iter() + .others_near(area) .filter(|s| { s.alive && (s.position.x - from.x).abs() <= range diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index b1088188c..1920026b9 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -716,7 +716,8 @@ impl MotionWorld<'_, '_, '_> { supporting_block: self.player.ground.supporting_block, } } - fn climbable(&mut self) -> Result { + /// `LivingEntity.onClimbable` at the player's feet (it remembers the block). + pub fn climbable(&mut self) -> Result { if self.player.spectator { return Ok(false); } diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 2e1eb8455..0cfe3c585 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -1305,8 +1305,73 @@ pub fn load_light(tag: &Tag, chunk: &mut Chunk, sky_light: bool) { }; layers[si as usize] = (layer("SkyLight"), layer("BlockLight")); } - let above = [if sky_light { 15 } else { 0 }; 256]; - crate::light::light_from_layers(chunk, &layers, above, sky_light); + // Uniform saved layers need no expanded allocation. Both nibbles of + // each byte must match, not merely the bytes across the layer. + let uniform_layer = |layer: &[u8]| { + let first = layer[0]; + (first & 15 == first >> 4 && layer.iter().all(|&v| v == first)).then_some(first & 15) + }; + let mut above = [if sky_light { 15 } else { 0 }; 256]; + for (si, (sky, block)) in layers.into_iter().enumerate().rev() { + let sky = sky.filter(|_| sky_light); + let sky_uniform = sky.map_or_else( + || above.iter().all(|&v| v == above[0]).then_some(above[0]), + uniform_layer, + ); + let block_uniform = block.map_or(Some(0), uniform_layer); + let section = Arc::make_mut(&mut chunk.sections[si]); + if let (Some(s), Some(b)) = (sky_uniform, block_uniform) { + section.light = Light::Uniform(s << 4 | b); + above.fill(s); + } else { + let mut data = Box::new([0u8; 4096]); + match (sky, block) { + (Some(sky), Some(block)) => { + for ((pair, &s), &b) in + data.as_chunks_mut::<2>().0.iter_mut().zip(sky).zip(block) + { + pair[0] = s << 4 | (b & 15); + pair[1] = (s & 0xf0) | (b >> 4); + } + } + (Some(sky), None) => { + for (pair, &s) in data.as_chunks_mut::<2>().0.iter_mut().zip(sky) { + pair[0] = s << 4; + pair[1] = s & 0xf0; + } + } + (None, Some(block)) => { + for (i, (pair, &b)) in data + .as_chunks_mut::<2>() + .0 + .iter_mut() + .zip(block) + .enumerate() + { + pair[0] = above[(i * 2) & 255] << 4 | (b & 15); + pair[1] = above[(i * 2 + 1) & 255] << 4 | (b >> 4); + } + } + (None, None) => { + for layer in data.as_chunks_mut::<256>().0 { + for (v, &s) in layer.iter_mut().zip(&above) { + *v = s << 4; + } + } + } + } + if let Some(sky) = sky { + for (pair, &s) in above.as_chunks_mut::<2>().0.iter_mut().zip(sky) { + pair[0] = s & 15; + pair[1] = s >> 4; + } + } + section.light = Light::Full(data); + } + section.compact(); + } + chunk.lit = true; + chunk.light_loaded = true; } type RegionCache = Mutex>>>>; @@ -3892,6 +3957,151 @@ mod tests { assert!(!unlit.lit && !unlit.light_loaded); } #[test] + fn saved_light_matches_reference_for_layers_and_metadata() { + fn reference(tag: &Tag, chunk: &mut Chunk, sky_light: bool) { + if tag.get("isLightOn") != Some(&Tag::Byte(1)) { + return; + } + let Some(Tag::List(sections)) = tag.get("sections") else { + return; + }; + let mut layers: Vec<(Option<&[u8]>, Option<&[u8]>)> = vec![(None, None); SECTIONS]; + for section in sections { + let Some(y) = number(section.get("Y")) else { + continue; + }; + let si = y as i32 - (MIN_Y >> 4); + if !(0..SECTIONS as i32).contains(&si) { + continue; + } + let layer = |name: &str| match section.get(name) { + Some(Tag::ByteArray(a)) if a.len() == 2048 => Some(&a[..]), + _ => None, + }; + layers[si as usize] = (layer("SkyLight"), layer("BlockLight")); + } + let above = [if sky_light { 15 } else { 0 }; 256]; + crate::light::light_from_layers(chunk, &layers, above, sky_light); + } + + let section = |y: Tag, sky: Option, block: Option| { + let mut entries = vec![("Y", y)]; + if let Some(v) = sky { + entries.push(("SkyLight", v)); + } + if let Some(v) = block { + entries.push(("BlockLight", v)); + } + Tag::compound(entries) + }; + let root = |sections| { + Tag::compound([ + ("isLightOn", Tag::Byte(1)), + ("sections", Tag::List(sections)), + ]) + }; + let check = |tag: &Tag| { + for sky_light in [false, true] { + let mut expected = Chunk::empty(-3, 5); + let s = Arc::make_mut(&mut expected.sections[0]); + s.light = Light::Full(Box::new([0xab; 4096])); + s.blocks.set(0, 1); + s.blocks.set(0, 0); + s.biomes.set(0, 1); + s.biomes.set(0, 0); + let mut actual = expected.clone(); + reference(tag, &mut expected, sky_light); + load_light(tag, &mut actual, sky_light); + assert_eq!( + (actual.lit, actual.light_loaded), + (expected.lit, expected.light_loaded) + ); + for (a, b) in actual.sections.iter().zip(&expected.sections) { + assert_eq!( + std::mem::discriminant(&a.light), + std::mem::discriminant(&b.light) + ); + assert_eq!( + format!("{:?}", a.blocks.to_wire()), + format!("{:?}", b.blocks.to_wire()) + ); + assert_eq!( + format!("{:?}", a.biomes.to_wire()), + format!("{:?}", b.biomes.to_wire()) + ); + for i in 0..4096 { + assert_eq!(a.light(i), b.light(i), "index {i}, sky {sky_light}"); + } + } + } + }; + for tag in [ + Tag::compound(Vec::<(&str, Tag)>::new()), + Tag::compound([("isLightOn", Tag::Byte(0))]), + Tag::compound([("isLightOn", Tag::Byte(2))]), + Tag::compound([("isLightOn", Tag::Int(1)), ("sections", Tag::List(vec![]))]), + Tag::compound([("isLightOn", Tag::Byte(1)), ("sections", Tag::Int(0))]), + root(vec![]), + ] { + check(&tag); + } + // Cover every repeated byte, including 0xF0/0x0F: a uniform byte + // array need not hold uniform nibbles. + for byte in 0..=255u8 { + check(&root(vec![section( + Tag::Byte(19), + Some(Tag::ByteArray(vec![byte; 2048])), + Some(Tag::ByteArray(vec![255 - byte; 2048])), + )])); + } + // Every pair of uniform sky/block nibble values, with missing + // sections below inheriting the stored bottom row. + for sky in 0..16u8 { + for block in 0..16u8 { + check(&root(vec![section( + Tag::Byte(1), + Some(Tag::ByteArray(vec![sky * 17; 2048])), + Some(Tag::ByteArray(vec![block * 17; 2048])), + )])); + } + } + for length in [0, 1, 2047, 2048, 2049] { + for invalid in [ + Tag::Int(1), + Tag::List(vec![]), + Tag::ByteArray(vec![0xf0; length]), + ] { + check(&root(vec![section( + Tag::Byte(-4), + Some(invalid.clone()), + Some(invalid), + )])); + } + } + let varied: Vec = (0..2048) + .map(|i| (i as u8).wrapping_mul(73).wrapping_add(31)) + .collect(); + check(&root(vec![ + section(Tag::Byte(-5), Some(Tag::ByteArray(varied.clone())), None), + section(Tag::Byte(20), Some(Tag::ByteArray(varied.clone())), None), + section( + Tag::String("19".into()), + Some(Tag::ByteArray(varied.clone())), + None, + ), + section(Tag::Byte(19), Some(Tag::ByteArray(varied.clone())), None), + section(Tag::Byte(17), None, Some(Tag::ByteArray(varied.clone()))), + section(Tag::Byte(-4), Some(Tag::ByteArray(varied.clone())), None), + // Last duplicate wins, even when its arrays have wrong types. + section( + Tag::Byte(-4), + Some(Tag::Int(15)), + Some(Tag::ByteArray(vec![7; 2047])), + ), + section(Tag::Byte(0), None, Some(Tag::ByteArray(varied))), + ])); + } + #[test] fn level_round_trips_through_the_vanilla_files() { let dir = std::env::temp_dir().join(format!("horizon-level-{}", std::process::id())); let _ = fs::remove_dir_all(&dir); diff --git a/crates/horizon-client/src/skins.rs b/crates/horizon-client/src/skins.rs index c47c9d47f..9014032c4 100644 --- a/crates/horizon-client/src/skins.rs +++ b/crates/horizon-client/src/skins.rs @@ -112,6 +112,24 @@ pub fn unpack(value: &str, signature: Signature, valid_uris: &[&str]) -> Texture out } +/// The skin URL of a `minecraft:profile` component's property list. Player +/// heads and mannequins read their profile this way, and `SkinManager` lets +/// those textures be unsigned (`getInsecureSkinInformation`). +pub fn profile_skin_url(profile: &serde_json::Value) -> Option { + let value = profile + .get("properties")? + .as_array()? + .iter() + .find_map(|p| { + if p.get("name")?.as_str()? == "textures" { + p.get("value")?.as_str() + } else { + None + } + })?; + unpack(value, Signature::Unsigned, &TEXTURE_URIS).skin +} + /// `MinecraftProfileTexture.getHash`: the base name of the URL's path. pub fn texture_hash(url: &str) -> Option { let rest = url.split_once("://")?.1; @@ -393,6 +411,21 @@ pub fn sha1(data: &[u8]) -> [u8; 20] { #[cfg(test)] mod tests { + #[test] + fn profile_components_supply_unsigned_head_skins() { + let value = "eyJ0ZXh0dXJlcyI6IHsiU0tJTiI6IHsidXJsIjogImh0dHBzOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlL2FiYzEyMyJ9fX0="; + let profile = serde_json::json!({"properties": [{"name": "textures", "value": value}]}); + assert_eq!( + super::profile_skin_url(&profile).as_deref(), + Some("https://textures.minecraft.net/texture/abc123") + ); + let other = serde_json::json!({"properties": [{"name": "other", "value": value}]}); + assert_eq!(super::profile_skin_url(&other), None); + let bad = serde_json::json!({"properties": [{"name": "textures", "value": "not base64"}]}); + assert_eq!(super::profile_skin_url(&bad), None); + assert_eq!(super::profile_skin_url(&serde_json::json!({})), None); + } + /// Textures come over plain HTTP too (a local server here; https is the /// same request through rustls), and only 2xx answers count. #[test] diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 5d5839539..15ed1674e 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -276,6 +276,8 @@ pub struct Streaming { /// chunks finish out to `radius + 1` (Chebyshev) and generation reaches /// past that as around the player. They are generated and kept but not meshed. pub extra: Vec<((i32, i32), i32)>, + /// `extra`'s squares as a grid, made again when `extra` changes. + cover: Option, /// Mesh the sections for drawing (false on a server thread). pub mesh: bool, } @@ -391,6 +393,7 @@ impl GenerationScan { radius: input.ranges.radius, extra: input.ranges.extra, forced: input.ranges.forced, + cover: input.ranges.cover, }; self.remember(ranges, input.world); } else { @@ -562,6 +565,7 @@ impl Streaming { meshed_total: 0, remote: false, extra: Vec::new(), + cover: None, mesh: true, } } @@ -808,6 +812,7 @@ impl Streaming { if self.paused { return (uploads, Vec::new()); } + ExtraCover::refresh(&mut self.cover, &self.extra); self.relight_edits(world); let deferred = std::mem::take(&mut self.deferred); let received = std::iter::from_fn(|| self.results.try_recv().ok()); @@ -982,6 +987,7 @@ impl Streaming { radius: self.radius, extra: &self.extra, forced: &self.forced, + cover: ExtraCover::matching(&self.cover, &self.extra), }; let (protos, generating) = (&self.protos, &self.generating); self.decoration_order.retain(|x, z| { @@ -1109,6 +1115,7 @@ impl Streaming { radius: self.radius, extra: &self.extra, forced: &self.forced, + cover: ExtraCover::matching(&self.cover, &self.extra), }; self.waiting.retain(|&(x, sy, z)| { let back = ranges.in_view(x, z); @@ -1185,6 +1192,7 @@ impl Streaming { radius: self.radius, extra: &self.extra, forced: &self.forced, + cover: ExtraCover::matching(&self.cover, &self.extra), }, world, generating: &self.generating, @@ -1280,6 +1288,7 @@ impl Streaming { radius: self.radius, extra: &self.extra, forced: &self.forced, + cover: ExtraCover::matching(&self.cover, &self.extra), } } fn near_finished(&self, x: i32, z: i32, reach: i32) -> bool { @@ -1365,6 +1374,100 @@ struct Ranges<'a> { radius: i32, extra: &'a [((i32, i32), i32)], forced: &'a HashSet<(i32, i32)>, + /// `extra` as a grid, when one was made for it: `in_extra` without a + /// scan of every area. + cover: Option<&'a ExtraCover>, +} +/// For every column near the extra areas, how far it lies outside the +/// nearest one's square (Chebyshev distance less its radius; 0 inside). A server has an area per player, and streaming asks of every +/// loaded and wanted column whether one reaches it, several times a tick: +/// with fifty players, a scan of fifty squares per question. +struct ExtraCover { + extra: Vec<((i32, i32), i32)>, + x0: i32, + z0: i32, + width: u32, + depth: u32, + cells: Box<[i8]>, +} +impl ExtraCover { + /// The largest margin the grid answers for; beyond it (and outside the + /// grid) a column is further than that from every square. + const REACH: i32 = 4; + /// The largest grid, in columns (a mebibyte). + const CELLS: u64 = 1 << 20; + fn matching<'a>( + cover: &'a Option, + extra: &[((i32, i32), i32)], + ) -> Option<&'a ExtraCover> { + cover.as_ref().filter(|c| c.extra == extra) + } + /// Make the grid again if `extra` changed; none for one area or none + /// (a scan is as quick), or areas too far apart. + fn refresh(cover: &mut Option, extra: &[((i32, i32), i32)]) { + if cover.as_ref().is_some_and(|c| c.extra == extra) { + return; + } + *cover = Self::new(extra); + } + fn new(extra: &[((i32, i32), i32)]) -> Option { + if extra.len() < 2 || extra.iter().any(|&(_, r)| !(0..=64).contains(&r)) { + return None; + } + let k = i64::from(Self::REACH); + let (mut x0, mut z0, mut x1, mut z1) = (i64::MAX, i64::MAX, i64::MIN, i64::MIN); + for &((x, z), r) in extra { + let (x, z, r) = (i64::from(x), i64::from(z), i64::from(r) + k); + (x0, z0, x1, z1) = (x0.min(x - r), z0.min(z - r), x1.max(x + r), z1.max(z + r)); + } + let (width, depth) = ((x1 - x0 + 1) as u64, (z1 - z0 + 1) as u64); + let fits = |lo: i64, hi: i64| lo >= i64::from(i32::MIN) && hi <= i64::from(i32::MAX); + if width * depth > Self::CELLS || !fits(x0, x1) || !fits(z0, z1) { + return None; + } + let (x0, z0, width, depth) = (x0 as i32, z0 as i32, width as u32, depth as u32); + let mut cells = vec![(Self::REACH + 1) as i8; (width * depth) as usize].into_boxed_slice(); + // Inside a square counts as 0: no margin asked for is below it. Each + // row of a square is a run of one value with a slope at either end. + let lower = |run: &mut [i8], v: i8| run.iter_mut().for_each(|c| *c = (*c).min(v)); + for &((cx, cz), r) in extra { + let reach = r + Self::REACH; + for dz in -reach..=reach { + let start = (cz + dz - z0) as usize * width as usize + (cx - x0) as usize; + let row = &mut cells[start - reach as usize..=start + reach as usize]; + let flat = dz.abs().max(r); + let centre = reach as usize; + lower( + &mut row[centre - flat as usize..=centre + flat as usize], + (flat - r) as i8, + ); + for d in flat + 1..=reach { + let v = (d - r) as i8; + lower(&mut row[centre - d as usize..=centre - d as usize], v); + lower(&mut row[centre + d as usize..=centre + d as usize], v); + } + } + } + Some(Self { + extra: extra.to_vec(), + x0, + z0, + width, + depth, + cells, + }) + } + /// Whether (x, z) is within `margin` of an area's square, for a + /// `margin` up to `REACH`. + fn within(&self, x: i32, z: i32, margin: i32) -> bool { + let (dx, dz) = ( + x.wrapping_sub(self.x0) as u32, + z.wrapping_sub(self.z0) as u32, + ); + dx < self.width + && dz < self.depth + && i32::from(self.cells[(dz * self.width + dx) as usize]) <= margin + } } impl Ranges<'_> { /// `distance`, or `rings` while the level loading screen is up. @@ -1441,6 +1544,11 @@ impl Ranges<'_> { /// Within `margin` of an extra area's square (Chebyshev distance, as /// vanilla's ticket levels spread). fn in_extra(&self, x: i32, z: i32, margin: i32) -> bool { + if let Some(cover) = self.cover + && (0..=ExtraCover::REACH).contains(&margin) + { + return cover.within(x, z, margin); + } self.extra .iter() .any(|&(c, radius)| (x - c.0).abs().max((z - c.1).abs()) <= radius + margin) @@ -1554,6 +1662,7 @@ mod tests { radius: self.radius, extra: &self.extra, forced: &self.forced, + cover: None, }, world: &self.world, generating: &self.generating, @@ -1866,6 +1975,7 @@ mod tests { radius, extra: &[], forced: &forced, + cover: None, }; let square = |x: i32, z: i32, n: i32| { (-n..=n).flat_map(move |dz| (-n..=n).map(move |dx| (x + dx, z + dz))) @@ -1920,6 +2030,7 @@ mod tests { radius: 12, extra: &[], forced: &forced, + cover: None, }; let at = |dx: i32, dz: i32| (2 + dx, -1 + dz); let key = |(x, z): (i32, i32), loading| r.priority(x, z, loading); @@ -1945,6 +2056,7 @@ mod tests { radius, extra: &[((radius * 2 + 9, 3), 4)], forced: &forced, + cover: None, }; let span = radius * 3 + 20; for x in -span..=span { @@ -1984,6 +2096,7 @@ mod tests { radius: 2, extra: &extra, forced: &forced, + cover: None, }; let level = |x: i32, z: i32| 31 + ((x - 40).abs().max((z + 9).abs()) - view).max(0); for x in 40 - view - 8..=40 + view + 8 { @@ -2021,3 +2134,128 @@ mod tests { } } } + +#[cfg(test)] +mod cover_tests { + use super::*; + + fn areas(seed: &mut u64, n: usize, spread: i32) -> Vec<((i32, i32), i32)> { + let mut next = |m: i32| { + *seed ^= *seed << 13; + *seed ^= *seed >> 7; + *seed ^= *seed << 17; + (*seed % (2 * m as u64 + 1)) as i32 - m + }; + (0..n) + .map(|_| ((next(spread), next(spread)), 2 + next(14).abs())) + .collect() + } + + /// Every question streaming asks gets the same answer with the grid. + #[test] + fn the_grid_answers_as_the_scan() { + let mut seed = 0x9E37_79B9_7F4A_7C15u64; + let forced: HashSet<(i32, i32)> = [(40, -40)].into(); + for case in 0..60 { + let extra = areas(&mut seed, 2 + case % 20, [4, 30, 120][case % 3]); + let cover = ExtraCover::new(&extra).expect("a grid"); + let ranges = |cover| Ranges { + center: (3, -2), + radius: 10, + extra: &extra, + forced: &forced, + cover, + }; + let (scan, grid) = (ranges(None), ranges(Some(&cover))); + let span = [4, 30, 120][case % 3] + 40; + for z in -span..=span { + for x in -span..=span { + for m in 0..=ExtraCover::REACH + 2 { + assert_eq!( + scan.in_extra(x, z, m), + grid.in_extra(x, z, m), + "case {case} ({x}, {z}) {m}" + ); + } + for d in [false, true] { + assert_eq!(scan.unloaded(x, z, d), grid.unloaded(x, z, d)); + assert_eq!(scan.requested(x, z, d), grid.requested(x, z, d)); + assert_eq!(scan.chunk_kept(x, z, d), grid.chunk_kept(x, z, d)); + } + } + } + } + } + + #[test] + fn a_stale_or_impossible_grid_is_not_used() { + let mut cover = None; + ExtraCover::refresh(&mut cover, &[((0, 0), 11), ((5, 5), 11)]); + assert!(ExtraCover::matching(&cover, &[((0, 0), 11), ((5, 5), 11)]).is_some()); + assert!(ExtraCover::matching(&cover, &[((0, 0), 11), ((5, 6), 11)]).is_none()); + // Too far apart for a mebibyte of grid, and one area alone: scans. + assert!(ExtraCover::new(&[((0, 0), 11), ((100_000, 0), 11)]).is_none()); + assert!(ExtraCover::new(&[((0, 0), 11)]).is_none()); + assert!(ExtraCover::new(&[((i32::MAX - 1, 0), 11), ((i32::MAX - 3, 0), 11)]).is_none()); + assert!(ExtraCover::new(&[((0, i32::MAX - 1), 11), ((0, i32::MAX - 3), 11)]).is_none()); + assert!(ExtraCover::new(&[((0, i32::MIN + 1), 11), ((0, i32::MIN + 3), 11)]).is_none()); + } + + /// cargo test --release -p horizon-client --lib cover_tests::cover_cost -- --ignored --nocapture + #[test] + #[ignore] + fn cover_cost() { + let forced = HashSet::new(); + for players in [10usize, 25, 50] { + // The benchmark's bots: most near spawn, a fifth flying outwards. + let extra: Vec<_> = (0..players) + .map(|i| { + let a = i as f64 * 2.399; + let d = if i % 5 == 0 { 30.0 } else { 3.0 }; + (((a.cos() * d) as i32, (a.sin() * d) as i32), 11) + }) + .collect(); + let cover = ExtraCover::new(&extra).unwrap(); + let ranges = |cover| Ranges { + center: (0, 0), + radius: 10, + extra: &extra, + forced: &forced, + cover, + }; + // The columns streaming asks about: everything kept, and the + // generation scan's ring past it. + let columns: Vec<(i32, i32)> = (-60..=60) + .flat_map(|z| (-60..=60).map(move |x| (x, z))) + .filter(|&(x, z)| { + ranges(None).requested(x, z, true) || !ranges(None).unloaded(x, z, true) + }) + .collect(); + let rounds = 100; + let time = |r: &Ranges| { + let t = std::time::Instant::now(); + let mut n = 0usize; + for _ in 0..rounds { + for &(x, z) in &columns { + n += usize::from(r.unloaded(x, z, true)); + n += usize::from(r.requested(x, z, true)); + n += usize::from(r.in_range(x, z, 1)); + } + } + std::hint::black_box(n); + t.elapsed().as_secs_f64() * 1e3 / f64::from(rounds) + }; + let t = std::time::Instant::now(); + for _ in 0..rounds { + std::hint::black_box(ExtraCover::new(std::hint::black_box(&extra))); + } + let build = t.elapsed().as_secs_f64() * 1e3 / f64::from(rounds); + println!( + "{players} players, {} columns, 3 questions each: scan {:.3} ms, grid {:.3} ms (+ {build:.3} ms to build)", + columns.len(), + time(&ranges(None)), + time(&ranges(Some(&cover))), + ); + } + } +} diff --git a/crates/horizon-client/src/ticket_levels.rs b/crates/horizon-client/src/ticket_levels.rs index 216815de1..de2c427ad 100644 --- a/crates/horizon-client/src/ticket_levels.rs +++ b/crates/horizon-client/src/ticket_levels.rs @@ -45,13 +45,52 @@ pub struct Sources { /// block ticking or lower; `None` ticks everywhere (a game with no server and /// no player: the headless fixtures). #[derive(Clone, Default)] -pub struct Levels(Option>>); +pub struct Levels(Option>); + +/// The levels by chunk: a grid over the tickets' bounding box while it is +/// small (players near each other, the usual case), a map otherwise. Every +/// block entity, mob and ticking chunk asks each tick, so an index beats a +/// hash; and a player crossing into another chunk rebuilds it all. +enum Map { + Grid { + x0: i32, + z0: i32, + width: u32, + depth: u32, + cells: Box<[(u8, u8)]>, + }, + Sparse(FxHashMap<(i32, i32), (u8, u8)>), +} + +/// The largest grid, in chunks: 1 MiB of levels, a box 724 chunks wide. +const GRID_CELLS: u64 = 1 << 19; + +impl Map { + fn get(&self, x: i32, z: i32) -> (u8, u8) { + match self { + Self::Grid { + x0, + z0, + width, + depth, + cells, + } => { + let (dx, dz) = (x.wrapping_sub(*x0) as u32, z.wrapping_sub(*z0) as u32); + if dx < *width && dz < *depth { + cells[(dz * width + dx) as usize] + } else { + NONE + } + } + Self::Sparse(map) => map.get(&(x, z)).copied().unwrap_or(NONE), + } + } +} impl Levels { /// Chunk coordinates. fn get(&self, x: i32, z: i32) -> Option<(u8, u8)> { - let map = self.0.as_ref()?; - Some(map.get(&(x, z)).copied().unwrap_or(NONE)) + Some(self.0.as_ref()?.get(x, z)) } /// `DistanceManager.inEntityTickingRange`, in an entity-ticking chunk: /// where entities tick. @@ -112,19 +151,89 @@ impl ChunkTickets { } } -fn compute(s: &Sources) -> FxHashMap<(i32, i32), (u8, u8)> { +/// How far a player's tickets reach, and the simulation ticket's level. +fn reach(s: &Sources) -> (i32, i32, i32) { let view = s.view_distance.clamp(0, 32); let simulation = s.simulation_distance.clamp(0, 32); + // PLAYER_LOADING within the view distance, PLAYER_SIMULATION at the + // player's chunk (`getPlayerTicketLevel`: never below 0). + let player_sim = (i32::from(ENTITY_TICKING) - simulation).max(0); + let reach = (view + 1).max(i32::from(BLOCK_TICKING) - player_sim); + (view, player_sim, reach) +} + +fn compute(s: &Sources) -> Map { + let (view, player_sim, reach) = reach(s); + let boxes = s + .players + .iter() + .map(|&p| (p, reach)) + .chain(s.forced.iter().map(|&f| (f, 1))); + let Some((x0, z0, x1, z1)) = boxes.fold(None, |b, ((x, z), r)| { + let (lo_x, lo_z, hi_x, hi_z) = ( + i64::from(x) - i64::from(r), + i64::from(z) - i64::from(r), + i64::from(x) + i64::from(r), + i64::from(z) + i64::from(r), + ); + Some(match b { + None => (lo_x, lo_z, hi_x, hi_z), + Some((a, b, c, d)) => (lo_x.min(a), lo_z.min(b), hi_x.max(c), hi_z.max(d)), + }) + }) else { + return Map::Sparse(FxHashMap::default()); + }; + let (width, depth) = ((x1 - x0 + 1) as u64, (z1 - z0 + 1) as u64); + if width * depth > GRID_CELLS { + return Map::Sparse(compute_sparse(s)); + } + let (x0, z0, width, depth) = (x0 as i32, z0 as i32, width as u32, depth as u32); + let mut cells = vec![NONE; (width * depth) as usize].into_boxed_slice(); + let mut lower = |x: i32, z: i32, loading: i32, sim: i32| { + let i = ((z - z0) as u32 * width + (x - x0) as u32) as usize; + let e = &mut cells[i]; + e.0 = e.0.min(loading.min(i32::from(NONE.0)) as u8); + e.1 = e.1.min(sim.min(i32::from(NONE.1)) as u8); + }; + for &(px, pz) in &s.players { + for dz in -reach..=reach { + for dx in -reach..=reach { + let d = dx.abs().max(dz.abs()); + lower( + px + dx, + pz + dz, + i32::from(ENTITY_TICKING) + (d - view).max(0), + player_sim + d, + ); + } + } + } + for &(fx, fz) in &s.forced { + for dz in -1i32..=1 { + for dx in -1i32..=1 { + let level = i32::from(ENTITY_TICKING) + dx.abs().max(dz.abs()); + lower(fx + dx, fz + dz, level, level); + } + } + } + Map::Grid { + x0, + z0, + width, + depth, + cells, + } +} + +/// The levels as a map, for tickets spread too far apart for a grid. +fn compute_sparse(s: &Sources) -> FxHashMap<(i32, i32), (u8, u8)> { + let (view, player_sim, reach) = reach(s); let mut levels: FxHashMap<(i32, i32), (u8, u8)> = FxHashMap::default(); let mut lower = |key, loading: i32, sim: i32| { let e = levels.entry(key).or_insert(NONE); e.0 = e.0.min(loading.min(i32::from(NONE.0)) as u8); e.1 = e.1.min(sim.min(i32::from(NONE.1)) as u8); }; - // PLAYER_LOADING within the view distance, PLAYER_SIMULATION at the - // player's chunk (`getPlayerTicketLevel`: never below 0). - let player_sim = (i32::from(ENTITY_TICKING) - simulation).max(0); - let reach = (view + 1).max(i32::from(BLOCK_TICKING) - player_sim); for &(px, pz) in &s.players { for dz in -reach..=reach { for dx in -reach..=reach { @@ -229,4 +338,111 @@ mod tests { t.update(None); assert!(t.levels().0.is_none()); } + + /// The grid answers as the map does, everywhere around the tickets. + #[test] + fn grid_matches_the_map() { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = |n: i32| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % (2 * n as u64 + 1)) as i32 - n + }; + for case in 0..200 { + let spread = [3, 20, 80][case % 3]; + let players: Vec<_> = (0..1 + case % 12) + .map(|_| (next(spread), next(spread))) + .collect(); + let forced: Vec<_> = (0..case % 4) + .map(|_| (next(spread), next(spread))) + .collect(); + let s = Sources { + players, + forced, + view_distance: 2 + next(12).abs(), + simulation_distance: 2 + next(12).abs(), + }; + let Map::Grid { .. } = compute(&s) else { + panic!("case {case} fell back to the map"); + }; + let (grid, map) = (compute(&s), Map::Sparse(compute_sparse(&s))); + let r = spread + 50; + for z in -r..=r { + for x in -r..=r { + assert_eq!(grid.get(x, z), map.get(x, z), "case {case} at ({x}, {z})"); + } + } + } + } + + #[test] + fn far_apart_tickets_use_the_map() { + let l = levels( + &[(0, 0), (100_000, -100_000)], + &[(i32::MAX - 2, i32::MIN + 2)], + 10, + 10, + ); + assert!(matches!(**l.0.as_ref().unwrap(), Map::Sparse(_))); + assert!(l.entity_ticking(100_010, -100_010) && !l.block_ticking(50_000, 0)); + assert!(l.entity_ticking(i32::MAX - 2, i32::MIN + 2)); + } + + /// cargo test --release -p horizon-client --lib ticket_levels::tests::levels_cost -- --ignored --nocapture + #[test] + #[ignore] + fn levels_cost() { + for players in [1usize, 10, 25, 50] { + // The benchmark's bots: most near spawn, a fifth flying outwards. + let at: Vec<_> = (0..players) + .map(|i| { + let a = i as f64 * 2.399; + let d = if i % 5 == 0 { 30.0 } else { 3.0 }; + ((a.cos() * d) as i32, (a.sin() * d) as i32) + }) + .collect(); + let s = Sources { + players: at.clone(), + forced: Vec::new(), + view_distance: 10, + simulation_distance: 10, + }; + let rounds = 200; + let t = std::time::Instant::now(); + for _ in 0..rounds { + std::hint::black_box(compute_sparse(std::hint::black_box(&s))); + } + let map_build = t.elapsed().as_secs_f64() * 1e3 / rounds as f64; + let t = std::time::Instant::now(); + for _ in 0..rounds { + std::hint::black_box(compute(std::hint::black_box(&s))); + } + let grid_build = t.elapsed().as_secs_f64() * 1e3 / rounds as f64; + // A tick's questions: every chunk within 12 of every player. + let (map, grid) = (Map::Sparse(compute_sparse(&s)), compute(&s)); + let ask = |m: &Map| { + let t = std::time::Instant::now(); + let mut n = 0u32; + for _ in 0..rounds { + for &(px, pz) in &at { + for z in pz - 12..=pz + 12 { + for x in px - 12..=px + 12 { + n += + u32::from(std::hint::black_box(m.get(x, z)).0 <= BLOCK_TICKING); + } + } + } + } + std::hint::black_box(n); + t.elapsed().as_secs_f64() * 1e3 / rounds as f64 + }; + println!( + "{players} players: build {map_build:.3} -> {grid_build:.3} ms, {} lookups {:.3} -> {:.3} ms", + players * 625, + ask(&map), + ask(&grid) + ); + } + } } diff --git a/crates/horizon-client/src/weather.rs b/crates/horizon-client/src/weather.rs index 3eb39e14c..ba15de9ae 100644 --- a/crates/horizon-client/src/weather.rs +++ b/crates/horizon-client/src/weather.rs @@ -114,10 +114,15 @@ pub fn snow_column( /// The constructor's 32x32 table of horizontal column half-widths, indexed /// relative to the camera block. The camera's own column divides 0 by 0. fn column_size(index: usize) -> (f32, f32) { - let delta_x = (index % 32) as f32 - 16.0; - let delta_z = (index / 32) as f32 - 16.0; - let distance = f64::from(delta_x * delta_x + delta_z * delta_z).sqrt() as f32; - (-delta_z / distance, delta_x / distance) + static SIZES: std::sync::LazyLock<[(f32, f32); 32 * 32]> = std::sync::LazyLock::new(|| { + std::array::from_fn(|index| { + let delta_x = (index % 32) as f32 - 16.0; + let delta_z = (index / 32) as f32 - 16.0; + let distance = f64::from(delta_x * delta_x + delta_z * delta_z).sqrt() as f32; + (-delta_z / distance, delta_x / distance) + }) + }); + SIZES[index] } /// `prepareInstances` for one column: rain uses `max_alpha` 1, snow 0.8. @@ -219,6 +224,27 @@ fn pieces(a: f32, b: f32) -> impl Iterator { mod tests { use super::*; + #[test] + fn column_size_table_matches_original_arithmetic() { + for z in 0..32 { + for x in 0..32 { + let delta_x = x as f32 - 16.0; + let delta_z = z as f32 - 16.0; + let distance = f64::from(delta_x * delta_x + delta_z * delta_z).sqrt() as f32; + let expected = [-delta_z / distance, delta_x / distance]; + let actual = column_size(z * 32 + x); + for (actual, expected) in [actual.0, actual.1].into_iter().zip(expected) { + if x == 16 && z == 16 { + assert!(expected.is_nan()); + assert!(actual.is_nan()); + } else { + assert_eq!(actual.to_bits(), expected.to_bits(), "column ({x}, {z})"); + } + } + } + } + } + #[test] fn rain_repeats_every_four_blocks() { let column = Column { @@ -282,6 +308,10 @@ mod tests { light_coords: 0, }; let quad = column_quad(&column, [0.5, 70.0, 0.5], 1.0, 10, 1.0); - assert!(quad[0].pos[0].is_nan()); + for vertex in quad { + assert!(vertex.pos[0].is_nan()); + assert!(vertex.pos[2].is_nan()); + assert!(vertex.pos[1].is_finite()); + } } } diff --git a/crates/horizon-core/src/density/end_islands.rs b/crates/horizon-core/src/density/end_islands.rs index 148f3575d..2ae9f9b5f 100644 --- a/crates/horizon-core/src/density/end_islands.rs +++ b/crates/horizon-core/src/density/end_islands.rs @@ -50,6 +50,64 @@ impl EndIslandSampler { } height } + // Nearby volume columns visit overlapping 25-by-25 island neighborhoods. + // Collect the eligible islands once, retaining their original X/Z order. + // Larger or coordinate-wrapping volumes keep the scalar evaluation path. + fn volume_islands(&self, volume: DensityVolume) -> Option> { + let sizes = volume.sizes(); + if sizes[0] * sizes[2] < 4 { + return None; + } + let minimum = volume.minimum(); + let steps = volume.steps(); + let end = |axis: usize| { + i32::try_from( + i64::from(minimum[axis]) + (sizes[axis] - 1) as i64 * i64::from(steps[axis]), + ) + .ok() + }; + let first_x = minimum[0] / 8 / 2 - 12; + let first_z = minimum[2] / 8 / 2 - 12; + let last_x = end(0)? / 8 / 2 + 12; + let last_z = end(2)? / 8 / 2 + 12; + if last_x - first_x >= 64 || last_z - first_z >= 64 { + return None; + } + let mut islands = Vec::new(); + for x in first_x..=last_x { + for z in first_z..=last_z { + if i64::from(x) * i64::from(x) + i64::from(z) * i64::from(z) <= 4096 + || self.noise.get2(f64::from(x), f64::from(z)) >= -0.9 + { + continue; + } + let scale = ((x as f32).abs() * 3439.0 + (z as f32).abs() * 147.0) % 13.0 + 9.0; + islands.push((x, z, scale)); + } + } + Some(islands) + } + fn density_from_islands(x: i32, z: i32, islands: &[(i32, i32, f32)]) -> f32 { + let x = x / 8; + let z = z / 8; + let center_x = x / 2; + let center_z = z / 2; + let mut height = -100.0; + for &(island_x, island_z, scale) in islands { + let offset_x = island_x - center_x; + let offset_z = island_z - center_z; + if !(-12..=12).contains(&offset_x) || !(-12..=12).contains(&offset_z) { + continue; + } + let dx = (x % 2 - offset_x * 2) as f32; + let dz = (z % 2 - offset_z * 2) as f32; + let candidate = 100.0 - ((dx * dx + dz * dz) as f64).sqrt() as f32 * scale; + let candidate = + super::arithmetic::java_min(super::arithmetic::java_max(candidate, -100.0), 80.0); + height = super::arithmetic::java_max(height, candidate); + } + (height - 8.0) / 128.0 + } fn density(&self, x: i32, z: i32) -> f32 { (self.height(x / 8, z / 8) - 8.0) / 128.0 } @@ -66,10 +124,15 @@ impl DensitySampler for EndIslandSampler { ) -> Result<(), SampleError> { check_buffer(buffer, volume)?; let [sx, sy, sz] = volume.sizes(); + let islands = self.volume_islands(volume); for z in 0..sz { let block_z = volume.block(Axis::Z, z).unwrap(); for x in 0..sx { - let value = self.density(volume.block(Axis::X, x).unwrap(), block_z); + let block_x = volume.block(Axis::X, x).unwrap(); + let value = match &islands { + Some(islands) => Self::density_from_islands(block_x, block_z, islands), + None => self.density(block_x, block_z), + }; let start = (x + z * sx) * sy; buffer[start..start + sy].fill(value); } @@ -77,3 +140,78 @@ impl DensitySampler for EndIslandSampler { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn end_island_volumes_match_scalar_at_truncation_and_world_boundaries() { + let cases = [ + ([5, 3, 5], [0, -64, 0], [4, 8, 4]), + ([5, 3, 5], [1920, -64, 2240], [8, 8, 8]), + ([5, 3, 5], [-2049, -64, 3071], [4, 8, 4]), + ([5, 3, 5], [1023, -64, -1025], [1, 8, 1]), + ([5, 3, 5], [30_000_000, 0, -30_000_000], [8, 1, 8]), + ([5, 3, 5], [i32::MIN, 0, i32::MIN], [8, 1, 8]), + ([5, 3, 5], [i32::MAX - 32, 0, i32::MAX - 32], [8, 1, 8]), + // Also exercise wrapping, wide, sparse and single-column volumes. + ([5, 3, 5], [i32::MAX - 12, 0, i32::MAX - 3], [8, 1, 8]), + ([5, 3, 5], [4096, 0, -8192], [1024, 1, 1024]), + ([2, 3, 2], [-4096, 0, 8192], [599, 1, 599]), + ([1, 4, 1], [-15, 0, -17], [1, 1, 1]), + ]; + for seed in [0, 12345, -1, i64::MIN, i64::MAX] { + let sampler = EndIslandSampler::new(seed); + let mut context = SamplerContext::default(); + let mut compare = |volume: DensityVolume| { + let sentinel = 123.0_f32; + let mut output = vec![sentinel; volume.size() + 1]; + sampler + .sample_volume(&mut context, &mut output, volume) + .unwrap(); + visit(volume, |index, position| { + let expected = sampler.sample_value(&mut context, position)?; + assert_eq!( + output[index].to_bits(), + expected.to_bits(), + "seed {seed}, position {position:?}, volume {volume:?}" + ); + Ok(()) + }) + .unwrap(); + assert_eq!(output[volume.size()], sentinel); + let mut short = vec![sentinel; volume.size() - 1]; + assert_eq!( + sampler.sample_volume(&mut context, &mut short, volume), + Err(DensityError::BufferTooShort.into()) + ); + assert!(short.iter().all(|&value| value == sentinel)); + }; + for (sizes, minimum, steps) in cases { + compare(DensityVolume::new(sizes, minimum, steps).unwrap()); + } + // Every signed remainder around both coordinate divisions, in a + // neighborhood that straddles the central-island exclusion circle. + for offset in -17..=17 { + compare( + DensityVolume::new([5, 2, 5], [1024 + offset, -32, -offset], [3, 16, 5]) + .unwrap(), + ); + } + } + let sampler = EndIslandSampler::new(12345); + assert!( + sampler + .volume_islands(DensityVolume::new([5, 2, 5], [-2049, 0, 3071], [4, 8, 4]).unwrap()) + .is_some() + ); + for (sizes, minimum, steps) in [cases[7], cases[8], cases[10]] { + assert!( + sampler + .volume_islands(DensityVolume::new(sizes, minimum, steps).unwrap()) + .is_none() + ); + } + } +} diff --git a/crates/horizon-core/src/geometry/mod.rs b/crates/horizon-core/src/geometry/mod.rs index 950403ee8..3081f66be 100644 --- a/crates/horizon-core/src/geometry/mod.rs +++ b/crates/horizon-core/src/geometry/mod.rs @@ -602,8 +602,18 @@ pub(crate) fn clamp(value: f64, min: f64, max: f64) -> f64 { java_min(value, max) } } +/// `Mth.floor`, which is `(int) Math.floor(v)`: truncate, then step down for +/// negative fractions. A truncating conversion and a compare, where +/// `f64::floor` is a libm call on baseline x86-64. Both casts saturate (NaN is +/// 0), so the step down saturates too: below `i32::MIN` stays `i32::MIN`. +#[inline] pub(crate) fn floor_i32(value: f64) -> i32 { - value.floor() as i32 + let truncated = value as i32; + if value < f64::from(truncated) { + truncated.saturating_sub(1) + } else { + truncated + } } fn lerp(amount: f64, start: f64, end: f64) -> f64 { start + amount * (end - start) @@ -635,6 +645,42 @@ fn next_down(value: f64) -> f64 { #[cfg(test)] mod tests { use super::*; + + #[test] + fn floor_i32_is_mths_floor() { + for v in [ + 0.0, + -0.0, + 0.5, + -0.5, + 1.0, + -1.0, + 2.999, + -2.999, + 1e-300, + -1e-300, + 16_777_215.5, + -16_777_215.5, + // Past the i32 range `(int) Math.floor` saturates (vanilla 26.3's + // BlockCollisions and BlockPos.containing rely on it). + 2_147_483_647.5, + 2_147_483_648.0, + -2_147_483_648.0, + -2_147_483_648.5, + -2_147_483_649.0, + 3e9, + -3e9, + f64::MAX, + f64::MIN, + f64::INFINITY, + f64::NEG_INFINITY, + ] { + assert_eq!(floor_i32(v), v.floor() as i32, "{v}"); + } + assert_eq!(floor_i32(f64::NAN), 0); + assert_eq!(floor_i32(-3e9), i32::MIN); + assert_eq!(floor_i32(-2_147_483_648.5), i32::MIN); + } #[test] fn ray_faces_and_half_open_bounds() { let b = Aabb::block(BlockPos::new(0, 0, 0)); diff --git a/crates/horizon-core/src/noise/mod.rs b/crates/horizon-core/src/noise/mod.rs index cb255fbe5..e715b10f0 100644 --- a/crates/horizon-core/src/noise/mod.rs +++ b/crates/horizon-core/src/noise/mod.rs @@ -61,8 +61,8 @@ impl GradientTable { i32::from(self.permutations[(index & 255) as usize]) } - fn gradient(&self, index: i32) -> [i32; 3] { - GRADIENTS[(self.permute(index) & 15) as usize] + fn gradient(&self, index: i32) -> [f32; 3] { + PERLIN_GRADIENTS[(self.permute(index) & 15) as usize] } } @@ -87,8 +87,24 @@ const GRADIENTS: [[i32; 3]; 16] = [ [0, -1, -1], ]; -fn dot(gradient: [i32; 3], point: [f32; 3]) -> f32 { - gradient[0] as f32 * point[0] + gradient[1] as f32 * point[1] + gradient[2] as f32 * point[2] +/// [`GRADIENTS`] as floats, so a dot product needs no conversions: every +/// component is -1, 0 or 1, which a float holds exactly. +const PERLIN_GRADIENTS: [[f32; 3]; 16] = { + let mut out = [[0.0; 3]; 16]; + let mut i = 0; + while i < 16 { + out[i] = [ + GRADIENTS[i][0] as f32, + GRADIENTS[i][1] as f32, + GRADIENTS[i][2] as f32, + ]; + i += 1; + } + out +}; + +fn dot(gradient: [f32; 3], point: [f32; 3]) -> f32 { + gradient[0] * point[0] + gradient[1] * point[1] + gradient[2] * point[2] } /// Vanilla's periodic coordinate reduction with the normal Far Lands flag off. diff --git a/crates/horizon-core/src/noise/perlin.rs b/crates/horizon-core/src/noise/perlin.rs index 725373eff..ddcccfe9f 100644 --- a/crates/horizon-core/src/noise/perlin.rs +++ b/crates/horizon-core/src/noise/perlin.rs @@ -39,7 +39,7 @@ impl PerlinNoise { ) } - fn gradients(&self, cell: [i32; 3]) -> [[i32; 3]; 8] { + fn gradients(&self, cell: [i32; 3]) -> [[f32; 3]; 8] { self.gradients_at( self.table.permute(cell[0]), self.table.permute(cell[0].wrapping_add(1)), @@ -52,7 +52,7 @@ impl PerlinNoise { /// resolved. `add_volume` reuses one X column across every Y, so hoisting /// the two X permutes out of that loop avoids repeating them per Y. #[inline] - fn gradients_at(&self, p: i32, q: i32, cell_y: i32, cell_z: i32) -> [[i32; 3]; 8] { + fn gradients_at(&self, p: i32, q: i32, cell_y: i32, cell_z: i32) -> [[f32; 3]; 8] { let lower = self.table.permute(p.wrapping_add(cell_y)); let upper = self.table.permute(p.wrapping_add(cell_y).wrapping_add(1)); let lower_x = self.table.permute(q.wrapping_add(cell_y)); @@ -66,7 +66,7 @@ impl PerlinNoise { }) } - fn corner_values(gradients: [[i32; 3]; 8], point: [f32; 3]) -> [f32; 8] { + fn corner_values(gradients: [[f32; 3]; 8], point: [f32; 3]) -> [f32; 8] { std::array::from_fn(|i| { dot( gradients[i], @@ -99,7 +99,7 @@ impl PerlinNoise { let values = Self::corner_values(gradients, point); let fade = point.map(smoothstep); let gradient = - std::array::from_fn::<_, 3, _>(|axis| lerp3(fade, gradients.map(|g| g[axis] as f32))); + std::array::from_fn::<_, 3, _>(|axis| lerp3(fade, gradients.map(|g| g[axis]))); let changes = [ lerp2( fade[1], @@ -164,6 +164,31 @@ impl PerlinNoise { return Err(DensityError::BufferTooShort); } let [size_x, size_y, size_z] = volume.sizes(); + // Every X/Z column walks the same Y coordinates, so their cells, offsets + // and fades are computed once per volume instead of once per column. + let mut stack = [YSample::default(); STACK_Y]; + let mut heap = Vec::new(); + let ys = if size_y <= STACK_Y { + &mut stack[..size_y] + } else { + heap.resize(size_y, YSample::default()); + &mut heap[..] + }; + for (y, sample) in ys.iter_mut().enumerate() { + let input_y = f64::from(volume.coordinate(1, y)) * y_scale; + let shifted_y = wrap(input_y) + self.table.offsets[1]; + let cell = floor_i32(shifted_y); + let dy = shifted_y - f64::from(cell); + *sample = YSample { + cell, + fade: smoothstep(dy as f32), + offset: match fudge_y_scale { + Some(scale) => (dy - compute_fudge_y(input_y, dy, scale)) as f32, + None => dy as f32, + }, + }; + } + let ys = &*ys; let mut index = 0; for z in 0..size_z { let shifted_z = @@ -182,37 +207,40 @@ impl PerlinNoise { let mut previous_y = i32::MIN; let mut xz_dots = [0.0_f32; 8]; let mut y_gradients = [0.0_f32; 8]; - for y in 0..size_y { - let input_y = f64::from(volume.coordinate(1, y)) * y_scale; - let shifted_y = wrap(input_y) + self.table.offsets[1]; - let cell_y = floor_i32(shifted_y); - let dy = shifted_y - f64::from(cell_y); - let fade_y = smoothstep(dy as f32); - if previous_y != cell_y { - let gradients = self.gradients_at(p, q, cell_y, cell_z); + for (sample, out) in ys.iter().zip(&mut buffer[index..index + size_y]) { + if previous_y != sample.cell { + let gradients = self.gradients_at(p, q, sample.cell, cell_z); for i in 0..8 { - xz_dots[i] = gradients[i][0] as f32 * (dx - (i & 1) as f32) - + gradients[i][2] as f32 * (dz - ((i >> 2) & 1) as f32); - y_gradients[i] = gradients[i][1] as f32; + xz_dots[i] = gradients[i][0] * (dx - (i & 1) as f32) + + gradients[i][2] * (dz - ((i >> 2) & 1) as f32); + y_gradients[i] = gradients[i][1]; } - previous_y = cell_y; + previous_y = sample.cell; } - let dy = match fudge_y_scale { - Some(scale) => (dy - compute_fudge_y(input_y, dy, scale)) as f32, - None => dy as f32, - }; + let dy = sample.offset; let values = std::array::from_fn(|i| { xz_dots[i] + y_gradients[i] * (dy - ((i >> 1) & 1) as f32) }); - buffer[index] += amplitude * lerp3([fade_x, fade_y, fade_z], values); - index += 1; + *out += amplitude * lerp3([fade_x, sample.fade, fade_z], values); } + index += size_y; } } Ok(()) } } +/// Y columns up to this height keep their per-Y samples on the stack. +const STACK_Y: usize = 64; + +#[derive(Clone, Copy, Default)] +struct YSample { + cell: i32, + fade: f32, + /// The Y offset inside the cell used for the corner values, after any fudge. + offset: f32, +} + #[derive(Clone, Debug)] pub struct SmearedPerlinNoise { base: PerlinNoise, diff --git a/crates/horizon-core/src/paletted.rs b/crates/horizon-core/src/paletted.rs index 3d56bb987..0730cf5e4 100644 --- a/crates/horizon-core/src/paletted.rs +++ b/crates/horizon-core/src/paletted.rs @@ -577,14 +577,21 @@ impl PalettedContainer { if list.len() == 1 << self.bits { return Ok(()); } - for i in 0..self.strategy.entries() { - let index = read(&self.words, self.bits, i); - if index as usize >= list.len() { - return Err(PaletteError::BadIndex { - index, - palette: list.len(), - }); + let per = 64 / usize::from(self.bits); + let mut remaining = self.strategy.entries(); + let mask = mask(self.bits); + for &word in &self.words { + let count = remaining.min(per); + for slot in 0..count { + let index = ((word >> (slot * usize::from(self.bits))) & mask) as u32; + if index as usize >= list.len() { + return Err(PaletteError::BadIndex { + index, + palette: list.len(), + }); + } } + remaining -= count; } Ok(()) } @@ -644,6 +651,18 @@ impl PalettedContainer { actual: data.len(), }); } + if let Config::List(bits) = config { + // List palettes already use the saved indices as resident storage. + // Validate them without allocating an unpacked copy that is unused. + let container = Self { + strategy, + bits, + words: data.to_vec(), + palette: Palette::List(palette), + }; + container.check_indices()?; + return Ok(container); + } let mut ids = Vec::with_capacity(entries); for i in 0..entries { let index = read(data, disc_bits, i); @@ -655,15 +674,7 @@ impl PalettedContainer { } ids.push(index); } - Ok(match config { - Config::List(bits) => Self { - strategy, - bits, - words: data.to_vec(), - palette: Palette::List(palette), - }, - _ => Self::build(strategy, palette, &ids), - }) + Ok(Self::build(strategy, palette, &ids)) } /// Whether any palette entry satisfies `predicate` (`maybeHas`): entries /// no longer used by any position still count. @@ -796,6 +807,113 @@ mod tests { assert!(PalettedContainer::from_wire(BLOCKS, 0, vec![9], vec![]).is_ok()); } #[test] + fn saved_validation_matches_entrywise_reference() { + // Keep the previous loader as an independent entry-at-a-time reference: + // errors, resident palette order and unused storage bits must all agree. + fn reference( + strategy: Strategy, + palette: Vec, + data: Option<&[u64]>, + ) -> Result { + if palette.is_empty() { + return Err(PaletteError::BadPalette { len: 0 }); + } + let config = strategy.config(ceil_log2(palette.len())); + let entries = strategy.entries(); + let bits = match config { + Config::Single => return Ok(PalettedContainer::new(strategy, palette[0])), + Config::List(bits) => bits, + Config::Global => ceil_log2(palette.len()), + }; + let expected = storage_len(bits, entries); + let data = data.ok_or(PaletteError::BadStorage { + expected, + actual: 0, + })?; + if data.len() != expected { + return Err(PaletteError::BadStorage { + expected, + actual: data.len(), + }); + } + let mut ids = Vec::with_capacity(entries); + for i in 0..entries { + let index = read(data, bits, i); + if index as usize >= palette.len() { + return Err(PaletteError::BadIndex { + index, + palette: palette.len(), + }); + } + ids.push(index); + } + Ok(match config { + Config::List(bits) => PalettedContainer { + strategy, + bits, + palette: Palette::List(palette), + words: data.to_vec(), + }, + _ => PalettedContainer::build(strategy, palette, &ids), + }) + } + fn compare(strategy: Strategy, palette: &[u32], data: Option<&[u64]>) { + let expected = reference(strategy, palette.to_vec(), data); + let actual = PalettedContainer::from_packed(strategy, palette.to_vec(), data); + match (actual, expected) { + (Ok(a), Ok(b)) => { + assert_eq!(a.strategy, b.strategy); + assert_eq!(a.bits, b.bits); + assert_eq!(a.palette, b.palette); + assert_eq!(a.words, b.words); + } + (Err(a), Err(b)) => assert_eq!(a, b), + (a, b) => panic!("loader disagreement: {a:?} vs {b:?}"), + } + } + for strategy in [BLOCKS, BIOMES] { + for len in [ + 0, 1, 2, 3, 4, 5, 8, 9, 15, 16, 17, 31, 32, 33, 63, 64, 65, 127, 128, 129, 255, + 256, 257, 511, 512, 513, 1023, 1024, 1025, 2047, 2048, 2049, 4096, 4097, + ] { + let palette: Vec = (0..len).map(|i| (i as u32 * 7) % 127).collect(); + compare(strategy, &palette, None); + compare(strategy, &palette, Some(&[])); + if len <= 1 { + compare(strategy, &palette, Some(&[u64::MAX])); + continue; + } + let bits = match strategy.config(ceil_log2(len)) { + Config::List(bits) => bits, + _ => ceil_log2(len), + }; + let entries = strategy.entries(); + let mut words = pack_words(bits, entries, (0..entries).map(|i| (i % len) as u32)); + compare(strategy, &palette, Some(&words)); + compare(strategy, &palette, Some(&words[..words.len() - 1])); + // Nonzero padding in every word and in the final partial word + // is legal and must be preserved by resident list palettes. + let per = 64 / usize::from(bits); + for (word, positions) in words.iter_mut().zip((0..entries).step_by(per)) { + let used = (entries - positions).min(per) * usize::from(bits); + if used < 64 { + *word |= u64::MAX << used; + } + } + compare(strategy, &palette, Some(&words)); + if len < 1usize << bits { + for i in [0, per - 1, per, entries / 2, entries - 1] { + let mut invalid = words.clone(); + write(&mut invalid, bits, i, len as u32); + // A second invalid entry verifies first-error ordering. + write(&mut invalid, bits, entries - 1, mask(bits) as u32); + compare(strategy, &palette, Some(&invalid)); + } + } + } + } + } + #[test] fn division_magic_is_exact() { for bits in 1..=32u8 { let per = 64 / usize::from(bits); diff --git a/crates/horizon-prepare/src/java.rs b/crates/horizon-prepare/src/java.rs index d54ef0949..a159fb055 100644 --- a/crates/horizon-prepare/src/java.rs +++ b/crates/horizon-prepare/src/java.rs @@ -41,11 +41,19 @@ fn javac_major(javac: &Path) -> Result { .skip_while(|w| *w != "javac") .nth(1) .ok_or_else(|| { - format!( - "{} -version printed no version: {}", - javac.display(), - text.trim() - ) + // macOS ships /usr/bin/javac as a placeholder that only says no Java is installed. + if text.contains("Unable to locate a Java Runtime") { + format!( + "{} is macOS's placeholder (no Java installed)", + javac.display() + ) + } else { + format!( + "{} -version printed no version: {}", + javac.display(), + text.trim() + ) + } })?; let mut parts = version.split(['.', '-', '+', '_']); let first: u32 = parts.next().and_then(|p| p.parse().ok()).unwrap_or(0); @@ -126,11 +134,38 @@ fn installed_jdks(parents: &[PathBuf], major: i64) -> Vec { homes } +/// The Java runtimes the official launcher downloaded into `runtime` (a game directory's +/// `runtime` folder: `///`, a macOS one in `jre.bundle`). Mojang's +/// runtimes are whole JDKs, javac included, so a player who has run Minecraft has one already. +pub fn minecraft_runtimes(runtime: &Path) -> Vec { + let children = |dir: &Path| -> Vec { + let mut paths: Vec = fs::read_dir(dir) + .map(|entries| entries.flatten().map(|e| e.path()).collect()) + .unwrap_or_default(); + paths.sort(); + paths + }; + let mut homes = Vec::new(); + for component in children(runtime) { + for platform in children(&component) { + let home = platform.join(component.file_name().unwrap_or_default()); + for home in [home.join("jre.bundle/Contents/Home"), home] { + if executable(&home.join("bin"), "javac").is_file() { + homes.push(home); + break; + } + } + } + } + homes +} + /// Finds a JDK with `javac` of at least `major`, the version research-lock.json pins: /// `JAVA_HOME` when it holds one, else `javac` and `java` on the PATH (as the Python preparer -/// ran them), else, on macOS, the JDK `/usr/libexec/java_home -v ` reports, else a JDK -/// in the folders installers put them in (`jdk_parents`). -pub fn find(major: i64) -> Result { +/// ran them), else, on macOS, the JDK `/usr/libexec/java_home -v ` reports, else the JDK +/// homes in `more` (the launcher's pick, Minecraft's own runtimes), else a JDK in the folders +/// installers put them in (`jdk_parents`). +pub fn find(major: i64, more: &[PathBuf]) -> Result { let need = format!( "Java {major} is needed (a JDK with javac, e.g. Eclipse Temurin {major}). \ Install it, or set JAVA_HOME to it, and try again." @@ -164,6 +199,14 @@ pub fn find(major: i64) -> Result { } } } + for home in more { + let bin = home.join("bin"); + candidates.push(( + executable(&bin, "javac"), + executable(&bin, "java"), + "Minecraft's Java", + )); + } for home in installed_jdks(&jdk_parents(), major) { let bin = home.join("bin"); candidates.push(( @@ -205,6 +248,15 @@ pub fn classpath<'a>(paths: impl IntoIterator) -> String { } impl Jdk { + /// The JDK's home, the folder above `bin` (what `JAVA_HOME` names). + pub fn home(&self) -> PathBuf { + self.javac + .parent() + .and_then(Path::parent) + .map(Path::to_path_buf) + .unwrap_or_default() + } + /// `javac --release -proc:none` with Python's `subprocess.run(..., check=True, /// stdout=log, stderr=STDOUT, timeout=3600)`. pub fn javac(&self, major: i64, args: &[String], log: &fs::File) -> Result<(), String> { @@ -301,4 +353,32 @@ mod tests { ); fs::remove_dir_all(&dir).unwrap(); } + + #[test] + fn minecraft_runtimes_are_found_in_the_launchers_layout() { + let dir = + std::env::temp_dir().join(format!("horizon-prepare-runtimes-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + let make = |home: PathBuf, javac: bool| { + fs::create_dir_all(home.join("bin")).unwrap(); + if javac { + fs::write(executable(&home.join("bin"), "javac"), b"").unwrap(); + } + home + }; + let gamma = make( + dir.join("java-runtime-gamma/linux/java-runtime-gamma"), + true, + ); + let epsilon = make( + dir.join( + "java-runtime-epsilon/mac-os-arm64/java-runtime-epsilon/jre.bundle/Contents/Home", + ), + true, + ); + make(dir.join("jre-legacy/linux/jre-legacy"), false); + assert_eq!(minecraft_runtimes(&dir), [epsilon, gamma]); + assert!(minecraft_runtimes(&dir.join("missing")).is_empty()); + fs::remove_dir_all(&dir).unwrap(); + } } diff --git a/crates/horizon-prepare/src/lib.rs b/crates/horizon-prepare/src/lib.rs index 66ff671f9..861db254d 100644 --- a/crates/horizon-prepare/src/lib.rs +++ b/crates/horizon-prepare/src/lib.rs @@ -74,6 +74,9 @@ pub struct Options { pub minecraft_dir: Option, /// The pinned server jar the player downloaded (`--server-jar`, else HORIZON_SERVER_JAR). pub server_jar: Option, + /// The JDK to try after JAVA_HOME and the PATH (the launcher's pick, e.g. Minecraft's + /// own Java it downloaded from Mojang). + pub java_home: Option, } pub(crate) fn hex(bytes: &[u8]) -> String { @@ -402,7 +405,11 @@ pub fn prepare(options: &Options, log: Log) -> Result { .map_err(|e| format!("{}: {e}", options.root.display()))?; let lock = artifacts::Lock::read(root)?; // Java first: nothing below can finish without it, and the player should hear it at once. - let jdk = java::find(lock.java_major)?; + let mut homes: Vec = options.java_home.iter().cloned().collect(); + homes.extend(java::minecraft_runtimes( + &artifacts::minecraft_dir(options.minecraft_dir.as_deref()).join("runtime"), + )); + let jdk = java::find(lock.java_major, &homes)?; if options.import && !artifacts::reuse_imported(root, log)? { artifacts::import( root, diff --git a/crates/horizon-prepare/src/main.rs b/crates/horizon-prepare/src/main.rs index 71b7a40cc..0d3a5685d 100644 --- a/crates/horizon-prepare/src/main.rs +++ b/crates/horizon-prepare/src/main.rs @@ -62,6 +62,7 @@ fn main() -> ExitCode { import: false, minecraft_dir: None, server_jar: None, + java_home: None, }; let mut root = None; let mut args = std::env::args_os().skip(1).peekable(); diff --git a/crates/horizon-protocol/src/entity_data.rs b/crates/horizon-protocol/src/entity_data.rs index d0e977568..574afd300 100644 --- a/crates/horizon-protocol/src/entity_data.rs +++ b/crates/horizon-protocol/src/entity_data.rs @@ -5,7 +5,7 @@ use crate::{ Result, buf::{Codec, Reader, Writer}, - item::{Slot, Stack}, + item::{Slot, Stack, Template}, }; use horizon_world::nbt::Tag; @@ -28,6 +28,150 @@ pub enum Value { Id(i32), /// Several VarInts (VillagerData). Ids(Vec), + /// A particle choice: the `minecraft:particle_type` id plus its data. + /// Rendered nowhere (the client spawns no world particles yet); decoded + /// so the rest of an entry list survives a particle slot. + Particle(Particle), + /// A particle list (PARTICLES: a VarInt count, then each particle). + Particles(Vec), +} +/// One `ParticleTypes.STREAM_CODEC` value: the `minecraft:particle_type` id, +/// then the data its type carries (26.3 registry order). +#[derive(Clone, Debug, PartialEq)] +pub struct Particle { + pub id: i32, + pub data: Option, +} +#[derive(Clone, Debug, PartialEq)] +pub enum ParticleData { + /// Block state id (block, block_marker, falling_dust, dust_pillar, + /// block_crumble). + State(i32), + /// ARGB color (entity_effect, tinted_leaves, flash). + Color(i32), + /// Dust: color then scale. + ColorScale(i32, f32), + /// Dust color transition: from color, to color, scale. + ColorScale2(i32, i32, f32), + /// Spell (effect, instant_effect): color then power. + ColorPower(i32, f32), + /// A bare float (dragon_breath power, sculk_charge roll). + Scalar(f32), + /// Delay in ticks (shriek). + Delay(i32), + /// Trail: target (3 doubles), ARGB color, duration. + Trail([f64; 3], i32, i32), + /// An item (ItemStackTemplate: item, count, patch). + Item(Stack), + /// Geyser and geyser_plume: water blocks. + Geyser(i32), + /// Geyser_base and geyser_poof: water blocks, then the burst impulse. + GeyserBase(i32, f32), + /// Vibration: where it travels to, then its arrival time in ticks. + Vibration { source: PositionSource, ticks: i32 }, +} +/// `PositionSource.STREAM_CODEC`: a `minecraft:position_source_type` id +/// (block 0, entity 1), then that type's data. +#[derive(Clone, Debug, PartialEq)] +pub enum PositionSource { + Block([i32; 3]), + Entity { id: i32, y_offset: f32 }, +} +impl Particle { + pub fn read(r: &mut Reader) -> Result { + let id = r.varint()?; + // `minecraft:particle_type` registry order as of 26.3. + let data = match id { + 1 | 2 | 36 | 121 | 125 => Some(ParticleData::State(r.varint()?)), + 28 | 46 | 52 => Some(ParticleData::Color(r.i32()?)), + 21 => { + let color = r.i32()?; + Some(ParticleData::ColorScale(color, r.f32()?)) + } + 22 => { + let from = r.i32()?; + let to = r.i32()?; + Some(ParticleData::ColorScale2(from, to, r.f32()?)) + } + 23 | 56 => { + let color = r.i32()?; + Some(ParticleData::ColorPower(color, r.f32()?)) + } + 15 | 48 => Some(ParticleData::Scalar(r.f32()?)), + 115 => Some(ParticleData::Delay(r.varint()?)), + 59 => { + let at = [r.f64()?, r.f64()?, r.f64()?]; + let color = r.i32()?; + Some(ParticleData::Trail(at, color, r.varint()?)) + } + 57 => Some(ParticleData::Item(Template::read(r)?)), + 58 => { + let source = match r.varint()? { + 0 => PositionSource::Block(crate::buf::Pos::read(r)?), + 1 => { + let id = r.varint()?; + PositionSource::Entity { + id, + y_offset: r.f32()?, + } + } + kind => return Err(crate::Error::new(format!("position source type {kind}"))), + }; + Some(ParticleData::Vibration { + source, + ticks: r.varint()?, + }) + } + 7 | 10 => Some(ParticleData::Geyser(r.i32()?)), + 8 | 9 => { + let water = r.i32()?; + Some(ParticleData::GeyserBase(water, r.f32()?)) + } + // Every other registered particle carries no data. + _ => None, + }; + Ok(Particle { id, data }) + } + pub fn write(&self, w: &mut Writer) { + w.varint(self.id); + let Some(data) = &self.data else { return }; + match data { + ParticleData::State(s) | ParticleData::Delay(s) => w.varint(*s), + ParticleData::Color(c) | ParticleData::Geyser(c) => w.i32(*c), + ParticleData::ColorScale(c, f) + | ParticleData::ColorPower(c, f) + | ParticleData::GeyserBase(c, f) => { + w.i32(*c); + w.f32(*f); + } + ParticleData::ColorScale2(a, b, f) => { + w.i32(*a); + w.i32(*b); + w.f32(*f); + } + ParticleData::Scalar(f) => w.f32(*f), + ParticleData::Trail(at, c, d) => { + at.iter().for_each(|v| w.f64(*v)); + w.i32(*c); + w.varint(*d); + } + ParticleData::Item(s) => Template::write(s, w), + ParticleData::Vibration { source, ticks } => { + match source { + PositionSource::Block(pos) => { + w.varint(0); + crate::buf::Pos::write(pos, w); + } + PositionSource::Entity { id, y_offset } => { + w.varint(1); + w.varint(*id); + w.f32(*y_offset); + } + } + w.varint(*ticks); + } + } + } } /// Serializer ids in EntityDataSerializers registration order. pub mod serializer { @@ -113,6 +257,15 @@ fn read_value(kind: i32, r: &mut Reader) -> Result> { | PAINTING_VARIANT..=WEATHERING_COPPER_STATE | HUMANOID_ARM | DYE_COLOR => Value::Id(r.varint()?), + PARTICLE => Value::Particle(Particle::read(r)?), + PARTICLES => { + let n = r.count(65536)?; + let mut list = Vec::with_capacity(n.min(64)); + for _ in 0..n { + list.push(Particle::read(r)?); + } + Value::Particles(list) + } _ => return Ok(None), })) } @@ -147,6 +300,11 @@ fn write_value(kind: i32, v: &Value, w: &mut Writer) { w.uuid(*u); } } + Value::Particle(p) => p.write(w), + Value::Particles(list) => { + w.varint(list.len() as i32); + list.iter().for_each(|p| p.write(w)); + } } let _ = kind; } @@ -208,10 +366,93 @@ mod tests { EntityData::read(&mut Reader::new(&w.data)).unwrap(), entries ); - // A particle (16) cannot be skipped: keep what came before. - let mut bytes = vec![0, 0, 7, 9, 16, 1, 2, 3]; + // Serializer 200 is unknown: the list stops there, earlier entries kept. + let mut bytes = vec![0, 0, 7, 9, 200, 1, 2, 3]; bytes.push(0xFF); let read = EntityData::read(&mut Reader::new(&bytes)).unwrap(); assert_eq!(read, vec![(0, 0, Value::Byte(7))]); + // A block particle decodes fully and round-trips. + let entries = vec![( + 10u8, + serializer::PARTICLE, + Value::Particle(Particle { + id: 1, + data: Some(ParticleData::State(2)), + }), + )]; + let mut w = Writer::new(); + EntityData::write(&entries, &mut w); + assert_eq!( + EntityData::read(&mut Reader::new(&w.data)).unwrap(), + entries + ); + } + + /// Every particle data shape (26.3 codecs) round-trips, and a PARTICLES + /// list is a VarInt count then each particle, so the entry after it + /// still decodes. + #[test] + fn particles_round_trip() { + let all = [ + (1, Some(ParticleData::State(2))), + (7, Some(ParticleData::Geyser(5))), + (8, Some(ParticleData::GeyserBase(3, 0.5))), + (15, Some(ParticleData::Scalar(1.0))), + (21, Some(ParticleData::ColorScale(0xff0000, 1.5))), + (22, Some(ParticleData::ColorScale2(1, 2, 0.75))), + (23, Some(ParticleData::ColorPower(-1, 2.0))), + (28, Some(ParticleData::Color(0x7f00ff00))), + ( + 57, + Some(ParticleData::Item(Stack { + item: 42, + count: 3, + added: Vec::new(), + removed: vec![7], + })), + ), + ( + 58, + Some(ParticleData::Vibration { + source: PositionSource::Block([-12, 64, 300]), + ticks: 20, + }), + ), + ( + 58, + Some(ParticleData::Vibration { + source: PositionSource::Entity { + id: 99, + y_offset: 1.25, + }, + ticks: 8, + }), + ), + (59, Some(ParticleData::Trail([1.5, -2.0, 3.25], 9, 40))), + (115, Some(ParticleData::Delay(6))), + (0, None), + ] + .map(|(id, data)| Particle { id, data }); + let mut entries: Vec<_> = all + .iter() + .map(|p| (10u8, serializer::PARTICLE, Value::Particle(p.clone()))) + .collect(); + entries.push((11, serializer::PARTICLES, Value::Particles(all.to_vec()))); + entries.push((12, serializer::BYTE, Value::Byte(4))); + let mut w = Writer::new(); + EntityData::write(&entries, &mut w); + assert_eq!( + EntityData::read(&mut Reader::new(&w.data)).unwrap(), + entries + ); + // Wire shape: an empty list is one 0 byte, then the next entry. + let bytes = [11, serializer::PARTICLES as u8, 0, 12, 0, 4, 0xFF]; + assert_eq!( + EntityData::read(&mut Reader::new(&bytes)).unwrap(), + vec![ + (11, serializer::PARTICLES, Value::Particles(Vec::new())), + (12, serializer::BYTE, Value::Byte(4)), + ] + ); } } diff --git a/crates/horizon-protocol/src/item.rs b/crates/horizon-protocol/src/item.rs index 02c9e4966..6f59228b5 100644 --- a/crates/horizon-protocol/src/item.rs +++ b/crates/horizon-protocol/src/item.rs @@ -25,7 +25,10 @@ pub mod component { pub const REPAIR_COST: i32 = 19; pub const CREATIVE_SLOT_LOCK: i32 = 20; pub const ENCHANTMENT_GLINT_OVERRIDE: i32 = 21; + /// `AttackRange`: six floats, in the record's field order. + pub const ATTACK_RANGE: i32 = 30; pub const STORED_ENCHANTMENTS: i32 = 45; + pub const PROFILE: i32 = 72; pub const DYED_COLOR: i32 = 47; pub const MAP_ID: i32 = 48; pub const MAP_POST_PROCESSING: i32 = 50; @@ -57,6 +60,8 @@ pub enum Component { Ident(String), Lore(Vec), Enchantments(Vec<(i32, i32)>), + AttackRange([f32; 6]), + Profile(Profile), CustomModelData { floats: Vec, flags: Vec, @@ -81,6 +86,15 @@ fn filterable(r: &mut Reader, value: impl Fn(&mut Reader) -> Result) -> Re } Ok(raw) } + +/// `ResolvableProfile`: an optional name and UUID and the profile's property +/// list, followed by `PlayerSkin.Patch`'s four optional textures. +#[derive(Clone, Debug, PartialEq)] +pub struct Profile { + pub name: Option, + pub id: Option, + pub properties: Vec<(String, String, Option)>, +} impl Component { fn read(kind: i32, r: &mut Reader) -> Result { use component::*; @@ -129,6 +143,56 @@ impl Component { .collect::>()?, ) } + ATTACK_RANGE => { + let mut values = [0.0f32; 6]; + for v in &mut values { + *v = r.f32()?; + } + Self::AttackRange(values) + } + PROFILE => { + fn properties(r: &mut Reader) -> Result)>> { + let n = r.count(1024)?; + let mut out = Vec::with_capacity(n); + for _ in 0..n { + let name = r.string(32767)?; + let value = r.string(32767)?; + let signature = if r.bool()? { + Some(r.string(32767)?) + } else { + None + }; + out.push((name, value, signature)); + } + Ok(out) + } + // Either: the partial form carries + // optional fields, the resolved one a UUID, a name and the + // properties. + let (name, id, properties) = if r.u8()? == 0 { + let name = if r.bool()? { Some(r.string(64)?) } else { None }; + let id = if r.bool()? { Some(r.uuid()?) } else { None }; + (name, id, properties(r)?) + } else { + let id = Some(r.uuid()?); + let name = Some(r.string(64)?); + (name, id, properties(r)?) + }; + // PlayerSkin.Patch: body, cape, elytra and model, each absent + // in the profiles servers send for heads. + for _ in 0..4 { + if r.bool()? { + // ClientAsset.ResourceTexture: its id and its texture path. + r.string(32767)?; + r.string(32767)?; + } + } + Self::Profile(Profile { + name, + id, + properties, + }) + } CUSTOM_MODEL_DATA => { let n = r.count(r.remaining())?; let floats = (0..n).map(|_| r.f32()).collect::>()?; @@ -175,6 +239,30 @@ impl Component { w.varint(*level); } } + Self::AttackRange(values) => values.iter().for_each(|v| w.f32(*v)), + Self::Profile(p) => { + w.u8(0); + w.bool(p.name.is_some()); + if let Some(name) = &p.name { + w.string(name); + } + w.bool(p.id.is_some()); + if let Some(id) = p.id { + w.uuid(id); + } + w.varint(p.properties.len() as i32); + for (name, value, signature) in &p.properties { + w.string(name); + w.string(value); + w.bool(signature.is_some()); + if let Some(signature) = signature { + w.string(signature); + } + } + for _ in 0..4 { + w.bool(false); + } + } Self::CustomModelData { floats, flags, @@ -471,4 +559,50 @@ mod tests { let bytes = [1, 5, 1, 0, 99]; assert!(Slot::read(&mut Reader::new(&bytes)).is_err()); } + + #[test] + fn attack_range_and_profiles_round_trip() { + let mut sword = Stack::new(900, 1); + sword.added.push(( + component::ATTACK_RANGE, + Component::AttackRange([0.0, 3.0, 0.0, 4.0, 0.1, 1.0]), + )); + sword.added.push(( + component::PROFILE, + Component::Profile(Profile { + name: Some("Player53470".into()), + id: Some(0x7a5d_6a1a_30d7_4187_88c5_efe9_1201_8922), + properties: vec![("textures".into(), "dGV4dHVyZXM=".into(), None)], + }), + )); + round::, Slot>(Some(sword)); + } + + #[test] + fn a_partial_profile_decodes_from_the_wire() { + // count 1, item 1, one added component of kind 72 (profile): a partial + // profile with an empty name, a UUID, one unsigned texture property + // and an empty skin patch. + let uuid = [ + 0x7a, 0x5d, 0x6a, 0x1a, 0x30, 0xd7, 0x41, 0x87, 0x88, 0xc5, 0xef, 0xe9, 0x12, 0x01, + 0x89, 0x22, + ]; + let mut bytes = vec![1, 1, 1, 0, 72, 0, 1, 0, 1]; + bytes.extend_from_slice(&uuid); + bytes.extend_from_slice(&[1, 8]); + bytes.extend_from_slice(b"textures"); + bytes.extend_from_slice(&[1, b'x', 0, 0, 0, 0, 0]); + let mut r = Reader::new(&bytes); + let stack = Slot::read(&mut r).unwrap().unwrap(); + assert_eq!(r.remaining(), 0); + let Some(Component::Profile(profile)) = stack.component(component::PROFILE) else { + panic!("the profile component did not decode"); + }; + assert_eq!(profile.name.as_deref(), Some("")); + assert_eq!(profile.id, Some(0x7a5d_6a1a_30d7_4187_88c5_efe9_1201_8922)); + assert_eq!( + profile.properties, + [("textures".to_owned(), "x".to_owned(), None)] + ); + } } diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index bfda58e9b..537ecf6ef 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -273,6 +273,68 @@ packet!(Login { online_mode: bool => Bool, enforces_secure_chat: bool => Bool, }); +packet!( +/// MapDecoration: a registry holder, its map position and rotation, and an +/// optional name. +MapDecoration { + kind: i32 => VarInt, + x: i8 => Byte, + y: i8 => Byte, + rot: i8 => Byte, + name: Option => Opt, +} +); + +/// MapItemSavedData.MapPatch: an empty patch is a zero width. +#[derive(Clone, Debug, PartialEq)] +pub struct MapPatch { + pub start_x: i32, + pub start_y: i32, + pub width: i32, + pub height: i32, + pub colors: Vec, +} +pub struct MapPatchOpt; +impl Codec> for MapPatchOpt { + fn read(r: &mut Reader) -> Result> { + let width = i32::from(r.u8()?); + if width == 0 { + return Ok(None); + } + let height = i32::from(r.u8()?); + let start_x = i32::from(r.u8()?); + let start_y = i32::from(r.u8()?); + let n = r.count(r.remaining())?; + let colors = r.bytes(n)?.to_vec(); + Ok(Some(MapPatch { + start_x, + start_y, + width, + height, + colors, + })) + } + fn write(patch: &Option, w: &mut Writer) { + let Some(patch) = patch else { + w.u8(0); + return; + }; + w.u8(patch.width as u8); + w.u8(patch.height as u8); + w.u8(patch.start_x as u8); + w.u8(patch.start_y as u8); + w.varint(patch.colors.len() as i32); + w.bytes(&patch.colors); + } +} + +packet!(MapItemData { + map_id: i32 => VarInt, + scale: i8 => Byte, + locked: bool => Bool, + decorations: Option> => Opt>, + patch: Option => MapPatchOpt, +}); /// VecDelta: per-axis deltas in 1/4096 blocks, linear or in timed steps. #[derive(Clone, Debug, PartialEq)] pub enum VecDelta { @@ -1425,6 +1487,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { LevelEvent(LevelEvent) = LEVEL_EVENT, LightUpdate(LightUpdate) = LIGHT_UPDATE, Login(Login) = LOGIN, + MapItemData(MapItemData) = MAP_ITEM_DATA, MoveEntityPos(MoveEntityPos) = MOVE_ENTITY_POS, MoveEntityPosRot(MoveEntityPosRot) = MOVE_ENTITY_POS_ROT, MoveEntityRot(MoveEntityRot) = MOVE_ENTITY_ROT, @@ -2490,4 +2553,26 @@ mod tests { assert_eq!(crate::ids::play::clientbound::UPDATE_ATTRIBUTES, 134); assert_eq!(Clientbound::decode(134, &body[2..]).unwrap(), p); } + + #[test] + fn map_item_data_carries_a_server_patch() { + let patch = MapPatch { + start_x: 3, + start_y: 4, + width: 2, + height: 1, + colors: vec![1, 2], + }; + let mut w = Writer::new(); + MapPatchOpt::write(&Some(patch.clone()), &mut w); + assert_eq!(w.data, [2, 1, 3, 4, 2, 1, 2]); + let p = Clientbound::MapItemData(MapItemData { + map_id: 2146483647, + scale: 1, + locked: true, + decorations: None, + patch: Some(patch), + }); + round_trip(p, Clientbound::encode, Clientbound::decode); + } } diff --git a/crates/horizon-world/examples/chunkgen_bench.rs b/crates/horizon-world/examples/chunkgen_bench.rs index 4992515c5..2eb433600 100644 --- a/crates/horizon-world/examples/chunkgen_bench.rs +++ b/crates/horizon-world/examples/chunkgen_bench.rs @@ -3,6 +3,7 @@ //! chunkgen_bench [--seed S] [--size N] [--threads T] //! [--center CX CZ] [--verify ] [--no-decorate] //! [--dimension overworld|the_nether|the_end] +//! [--warmup] [--json] [--no-map] [--snapshot PATH] use horizon_core::position::ChunkPos; use horizon_world::{ DATA_VERSION, @@ -274,7 +275,9 @@ fn main() -> Result<(), Error> { let resources = PathBuf::from(args.next().expect("client resource directory")); let (mut seed, mut size, mut threads, mut center) = (0i64, 16i32, 2usize, (0, 0)); let mut parity = None; + let mut snapshot_path = None; let mut decorate = true; + let (mut warmup, mut json, mut map) = (false, false, true); let mut dimension = String::from("minecraft:overworld"); let mut starts: Option<(i32, i32, i32, i32, PathBuf)> = None; while let Some(arg) = args.next() { @@ -285,7 +288,11 @@ fn main() -> Result<(), Error> { "--threads" => threads = next().parse()?, "--center" => center = (next().parse()?, next().parse()?), "--verify" => parity = Some(PathBuf::from(next())), + "--snapshot" => snapshot_path = Some(PathBuf::from(next())), "--no-decorate" => decorate = false, + "--warmup" => warmup = true, + "--json" => json = true, + "--no-map" => map = false, "--dimension" => { let d = next(); dimension = if d.contains(':') { @@ -326,6 +333,16 @@ fn main() -> Result<(), Error> { dump_starts(&generator, seed, [x0, z0, x1, z1], &out)?; return Ok(()); } + if warmup { + let mut worker = generator.worker(); + for z in -4..=4 { + for x in -4..=4 { + std::hint::black_box( + worker.generate_proto(ChunkPos::new(center.0 + 64 + x, center.1 + 64 + z))?, + ); + } + } + } let (x0, z0) = (center.0 - size / 2, center.1 - size / 2); let count = (size * size) as usize; let next = AtomicUsize::new(0); @@ -353,6 +370,7 @@ fn main() -> Result<(), Error> { handles.into_iter().try_for_each(|h| h.join().unwrap()) })?; let elapsed = start.elapsed(); + let cpu_elapsed = cpu_seconds() - cpu; println!( "generated {count} proto chunks with {threads} threads in {elapsed:.2?}: {:.1} chunks/s ({:.1} ms/chunk/thread)", count as f64 / elapsed.as_secs_f64(), @@ -360,7 +378,7 @@ fn main() -> Result<(), Error> { ); println!( " cpu time {:.1} ms/chunk", - (cpu_seconds() - cpu) * 1000. / count as f64 + cpu_elapsed * 1000. / count as f64 ); let timings = timings.into_inner().unwrap(); let per_chunk = |f: fn(&StageTimings) -> std::time::Duration| { @@ -379,10 +397,23 @@ fn main() -> Result<(), Error> { per_chunk(|t| t.surface), per_chunk(|t| t.carvers) ); + if json { + println!( + "BENCH {}", + serde_json::json!({"phase": "proto", "chunks": count, + "threads": threads, "wall_s": elapsed.as_secs_f64(), "cpu_s": cpu_elapsed, + "biomes_ms_chunk": per_chunk(|t| t.biomes), "noise_ms_chunk": per_chunk(|t| t.noise), + "structures_ms_chunk": per_chunk(|t| t.structures), + "surface_ms_chunk": per_chunk(|t| t.surface), "carvers_ms_chunk": per_chunk(|t| t.carvers)}) + ); + } let mut chunks: Vec> = slots .into_iter() .map(|slot| slot.into_inner().unwrap()) .collect(); + if let Some(path) = &snapshot_path { + snapshot(&chunks, path, "terrain")?; + } if decorate && size >= 3 { let totals = Mutex::new(DecorateStats::default()); let start = Instant::now(); @@ -441,6 +472,13 @@ fn main() -> Result<(), Error> { } } let elapsed = start.elapsed(); + if json { + println!( + "BENCH {}", + serde_json::json!({"phase": "decorate", "chunks": decorated, + "wall_s": elapsed.as_secs_f64()}) + ); + } let totals = totals.into_inner().unwrap(); println!( "decorated {decorated} chunks in {elapsed:.2?}: {:.1} chunks/s; feature roots placed {}, unsupported {}, failed {}", @@ -461,6 +499,9 @@ fn main() -> Result<(), Error> { ); } } + if let Some(path) = &snapshot_path { + snapshot(&chunks, path, "decorated")?; + } let mut structures = BTreeMap::<(String, i32, i32), [[i32; 3]; 2]>::new(); for chunk in chunks.iter().flatten() { for (name, start, min, max) in chunk.structures() { @@ -492,6 +533,9 @@ fn main() -> Result<(), Error> { } } } + if !map { + return Ok(()); + } let mut legend = BTreeMap::>::new(); let step = (size * 16 / 96).max(1); for bz in (0..size * 16).step_by(step as usize) { @@ -534,3 +578,75 @@ fn main() -> Result<(), Error> { ); Ok(()) } + +// Diagnostic only: full ordered chunk state, outside performance measurements. +fn snapshot(chunks: &[Option], path: &Path, phase: &str) -> Result<(), Error> { + use std::io::Write; + let mut out = + std::io::BufWriter::new(fs::File::create(format!("{}-{phase}.bin", path.display()))?); + for chunk in chunks.iter().flatten() { + let terrain = &chunk.terrain; + writeln!( + out, + "chunk {:?} {:?} {} {:?} {:?}", + chunk.position(), + terrain.generation_stage(), + chunk.is_decorated(), + chunk.structures(), + terrain.below_zero_retrogen().map(|v| v.to_nbt()) + )?; + for section in 0..terrain.height() as usize / 16 { + let data = terrain.section(section).unwrap(); + writeln!(out, "section {section} {:?}", data.to_nbt()?)?; + for index in 0..4096 { + out.write_all(&data.get(index)?.0.to_le_bytes())?; + } + } + // Compare public reads too, including all-air section behavior. + for y in terrain.min_y()..terrain.min_y() + terrain.height() { + for z in 0..16 { + for x in 0..16 { + out.write_all(&terrain.block(x, y, z).0.to_le_bytes())?; + } + } + } + for y in (terrain.min_y() >> 2)..((terrain.min_y() + terrain.height()) >> 2) { + for z in 0..4 { + for x in 0..4 { + writeln!( + out, + "biome {}", + chunk.biome_at( + chunk.position().x * 16 + x * 4, + y * 4, + chunk.position().z * 16 + z * 4 + ) + )?; + } + } + } + for kind in HeightmapType::ALL { + writeln!( + out, + "heightmap {kind:?} {:?}", + terrain.heightmap(kind).map(|m| m.raw_data()) + )?; + } + writeln!(out, "post {:?}", terrain.postprocessing())?; + writeln!(out, "blockticks {:?}", terrain.block_ticks().pack(0))?; + writeln!(out, "fluidticks {:?}", terrain.fluid_ticks().pack(0))?; + for (position, tag) in &chunk.block_entities { + writeln!(out, "blockentity {position:?}")?; + let bytes = + horizon_world::nbt::write_network(&Tag::Compound(tag.clone()), Default::default())?; + out.write_all(&(bytes.len() as u64).to_le_bytes())?; + out.write_all(&bytes)?; + } + let entities = Tag::List(chunk.entities.iter().cloned().map(Tag::Compound).collect()); + let bytes = horizon_world::nbt::write_network(&entities, Default::default())?; + out.write_all(&(bytes.len() as u64).to_le_bytes())?; + out.write_all(&bytes)?; + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-world/examples/level_place_fixture.rs b/crates/horizon-world/examples/level_place_fixture.rs index a8f00edd1..13595726d 100644 --- a/crates/horizon-world/examples/level_place_fixture.rs +++ b/crates/horizon-world/examples/level_place_fixture.rs @@ -20,6 +20,7 @@ struct Cells { cells: HashMap, air: BlockStateId, random: LegacyRandom, + obstructed: bool, } impl LevelAccess for Cells { fn block_state(&self, pos: BlockPos) -> BlockStateId { @@ -37,6 +38,9 @@ impl LevelAccess for Cells { fn game_time(&self) -> i64 { 0 } + fn is_unobstructed(&self, _pos: BlockPos, _state: BlockStateId) -> bool { + !self.obstructed + } } fn main() -> Result<(), Box> { @@ -68,6 +72,7 @@ fn main() -> Result<(), Box> { cells, air, random: LegacyRandom::new(case["seed"].as_i64().unwrap()), + obstructed: case["obstructed"].as_bool().unwrap_or(false), }; let mut ticks = Ticks::new(0); for x in -2..=2 { diff --git a/crates/horizon-world/src/worldgen/aquifer/noise_based.rs b/crates/horizon-world/src/worldgen/aquifer/noise_based.rs index 30181686b..3f3c7dc2c 100644 --- a/crates/horizon-world/src/worldgen/aquifer/noise_based.rs +++ b/crates/horizon-world/src/worldgen/aquifer/noise_based.rs @@ -120,6 +120,7 @@ pub struct NoiseBasedAquifer { statuses: Vec>, locations: Vec, surfaces: HashMap, + neighborhood: Option<([i32; 3], [(usize, BlockPos); 12])>, skip_above_y: i32, schedule: bool, } @@ -180,6 +181,7 @@ impl NoiseBasedAquif statuses, locations, surfaces: HashMap::new(), + neighborhood: None, skip_above_y: 0, schedule: false, }; @@ -479,48 +481,76 @@ impl NoiseBasedAquif y.wrapping_add(1).div_euclid(12), z.wrapping_sub(5) >> 4, ]; - let mut distances = [i32::MAX; 4]; - let mut indices = [0usize; 4]; - for dx in 0..=1i32 { - for dy in -1..=1i32 { - for dz in 0..=1i32 { - let cell = [ - grid[0].wrapping_add(dx), - grid[1].wrapping_add(dy), - grid[2].wrapping_add(dz), - ]; - let index = self.grid_index(cell)?; - if self.locations[index] == i64::MAX { - let mut random = self.random.at(BlockPos::new(cell[0], cell[1], cell[2])); - let px = cell[0] - .wrapping_shl(4) - .wrapping_add(random.next_int_bound(10).expect("positive bound")); - let py = cell[1] - .wrapping_mul(12) - .wrapping_add(random.next_int_bound(9).expect("positive bound")); - let pz = cell[2] - .wrapping_shl(4) - .wrapping_add(random.next_int_bound(10).expect("positive bound")); - self.locations[index] = BlockPos::new(px, py, pz).pack(); - } - let point = BlockPos::unpack(self.locations[index]); - let ax = point.x.wrapping_sub(x); - let ay = point.y.wrapping_sub(y); - let az = point.z.wrapping_sub(z); - let distance = ax - .wrapping_mul(ax) - .wrapping_add(ay.wrapping_mul(ay)) - .wrapping_add(az.wrapping_mul(az)); - if let Some(slot) = distances.iter().position(|old| distance <= *old) { - for i in (slot + 1..4).rev() { - distances[i] = distances[i - 1]; - indices[i] = indices[i - 1]; + // Fill in the original cell order, publishing only after checked traversal + // succeeds. Failed traversal keeps the last complete neighborhood. + if self.neighborhood.as_ref().map(|(key, _)| *key) != Some(grid) { + let mut entries = [(0, BlockPos::default()); 12]; + let mut next = 0; + for dx in 0..=1i32 { + for dy in -1..=1i32 { + for dz in 0..=1i32 { + let cell = [ + grid[0].wrapping_add(dx), + grid[1].wrapping_add(dy), + grid[2].wrapping_add(dz), + ]; + let index = self.grid_index(cell)?; + if self.locations[index] == i64::MAX { + let mut random = + self.random.at(BlockPos::new(cell[0], cell[1], cell[2])); + let px = cell[0] + .wrapping_shl(4) + .wrapping_add(random.next_int_bound(10).expect("positive bound")); + let py = cell[1] + .wrapping_mul(12) + .wrapping_add(random.next_int_bound(9).expect("positive bound")); + let pz = cell[2] + .wrapping_shl(4) + .wrapping_add(random.next_int_bound(10).expect("positive bound")); + self.locations[index] = BlockPos::new(px, py, pz).pack(); } - distances[slot] = distance; - indices[slot] = index; + entries[next] = (index, BlockPos::unpack(self.locations[index])); + next += 1; } } } + self.neighborhood = Some((grid, entries)); + } + let mut distances = [i32::MAX; 4]; + let mut indices = [0usize; 4]; + for &(index, point) in &self + .neighborhood + .as_ref() + .expect("populated neighborhood") + .1 + { + let ax = point.x.wrapping_sub(x); + let ay = point.y.wrapping_sub(y); + let az = point.z.wrapping_sub(z); + let distance = ax + .wrapping_mul(ax) + .wrapping_add(ay.wrapping_mul(ay)) + .wrapping_add(az.wrapping_mul(az)); + // Equal distances insert before existing entries, as in vanilla. + if distance <= distances[0] { + distances = [distance, distances[0], distances[1], distances[2]]; + indices = [index, indices[0], indices[1], indices[2]]; + } else if distance <= distances[1] { + distances[3] = distances[2]; + distances[2] = distances[1]; + distances[1] = distance; + indices[3] = indices[2]; + indices[2] = indices[1]; + indices[1] = index; + } else if distance <= distances[2] { + distances[3] = distances[2]; + distances[2] = distance; + indices[3] = indices[2]; + indices[2] = index; + } else if distance <= distances[3] { + distances[3] = distance; + indices[3] = index; + } } let a = self.status(context, indices[0])?; let s01 = similarity(distances[0], distances[1]); diff --git a/crates/horizon-world/src/worldgen/biome_temperature.rs b/crates/horizon-world/src/worldgen/biome_temperature.rs index c7e22c985..7111214f4 100644 --- a/crates/horizon-world/src/worldgen/biome_temperature.rs +++ b/crates/horizon-world/src/worldgen/biome_temperature.rs @@ -123,10 +123,12 @@ pub struct BiomeTemperature { } impl BiomeTemperature { pub fn new(settings: BiomeTemperatureSettings) -> Self { + // Empty until used: a decoration region makes one per biome, and + // most biomes never ask for a temperature. Self { settings, - values: HashMap::with_capacity(1024), - order: VecDeque::with_capacity(1024), + values: HashMap::new(), + order: VecDeque::new(), } } pub fn settings(&self) -> BiomeTemperatureSettings { diff --git a/crates/horizon-world/src/worldgen/climate/index.rs b/crates/horizon-world/src/worldgen/climate/index.rs index 3e9b50f51..6a602ed92 100644 --- a/crates/horizon-world/src/worldgen/climate/index.rs +++ b/crates/horizon-world/src/worldgen/climate/index.rs @@ -202,8 +202,11 @@ fn build( #[derive(Debug)] pub struct ClimateIndex { entries: Vec<(ParameterPoint, T)>, - nodes: Vec, - root: usize, + /// The built tree renumbered breadth first, root at 0, so each branch's + /// children are one contiguous run and a search walks memory in order. + spaces: Vec<[Parameter; 7]>, + /// Per node: its first child and child count, or its entry and 0 for a leaf. + links: Vec<(u32, u32)>, } impl ClimateIndex { pub fn new(entries: Vec<(ParameterPoint, T)>) -> Result { @@ -232,10 +235,25 @@ impl ClimateIndex { .collect(); let children = (0..nodes.len()).collect(); let root = build(&mut nodes, children, branching)?; + let mut order = vec![root]; + let mut links = Vec::with_capacity(nodes.len()); + let mut next = 0; + while next < order.len() { + let node = &nodes[order[next]]; + next += 1; + links.push(match &node.children { + Children::Leaf(entry) => (*entry as u32, 0), + Children::Branch(children) => { + let first = order.len() as u32; + order.extend_from_slice(children); + (first, children.len() as u32) + } + }); + } Ok(Self { entries, - nodes, - root, + spaces: order.iter().map(|id| nodes[*id].space).collect(), + links, }) } pub fn entries(&self) -> &[(ParameterPoint, T)] { @@ -263,18 +281,18 @@ impl ClimateIndex { } /// Preorder leaf entry indices expose stable tree layout for comparison. pub fn leaf_order(&self) -> Vec { - fn walk(nodes: &[Node], id: usize, out: &mut Vec) { - match &nodes[id].children { - Children::Leaf(entry) => out.push(*entry), - Children::Branch(children) => { - for child in children { - walk(nodes, *child, out); + fn walk(links: &[(u32, u32)], id: usize, out: &mut Vec) { + match links[id] { + (entry, 0) => out.push(entry as usize), + (first, count) => { + for child in first..first + count { + walk(links, child as usize, out); } } } } let mut result = Vec::with_capacity(self.entries.len()); - walk(&self.nodes, self.root, &mut result); + walk(&self.links, 0, &mut result); result } fn search( @@ -283,19 +301,20 @@ impl ClimateIndex { values: &[i64; 7], previous: Option, ) -> Result { - let Children::Branch(children) = &self.nodes[id].children else { + let (first, count) = self.links[id]; + if count == 0 { return Ok(id); - }; + } let mut best = previous; - let mut fitness = previous.map_or(i64::MAX, |id| distance(&self.nodes[id].space, values)); - for child in children { - let lower = distance(&self.nodes[*child].space, values); + let mut fitness = previous.map_or(i64::MAX, |id| distance(&self.spaces[id], values)); + for child in first as usize..(first + count) as usize { + let lower = distance(&self.spaces[child], values); if fitness > lower { - let result = self.search(*child, values, best)?; - let next = if result == *child { + let result = self.search(child, values, best)?; + let next = if result == child { lower } else { - distance(&self.nodes[result].space, values) + distance(&self.spaces[result], values) }; if fitness > next { fitness = next; @@ -313,13 +332,11 @@ pub struct ClimateSearch<'a, T> { } impl<'a, T> ClimateSearch<'a, T> { pub fn find(&mut self, target: TargetPoint) -> Result<&'a T, IndexError> { - let result = self - .index - .search(self.index.root, &target.parameters(), self.last)?; + let result = self.index.search(0, &target.parameters(), self.last)?; self.last = Some(result); - let Children::Leaf(entry) = self.index.nodes[result].children else { + let (entry, 0) = self.index.links[result] else { unreachable!("search returns a leaf"); }; - Ok(&self.index.entries[entry].1) + Ok(&self.index.entries[entry as usize].1) } } diff --git a/crates/horizon-world/src/worldgen/feature_region.rs b/crates/horizon-world/src/worldgen/feature_region.rs index 5ab361985..b4e8c07b0 100644 --- a/crates/horizon-world/src/worldgen/feature_region.rs +++ b/crates/horizon-world/src/worldgen/feature_region.rs @@ -22,7 +22,7 @@ use horizon_core::{ }, }; use std::{ - collections::{BTreeMap, BTreeSet}, + collections::{BTreeMap, BTreeSet, HashMap}, sync::Arc, }; @@ -58,7 +58,10 @@ impl From for PlacementQueryError { } } pub struct TerrainRegion<'r, B: TerrainBlockStates> { - chunks: BTreeMap<(i32, i32), TerrainChunk<'r, B>>, + /// Ordered by X then Z. + chunks: Vec>, + /// Each chunk's index in `chunks`: every block access looks one up. + index: ChunkIndex, min_y: i32, height: i32, generation: WorldGenerationContext, @@ -68,6 +71,77 @@ pub struct TerrainRegion<'r, B: TerrainBlockStates> { block_queries: Option, world_seed: Option, } +/// Where each chunk of a region sits in its list: a grid over the chunks' +/// bounding box while it is small (the usual square of neighbours), else a +/// map (chunks spread far apart). +enum ChunkIndex { + Grid { + origin: (i32, i32), + columns: i64, + rows: i64, + /// Row by row from `origin`; `u32::MAX` where no chunk is. + cells: Vec, + }, + Sparse(HashMap<(i32, i32), u32>), +} +impl ChunkIndex { + /// The largest grid, in chunk columns. + const GRID_CELLS: i64 = 1 << 20; + /// `None` when two chunks share a position. + fn new(positions: &[(i32, i32)]) -> Option { + let x0 = positions.iter().map(|p| p.0).min()?; + let z0 = positions.iter().map(|p| p.1).min()?; + let columns = i64::from(positions.iter().map(|p| p.0).max()?) - i64::from(x0) + 1; + let rows = i64::from(positions.iter().map(|p| p.1).max()?) - i64::from(z0) + 1; + if columns * rows > Self::GRID_CELLS { + let mut map = HashMap::with_capacity(positions.len()); + for (i, &p) in positions.iter().enumerate() { + if map.insert(p, i as u32).is_some() { + return None; + } + } + return Some(Self::Sparse(map)); + } + let mut cells = vec![u32::MAX; (columns * rows) as usize]; + for (i, &(x, z)) in positions.iter().enumerate() { + let cell = (i64::from(z) - i64::from(z0)) * columns + (i64::from(x) - i64::from(x0)); + let cell = &mut cells[cell as usize]; + if *cell != u32::MAX { + return None; + } + *cell = i as u32; + } + Some(Self::Grid { + origin: (x0, z0), + columns, + rows, + cells, + }) + } + fn get(&self, x: i32, z: i32) -> Option { + match self { + Self::Grid { + origin, + columns, + rows, + cells, + } => { + let (dx, dz) = ( + i64::from(x) - i64::from(origin.0), + i64::from(z) - i64::from(origin.1), + ); + if !(0..*columns).contains(&dx) || !(0..*rows).contains(&dz) { + return None; + } + match cells[(dz * columns + dx) as usize] { + u32::MAX => None, + i => Some(i as usize), + } + } + Self::Sparse(map) => map.get(&(x, z)).map(|&i| i as usize), + } + } +} impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { pub fn new( chunks: Vec>, @@ -83,15 +157,16 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { }) { return Err(RegionError::InvalidChunks); } - let mut stored = BTreeMap::new(); - for chunk in chunks { - let p = chunk.position(); - if stored.insert((p.x, p.z), chunk).is_some() { - return Err(RegionError::InvalidChunks); - } - } + let mut chunks = chunks; + chunks.sort_by_key(|c| (c.position().x, c.position().z)); + let positions: Vec<(i32, i32)> = chunks + .iter() + .map(|c| (c.position().x, c.position().z)) + .collect(); + let index = ChunkIndex::new(&positions).ok_or(RegionError::InvalidChunks)?; Ok(Self { - chunks: stored, + chunks, + index, sea_level: generator.sea_level, game_time: 0, next_tick_order: 0, @@ -114,10 +189,7 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { mut self, bindings: &super::block_feature::FeatureBlockBindings<'r>, ) -> Result { - if !std::ptr::eq( - self.chunks.first_key_value().unwrap().1.registry(), - bindings.registry(), - ) { + if !std::ptr::eq(self.chunks[0].registry(), bindings.registry()) { return Err(RegionError::InvalidBindings); } self.block_queries = Some(RegionBlockQueries { @@ -186,20 +258,25 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { } /// Release the resident chunks, ordered by X then Z; match them by position. pub fn into_chunks(self) -> Vec> { - self.chunks.into_values().collect() + self.chunks } pub fn chunks(&self) -> impl Iterator> { - self.chunks.values() + self.chunks.iter() + } + fn index(&self, x: i32, z: i32) -> Option { + self.index.get(x, z) } pub fn chunk(&self, x: i32, z: i32) -> Result<&TerrainChunk<'r, B>, RegionError> { - self.chunks - .get(&(x, z)) - .ok_or(RegionError::MissingChunk([x, z])) + match self.index(x, z) { + Some(i) => Ok(&self.chunks[i]), + None => Err(RegionError::MissingChunk([x, z])), + } } pub fn chunk_mut(&mut self, x: i32, z: i32) -> Result<&mut TerrainChunk<'r, B>, RegionError> { - self.chunks - .get_mut(&(x, z)) - .ok_or(RegionError::MissingChunk([x, z])) + match self.index(x, z) { + Some(i) => Ok(&mut self.chunks[i]), + None => Err(RegionError::MissingChunk([x, z])), + } } pub fn block(&self, [x, y, z]: [i32; 3]) -> Result { Ok(self.chunk(x >> 4, z >> 4)?.block(x, y, z)) @@ -302,12 +379,7 @@ impl PlacementContext for TerrainRegion<'_, B> { block: BlockStateId, delay: i32, ) -> Result<(), PlacementQueryError> { - let registry = self - .chunks - .first_key_value() - .expect("nonempty region") - .1 - .registry(); + let registry = self.chunks[0].registry(); let state = registry .state(block) .ok_or(RegionError::InvalidTickState(block))?; diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 2d7dd251c..fdba843b0 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -995,6 +995,46 @@ where worker.terrain_context = context; result } + /// With the native End source there are no badlands/iceberg extensions. + /// Disabled aquifers with air as their default fluid can only add lava or + /// air to the default solid, so this constant rule would rewrite each solid + /// with the state it already has. Check their imported material flags too. + /// Noise filling already built the WG maps; these writes add no fluid marks. + fn identity_end_surface(&self, pos: ChunkPos) -> bool { + if !matches!(self.source, ResolvedBiomeSource::End(_)) + // At wrapped block coordinates the ordinary biome-region lookup + // can fail; retain that lookup and its error outside this range. + || ![pos.x, pos.z].into_iter().all(|c| { + c.checked_mul(16).is_some_and(|b| { + b.checked_sub(16).is_some() && b.checked_add(31).is_some() + }) + }) + || self.aquifer.is_some() + || Some(self.settings.default_block) + != self.data.registry.default_state("minecraft:end_stone") + || Some(self.settings.default_fluid) + != self.data.registry.default_state("minecraft:air") + || !self.data.states.get(self.settings.default_fluid).air + || !self + .data + .registry + .default_state("minecraft:lava") + .is_some_and(|lava| self.data.states.get(lava).fluid) + { + return false; + } + let mut rule = &self.rule; + // Restrict the shortcut to shallow block references; other rules still + // run their normal compilation, queries and error handling. + for _ in 0..32 { + match rule { + MaterialRule::Reference(next) => rule = next, + MaterialRule::Block(state) => return *state == self.settings.default_block, + _ => return false, + } + } + false + } fn generate_with_context( &self, worker: &mut WorkerState, @@ -1103,27 +1143,29 @@ where .map_err(stage("noise"))?; let generation = self.generation(); worker.timings.noise += lap(&mut clock); - build_surface( - &mut chunk, - self.rule.clone(), - SurfaceInputs:: { - generation, - noise_volume: volume, - root: self.root.clone(), - surface: SurfaceQueries { - pipeline: self, - temperatures: &mut worker.temperatures, - biome: Biomes::Region(&biomes), - possible: Some(possible), + if !self.identity_end_surface(pos) { + build_surface( + &mut chunk, + self.rule.clone(), + SurfaceInputs:: { + generation, + noise_volume: volume, + root: self.root.clone(), + surface: SurfaceQueries { + pipeline: self, + temperatures: &mut worker.temperatures, + biome: Biomes::Region(&biomes), + possible: Some(possible), + }, + preliminary_surface: self.preliminary.clone(), + density_context: context, + write_min_y: min, + write_max_y: min + height - 1, }, - preliminary_surface: self.preliminary.clone(), - density_context: context, - write_min_y: min, - write_max_y: min + height - 1, - }, - &self.extensions, - ) - .map_err(stage("surface"))?; + &self.extensions, + ) + .map_err(stage("surface"))?; + } worker.timings.surface += lap(&mut clock); let carvers = &data.biome_carvers; let mask = generate_carving_mask(self.seed, pos, generation, false, |origin| { @@ -2407,6 +2449,108 @@ impl GeneratorWorker { #[cfg(test)] mod tests { use super::*; + #[test] + fn end_identity_surface_matches_normal_surface_and_rejects_custom_rules() { + let root = std::env::var_os("HORIZON_TEST_RESOURCES") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3") + }); + if !root.join("worldgen/world_presets.json").exists() { + eprintln!("skipping: no worldgen bundle at {}", root.display()); + return; + } + let registry = Box::leak(Box::new(crate::level::data::load_registry(&root).unwrap())); + let data = GeneratorData::load(&root.join("worldgen"), registry).unwrap(); + let preset: Value = serde_json::from_str(&data.world_presets["minecraft:normal"]).unwrap(); + let settings: Value = serde_json::from_str(&data.settings["minecraft:end"]).unwrap(); + let mut pipeline = Pipeline::new( + data.clone(), + 12345, + LegacyRandom::new(12345), + &preset["dimensions"]["minecraft:the_end"]["generator"], + &settings, + false, + None, + ) + .unwrap(); + let mut worker = OverworldGenerator::for_world( + data.clone(), + 12345, + "minecraft:normal", + "minecraft:the_end", + false, + ) + .unwrap() + .worker(); + assert!(pipeline.identity_end_surface(ChunkPos::new(0, 0))); + for pos in [ + ChunkPos::new(0, 0), + ChunkPos::new(128, 128), + ChunkPos::new(-128, 192), + ChunkPos::new(1_875_000, -1_875_000), + ] { + let actual = pipeline.generate(&mut worker.state, pos).unwrap(); + let rule = pipeline.rule.clone(); + // A singleton sequence evaluates the same block rule through the full surface path. + pipeline.rule = MaterialRule::Sequence(vec![rule.clone()]); + assert!(!pipeline.identity_end_surface(ChunkPos::new(0, 0))); + let expected = pipeline.generate(&mut worker.state, pos).unwrap(); + pipeline.rule = rule; + assert_eq!( + actual.terrain.generation_stage(), + expected.terrain.generation_stage() + ); + for section in 0..actual.terrain.height() as usize / 16 { + assert_eq!( + actual.terrain.section(section).unwrap().to_nbt().unwrap(), + expected.terrain.section(section).unwrap().to_nbt().unwrap() + ); + } + for kind in HeightmapType::ALL { + assert_eq!( + actual.terrain.heightmap(kind).map(|m| m.raw_data()), + expected.terrain.heightmap(kind).map(|m| m.raw_data()) + ); + } + assert_eq!( + actual.terrain.postprocessing(), + expected.terrain.postprocessing() + ); + assert_eq!( + actual.terrain.block_ticks().pack(0), + expected.terrain.block_ticks().pack(0) + ); + assert_eq!( + actual.terrain.fluid_ticks().pack(0), + expected.terrain.fluid_ticks().pack(0) + ); + assert_eq!(actual.block_entities, expected.block_entities); + assert_eq!(actual.entities, expected.entities); + assert_eq!(actual.structures(), expected.structures()); + } + assert!(!pipeline.identity_end_surface(ChunkPos::new(i32::MAX, 0))); + let old_rule = pipeline.rule.clone(); + pipeline.rule = MaterialRule::Block(registry.default_state("minecraft:stone").unwrap()); + assert!(!pipeline.identity_end_surface(ChunkPos::new(0, 0))); + pipeline.rule = old_rule; + let old_fluid = pipeline.settings.default_fluid; + pipeline.settings.default_fluid = registry.default_state("minecraft:stone").unwrap(); + assert!(!pipeline.identity_end_surface(ChunkPos::new(0, 0))); + pipeline.settings.default_fluid = old_fluid; + let old_source = std::mem::replace( + &mut pipeline.source, + ResolvedBiomeSource::Fixed(super::super::biome_source::FixedBiomeSource { + biome: "minecraft:the_end".into(), + }), + ); + assert!(!pipeline.identity_end_surface(ChunkPos::new(0, 0))); + pipeline.source = old_source; + pipeline.aquifer = Some(std::array::from_fn(|_| { + pipeline.router.get(RouterField::Erosion).clone() + })); + assert!(!pipeline.identity_end_surface(ChunkPos::new(0, 0))); + } #[test] fn far_surface_matches_undecorated_land_and_keeps_end_void() { diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs index 1284d0054..fc1cd8bcf 100644 --- a/crates/horizon-world/src/worldgen/generator_decoration.rs +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -1129,4 +1129,41 @@ impl PlacementContext for World<'_> { fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result { self.region.height(kind, x, z) } + /// OreFeature's search for a column under its blob, without a trait call + /// per column. Defers to `height` when a heightmap still has to be primed. + fn any_height_at_least( + &mut self, + kind: HeightmapType, + [x0, z0]: [i32; 2], + size: i32, + y: i32, + ) -> Result, PlacementQueryError> { + let (x1, z1) = (x0.wrapping_add(size), z0.wrapping_add(size)); + if size < 0 || x1 < x0 || z1 < z0 { + return Ok(None); + } + for cx in x0 >> 4..=x1 >> 4 { + for cz in z0 >> 4..=z1 >> 4 { + if !self + .region + .chunk(cx, cz) + .is_ok_and(|c| c.heightmap(kind).is_some()) + { + return Ok(None); + } + } + } + for x in x0..=x1 { + for z in z0..=z1 { + let map = self.region.chunk(x >> 4, z >> 4)?.heightmap(kind).unwrap(); + let floor = map + .first_available(x & 15, z & 15) + .map_err(|e| RegionError::from(super::terrain::TerrainError::from(e)))?; + if y <= floor { + return Ok(Some(true)); + } + } + } + Ok(Some(false)) + } } diff --git a/crates/horizon-world/src/worldgen/ore_feature.rs b/crates/horizon-world/src/worldgen/ore_feature.rs index 9d723ae40..d69874d76 100644 --- a/crates/horizon-world/src/worldgen/ore_feature.rs +++ b/crates/horizon-world/src/worldgen/ore_feature.rs @@ -180,6 +180,27 @@ impl OreFeature { let z_start = origin[2].wrapping_sub(spread_ceil).wrapping_sub(max_radius); let size_xz = 2 * (spread_ceil + max_radius); let size_y = 2 * (2 + max_radius); + if let Some(found) = world + .any_height_at_least( + HeightmapType::OceanFloorWg, + [x_start, z_start], + size_xz, + y_start, + ) + .map_err(FeatureExecutionError::Query)? + { + return match found { + true => self.do_place( + world, + random, + [x0, x1, z0, z1, y0, y1], + [x_start, y_start, z_start], + size_xz, + size_y, + ), + false => Ok(false), + }; + } for x in 0..=size_xz { for z in 0..=size_xz { let (px, pz) = (x_start.wrapping_add(x), z_start.wrapping_add(z)); @@ -243,7 +264,8 @@ impl OreFeature { } } } - let mut tested = vec![false; (size_xz as usize) * (size_y as usize) * (size_xz as usize)]; + let tested_len = (size_xz as usize) * (size_y as usize) * (size_xz as usize); + let mut tested = vec![0u64; tested_len.div_ceil(64)]; let mut placed = 0; for [xx, yy, zz, r] in data { if r < 0.0 { @@ -280,16 +302,15 @@ impl OreFeature { * i64::from(size_xz) * i64::from(size_y); // The sphere bounds keep indices inside the native BitSet. - let Some(bit) = usize::try_from(index) - .ok() - .and_then(|index| tested.get_mut(index)) + let Some(index) = usize::try_from(index).ok().filter(|&i| i < tested_len) else { return Err(FeatureExecutionError::WorkLimit); }; - if *bit { + let (word, bit) = (&mut tested[index / 64], 1u64 << (index % 64)); + if *word & bit != 0 { continue; } - *bit = true; + *word |= bit; let p = [x, y, z]; if !world .ensure_can_write(p) diff --git a/crates/horizon-world/src/worldgen/placement/context.rs b/crates/horizon-world/src/worldgen/placement/context.rs index 96a5df130..654ff849c 100644 --- a/crates/horizon-world/src/worldgen/placement/context.rs +++ b/crates/horizon-world/src/worldgen/placement/context.rs @@ -351,6 +351,18 @@ pub trait PlacementContext { /// World minimum, which can differ from the generator's minimum. fn min_y(&mut self) -> Result; fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result; + /// Whether any column of the square `x..=x + size`, `z..=z + size` has + /// `height(kind)` at least `y`, read faster than column by column; `None` + /// when the world can't (callers then ask `height` for each column). + fn any_height_at_least( + &mut self, + _kind: HeightmapType, + _corner: [i32; 2], + _size: i32, + _y: i32, + ) -> Result, PlacementQueryError> { + Ok(None) + } } impl PlacementContext for WorldGenerationContext { fn max_y(&mut self) -> Result { diff --git a/crates/horizon-world/tests/feature_region.rs b/crates/horizon-world/tests/feature_region.rs index c484393bf..7ff34da6f 100644 --- a/crates/horizon-world/tests/feature_region.rs +++ b/crates/horizon-world/tests/feature_region.rs @@ -385,3 +385,46 @@ fn retained_upgrade_status_allows_old_biome_reads() { } } } +#[test] +fn spread_out_regions_route_like_dense_ones() { + // Chunks too far apart for a grid over their bounding box (fixtures put + // one at the far edge of the world beside the origin's neighbours). + let registry = registry(); + let context = WorldGenerationContext::new(0, 16, 8); + let chunk = + |x, z| TerrainChunk::new(ChunkPos::new(x, z), 0, 16, ®istry, Properties).unwrap(); + for far in [4_194_304, -4_194_304] { + let mut region = TerrainRegion::new( + vec![chunk(0, 0), chunk(far, 0), chunk(1, -1), chunk(-1, 1)], + context, + ) + .unwrap(); + let x = far * 16 + 3; + region + .set_block_worldgen([x, 7, 5], BlockStateId(2)) + .unwrap(); + assert_eq!(region.block([x, 7, 5]).unwrap(), BlockStateId(2)); + assert_eq!(region.block([3, 7, 5]).unwrap(), BlockStateId(0)); + assert_eq!(region.block([16, 7, -1]).unwrap(), BlockStateId(0)); + assert!(matches!( + region.block([x + 16, 7, 5]), + Err(RegionError::MissingChunk([_, 0])) + )); + assert!(matches!( + region.block([0, 7, 16]), + Err(RegionError::MissingChunk([0, 1])) + )); + let order: Vec<_> = region + .into_chunks() + .iter() + .map(|c| (c.position().x, c.position().z)) + .collect(); + let mut sorted = order.clone(); + sorted.sort(); + assert_eq!(order, sorted, "into_chunks is ordered by X then Z"); + // A position twice is refused either way. + assert!( + TerrainRegion::new(vec![chunk(0, 0), chunk(far, 0), chunk(far, 0)], context).is_err() + ); + } +} diff --git a/docs/media/command-suggestions/after.png b/docs/media/command-suggestions/after.png new file mode 100644 index 000000000..9c1a9cd4c Binary files /dev/null and b/docs/media/command-suggestions/after.png differ diff --git a/docs/media/command-suggestions/before.png b/docs/media/command-suggestions/before.png new file mode 100644 index 000000000..66c3925c4 Binary files /dev/null and b/docs/media/command-suggestions/before.png differ diff --git a/docs/microsoft-account.md b/docs/microsoft-account.md index 61b402211..380aa0785 100644 --- a/docs/microsoft-account.md +++ b/docs/microsoft-account.md @@ -7,7 +7,7 @@ they are. This note is the design, the status of each part and what Ludovic has ## What Ludovic registers (needs his accounts) Nothing below can be done by an agent: the app registrations belong to Ludovic. Until the client ID -is set, the launcher's sign-in shows "Microsoft sign-in is not configured yet" and everything else +is set, the launcher's sign-in shows "Coming soon" ("Microsoft sign-in is coming soon") and everything else works as before. 1. **Azure app registration** (https://portal.azure.com → Microsoft Entra ID → App registrations → diff --git a/docs/release-flow.md b/docs/release-flow.md index 52a9d5596..6cc4bcd3c 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -2,9 +2,9 @@ How a change gets from a pull request to players: the checks a pull request passes, how it merges, and the automatic releases that follow. Releases are automatic and frequent so the latest Horizon is always playable. -Each one goes out as a **beta**, which launchers on the **Nightly** channel install at once, and becomes **stable** in +Each one goes out as an **alpha** build, which launchers on the **Alpha** channel install at once, and becomes **stable** in the next daily promotion unless something holds it back ([Channels](#channels)): launchers and servers install -stable builds unless their owner picks Nightly. +stable builds unless their owner picks Alpha. ## Pull request checks @@ -101,8 +101,8 @@ flowchart LR windows["Windows x64
GitHub windows-latest"] mac["macOS arm64
Mac mini runner
+ offscreen game run"] end - build --> publish["publish vX.Y.Z as a beta
notes from the merged PRs"] - publish --> beta(["launchers on Nightly install it"]) + build --> publish["publish vX.Y.Z as an alpha
notes from the merged PRs"] + publish --> alpha(["launchers on Alpha install it"]) publish --> promote{"promote.yml, daily at 20:00 UTC:
6 h old by then, smoke test, no release-blocker"} promote --> stable["stable and latest
notes since the last stable"] stable --> launcher(["every launcher and server installs it"]) @@ -121,7 +121,7 @@ commits) since the last **published** game release: - It releases when at least one pull request counts and the newest of them merged at least 5 minutes ago, so a wave of merges becomes one release; if merges never pause, it releases once the oldest has waited 20 minutes. There is no minimum time between releases: every settled player-facing change ships, limited only by the release already - building. That is the Nightly channel, many releases a day. + building. That is the Alpha channel, many releases a day. - A pull request labelled `release-now` (a crash or a blocker) releases at once. - A pull request labelled `skip-release` (work players don't see) doesn't count and isn't listed in the notes. - One release at a time (concurrency group `game-release`); a run that finds nothing new does nothing. @@ -180,21 +180,26 @@ runs the game: GitHub's runners have neither a GPU worth the name nor the game f - `### Known issues`: the bullets of [docs/known-issues.md](known-issues.md); - thanks to outside contributors, how to install, the disclaimer. -Kira posts every published release in #releases and pings the releases role only when the notes have a -`### New` section. +Kira posts every release in Discord's #releases. An Alpha build (a game pre-release) is posted silently: no ping and +Discord's @silent flag, so nobody gets a notification. When the same release becomes Stable it is posted again, and +that post pings the releases role when the notes have a `### New` section (at most once every 6 hours). Launcher +releases post without a ping. ### Channels -Every game release is published as a **beta**, a GitHub pre-release, so GitHub's *latest* release stays the last +Every game release is published as an **alpha** build, a GitHub pre-release (the workflows, tools and labels +call it a *beta*: `release-blocker` holds every beta), so GitHub's *latest* release stays the last **stable** one. The launcher's Settings has an **Updates** choice of two channels (`update_channel` in its `settings.json`, `horizon-launcher update-channel`): -- **Stable**, the default: a tested build about once a day, the betas promoted below. -- **Nightly**: every beta as soon as it is built, many times a day; it can break. "Nightly" is a name, not a - schedule. An open launcher looks for releases every 30 minutes on Nightly (4 hours on Stable). Launchers from before 0.2 had a "Beta builds" switch instead; on, it reads as Nightly. +- **Stable**, the default: a tested build about once a day, the alpha builds promoted below. +- **Alpha**: every alpha build as soon as it is built, many times a day; it can break. "Alpha" is the project's + word for builds that are still being tested (the whole of Horizon is in beta); Stable is the tested ones. An open + launcher looks for releases every 30 minutes on Alpha (4 hours on Stable). Launchers from before 0.2 had a "Beta + builds" switch instead; on, it reads as Alpha. -`horizon-server update` installs stable builds (`--version ` takes one by name), and Kira announces a release -when it becomes stable: Discord's #releases only ever shows stable ones. +`horizon-server update` installs stable builds (`--version ` takes an alpha build by name). In Discord's #releases every +Alpha is posted silently and only Stable posts notify (above). `.github/workflows/promote.yml` runs `tools/release_channels.py promote` once a day at 20:00 UTC (21:00 in Paris in winter time, 22:00 in summer), with retries until 21:37 for a run GitHub starts late or skips. It promotes the newest @@ -229,7 +234,7 @@ gh workflow run promote -f tag=v0.2.3 -f force=true # even blocked or without gh workflow run promote -f dry_run=true # what would be promoted now ``` -A beta's notes cover only what changed since the release before it (beta or stable), and say it is a nightly build. +An alpha build's notes cover only what changed since the release before it (alpha or stable), and say it is an alpha build. `release_train.py decide` counts pull requests from the newest release of either channel, so betas don't release the same changes again. diff --git a/docs/security.md b/docs/security.md index d61198ec2..175e5d21d 100644 --- a/docs/security.md +++ b/docs/security.md @@ -38,7 +38,7 @@ and some are waiting for Ludovic: | Private vulnerability reporting | **Live** (see the end of this page). | | Signed checksums on releases | **Live** for new releases (#1011): the `release` environment holds the key, and its public half is in `release-keys.txt` (#1023). Releases from before then are unsigned. | | Launchers and servers checking signatures | **Not yet**: #1014 waits as a draft until a signed stable game release and a signed launcher release exist. Until then they trust GitHub's checksum, as before. | -| Beta, then stable | **Live** (#1012): every release is first a beta. The launcher's Updates setting picks Stable (the default) or Nightly (the betas). | +| Alpha, then stable | **Live** (#1012): every release is first an alpha build. The launcher's Updates setting picks Stable (the default) or Alpha (the pre-releases). | | Reports marked suspicious | **Partly**: the scan of Discord for agents does it. Kira's issues do it once its pull request merges. | | Code owners' review of the pipeline | **Not yet**: `.github/CODEOWNERS` and its protection (#1015) wait for the App, below. Until then pipeline changes merge like any other once `verify` passes. | | Agents on their own GitHub App | **Not yet**: prepared, waiting for Ludovic to create it. Agents still use his account. | @@ -53,11 +53,11 @@ and some are waiting for Ludovic: - **`verify` always runs.** Labels no longer start the checks, and the required `verify` job has no condition, so the only `verify` a change can have is one that ran. Main requires it, from GitHub Actions only, for everyone, admins included. -- **Beta, then stable.** Every release is first a **beta**. It becomes **stable**, the version launchers and +- **Alpha, then stable.** Every release is first an **alpha** build (a GitHub pre-release). It becomes **stable**, the version launchers and servers install by themselves, in the daily promotion (20:00 UTC), only after it has been out 6 hours and passed its smoke test (the game started and drew a world on the Mac mini), and only while no issue labelled `release-blocker` is open. If a beta misses a promotion it was due for, an issue says so. Players who want the newest builds at once - pick **Nightly** under Updates in the launcher's Settings. Discord announces stable releases only. + pick **Alpha** under Updates in the launcher's Settings. Discord announces stable releases only. - **Signed updates.** Each release carries a list of its files' checksums, signed with Horizon's release key. The launcher (for the game and for itself) and `horizon-server update` check that signature against the public key built into them, then check the download against the list. Anything unsigned, signed with another key, signed diff --git a/docs/versioning.md b/docs/versioning.md index 4481e72f6..6032b54a1 100644 --- a/docs/versioning.md +++ b/docs/versioning.md @@ -22,8 +22,8 @@ game and the launcher of the 0.2 line. 0.2. A `feature` label no longer bumps anything: it only lists the change under **New**. - **Patch releases** are every release the train makes: the patch after the newest release tagged on the line, game and launcher counted separately (the game releases more often, so `v0.2.14` can go with `launcher@0.2.3`). -- **Betas** are not separate tags. As before, every game release is published as a GitHub pre-release (a beta, what - the launcher's Nightly channel installs) under its final tag and promoted in place to stable in the daily +- **Alpha builds** are not separate tags. As before, every game release is published as a GitHub pre-release (an alpha build, what + the launcher's Alpha channel installs) under its final tag and promoted in place to stable in the daily promotion at 20:00 UTC, once it has been out 6 hours ([Channels](release-flow.md#channels)). `v0.2.4` is the same build whether it is still a beta or already stable. - **Pre-release tags** (`v0.3.0-rc.1`, `v0.3.0-beta.2`) are semver's and are reserved for a hand-made preview of a @@ -126,7 +126,7 @@ Run by the orchestrator, in this order. Until step 3, nothing is published. makes it *latest*. Do not force it (`promote` with `force=true`): it carries about 43 player-facing pull requests from the freeze and needs its beta like any release. Check it is *latest*: `gh api repos/ludovic111/horizon/releases/latest --jq .tag_name`. -5. Only then merge the update channels pull request (the launcher's Stable and Nightly, the daily promotion), then +5. Only then merge the update channels pull request (the launcher's Stable and Alpha, the daily promotion), then mark the switch pull request (#1132) ready and merge it (`.github/release-line.txt` = `0.2`, and the docs that talk about 0.2). On the next run, about 10 minutes, the train publishes `v0.2.0` as a beta and `launcher@0.2.0`, both "the first release of 0.2", built from the same code as the bridges plus that pull request. diff --git a/launcher/README.md b/launcher/README.md index c1935c7cf..08ec11f98 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -83,11 +83,11 @@ page `servers.json` (the list), `servers//` (the servers created there) an the game's menu style, the game's extra command-line arguments, and the launcher's own version and update state. - **Updates**: **Stable** (the default) installs a tested build about once a day, the betas that - `promote.yml` makes stable; **Nightly** installs every release as soon as it is built, several + `promote.yml` makes stable; **Alpha** installs every release as soon as it is built, several times a day, and can break (docs/release-flow.md, "Channels"). While it is open, the launcher - looks for new releases every 4 hours on Stable and every 30 minutes on Nightly. Kept as `update_channel` in - `settings.json`; a `beta_builds: true` from launchers before 0.2 reads as Nightly. - `horizon-launcher update-channel [stable|nightly]` shows or sets it. The **Versions** page + looks for new releases every 4 hours on Stable and every 30 minutes on Alpha. Kept as `update_channel` in + `settings.json`; a `beta_builds: true` from launchers before 0.2 reads as Alpha (so does a `nightly` from the channel's first name). + `horizon-launcher update-channel [stable|alpha]` shows or sets it. The **Versions** page shows each release's channel. The launcher's own updates don't depend on it. - **Game arguments**: extra arguments added to the game's command line (for example `--server-thread`), one line where quotes group a word with spaces. They are appended after the @@ -140,7 +140,7 @@ The same binary is a command-line tool; without a subcommand it opens the window horizon-launcher notes [] patch notes as plain text horizon-launcher links the Discord, sponsor and website links horizon-launcher menu-style [horizon|classic] show or set the game's menu style - horizon-launcher update-channel [stable|nightly] show or set which releases install by themselves + horizon-launcher update-channel [stable|alpha] show or set which releases install by themselves horizon-launcher game-args [] show or set the extra arguments the game starts with horizon-launcher update [--check] Horizon and the launcher horizon-launcher logs [--lines N] [--crash] the end of the game's log, or its newest crash report diff --git a/launcher/src/account.rs b/launcher/src/account.rs index 44fa96cb6..8958fb3d4 100644 --- a/launcher/src/account.rs +++ b/launcher/src/account.rs @@ -16,7 +16,8 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; pub const SERVICE: &str = "dev.playhorizon.launcher"; const SCOPE: &str = "XboxLive.signin offline_access"; pub const NOT_CONFIGURED: &str = - "Microsoft sign-in is not configured yet in this build of the launcher (no client ID)."; + "Microsoft sign-in is coming soon. Until then the game plays offline: single player, \ + LAN and servers in offline mode work."; const SIGN_IN_AGAIN: &str = "Your Microsoft sign-in expired. Sign in again."; /// The Minecraft token is renewed when it has less than this left. const RENEW_BEFORE: u64 = 3600; diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index ba854730f..81c38f933 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -346,7 +346,7 @@ pub fn latest(releases: &[Release]) -> Option<&Release> { releases.iter().find(|r| r.asset.is_some()) } -/// The releases a launcher installs by itself: stable ones, and betas too on the Nightly channel. +/// The releases a launcher installs by itself: stable ones, and betas too on the Alpha channel. pub fn channel(releases: &[Release], channel: UpdateChannel) -> Vec { releases .iter() @@ -362,15 +362,17 @@ pub enum UpdateChannel { /// A tested build about once a day: the betas promote.yml makes stable. #[default] Stable, - /// Every release as soon as it is built, betas included. - Nightly, + /// Every release as soon as it is built, pre-releases included. It was called "nightly" + /// while the channels were new: that name is still read. + #[serde(alias = "nightly")] + Alpha, } impl UpdateChannel { pub fn name(self) -> &'static str { match self { UpdateChannel::Stable => "stable", - UpdateChannel::Nightly => "nightly", + UpdateChannel::Alpha => "alpha", } } @@ -378,36 +380,36 @@ impl UpdateChannel { pub fn label(self) -> &'static str { match self { UpdateChannel::Stable => "Stable", - UpdateChannel::Nightly => "Nightly", + UpdateChannel::Alpha => "Alpha", } } pub fn parse(name: &str) -> Option { match name { "stable" => Some(UpdateChannel::Stable), - "nightly" => Some(UpdateChannel::Nightly), + "alpha" | "nightly" => Some(UpdateChannel::Alpha), _ => None, } } - /// Whether this channel installs `release`: betas only reach Nightly. + /// Whether this channel installs `release`: betas only reach Alpha. pub fn takes(self, release: &Release) -> bool { - self == UpdateChannel::Nightly || !release.beta + self == UpdateChannel::Alpha || !release.beta } - /// How often a launcher left open looks for new releases: Nightly's come many times a day, + /// How often a launcher left open looks for new releases: Alpha's come many times a day, /// Stable's once. pub fn check_every(self) -> std::time::Duration { std::time::Duration::from_secs(match self { UpdateChannel::Stable => 4 * 3600, - UpdateChannel::Nightly => 30 * 60, + UpdateChannel::Alpha => 30 * 60, }) } - /// The channel a release is on when it is listed: betas are Nightly's only. + /// The channel a release is on when it is listed: betas are Alpha's only. pub fn of(release: &Release) -> Self { if release.beta { - UpdateChannel::Nightly + UpdateChannel::Alpha } else { UpdateChannel::Stable } @@ -993,6 +995,78 @@ fn download_for_owner( } } +/// A JDK of at least `major` for the preparation. `None` when horizon-prepare finds one by +/// itself (JAVA_HOME, the PATH, an installed JDK): the preparation then runs as before, in an +/// unchanged environment (a JDK found on the PATH can be a stub such as macOS's +/// /usr/bin/javac, whose folder is no Java home: `JAVA_HOME=/usr` makes it call itself +/// forever). Else the home of the Java the official launcher downloaded into one of the +/// `games` folders, else of Minecraft's own Java downloaded from Mojang into Horizon's game +/// folder, the runtime the version JSON at `manifest` names (Mojang's runtimes are whole JDKs). +fn java( + major: i64, + games: &[PathBuf], + manifest: &Path, + log: &dyn Fn(String), +) -> Result, String> { + if horizon_prepare::java::find(major, &[]).is_ok() { + return Ok(None); + } + let mut runtimes: Vec = Vec::new(); + for home in games + .iter() + .flat_map(|game| horizon_prepare::java::minecraft_runtimes(&game.join("runtime"))) + { + if !runtimes.contains(&home) { + runtimes.push(home); + } + } + let missing = match horizon_prepare::java::find(major, &runtimes) { + Ok(jdk) => return Ok(Some(jdk.home())), + Err(e) => e, + }; + let component = read_json(manifest) + .and_then(|json| json["javaVersion"]["component"].as_str().map(String::from)) + .ok_or_else(|| missing.clone())?; + // Mojang builds its Linux Java for glibc: without glibc's loader (NixOS without nix-ld, + // musl distributions) it cannot start, so don't download it. + if cfg!(all(target_os = "linux", target_arch = "x86_64")) && !Path::new(GLIBC_LOADER).exists() { + return Err(format!( + "{missing}\n • Minecraft's own Java from Mojang needs glibc ({GLIBC_LOADER} is missing; on NixOS, enable programs.nix-ld), so install a JDK instead." + )); + } + let fetch = |url: &str| -> Result, String> { + let mut body = Vec::new(); + get(url)? + .into_reader() + .read_to_end(&mut body) + .map_err(|e| e.to_string())?; + Ok(body) + }; + let runtime = data_dir().join("minecraft").join("runtime"); + let home = mojang::java_runtime(&component, &runtime, 8, &fetch, log).map_err(|e| { + format!("{missing}\n • Horizon also tried to download Minecraft's own Java from Mojang, but: {e}") + })?; + horizon_prepare::java::find(major, &[home]).map(|jdk| Some(jdk.home())) +} + +/// The dynamic loader glibc programs on x86-64 Linux start through. +const GLIBC_LOADER: &str = "/lib64/ld-linux-x86-64.so.2"; + +/// Runs `cmd` with the JDK at `home`: JAVA_HOME names it and its `bin` leads the PATH, as the +/// versions' own preparers look for Java. +fn with_java(cmd: &mut Command, home: &Path) { + let mut path = vec![home.join("bin")]; + path.extend( + std::env::var_os("PATH") + .iter() + .flat_map(std::env::split_paths), + ); + cmd.env("JAVA_HOME", home); + if let Ok(path) = std::env::join_paths(path) { + cmd.env("PATH", path); + } +} + /// Checks what the preparation needs and picks how to run it. PLAY.txt describes the same /// steps: the player's own launcher install, the server jar from that version's own json, and /// Java (and Python, for versions before horizon-prepare). Also returns the Minecraft folder @@ -1006,6 +1080,7 @@ pub fn preparer( let version = game_version(tag); let dir = version_dir(tag); let reused = horizon_prepare::artifacts::reuse_imported(&dir, &|line| log(line.to_string()))?; + let chosen = minecraft.to_path_buf(); let minecraft = if reused { minecraft.to_path_buf() } else { @@ -1042,25 +1117,27 @@ pub fn preparer( .join(&version) .join(format!("{version}.json")); let binary = preparer_binary(&dir); - let python = if binary.is_some() { - // The JDK the version pins, found as horizon-prepare finds it, so a missing one is - // reported before the server jar is downloaded. - let major = read_json(&dir.join("research-lock.json")) - .and_then(|lock| lock["minecraft"]["java_major"].as_i64()) - .ok_or("The version's research-lock.json has no java_major")?; - horizon_prepare::java::find(major)?; - None - } else { - let python = python() - .ok_or("This version prepares with Python: Python 3.10 or newer is needed. Install it, or pick a newer version.")?; - if !found("java", "-version") { - return Err( - "Java 25 is needed (a JDK, e.g. Eclipse Temurin 25). Install it and try again." - .into(), - ); - } - Some(python) + let python = match binary { + Some(_) => None, + None => Some(python().ok_or( + "This version prepares with Python: Python 3.10 or newer is needed. Install it, or pick a newer version.", + )?), }; + // The JDK the version pins, found as horizon-prepare finds it, so a missing one is + // reported (or downloaded) before the server jar is downloaded. Versions from before + // java_major ran Java 25. + let major = read_json(&dir.join("research-lock.json")) + .and_then(|lock| lock["minecraft"]["java_major"].as_i64()) + .unwrap_or(25); + let mut games = vec![chosen, minecraft.clone(), data_dir().join("minecraft")]; + games.extend( + sources::Folders::current() + .map(|f| sources::known_folders(sources::Os::current(), &f)) + .unwrap_or_default() + .into_iter() + .map(|(_, dir)| dir), + ); + let java_home = java(major, &games, &manifest, log)?; let jar = data_dir() .join("server-jars") .join(format!("{version}.jar")); @@ -1092,10 +1169,14 @@ pub fn preparer( import: !reused, minecraft_dir: Some(minecraft.clone()), server_jar: (!reused).then_some(jar), + java_home: java_home.clone(), }; return Ok((Preparer::InProcess(options), minecraft)); } let mut cmd = Command::new(binary); + if let Some(home) = &java_home { + with_java(&mut cmd, home); + } cmd.current_dir(&dir).arg("--root").arg(&dir); if !reused { cmd.args(["--prepare", "--server-jar"]).arg(&jar); @@ -1104,6 +1185,9 @@ pub fn preparer( return Ok((Preparer::Process(cmd), minecraft)); } let mut cmd = Command::new(python.unwrap()); + if let Some(home) = &java_home { + with_java(&mut cmd, home); + } cmd.current_dir(&dir) .args(["-u", "tools/prepare_native_client.py"]); if !reused { @@ -2214,7 +2298,7 @@ pub struct Settings { #[serde(default, skip_serializing_if = "String::is_empty")] pub game_args: String, /// Which releases install by themselves: Stable by default. Launchers before 0.2 had a "Beta - /// builds" switch instead; [`Settings::parse`] reads its `beta_builds: true` as Nightly. + /// builds" switch instead; [`Settings::parse`] reads its `beta_builds: true` as Alpha. #[serde(default)] pub update_channel: UpdateChannel, /// The player has read what the "I'm playing" ping holds (`telemetry::PING`): on the @@ -2232,11 +2316,11 @@ impl Settings { return Self::default(); }; if let Some(fields) = value.as_object_mut() { - // The switch from before 0.2: on meant every release at once, the Nightly channel. + // The switch from before 0.2: on meant every release at once, the Alpha channel. if fields.remove("beta_builds") == Some(serde_json::Value::Bool(true)) { fields .entry("update_channel") - .or_insert_with(|| UpdateChannel::Nightly.name().into()); + .or_insert_with(|| UpdateChannel::Alpha.name().into()); } // A channel this launcher doesn't know is Stable, not a reason to lose every setting. if fields @@ -2458,10 +2542,10 @@ mod tests { assert_eq!(offered(&["v2026.10.15.1", "v2026.10.14"]), None); } - /// Betas (GitHub pre-releases) install by themselves only on the Nightly channel; Stable waits + /// Betas (GitHub pre-releases) install by themselves only on the Alpha channel; Stable waits /// for promote.yml's daily promotion (docs/release-flow.md, "Channels"). #[test] - fn updates_follow_the_stable_channel_unless_nightly_is_picked() { + fn updates_follow_the_stable_channel_unless_alpha_is_picked() { let asset = ASSET.unwrap_or("horizon-linux-x86_64.tar.gz"); let list = serde_json::json!([ {"tag_name": "v2026.10.19.02", "prerelease": true, "assets": [{"name": asset, "browser_download_url": "b", "size": 1}]}, @@ -2472,10 +2556,10 @@ mod tests { releases.iter().map(|r| r.beta).collect::>(), [true, false] ); - let offered = |nightly: bool, installed: &[&str]| { + let offered = |alpha: bool, installed: &[&str]| { let installed: Vec = installed.iter().map(|t| t.to_string()).collect(); - let on = if nightly { - UpdateChannel::Nightly + let on = if alpha { + UpdateChannel::Alpha } else { UpdateChannel::Stable }; @@ -2491,12 +2575,12 @@ mod tests { assert_eq!(offered(false, &["v2026.10.19.02"]), None); assert_eq!( releases.iter().map(UpdateChannel::of).collect::>(), - [UpdateChannel::Nightly, UpdateChannel::Stable] + [UpdateChannel::Alpha, UpdateChannel::Stable] ); } #[test] - fn the_update_channel_is_stored_by_name_and_the_old_beta_switch_reads_as_nightly() { + fn the_update_channel_is_stored_by_name_and_the_old_beta_switch_reads_as_alpha() { let read = |text: &str| Settings::parse(text).update_channel; assert_eq!(read(""), UpdateChannel::Stable); assert_eq!(read("{}"), UpdateChannel::Stable); @@ -2504,12 +2588,15 @@ mod tests { read(r#"{"update_channel": "stable"}"#), UpdateChannel::Stable ); + assert_eq!(read(r#"{"update_channel": "alpha"}"#), UpdateChannel::Alpha); + // The channel's first name, from launchers built while it was called Nightly. assert_eq!( read(r#"{"update_channel": "nightly"}"#), - UpdateChannel::Nightly + UpdateChannel::Alpha ); - // Launchers before 0.2: "Beta builds" on is Nightly, off is Stable. - assert_eq!(read(r#"{"beta_builds": true}"#), UpdateChannel::Nightly); + assert_eq!(UpdateChannel::parse("nightly"), Some(UpdateChannel::Alpha)); + // Launchers before 0.2: "Beta builds" on is Alpha, off is Stable. + assert_eq!(read(r#"{"beta_builds": true}"#), UpdateChannel::Alpha); assert_eq!(read(r#"{"beta_builds": false}"#), UpdateChannel::Stable); // Once a channel is picked, it wins over a switch left behind. let both = r#"{"beta_builds": true, "update_channel": "stable"}"#; @@ -2522,19 +2609,19 @@ mod tests { // Saved as a name, without the old switch. let mut settings = Settings::parse(r#"{"selected": "v0.2.0", "beta_builds": true}"#); let saved = serde_json::to_value(&settings).unwrap(); - assert_eq!(saved["update_channel"], "nightly"); + assert_eq!(saved["update_channel"], "alpha"); assert!(saved.get("beta_builds").is_none()); assert_eq!(saved["selected"], "v0.2.0"); settings.update_channel = UpdateChannel::Stable; let text = serde_json::to_string(&settings).unwrap(); assert_eq!(read(&text), UpdateChannel::Stable); - for c in [UpdateChannel::Stable, UpdateChannel::Nightly] { + for c in [UpdateChannel::Stable, UpdateChannel::Alpha] { assert_eq!(UpdateChannel::parse(c.name()), Some(c)); } - // An open launcher looks again every 4 hours on Stable, every 30 minutes on Nightly. + // An open launcher looks again every 4 hours on Stable, every 30 minutes on Alpha. let minutes = |c: UpdateChannel| c.check_every().as_secs() / 60; assert_eq!(minutes(UpdateChannel::Stable), 240); - assert_eq!(minutes(UpdateChannel::Nightly), 30); + assert_eq!(minutes(UpdateChannel::Alpha), 30); } #[test] @@ -2665,8 +2752,8 @@ mod tests { let releases = parse_releases(&list, Some(asset), is_game_tag); let installed = ["v2026.10.19.15".to_string(), "v2026.10.12".to_string()]; let offered = |on| horizon_update(&channel(&releases, on), &installed).map(|r| r.tag); - // A beta 0.2.0 reaches launchers on Nightly; Stable ones wait for its promotion. - assert_eq!(offered(UpdateChannel::Nightly), Some("v0.2.0".into())); + // A beta 0.2.0 reaches launchers on Alpha; Stable ones wait for its promotion. + assert_eq!(offered(UpdateChannel::Alpha), Some("v0.2.0".into())); assert_eq!(offered(UpdateChannel::Stable), None); let mut sorted = vec![ "v2026.10.19.15".to_string(), diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index a3903bf2f..e498fed2b 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -278,10 +278,10 @@ enum Cmd { style: Option, }, /// Show or set which Horizon releases install by themselves: stable (a tested build about once - /// a day) or nightly (every release as soon as it is built; can break) + /// a day) or alpha (every release as soon as it is built; can break) UpdateChannel { /// Omit to show the current channel - #[arg(value_parser = ["stable", "nightly"])] + #[arg(value_parser = ["stable", "alpha"])] channel: Option, }, /// Show or set the extra arguments the game starts with (for example --server-thread); diff --git a/launcher/src/main.rs b/launcher/src/main.rs index ec418a213..c1184fe10 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -1830,11 +1830,11 @@ impl Launcher { cx.notify(); }), ); - use backend::UpdateChannel::{Nightly, Stable}; + use backend::UpdateChannel::{Alpha, Stable}; let this = cx.entity().downgrade(); let update_channel = segments( "update-channel", - &[(Stable, Stable.label()), (Nightly, Nightly.label())], + &[(Stable, Stable.label()), (Alpha, Alpha.label())], self.settings.update_channel, &t, move |picked, _, cx| { @@ -2011,7 +2011,7 @@ impl Launcher { .flex_col() .child("Stable: a tested build about once a day.") .child( - "Nightly: every change as soon as it is built, several times a day; can break.", + "Alpha: every change as soon as it is built, several times a day; can break.", ) .into_any_element(), ), @@ -2262,7 +2262,8 @@ impl Launcher { .child(div().child(account::NO_KEYCHAIN)) }; let action = if !configured { - None + // No client ID in this build: the button says what's coming and does nothing. + Some(button("sign-in", "Coming soon", Kind::Ghost, &t).into_any_element()) } else if let Some(SignInState::Code(code)) = &self.sign_in_state { let (uri, user_code) = (code.verification_uri.clone(), code.user_code.clone()); Some( @@ -2309,7 +2310,9 @@ impl Launcher { ) }; n += 1; - let title = if self.accounts.accounts.is_empty() { + let title = if !configured { + "Microsoft account (coming soon)" + } else if self.accounts.accounts.is_empty() { "Microsoft account" } else { "Another account" diff --git a/launcher/src/mcp.rs b/launcher/src/mcp.rs index 0d77c3545..42af1c5d3 100644 --- a/launcher/src/mcp.rs +++ b/launcher/src/mcp.rs @@ -51,8 +51,8 @@ fn tools() -> Value { { "name": "links", "description": "The Horizon links: the Discord invite, the GitHub Sponsors page and the website (an empty one is not offered).", "inputSchema": none }, { "name": "menu_style", "description": "Show or set the game's menu style. \"horizon\" is Horizon's own menus, \"classic\" is vanilla's screens, which have no way back inside the game. The game reads it when it starts.", "inputSchema": { "type": "object", "properties": { "style": { "type": "string", "enum": ["horizon", "classic"], "description": "Omit to show the current style." } } } }, - { "name": "update_channel", "description": "Show or set which Horizon releases install by themselves. \"stable\" (the default) is a tested build about once a day; \"nightly\" is every release as soon as it is built, several times a day, and can break. Only when the player asks to change it.", - "inputSchema": { "type": "object", "properties": { "channel": { "type": "string", "enum": ["stable", "nightly"], "description": "Omit to show the current channel." } } } }, + { "name": "update_channel", "description": "Show or set which Horizon releases install by themselves. \"stable\" (the default) is a tested build about once a day; \"alpha\" is every release as soon as it is built, several times a day, and can break. Only when the player asks to change it.", + "inputSchema": { "type": "object", "properties": { "channel": { "type": "string", "enum": ["stable", "alpha"], "description": "Omit to show the current channel." } } } }, { "name": "logs", "description": "Read the game's log: the last lines of logs/latest.log in the game folder, or with crash the newest crash report (what the game wrote when it last crashed). Read-only.", "inputSchema": { "type": "object", "properties": { "lines": { "type": "integer", "minimum": 1, "maximum": 5000, "description": "How many lines of latest.log (default 100)." }, "crash": { "type": "boolean", "description": "Return the newest crash report instead." } } } }, { "name": "accounts", "description": "The Microsoft accounts signed in to the launcher (names and UUIDs, never tokens), which one the game plays as (none = offline), and how a sign-in started with sign_in is going.", "inputSchema": none }, @@ -291,7 +291,7 @@ impl Session { let mut settings = backend::Settings::load(); if let Some(name) = arg_str(args, "channel") { settings.update_channel = backend::UpdateChannel::parse(name) - .ok_or("channel is \"stable\" or \"nightly\"")?; + .ok_or("channel is \"stable\" or \"alpha\"")?; settings.save(); } Ok(format!( diff --git a/launcher/src/mojang.rs b/launcher/src/mojang.rs index dbe2aa7fb..070db43aa 100644 --- a/launcher/src/mojang.rs +++ b/launcher/src/mojang.rs @@ -13,6 +13,8 @@ use std::sync::Mutex; use std::time::Duration; const OBJECTS: &str = "https://resources.download.minecraft.net"; +/// The index of Mojang's Java runtimes, the one the official launcher reads. +const JAVA_RUNTIMES: &str = "https://launchermeta.mojang.com/v1/products/java-runtime/2ec0cc96c44e5a76b9c8b7c39df7210883d12871/all.json"; /// One file to download. struct File { @@ -84,6 +86,120 @@ pub fn download( Ok(()) } +/// Mojang's name for this system in its Java runtime index. +fn java_platform() -> Option<&'static str> { + Some(match (std::env::consts::OS, std::env::consts::ARCH) { + ("macos", "aarch64") => "mac-os-arm64", + ("macos", "x86_64") => "mac-os", + ("linux", "x86_64") => "linux", + ("linux", "x86") => "linux-i386", + ("windows", "x86_64") => "windows-x64", + ("windows", "aarch64") => "windows-arm64", + ("windows", "x86") => "windows-x86", + _ => return None, + }) +} + +/// Downloads Mojang's Java runtime `component` (the version JSON's `javaVersion.component`, e.g. +/// `java-runtime-epsilon`) into the game directory's `runtime` folder, as the official launcher +/// lays it out: `///`. Each file is checked against its sha1; +/// files already there and whole are kept. Mojang's runtimes are whole JDKs, javac included, +/// which is what the exporters need. +pub fn java_runtime( + component: &str, + runtime: &Path, + jobs: usize, + fetch: Fetch, + log: &dyn Fn(String), +) -> Result { + let platform = java_platform().ok_or("Mojang has no Java for this system")?; + let index: Value = serde_json::from_slice(&fetch(JAVA_RUNTIMES)?) + .map_err(|e| format!("Mojang's Java index: {e}"))?; + let entry = &index[platform][component][0]; + if entry.is_null() { + return Err(format!("Mojang has no {component} for {platform}")); + } + let manifest = &entry["manifest"]; + let manifest: Value = serde_json::from_slice(&fetch_checked( + fetch, + &text(manifest, "url")?, + &text(manifest, "sha1")?, + )?) + .map_err(|e| format!("Mojang's {component} manifest: {e}"))?; + let files = manifest["files"] + .as_object() + .ok_or_else(|| format!("Mojang's {component} manifest lists no files"))?; + let home = runtime.join(component).join(platform).join(component); + let mut downloads = Vec::new(); + let mut executables = Vec::new(); + let mut links = Vec::new(); + for (name, file) in files { + let path = home.join(relative(name)?); + match file["type"].as_str() { + Some("file") => { + let raw = &file["downloads"]["raw"]; + if file["executable"] == true { + executables.push(path.clone()); + } + downloads.push(File { + url: text(raw, "url")?, + sha1: text(raw, "sha1")?, + path, + }); + } + Some("link") => links.push((path, text(file, "target")?)), + _ => {} + } + } + let name = entry["version"]["name"].as_str().unwrap_or(component); + log(format!( + "Downloading Minecraft's Java {name} from Mojang ({} files)", + downloads.len() + )); + fetch_all(&downloads, jobs, fetch, log)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + for path in &executables { + fs::set_permissions(path, fs::Permissions::from_mode(0o755)) + .map_err(|e| format!("{}: {e}", path.display()))?; + } + for (path, target) in &links { + if !link_stays_inside(name_in(&home, path), target) { + return Err(format!( + "Unsafe link {target:?} in Mojang's {component} manifest" + )); + } + let _ = fs::remove_file(path); + fs::create_dir_all(path.parent().unwrap()) + .and_then(|_| std::os::unix::fs::symlink(target, path)) + .map_err(|e| format!("{}: {e}", path.display()))?; + } + } + #[cfg(not(unix))] + let _ = (executables, links); + Ok(home) +} + +fn name_in<'a>(home: &Path, path: &'a Path) -> &'a Path { + path.strip_prefix(home).unwrap_or(path) +} + +/// Whether a link at `link` (relative to the runtime's home) pointing at `target` stays in the +/// home. +fn link_stays_inside(link: &Path, target: &str) -> bool { + let mut depth = link.components().count().saturating_sub(1); + for c in Path::new(target).components() { + match c { + Component::Normal(_) => depth += 1, + Component::CurDir => {} + Component::ParentDir if depth > 0 => depth -= 1, + _ => return false, + } + } + true +} + fn read_json(path: &Path) -> Result { let text = fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display())) diff --git a/launcher/src/mojang_tests.rs b/launcher/src/mojang_tests.rs index b50a77a93..24ed80bca 100644 --- a/launcher/src/mojang_tests.rs +++ b/launcher/src/mojang_tests.rs @@ -230,3 +230,99 @@ fn version_file_paths_stay_in_the_folder() { assert!(relative(bad).is_err(), "{bad}"); } } + +#[test] +fn links_stay_inside_the_runtime() { + let at = |p: &str| PathBuf::from(p); + assert!(link_stays_inside( + &at("legal/java.compiler/LICENSE"), + "../java.base/LICENSE" + )); + assert!(link_stays_inside(&at("lib/a"), "b")); + assert!(!link_stays_inside(&at("lib/a"), "../../b")); + assert!(!link_stays_inside(&at("a"), "/etc/passwd")); +} + +#[cfg(all(target_os = "linux", target_arch = "x86_64"))] +#[test] +fn java_runtime_lays_out_mojangs_runtime_with_its_executables_and_links() { + const JAVAC: &[u8] = b"#!/bin/sh\necho javac 25.0.1\n"; + const LICENSE: &[u8] = b"a fake license"; + let manifest = serde_json::json!({"files": { + "bin": {"type": "directory"}, + "bin/javac": {"type": "file", "executable": true, "downloads": {"raw": + {"sha1": sha1_hex(JAVAC), "size": JAVAC.len(), "url": "https://piston-data.mojang.com/javac"}}}, + "legal/java.base/LICENSE": {"type": "file", "executable": false, "downloads": {"raw": + {"sha1": sha1_hex(LICENSE), "size": LICENSE.len(), "url": "https://piston-data.mojang.com/license"}}}, + "legal/java.compiler/LICENSE": {"type": "link", "target": "../java.base/LICENSE"}, + }}) + .to_string(); + let index = serde_json::json!({"linux": {"java-runtime-epsilon": [{ + "manifest": {"sha1": sha1_hex(manifest.as_bytes()), "url": "https://piston-meta.mojang.com/m.json"}, + "version": {"name": "25.0.1"}, + }]}}) + .to_string(); + let server = Server { + files: HashMap::from([ + (JAVA_RUNTIMES.to_string(), index.into_bytes()), + ( + "https://piston-meta.mojang.com/m.json".into(), + manifest.into_bytes(), + ), + ( + "https://piston-data.mojang.com/javac".into(), + JAVAC.to_vec(), + ), + ( + "https://piston-data.mojang.com/license".into(), + LICENSE.to_vec(), + ), + ]), + asked: Mutex::new(Vec::new()), + }; + let dir = scratch("java"); + let home = java_runtime( + "java-runtime-epsilon", + &dir, + 2, + &|url| server.fetch(url), + &|_| {}, + ) + .unwrap(); + assert_eq!( + home, + dir.join("java-runtime-epsilon/linux/java-runtime-epsilon") + ); + use std::os::unix::fs::PermissionsExt; + let mode = fs::metadata(home.join("bin/javac")) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o111, 0o111); + assert_eq!( + fs::read(home.join("legal/java.compiler/LICENSE")).unwrap(), + LICENSE + ); + // horizon-prepare finds it where the official launcher would have put it. + assert_eq!(horizon_prepare::java::minecraft_runtimes(&dir), [home]); + // A second call keeps the files: only the index and manifest are asked again. + server.asked(); + java_runtime( + "java-runtime-epsilon", + &dir, + 2, + &|url| server.fetch(url), + &|_| {}, + ) + .unwrap(); + assert_eq!(server.asked().len(), 2); + assert!(java_runtime( + "java-runtime-zeta", + &dir, + 2, + &|url| server.fetch(url), + &|_| {} + ) + .is_err()); + fs::remove_dir_all(&dir).unwrap(); +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPlacementOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPlacementOracle.java index 0757bc2ef..e204d3cc0 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPlacementOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPlacementOracle.java @@ -27,7 +27,7 @@ import net.minecraft.world.phys.shapes.CollisionContext; /** * Native BlockItem placement-state selection (BlockPlaceContext resolution, * updatePlacementContext and getPlacementState) over generated neighbourhoods. - * Entities never obstruct; nothing is written to the world. + * Entity obstruction can be scripted; nothing is written to the world. */ public final class VanillaBlockPlacementOracle { static Object unsafe; @@ -67,6 +67,7 @@ public final class VanillaBlockPlacementOracle { static final class World extends net.minecraft.server.level.ServerLevel { Map cells; RandomSource random; + boolean obstructed; World() { super(null, null, null, null, null, null, false, 0L, List.of(), false); } @@ -77,7 +78,7 @@ public final class VanillaBlockPlacementOracle { @Override public RandomSource getRandom() { return random; } @Override public int getMinY() { return -64; } @Override public int getHeight() { return 384; } - @Override public boolean isUnobstructed(BlockState state, BlockPos pos, CollisionContext context) { return true; } + @Override public boolean isUnobstructed(BlockState state, BlockPos pos, CollisionContext context) { return !obstructed; } @Override public boolean isUnobstructed(Entity entity) { return true; } @Override public void scheduleTick(BlockPos pos, Block block, int delay) { } @Override public net.minecraft.core.RegistryAccess registryAccess() { return RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY); } @@ -116,6 +117,7 @@ public final class VanillaBlockPlacementOracle { world.cells.put(new BlockPos(c.get(0).getAsInt(), c.get(1).getAsInt(), c.get(2).getAsInt()), Block.stateById(c.get(3).getAsInt())); } world.random = new LegacyRandomSource(f.get("seed").getAsLong()); + world.obstructed = f.has("obstructed") && f.get("obstructed").getAsBoolean(); var player = make(FakePlayer.class); player.world = world; player.yaw = f.get("yaw").getAsFloat(); diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeldDropOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeldDropOracle.java index 8034968a5..b2cdb3383 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeldDropOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeldDropOracle.java @@ -6,9 +6,14 @@ import java.io.PrintWriter; import net.minecraft.client.*; import net.minecraft.client.gui.Gui; import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.multiplayer.ClientPacketListener; import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket; +import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.*; import net.minecraft.world.item.*; +import net.minecraft.world.item.component.SwingAnimation; import net.minecraft.world.level.GameType; /** Runs the real key handler through its drop loop; stops before item-use handling. */ @@ -41,16 +46,36 @@ public final class VanillaHeldDropOracle { } static final class Actor extends LocalPlayer { GameType mode; + int swings; Actor() { super(null, null, null, null, null, null, false, null, null); } @Override public GameType gameMode() { return mode; } @Override public boolean isUsingItem() { throw new Done(); } + @Override public boolean swing(InteractionHand hand, SwingAnimation animation, boolean sendPacket) { + if (hand != InteractionHand.MAIN_HAND || !animation.equals(SwingAnimation.DEFAULT) || sendPacket) + throw new AssertionError("unexpected drop swing"); + swings++; + return true; + } + } + static final class Connection extends ClientPacketListener { + int drops; + ServerboundPlayerActionPacket.Action expected; + Connection() { super(null, null, null); } + @Override public void send(Packet packet) { + if (packet instanceof ServerboundPlayerActionPacket action) { + if (action.getAction() != expected) throw new AssertionError("unexpected drop action"); + drops++; + } + } } static final class Controller extends MultiPlayerGameMode { int dropped; Controller() { super(null, null); } - // Controlled dispatch boundary: no networking, swings, statistics or item entities. + // Run vanilla's actual prediction, packet dispatch and conditional swing. @Override public void dropItem(LocalPlayer player, boolean all) { - dropped += player.getInventory().removeFromSelected(all).getCount(); + int before = player.getInventory().getSelectedItem().getCount(); + super.dropItem(player, all); + dropped += before - player.getInventory().getSelectedItem().getCount(); } } public static void main(String[] args) throws Exception { @@ -81,6 +106,9 @@ public final class VanillaHeldDropOracle { field(Player.class, "inventory").set(actor, inventory); field(Minecraft.class, "player").set(client, actor); var controller = make(Controller.class); + var connection = make(Connection.class); + field(MultiPlayerGameMode.class, "minecraft").set(controller, client); + field(MultiPlayerGameMode.class, "connection").set(controller, connection); field(Minecraft.class, "gameMode").set(client, controller); try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[0])))) { for (var mode : GameType.values()) for (boolean all : new boolean[]{false, true}) { @@ -91,6 +119,10 @@ public final class VanillaHeldDropOracle { inventory.setSelectedSlot(selected); inventory.setItem(selected, new ItemStack(Items.STONE, count)); controller.dropped = 0; + actor.swings = 0; + connection.drops = 0; + connection.expected = all ? ServerboundPlayerActionPacket.Action.DROP_ALL_ITEMS + : ServerboundPlayerActionPacket.Action.DROP_ITEM; // Two consecutive key presses also cover an emptied stack and repeated spectator drops. for (int press = 0; press < 2; press++) { ((Key) options.keyDrop).clicks = 1; @@ -100,7 +132,8 @@ public final class VanillaHeldDropOracle { } catch (InvocationTargetException e) { if (!(e.getCause() instanceof Done)) throw e; } - out.println(inventory.getSelectedItem().getCount() + " " + controller.dropped); + out.println(inventory.getSelectedItem().getCount() + " " + controller.dropped + + " " + actor.swings + " " + connection.drops); } } } diff --git a/tests/test_release_channels.py b/tests/test_release_channels.py index ed183afed..288fa7939 100644 --- a/tests/test_release_channels.py +++ b/tests/test_release_channels.py @@ -137,10 +137,10 @@ class ReleaseChannelTests(unittest.TestCase): pr = {"number": 1, "title": "Fix a thing", "labels": [], "paths": ["crates/x.rs"], "issues": [], "author": "ludovic111"} _, beta = train.notes("game", "v2026.10.19", [pr], [], beta=True) _, stable = train.notes("game", "v2026.10.19", [pr], [], beta=False) - self.assertIn("This is a nightly build: launchers on the Nightly channel", beta) - self.assertNotIn("nightly", stable.lower()) + self.assertIn("This is an alpha build: launchers on the Alpha channel", beta) + self.assertNotIn("alpha", stable.lower()) _, launcher = train.notes("launcher", "launcher-v0.9.0", [pr], [], beta=True) - self.assertNotIn("nightly", launcher.lower()) + self.assertNotIn("alpha", launcher.lower()) if __name__ == "__main__": diff --git a/tests/test_remote_mining.py b/tests/test_remote_mining.py new file mode 100644 index 000000000..236b85c28 --- /dev/null +++ b/tests/test_remote_mining.py @@ -0,0 +1,149 @@ +"""Exercise the live remote_mining method with scripted world and packet sinks. + +Vanilla reference: MultiPlayerGameMode.startDestroyBlock/continueDestroyBlock. +The first_person parity harness separately checks consecutive instant breaks +against the pinned client; this fixture catches drift in the multiplayer path. +""" +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[1] + + +@unittest.skipUnless(shutil.which("rustc"), "requires Rust") +class RemoteMiningTests(unittest.TestCase): + def test_break_timing_and_packets(self): + source = (ROOT / "crates/horizon-client/src/game/remote.rs").read_text() + start = source.index(" fn remote_mining(") + end = source.index(" /// MultiPlayerGameMode.destroyBlock", start) + fixture = r''' +#![allow(dead_code)] +#[derive(Clone, Copy)] +struct Hit { pos: [i32; 3], face: u8 } +struct Mining { pos: [i32; 3], progress: f32, ticks: u32 } +#[derive(Default)] +struct Remote { destroy_delay: u32, destroying: Option<([i32; 3], u8, f32)> } +struct Ground { on_ground: bool } +struct Player { ground: Ground } +#[derive(Clone)] +struct Sounds { hit: String, volume: f32, pitch: f32 } +#[derive(Clone)] +struct Facts { hardness: f32, name: String, requires_tool: bool, sounds: Sounds } +struct Resources { facts: Facts, speed: f32 } +impl Resources { + fn facts(&self) -> &Self { self } + fn items(&self) -> &Self { self } + fn get(&self, _: u32) -> &Facts { &self.facts } + fn is_air(&self, state: u32) -> bool { state == 0 } + fn mining_speed(&self, _: Option<&()>, _: &str) -> f32 { self.speed } + fn correct_for_drops(&self, _: Option<&()>, _: &str) -> bool { true } +} +#[derive(Default)] +struct World { broken: Vec<[i32; 3]> } +impl World { + fn block(&self, x: i32, y: i32, z: i32) -> u32 { + u32::from(!self.broken.contains(&[x, y, z])) + } +} +struct Audio; +impl Audio { + fn play(&self, _: &str, _: Option<[f64; 3]>, _: f32, _: f32) {} +} +mod play { + #[derive(Debug, PartialEq)] + pub struct PlayerAction { + pub action: u8, pub pos: [i32; 3], pub direction: u8, pub sequence: i32, + } +} +enum S { PlayerAction(play::PlayerAction) } +fn face_direction(face: u8) -> u8 { face } +struct Game { + remote: Option, mining: Option, creative: bool, + world: World, res: Resources, player: Option, audio: Audio, + hit: Hit, sequence: i32, packets: Vec, +} +impl Game { + fn new(hardness: f32, speed: f32, creative: bool) -> Self { + Self { + remote: Some(Remote::default()), mining: None, creative, + world: World::default(), + res: Resources { facts: Facts { hardness, name: "block".into(), + requires_tool: false, sounds: Sounds { hit: "hit".into(), volume: 1.0, pitch: 1.0 } }, speed }, + player: Some(Player { ground: Ground { on_ground: true } }), audio: Audio, + hit: Hit { pos: [0, 64, 0], face: 1 }, sequence: 0, packets: vec![], + } + } + fn pick(&self) -> Option { Some(self.hit) } + fn held(&self) -> Option<&()> { None } + fn next_sequence(&mut self) -> i32 { self.sequence += 1; self.sequence } + fn predict_break(&mut self, pos: [i32; 3], _: u32, _: i32) { self.world.broken.push(pos); } + fn send(&mut self, S::PlayerAction(packet): S) { self.packets.push(packet); } + fn crack_particle(&mut self, _: [i32; 3], _: u8, _: u32) {} +METHOD +} +fn main() { + // Zero-hardness blocks and a tool fast enough to break in one tick. + for (hardness, speed) in [(0.0, 1.0), (0.5, 15.0), (0.5, 30.0)] { + let mut game = Game::new(hardness, speed, false); + for tick in 0..8 { + game.hit.pos[0] = tick; + game.remote_mining(tick == 0); + assert_eq!(game.world.broken.len(), tick as usize + 1, + "instant break must happen every held tick"); + let remote = game.remote.as_ref().unwrap(); + assert_eq!(remote.destroy_delay, 0); + assert!(remote.destroying.is_none()); + assert!(game.mining.is_none()); + assert_eq!(game.packets[tick as usize], play::PlayerAction { + action: 0, pos: [tick, 64, 0], direction: 1, sequence: tick + 1, + }); + } + assert_eq!(game.packets.len(), 8, "instant breaks only send START"); + } + // Gradual breaking still sends STOP and waits five continuation ticks. + let mut game = Game::new(1.0, 15.0, false); + game.remote_mining(true); + assert!(game.world.broken.is_empty()); + game.remote_mining(false); + assert!(game.world.broken.is_empty()); + game.remote_mining(false); + assert_eq!(game.world.broken.len(), 1); + assert_eq!(game.packets.iter().map(|p| p.action).collect::>(), [0, 3]); + assert_eq!(game.remote.as_ref().unwrap().destroy_delay, 5); + game.hit.pos[0] = 1; + for _ in 0..5 { + game.remote_mining(false); + assert_eq!(game.packets.len(), 2); + } + game.remote_mining(false); + assert_eq!(game.packets.len(), 3); + assert_eq!(game.packets[2].action, 0); + // Creative also keeps its five-tick delay, even for zero-hardness blocks. + let mut game = Game::new(0.0, 1.0, true); + game.remote_mining(true); + game.hit.pos[0] = 1; + assert_eq!(game.remote.as_ref().unwrap().destroy_delay, 5); + for _ in 0..5 { + game.remote_mining(false); + assert_eq!(game.world.broken.len(), 1); + } + game.remote_mining(false); + assert_eq!(game.world.broken.len(), 2); + assert_eq!(game.remote.as_ref().unwrap().destroy_delay, 5); +} +'''.replace("METHOD", source[start:end]) + with tempfile.TemporaryDirectory(prefix="remote-mining-") as directory: + path = Path(directory) + (path / "main.rs").write_text(fixture) + subprocess.run(["rustc", "--edition=2024", str(path / "main.rs"), "-o", str(path / "probe")], + check=True, capture_output=True, text=True) + result = subprocess.run([str(path / "probe")], capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/agent_control_e2e.py b/tools/agent_control_e2e.py index 977d2e292..6f75b8a14 100644 --- a/tools/agent_control_e2e.py +++ b/tools/agent_control_e2e.py @@ -10,7 +10,8 @@ the options scenario reads and sets options.txt values by key; the events scenar states (wait-for) and reads the event log; the consume scenario eats and drinks consumables (a golden apple, milk, honey, chorus fruit) and checks their effects, remainders and teleport; the pick scenario middle-clicks slots (AbstractContainerScreen's cloning): a full stack in creative, from -the hotbar and from an item tab, and nothing in survival. +the hotbar and from an item tab, and nothing in survival; the suggestions scenario checks +slash-command Tab completion on single player's connected client after a fresh launch. python3 tools/agent_control_e2e.py # both modes python3 tools/agent_control_e2e.py --mode mcp # one of them @@ -45,6 +46,7 @@ LOG_KINDS = ['oak_log', 'birch_log', 'spruce_log', 'jungle_log', 'acacia_log', ' 'mangrove_log', 'cherry_log'] # Positional arguments of the commands the scenario uses, for the CLI. POSITIONAL = { + 'key': ['key', 'action'], 'goto': ['x', 'y', 'z'], 'break': ['x', 'y', 'z'], 'place': ['x', 'y', 'z'], 'block': ['x', 'y', 'z'], 'find_block': ['block', 'radius'], 'entities': ['radius', 'type'], 'click_slot': ['slot'], 'click_button': ['label'], 'type': ['text'], 'wait': ['ticks'], 'wait_ready': ['seconds'], @@ -522,8 +524,50 @@ def pick_scenario(d, out): return {'cloned': shown['item']} +def suggestions_scenario(d, out): + # Start from the title screen: single player's client joins through memory, + # without opening a server world and building its command registries. + d('click', id='singleplayer') + if 'game' not in widgets(d): + d('click', id='create-new-world') + d('type', field='name', replace=True, text='Suggestions') + d('click', id='game-mode') # survival -> hardcore -> creative (commands on) + d('click', id='game-mode') + d('type', field='seed', text='5') + d('click', id='world') + d('click', id='world-type') # superflat: this checks chat, without a spawn search + d('click', id='create-new-world') + d('wait_for', condition='loaded', timeout=400) + d('wait_ready', seconds=400) + + cases = [ + ('/giv', '/give'), + ('/fill ^', '/fill ^ ^'), + ('/give @s diamond_sw', '/give @s minecraft:diamond_sword'), + ('/setblock ~ ~ ~ diamond_blo', '/setblock ~ ~ ~ minecraft:diamond_block'), + ('/fill ~ ~ ~ ~1 ~1 ~1 diamond_blo', '/fill ~ ~ ~ ~1 ~1 ~1 minecraft:diamond_block'), + ('/setblock ~ ~ ~ oak_stairs[fa', '/setblock ~ ~ ~ oak_stairs[facing='), + ('/clear @s diamond_sw', '/clear @s minecraft:diamond_sword'), + ('/execute run give @s diamond_sw', '/execute run give @s minecraft:diamond_sword'), + ] + for text, expected in cases: + d('key', key='t', action='tap') + d('type', text=text) + if text == '/give @s diamond_sw': + shot = d('screenshot', path=str((out / f'{d.name}-suggestions.png').resolve())) + if '_image' in shot: + (out / f'{d.name}-suggestions.png').write_bytes(shot['_image']) + d('key', key='tab', action='tap') + actual = d('screen')['chat_input'] + assert actual == expected, (text, expected, actual) + d('key', key='esc', action='tap') + if d('screen')['screen'] == 'chat': # Escape first dismisses suggestions + d('key', key='esc', action='tap') + return {'completions': len(cases)} + + SCENARIOS = {'survival': scenario, 'ui': ui_scenario, 'options': options_scenario, 'events': events_scenario, - 'consume': consume_scenario, 'pick': pick_scenario} + 'consume': consume_scenario, 'pick': pick_scenario, 'suggestions': suggestions_scenario} def run(mode, ctl, out, resources, which='survival'): diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index dffa2bde0..db51d4992 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -121,6 +121,10 @@ address. The script then checks, from both sides, what a guest's game used to ge server's game time after the guest's game stalls for a few seconds (#848). - growth: far from the host, the chunks around the guest tick (#890): water placed there flows and wheat on farmland grows (random ticks), however the host runs its world. +- ladder: the guest climbs down ten blocks of ladder and lands unhurt: the server resets its fall + distance on a ladder every tick, as LivingEntity.handleOnClimbable does (#1255). +- boats: the host (single player, on its server thread with --server-thread) right-clicks a + boat on water and rides it, sneaks out, and breaks it with its fists (#1222). - flight: a player in creative double-taps jump and flies, stays up, and stops flying in survival: the guest, and on the server thread the host's window too, take what may fly from the server's abilities (ClientPacketListener.handlePlayerAbilities). @@ -162,7 +166,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'levels'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'levels'] class Game: @@ -2573,6 +2577,80 @@ def check_flight(host, guest, out): return seen + +def check_ladder(host, guest, out): + """#1255: climbing down a ladder doesn't hurt where the guest lands.""" + x, y, z = (int(v // 1) for v in pos_of(guest)) + lx, lz = x + 6, z + guest('command', command='gamemode survival') + guest('command', command=f'fill {lx - 2} {y} {lz - 2} {lx + 2} {y + 12} {lz + 2} minecraft:air') + guest('command', command=f'fill {lx - 2} {y - 1} {lz - 2} {lx + 2} {y - 1} {lz + 2} minecraft:stone') + guest('command', command=f'fill {lx} {y} {lz + 1} {lx} {y + 10} {lz + 1} minecraft:stone') + guest('command', command=f'fill {lx} {y} {lz} {lx} {y + 10} {lz} minecraft:ladder[facing=north]') + guest.wait(10) + try: + before = remote(guest)['health'] + # No input on a ladder: the guest slides down at 0.15 a tick (LivingEntity.handleOnClimbable). + guest('command', command=f'tp @s {lx + 0.5} {y + 10} {lz + 0.4} 0 0') + for _ in range(40): + guest.wait(5) + if pos_of(guest)[1] < y + 0.01: + break + guest.wait(20) + landed, after = pos_of(guest), remote(guest)['health'] + assert landed[1] < y + 0.01, f'the guest stayed on the ladder at {landed}' + assert after >= before, f'climbing down ten blocks of ladder took the guest from {before} to {after} health' + return {'landed': landed, 'health': after} + finally: + guest('command', command=f'fill {lx} {y} {lz} {lx} {y + 10} {lz + 1} minecraft:air') + guest('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}') + + +def check_boats(host, guest, out): + """#1222: the single player boards a boat on water with a right click, sneaks out, and breaks it.""" + x, y, z = (int(v // 1) for v in pos_of(host)) + bx = x + 3 + host('command', command='gamemode survival') + host('command', command=f'fill {bx - 1} {y} {z - 1} {bx + 1} {y + 3} {z + 1} minecraft:air') + host('command', command=f'fill {bx - 1} {y - 1} {z - 1} {bx + 1} {y - 1} {z + 1} minecraft:water') + host('command', command=f'summon minecraft:oak_boat {bx + 0.5} {y - 0.1} {z + 0.5}') + host.wait(30) + boats = [o for o in host('status')['objects'] if o['kind'].endswith('oak_boat') + and abs(o['position'][0] - (bx + 0.5)) < 2 and abs(o['position'][2] - (z + 0.5)) < 2] + try: + assert boats, 'the host sees no boat on the water' + boat = boats[0] + bp = boat['position'] + host.raw('look-at', f'{bp[0]:.2f}', f'{bp[1] + 0.3:.2f}', f'{bp[2]:.2f}') + host.raw('mouse', 'right', 'click') + host.wait(10) + riding = host('status').get('riding') + assert riding == boat['id'], f'right-clicking the boat {boat["id"]}: riding {riding}' + host.raw('key', 'shift', 'down') + host.wait(10) + host.raw('key', 'shift', 'up') + host.wait(10) + riding = host('status').get('riding') + assert riding is None, f'sneaking out of the boat: riding {riding}' + host('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}') + host.wait(5) + gone = False + for _ in range(10): + here = [o for o in host('status')['objects'] if o['id'] == boat['id']] + if not here: + gone = True + break + bp = here[0]['position'] + host.raw('look-at', f'{bp[0]:.2f}', f'{bp[1] + 0.3:.2f}', f'{bp[2]:.2f}') + host.raw('mouse', 'left', 'click') + # VehicleEntity.tick takes 1 off the damage every tick: hit fast. + host.wait(2) + assert gone, 'ten hits left the boat in place' + return {'boat': boat['id'], 'rode': True, 'broken': True} + finally: + host('command', command=f'kill @e[type=minecraft:oak_boat,x={bx},y={y},z={z},distance=..6]') + host('command', command=f'fill {bx - 1} {y - 1} {z - 1} {bx + 1} {y - 1} {z + 1} minecraft:stone') + def check_growth(host, guest, out): """Block ticks near a guest 1000 blocks from the host: only the guest's tickets tick them.""" x0, y0, z0 = pos_of(guest) @@ -2885,14 +2963,19 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, + 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'levels': check_levels} def run(ctl, out, resources, checks): host, guest = Game('host', ctl, resources), Game('guest', ctl, resources) - # Either way explicitly: the game's default is the server thread. - host.d.env['HORIZON_SERVER_THREAD'] = '1' if SERVER_THREAD else '0' + # Without --server-thread the host runs the game's default, the world in the frame, as players + # get it (`boats` fails there if the default goes back to the server thread before it has + # vehicles, #1222). + if SERVER_THREAD: + host.d.env['HORIZON_SERVER_THREAD'] = '1' + else: + host.d.env.pop('HORIZON_SERVER_THREAD', None) results = {} try: host.pid = host('launch', wait=False, offscreen=sys.platform == 'darwin')['pid'] diff --git a/tools/release_channels.py b/tools/release_channels.py index be0f2ca73..869127c5c 100644 --- a/tools/release_channels.py +++ b/tools/release_channels.py @@ -6,7 +6,7 @@ python3 tools/release_channels.py promote --tag v2026.10.19.03 --force # even if blocked or untested python3 tools/release_channels.py promote --dry-run # say what would happen, change nothing -Every game release goes out as a beta (a GitHub pre-release): launchers on the Nightly channel install it at once. +Every game release goes out as a beta (a GitHub pre-release): launchers on the Alpha channel install it at once. Stable moves once a day, at PROMOTE_AT (20:00 UTC). A beta is due for stable when: - it is newer than the stable release (GitHub's "latest", which launchers and servers install by default), - it had been out PROMOTE_AFTER (6 hours) at the day's promotion time, so every run until the next one picks the diff --git a/tools/release_train.py b/tools/release_train.py index 5f6239edc..0cc37eef7 100644 --- a/tools/release_train.py +++ b/tools/release_train.py @@ -37,7 +37,7 @@ import sys ROOT = Path(__file__).resolve().parents[1] REPO = os.environ.get("GITHUB_REPOSITORY", "ludovic111/horizon") -# Nightly builds ship constantly: a merge starts a release within minutes, once its wave of merges has settled. +# Alpha builds ship constantly: a merge starts a release within minutes, once its wave of merges has settled. DEBOUNCE = dt.timedelta(minutes=5) MAX_WAIT = dt.timedelta(minutes=20) # Kept as typed in release titles, where the clauses after the first are lowercased. @@ -72,7 +72,7 @@ LAUNCHER_IGNORED = ["launcher/links.json", "launcher/docs/", "launcher/tests/"] FOOTER = { "game": "Install or update it from the Horizon launcher: it installs new versions by itself. " "New here? Get the launcher at https://playhorizon.dev. You need your own copy of Minecraft: Java Edition.", - "beta": "This is a nightly build: launchers on the Nightly channel (Settings, Updates) install it now; Stable gets it " + "beta": "This is an alpha build: launchers on the Alpha channel (Settings, Updates) install it now; Stable gets it " "in the next daily update if it holds up.", "launcher": "Your launcher updates itself. New here? Download the archive for your system below, extract it, " "and run `horizon-launcher`. Website: https://playhorizon.dev", diff --git a/tools/test_chat_screen_parity.py b/tools/test_chat_screen_parity.py index 52febd9f6..1447ebaa6 100644 --- a/tools/test_chat_screen_parity.py +++ b/tools/test_chat_screen_parity.py @@ -69,6 +69,16 @@ def cases(count): 'history': rng.sample(HISTORY, rng.randint(0, len(HISTORY))), 'autoSuggest': rng.random() < 0.85, 'chatOnly': rng.random() < 0.7, 'opacity': rng.choice([0.0, 0.5, 1.0]), 'actions': actions, 'mouse': list(mouse), 'blink': rng.choice([0, 100, 400, 650])}) + # Always exercise registry-backed suggestions and their replacement ranges, + # before and after Tab, including the redirect through execute's root. + for text in ['/give @s diamond_sw', '/setblock ~ ~ ~ sto', '/fill ~ ~ ~ ~1 ~1 ~1 sto', + '/setblock ~ ~ ~ oak_stairs[fa', '/clear @s diamond_sw', + '/execute run give @s diamond_sw', '/fill ']: + for keys in [[], ['tab'], ['tab', 'tab', 'shift+tab']]: + out.append({'width': 640, 'height': 360, 'initial': '', 'history': [], 'autoSuggest': True, + 'chatOnly': True, 'opacity': 0.5, 'mouse': [0, 0], 'blink': 0, + 'actions': [{'type': 'type', 'text': text}] + + [{'type': 'key', 'key': key} for key in keys]}) return out diff --git a/tools/test_firework_tooltip_parity.py b/tools/test_firework_tooltip_parity.py index e6cea9925..b3114c01a 100644 --- a/tools/test_firework_tooltip_parity.py +++ b/tools/test_firework_tooltip_parity.py @@ -67,6 +67,7 @@ if __name__ == '__main__': 'firework-tooltip-parity', 'VanillaFireworkTooltipOracle', 'firework_tooltip_fixture', cases, 'Firework rocket and star tooltip lines: flight duration, explosions (counted runs), colours, fade, trail, ' 'twinkle, defaults and tooltip_display', - sources=[lab.ROOT / 'crates/horizon-client/src/item_tooltip.rs', lab.ROOT / 'crates/horizon-client/src/item_data.rs', + sources=[lab.ROOT / 'crates/horizon-client/src/enchant.rs', + lab.ROOT / 'crates/horizon-client/src/item_tooltip.rs', lab.ROOT / 'crates/horizon-client/src/item_data.rs', lab.ROOT / 'crates/horizon-client/src/particles.rs'], expected_lines=COUNT) diff --git a/tools/test_first_person_parity.py b/tools/test_first_person_parity.py index d73262595..476d2cc52 100644 --- a/tools/test_first_person_parity.py +++ b/tools/test_first_person_parity.py @@ -69,6 +69,12 @@ def block_hit(pos, face=1): def scenarios(): stone = {TARGETS[0]: 'minecraft:stone', TARGETS[1]: 'minecraft:dirt', TARGETS[2]: 'minecraft:glass'} + # Consecutive instant survival breaks have no destroy delay. Cover both + # zero hardness and a shovel with haste reaching one-tick destroy progress. + for block, main, haste in [('minecraft:short_grass', None, None), + ('minecraft:dirt', ['minecraft:diamond_shovel', 1], 9)]: + steps = [step(block_hit(p), ac=int(i == 0), ad=True) for i, p in enumerate(TARGETS)] + yield case(steps + [step()] * 6, main=main, blocks={p: block for p in TARGETS}, haste=haste) for creative in (False, True): for main in ITEMS: # Hold attack on blocks until they break, then on the air behind. diff --git a/tools/test_held_drop_parity.py b/tools/test_held_drop_parity.py index c546c5987..842ad3d8a 100644 --- a/tools/test_held_drop_parity.py +++ b/tools/test_held_drop_parity.py @@ -2,10 +2,12 @@ """Compare selected-slot drops with Minecraft.handleKeybinds in all four game modes. The oracle invokes the unmodified native key handler, consuming real drop-key -clicks. Its controlled dropItem callback removes from the real player Inventory; -other keys are idle and execution stops at the following item-use boundary. +clicks, and MultiPlayerGameMode.dropItem's real prediction and swing dispatch. +Other keys are idle and execution stops at the following item-use boundary. Checks Q/Ctrl+Q, slots 0/8, empty/single/partial/full stacks and repeated drops. -Packet delivery, item entities, swing animation and statistics are outside scope. +Checks swing attempts and drop packet counts, including packets without swings +for empty slots. Packet delivery, animation ticks, item entities and statistics +are outside scope. """ import os import subprocess @@ -35,7 +37,7 @@ def main(): subprocess.run(['cargo', 'run', '--quiet', '-p', 'horizon-client', '--example', 'held_drop_fixture'], cwd=lab.ROOT, stdout=out, check=True) matched = base.compare(build / 'vanilla.txt', build / 'rust.txt') - print(f'Held drop parity passed: {matched} selected-stack/drop-count snapshots match vanilla') + print(f'Held drop parity passed: {matched} inventory/drop/swing/packet snapshots match vanilla') if __name__ == '__main__': diff --git a/tools/test_level_place_parity.py b/tools/test_level_place_parity.py index 423951942..23a68800c 100644 --- a/tools/test_level_place_parity.py +++ b/tools/test_level_place_parity.py @@ -68,6 +68,22 @@ def generate(resources, count, seed): return cases +def obstruction_cases(resources): + """Placement failures must not predict a hand swing. + + Exercise BlockItem.canPlace's entity-obstruction gate with the same + otherwise valid placements, including partial shapes and two-block items. + """ + facts = json.loads((resources / 'facts.json').read_text()) + states = {s[0]: i for i, s in reversed(list(enumerate(facts['states'])))} + stone = states['minecraft:stone'] + for item in ['minecraft:stone', 'minecraft:oak_slab', 'minecraft:oak_stairs', + 'minecraft:oak_door', 'minecraft:torch']: + for obstructed in [False, True]: + yield dict(seed=0, item=item, pos=[0, 0, 0], face=1, hit=[0.5, 1.0, 0.5], + yaw=0, pitch=45, sneak=False, cells=[[0, 0, 0, stone]], obstructed=obstructed) + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--count', type=int, default=20000) @@ -77,7 +93,7 @@ def main(): resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version'] work = lab.LOCAL / 'level-place-parity' work.mkdir(parents=True, exist_ok=True) - cases = generate(resources, args.count, args.seed) + cases = list(obstruction_cases(resources)) + generate(resources, args.count, args.seed) (work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in cases)) classes = work / 'classes' classes.mkdir(exist_ok=True) diff --git a/website/README.md b/website/README.md index 76d8ecaf0..b5a3ac51d 100644 --- a/website/README.md +++ b/website/README.md @@ -84,7 +84,7 @@ and characters per line, for 360 to 1920 px wide and a 1250×700 window. ## Railway -The service deploys the `website` branch and answers on https://playhorizon.dev. Its +The service deploys `main` (Railway's GitHub integration; there is no `website` branch any more) when `/website/**`, `README.md` or `launcher/links.json` change, and answers on https://playhorizon.dev. Its `*.up.railway.app` address redirects there with a 301 (the Caddyfile), so search engines index one URL; the page also names it as canonical, in its Open Graph tags and in `sitemap.xml`. Railway's healthcheck reaches `$PORT` under its own host name and is served normally. diff --git a/website/docs/faq.md b/website/docs/faq.md index bb810a42f..3bde1e7ea 100644 --- a/website/docs/faq.md +++ b/website/docs/faq.md @@ -56,11 +56,11 @@ In part. Horizon runs the full-screen effects of Java shader packs, not their ge ## Does Horizon collect data? -Only if you say yes, and each kind has its own switch. Everything is off by default. The one thing sent without asking is an anonymous "I'm playing" ping, for the count of how many play right now: it holds a random number made each time the game starts, the version, your OS and whether a world is open to LAN, and nothing about you. See [Privacy](/privacy). +Only if you say yes, and each kind has its own switch. Everything is off by default. The game has an anonymous "I'm playing" ping for a live player count, but it is off today: no server receives it yet, so the game sends nothing. See [Privacy](/privacy). ## How often does it update? -Often. Every change players can see is released automatically after it is merged, so new versions can come out several times a day. On the **Nightly** channel the launcher installs each one as soon as it is built; on **Stable**, the default, it installs a tested build about once a day. See [Install](/docs/install#updating). +Often. Every change players can see is released automatically after it is merged, so new versions can come out several times a day. On the **Alpha** channel the launcher installs each one as soon as it is built; on **Stable**, the default, it installs a tested build about once a day. See [Install](/docs/install#updating). ## How do I report a bug? diff --git a/website/docs/index.md b/website/docs/index.md index 4e84a6591..4acdd49d0 100644 --- a/website/docs/index.md +++ b/website/docs/index.md @@ -7,7 +7,7 @@ Horizon is Minecraft: Java Edition 26.3 rewritten in Rust. You install it with a - **A new game program, not a mod.** Horizon is written from scratch in Rust. It reads the same worlds, plays by the same rules and generates the same terrain as the Java game. - **Checked against vanilla.** {{HARNESSES}} automated tests ("harnesses") feed the same inputs to Horizon and to the real game, then compare the results. Today every subsystem matches in every harness that compares it. That is {{PERCENT}} of what the harnesses compare, which is not proof that nothing else differs. The [status table](/#parity) lists what is covered. - **Light and fast.** It starts quickly, uses little memory and draws efficiently. See [Performance](/docs/performance) for what is measured and what is not. -- **A few things vanilla doesn't have.** Its own menus (vanilla's are one setting away), graphics presets, distant terrain, controller support, optional extras such as zoom and a minimap, and a server you can run without Java. +- **A few things vanilla doesn't have.** Its own menus (vanilla's are one setting away), graphics presets, distant terrain, controller support, optional extras such as zoom, a minimap and dynamic lights (dynamic lights are in Alpha builds for now), an invite code to play your world with friends, and a server you can run without Java. ## What Horizon is not diff --git a/website/docs/install.md b/website/docs/install.md index b898d79de..6ecaf6c07 100644 --- a/website/docs/install.md +++ b/website/docs/install.md @@ -5,7 +5,7 @@ Download the launcher, let it install Horizon, then prepare the game from your o ## What you need - **Minecraft: Java Edition 26.3, played once.** Install it with the official Minecraft launcher (or Prism Launcher, MultiMC, the Modrinth App, ATLauncher or GDLauncher) and start 26.3 once, so it downloads its files. Horizon reads them from there and never copies them anywhere else. -- **Java 25, a JDK.** For example [Eclipse Temurin 25](https://adoptium.net/temurin/releases/?version=25). Only the one-time preparation uses it. The game itself needs no Java. +- **Java 25, a JDK**, for the one-time preparation only (the game itself needs no Java). Nothing to install: the launcher uses the Java the Minecraft launcher downloaded for 26.3, or downloads that same Java from Mojang. A JDK you installed yourself (for example [Eclipse Temurin 25](https://adoptium.net/temurin/releases/?version=25)) works too. - **A computer on the [supported list](/docs/#supported-systems).** On Linux and Windows that means a graphics card with Vulkan (or DirectX 12 on Windows). ## Download the launcher @@ -37,14 +37,16 @@ The game opens on Horizon's own title screen. Your worlds, options and logs live - **Horizon.** The launcher looks for a new release when it starts and every four hours while it is open. With **Install new versions automatically** on (the default), it installs one and moves you to it if you were on the newest. New releases come out many times a day, and old versions stay installed until you remove them on the **Versions** page. - **The launcher.** It updates itself from its own releases, then shows **Restart** in its footer. -## Stable and Nightly +## Stable and Alpha + +> **Next launcher release.** The Updates switch below is merged but not in a launcher release yet. Launcher 0.17 has a **Beta builds** switch in Settings instead, which installs every new build at once, as Alpha does. In **Settings**, **Updates** picks which builds install by themselves: - **Stable** (the default): a tested build about once a day. -- **Nightly**: every change as soon as it is built, several times a day. It can break. A launcher left open looks for new builds every 30 minutes, instead of every four hours. +- **Alpha**: every change as soon as it is built, several times a day. It can break. A launcher left open looks for new builds every 30 minutes, instead of every four hours. -Every new release is a Nightly build first. Once a day (20:00 UTC, 21:00 in Paris in winter), the newest one that has been out for six hours, passed its smoke test and has no known blocker becomes Stable. "Nightly" is just the name: it updates many times a day, not once a night. The **Versions** page shows each version's channel, and you can install any of them by hand. +Every new release is an Alpha build first. Once a day (20:00 UTC, 21:00 in Paris in winter), the newest one that has been out for six hours, passed its smoke test and has no known blocker becomes Stable. Alpha builds come out many times a day, and Horizon as a whole is still in beta; Stable is the tested ones. The **Versions** page shows each version's channel, and you can install any of them by hand. ## The Versions page diff --git a/website/docs/modpacks.md b/website/docs/modpacks.md index 14455f1a4..a4396392b 100644 --- a/website/docs/modpacks.md +++ b/website/docs/modpacks.md @@ -8,7 +8,7 @@ Java mod jars do not run in Horizon. Instead, the launcher reads a modpack, tell Open **Modpacks** in the launcher. -1. **Import a pack.** Choose **Import a pack file…** for a Modrinth `.mrpack` or a CurseForge zip, or **Import an instance folder…** for a Prism, MultiMC or CurseForge instance. +1. **Import a pack.** Choose **Import a pack file…** for a Modrinth `.mrpack` or a CurseForge zip, or **Import an instance folder…** for a Prism, MultiMC or CurseForge instance. The **Mods** page can also find a Modrinth modpack and import it for you (see [Mods and data packs](/docs/mods#finding-resource-packs-shader-packs-and-modpacks)). 2. **Read the coverage report.** For every mod in the pack it says **Ported**, **Partial**, **Not yet** or **Not needed**, with the reason. You can filter the list by status. 3. **Port.** **Port N mods** gets the jars of the mods this computer can carry over today, and carries them over for the version you picked. It copies the jars from a folder you have, or downloads them from the pack's own links (or the same file from Modrinth's download network), and checks their hashes. Files that only CurseForge has need CurseForge's API key, so for those choose **Use jars from my instance…** and point it at your installed instance. 4. **Play.** **Play with N mods** starts the game as the pack's own profile, with its own saves and options, and those mods on. diff --git a/website/docs/mods.md b/website/docs/mods.md index 3e2721058..05dcaee2d 100644 --- a/website/docs/mods.md +++ b/website/docs/mods.md @@ -6,7 +6,7 @@ Horizon has its own mod system, written for Horizon and not compatible with Java Horizon mods are written in Rust, compiled to WebAssembly and run in a sandbox. A mod can only do what it asks for and you allow, and a mod that crashes is switched off without taking the game down. -> **Early.** The mod system is new. There is no mod store yet, and a mod browser in the launcher is planned. Mods you find are files to put in a folder. +> **Early.** The mod system is new. There is no store for Horizon mods yet: they are files to put in a folder. The launcher's **Mods** page (see below) finds resource packs, shader packs and modpacks, not `.hmod` mods. **Playing with mods** @@ -32,6 +32,12 @@ cargo horizon-mod run `run` builds the mod and starts the game with it. After an edit, `cargo horizon-mod build` rebuilds it and the running game reloads it. The full guide, with the API, the manifest and the roadmap, is [docs/mods.md](https://github.com/ludovic111/horizon/blob/main/docs/mods.md). What carries over from Java mods, and why jars cannot run, is in [the Java mod notes](https://github.com/ludovic111/horizon/blob/main/docs/research/java-mod-compat.md). +## Finding resource packs, shader packs and modpacks + +The launcher's **Mods** page (launcher 0.17 and newer) searches [Modrinth](https://modrinth.com) for what Horizon can load: resource packs, Java shader packs and modpacks. Each result says how well it runs in Horizon (**Works**, **Partly**, or **Doesn't run**), and by default the page shows only what runs. **Install** downloads the file, checks it against the checksum Modrinth lists and refuses anything that does not match, then puts it in the right folder, with the packs it needs. **Update** and **Remove** are there too. A resource pack still has to be turned on in the game's Resource Packs screen, and a shader pack in Video, Shader Packs. A modpack is imported on the [Modpacks page](/docs/modpacks). + +The page cannot search CurseForge yet. Java mod jars are never offered, because they do not run. The same things work from a terminal: `horizon-launcher mods search`, `install`, `update` and `remove`. + ## Data packs A world's data packs go in its `datapacks` folder, as folders or `.zip` files with a `pack.mcmeta`, as in vanilla. diff --git a/website/docs/multiplayer.md b/website/docs/multiplayer.md index 71e3f36cd..ddd490aab 100644 --- a/website/docs/multiplayer.md +++ b/website/docs/multiplayer.md @@ -20,6 +20,8 @@ There is no Horizon server in the middle. The code holds the host's addresses an Guests join with the name their game uses. There is no account check, so only share the code with people you trust. +In Alpha builds, guests can also use the host's workstations: the crafter, loom, stonecutter, grindstone, anvil, smithing table, enchanting table, beacon, lectern and cartography table. Stable gets this once it has passed. + ## Open to LAN As in vanilla, **Open to LAN** in the pause menu lets people on the same network join your world. They see it in their server list. A vanilla 26.3 client can join a Horizon LAN world, and Horizon can join a vanilla one. LAN worlds are in offline mode. diff --git a/website/docs/settings.md b/website/docs/settings.md index 24d055d26..53d2011a2 100644 --- a/website/docs/settings.md +++ b/website/docs/settings.md @@ -46,12 +46,16 @@ The change applies at the next start. If Vulkan gives you trouble, try DirectX 1 Shader packs are **experimental**. Put a pack's folder in the `shaderpacks` folder of the game folder (see [Install](/docs/install#first-launch) for where that is), then choose it in **Options, Video, Shader Packs**. With no pack selected the game draws exactly what vanilla draws. A pack that fails to load shows why in red and leaves the normal picture on. -Horizon can run the full-screen effects of Java shader packs (OptiFine and Iris packs: colour grading, bloom, sky and fog effects). It does not run their geometry and shadow passes yet, so packs do not look as they do in Iris. Horizon's own shader format, in WGSL with hot reload, is planned. The details are in the [shader pack notes](https://github.com/ludovic111/horizon/blob/main/docs/shader-packs.md). +Horizon can run the full-screen effects of Java shader packs (OptiFine and Iris packs: colour grading, bloom, sky and fog effects). It does not run their geometry and shadow passes yet, so packs do not look as they do in Iris. Horizon also has its own shader pack format, in WGSL, with a `pack.toml` manifest, options and hot reload. It has full-screen passes too; stages that draw the world's terrain and shadows are planned. The details are in the [shader pack notes](https://github.com/ludovic111/horizon/blob/main/docs/shader-packs.md). + +In Alpha builds, the **Shader Packs** page shows the full path of the `shaderpacks` folder with an **Open Folder** button, then one switch per pack. Turning a pack on picks it, and turning it off gives the vanilla picture. Packs tested so far: BSL, Complementary Reimagined, Steadfast and Sildur's Vibrant Extreme draw their full-screen passes; Bliss, Bloop, Noble, Photon and Rethinking Voxels do not load yet. To find packs, the launcher's **Mods** page installs shader packs from Modrinth (see [Mods and data packs](/docs/mods#finding-resource-packs-shader-packs-and-modpacks)). ## Resource packs Java Edition resource packs work. Put the folder or `.zip` in the `resourcepacks` folder of the game folder and pick it on the **Resource Packs** screen, which is vanilla's screen. The game reloads every loader from the pack, as vanilla does. +The launcher's **Mods** page can download them from Modrinth (see [Mods and data packs](/docs/mods#finding-resource-packs-shader-packs-and-modpacks)). + [Resource packs: what works](https://github.com/ludovic111/horizon/blob/main/docs/resource-packs.md) lists everything a 26.3 resource pack can change and whether Horizon honours it. ## Controllers @@ -65,7 +69,7 @@ Horizon plays with PlayStation (DualShock 4 and DualSense), Xbox (360, One and S ## Extras -**Options, Extras** holds small, optional conveniences. Every one is off by default, so a fresh install behaves like vanilla: fullbright, zoom, a minimap, an FPS counter, a keystroke display, auto-reconnect, Mouse Tweaks-style inventory controls and inventory sorting. +**Options, Extras** holds small, optional conveniences. Every one is off by default, so a fresh install behaves like vanilla: fullbright, zoom, a minimap, an FPS counter, a keystroke display, auto-reconnect, Mouse Tweaks-style inventory controls and inventory sorting. In Alpha builds there is one more, **dynamic lights**: a torch, lantern or other light source that you hold, that lies dropped as an item, or a burning mob, lights the blocks around it. It is client-side only, so other players do not see it. ## Where your settings are stored diff --git a/website/docs/troubleshooting.md b/website/docs/troubleshooting.md index b7dac8fe4..6876e85d2 100644 --- a/website/docs/troubleshooting.md +++ b/website/docs/troubleshooting.md @@ -30,7 +30,7 @@ The launcher's **Settings** page has a **Logs** row with an **Open** button. On - **The game does not start, or crashes straight away.** Update the launcher and Horizon, and your graphics drivers. On Windows, try **Graphics API: DirectX 12** (see [Settings](/docs/settings#graphics-api-on-windows)). - **"Not prepared" or "Minecraft 26.3 was not found".** Play 26.3 once in the official Minecraft launcher, or point the launcher at your Minecraft folder (**Choose…** next to Minecraft folder on the Play page), then choose **Prepare** again. -- **Preparation says Java 25 is needed.** Install a Java 25 JDK, for example Eclipse Temurin 25. +- **Preparation says Java 25 is needed.** Update the launcher: it then uses the Java the Minecraft launcher downloaded for 26.3, or downloads it from Mojang. If it still can't (no internet, say), install a Java 25 JDK, for example Eclipse Temurin 25. - **Slow or stuttering.** Lower the render distance, turn LOD off, or pick the **Performance** preset. The performance overlay (Video, Advanced, Overlay) shows what is slow. - **A resource or shader pack broke something.** Switch it off, or take it out of its folder. @@ -52,4 +52,4 @@ A Horizon bug is any place where it differs from vanilla 26.3, so "vanilla does ## Data the launcher can send -The launcher can send performance statistics, crash reports, bug reports and benchmarks, but only the kinds you allow, and everything is off until you say yes. The game also sends an anonymous "I'm playing" ping while it runs, for the live player count. See [Privacy](/privacy) for what is sent, how long it is kept and how to delete it. +The launcher can send performance statistics, crash reports, bug reports and benchmarks, but only the kinds you allow, and everything is off until you say yes. See [Privacy](/privacy) for what is sent, how long it is kept and how to delete it. diff --git a/website/src/index.html b/website/src/index.html index 7668951a7..270128d91 100644 --- a/website/src/index.html +++ b/website/src/index.html @@ -165,8 +165,9 @@
  • 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 a dedicated server in a folder you choose, with a live console.

  • +
  • 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.

  • Your choice of menus

    Play with Horizon's own menus, shown here, or vanilla's classic screens.

  • +
  • 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, shader packs and modpacks from Modrinth.

Download the launcher diff --git a/website/src/privacy.html b/website/src/privacy.html index c6fa0610e..def61dcc9 100644 --- a/website/src/privacy.html +++ b/website/src/privacy.html @@ -17,8 +17,8 @@

PrivacyData collection

-

Nothing about you 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. The only thing sent without asking is an anonymous "I'm playing" ping, which says nothing about you.

+

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:

@@ -33,15 +33,15 @@

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

-

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

-

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 doesn't 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.

+

The game has an anonymous "I'm playing" ping, so the launcher can show how many people play Horizon right now. It is off today: no server receives it yet, so the game sends nothing. This is what it would hold, so you know before it is ever switched on. It would be sent once a minute while you play, whatever the switches say.

+

It would hold: 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 would 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 would keep 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 would count while it pinged in the last two minutes and is then forgotten. What it would show 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.

+

To find what is slow or crashes on which machines, and fix it. If it is switched on, 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.

+

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 would hold nothing that identifies you; the address it comes from would be 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 at Railway. 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.