diff --git a/.github/workflows/promote.yml b/.github/workflows/promote.yml index b7ef0b38b..3966f571b 100644 --- a/.github/workflows/promote.yml +++ b/.github/workflows/promote.yml @@ -1,17 +1,20 @@ name: promote -# Beta game releases become stable (docs/release-flow.md, "Channels"): every 30 minutes tools/release_channels.py -# promotes the newest beta that has been out 6 hours, passed its release smoke test and isn't covered by an issue -# labelled release-blocker. By hand, from GitHub's app too (Actions > promote > Run workflow): -# gh workflow run promote -f tag=v2026.10.19.03 # that beta now, without the wait -# gh workflow run promote -f tag=v2026.10.19.03 -f force=true # even blocked or without its smoke test -# gh workflow run promote -f dry_run=true # say what would be promoted +# 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 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): +# gh workflow run promote -f tag=v0.2.3 # that beta now, without waiting for 20:00 +# gh workflow run promote -f tag=v0.2.3 -f force=true # even blocked or without its smoke test +# gh workflow run promote -f dry_run=true # say what would be promoted # Holding betas back: label an issue release-blocker. While it is open it holds every beta; closed as completed it # still holds the betas published before it closed. The issue's text is never read (its author could edit it). -# When the oldest waiting beta is 24 hours old, an issue "Promotion to stable has stalled" says so; it closes itself -# after the next promotion. +# When the oldest waiting beta is 30 hours old (it missed a promotion it was due for), an issue "Promotion to stable +# has stalled" says so; it closes itself after the next promotion. on: schedule: - - cron: '13,43 * * * *' + - cron: '7,37 20-21 * * *' workflow_dispatch: inputs: tag: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cd882a787..b19ba9ce5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,14 +1,14 @@ name: release # Automatic game releases (docs/release-flow.md). After every green `checks` run on main, every 10 minutes (so a # release waiting for merges to settle goes out without another merge) and by hand, tools/release_train.py decides: -# a release when pull requests merged since the last one changed what players run and the newest merged 15 minutes -# ago (the oldest an hour ago, if merges never pause), or at once for a pull request labelled release-now. +# a release when pull requests merged since the last one changed what players run and the newest merged 5 minutes +# ago (the oldest 20 minutes ago, if merges never pause), or at once for a pull request labelled release-now. # RELEASES_PAUSED=1 (repository variable) stops them. # Builds Linux (an older Ubuntu, so the binary runs on any recent distribution and on NixOS through nix-ld) and # Windows on GitHub, macOS on the Mac mini's runner (MAC_RUNNER=macos-latest sends it to GitHub), then # publishes vX.Y.Z on the release line in .github/release-line.txt (docs/versioning.md; without it, the dated # vYYYY.MM.DD[.N] from before 0.2) with notes from the merged pull requests, as a beta (a pre-release) that promote.yml makes -# stable after 6 hours. macOS: with the repository variable MACOS_SIGN_IDENTITY set, the programs are signed with +# stable in its daily promotion. macOS: with the repository variable MACOS_SIGN_IDENTITY set, the programs are signed with # Developer ID and the hardened runtime and the zip is notarized, from the runner's signing keychain # (packaging/macos/README.md); unset (forks), ad hoc. # gh workflow run release --ref # dry run: builds and notes, publishes nothing @@ -349,7 +349,8 @@ 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): promote.yml makes it stable and latest after 6 hours (docs/release-flow.md). + # 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 \ dist/horizon-windows-x64.zip dist/horizon-macos-arm64.zip dist/horizon-server-linux-x86_64.tar.gz \ diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 1a7a4d25c..48e2e57d4 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -42,8 +42,9 @@ log = "0.4" chrono = { version = "0.4.42", default-features = false, features = ["clock", "std"] } flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] } horizon-theme = { path = "../horizon-theme" } -# Opt-in data collection: the game keeps, the launcher sends (docs/telemetry.md). -horizon-telemetry = { path = "../horizon-telemetry", default-features = false } +# Opt-in data collection: the game keeps, the launcher sends (docs/telemetry.md); `live` is +# the anonymous "I'm playing" ping the game sends itself (`heartbeat.rs`). +horizon-telemetry = { path = "../horizon-telemetry", default-features = false, features = ["live"] } horizon-bench = { path = "../horizon-bench" } arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] } zip = { version = "2", default-features = false, features = ["deflate"] } diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/cauldron_fixture.rs index 584425ced..6aa942d42 100644 --- a/crates/horizon-client/examples/cauldron_fixture.rs +++ b/crates/horizon-client/examples/cauldron_fixture.rs @@ -82,12 +82,19 @@ fn main() -> horizon_client::Result<()> { let brewing = horizon_client::brewing::Brewing::load(root, &items); // The inventory menu never reads banner patterns. let banners = horizon_client::banner::Banners::default(); + let station_recipes = horizon_client::stations::StationRecipes::default(); + let enchantments = horizon_client::enchant::Enchantments::default(); + let names = horizon_client::creative::Names::default(); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, + station_recipes: &station_recipes, + enchantments: &enchantments, + names: &names, trade: None, + maps: None, }; let mut out = String::new(); for line in input.lines() { 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/menu_fixture.rs b/crates/horizon-client/examples/menu_fixture.rs index 63a5351a3..1da4a0278 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -11,8 +11,41 @@ use horizon_client::{ items::Items, menu::{Env, Input, Kind, Menu}, }; +use horizon_protocol::registry::Ids; use serde_json::Value; -use std::{fs, path::Path}; +use std::{ + cell::{Cell, RefCell}, + collections::HashMap, + fs, + path::Path, +}; + +/// The case's maps: (locked, scale) by id, and the next free id. +#[derive(Default)] +struct CaseMaps { + maps: RefCell>, + next: Cell, +} + +impl horizon_client::menu::Maps for CaseMaps { + fn state(&self, id: i32) -> Option<(bool, u8)> { + self.maps.borrow().get(&id).copied() + } + + /// `MapItemSavedData.scaled` (unlocked, one scale up) or `locked`. + fn derive(&self, id: i32, scale: bool) -> Option { + let (_, s) = self.state(id)?; + let new = self.next.get(); + self.next.set(new + 1); + let made = if scale { + (false, (s + 1).min(4)) + } else { + (true, s) + }; + self.maps.borrow_mut().insert(new, made); + Some(new) + } +} fn state(menu: &Menu) -> String { let slots: Vec = (0..menu.slot_count()) @@ -24,13 +57,21 @@ fn state(menu: &Menu) -> String { .iter() .map(|(slot, stack)| format!("{slot}:{}", canon_stack(stack.as_ref()))) .collect(); - format!( + let line = format!( "{} | {} |{data} | {} | {}", slots.join(" "), canon_stack(menu.carried.as_ref()), menu.drops.join(";"), equipped.join(";") - ) + ); + if menu.kind() != Kind::Lectern { + return line; + } + // No inventory slots: the inventory Take Book fills. + let items: String = (0..36) + .map(|i| format!(" {}", canon_stack(menu.player_item(i)))) + .collect(); + format!("{line} | inv{items}") } fn main() -> horizon_client::Result<()> { @@ -44,13 +85,28 @@ fn main() -> horizon_client::Result<()> { let recipes = Recipes::load(root, &items)?; let brewing = horizon_client::brewing::Brewing::load(root, &items); let banners = horizon_client::banner::Banners::load(root); + let station_recipes = horizon_client::stations::StationRecipes::load(root, &items); + let enchantments = horizon_client::enchant::Enchantments::load(root); + let names = horizon_client::creative::Names::load(root); + let case_maps = CaseMaps::default(); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, + station_recipes: &station_recipes, + enchantments: &enchantments, + names: &names, trade: None, + maps: Some(&case_maps), }; + // The mob effects' network ids (BeaconMenu.encodeEffect). + let builtin = horizon_protocol::registry::Builtin::find(root) + .and_then(|p| horizon_protocol::registry::Builtin::load(&p).ok()); + let effects = builtin + .as_ref() + .and_then(|b| b.get("minecraft:mob_effect")) + .cloned(); let mut out = String::new(); for line in input.lines() { let case: Value = serde_json::from_str(line)?; @@ -68,15 +124,41 @@ fn main() -> horizon_client::Result<()> { .unwrap_or(name), ) .ok_or("menu kind")?; + // [id, scale, locked] each; the level's new maps from 1000. + case_maps.next.set(1000); + *case_maps.maps.borrow_mut() = case["maps"] + .as_array() + .into_iter() + .flatten() + .map(|m| { + let id = m[0].as_i64().unwrap_or(0) as i32; + ( + id, + ( + m[2].as_bool().unwrap_or(false), + m[1].as_u64().unwrap_or(0) as u8, + ), + ) + }) + .collect(); let mut menu = Menu::new(kind); menu.creative = case["creative"].as_bool().unwrap_or(false); + menu.levels = case["levels"].as_i64().unwrap_or(0) as i32; for (i, slot) in case["slots"].as_array().ok_or("slots")?.iter().enumerate() { menu.set_slot(&env, i, parse_stack(slot.as_str().unwrap_or("-"))?); } menu.carried = parse_stack(case["carried"].as_str().unwrap_or("-"))?; + for (i, item) in case["inventory"] + .as_array() + .into_iter() + .flatten() + .enumerate() + { + menu.set_player_item(i, parse_stack(item.as_str().unwrap_or("-"))?); + } menu.settle(&env); for (i, v) in case["data"].as_array().ok_or("data")?.iter().enumerate() { - menu.data[i] = v.as_i64().unwrap_or(0) as i32; + menu.set_data(i, v.as_i64().unwrap_or(0) as i32); } let mut furnace = furnace_kind.map(|kind| Furnace { kind, @@ -100,6 +182,26 @@ fn main() -> horizon_client::Result<()> { out += &format!("{}\n", state(&menu)); continue; } + // ServerboundRenameItemPacket: AnvilMenu.setItemName. + "RENAME" => { + menu.rename(&env, op[3].as_str().unwrap_or_default()); + out += &format!("{}\n", state(&menu)); + continue; + } + // ServerboundSetBeaconPacket: BeaconMenu.updateEffects. + "SET_BEACON" => { + fn power<'a>(ids: Option<&Ids>, v: &'a Value) -> Option<(i32, &'a str)> { + let name = v.as_str()?; + Some((ids?.id(name)?, name)) + } + let (primary, secondary) = ( + power(effects.as_ref(), &op[3]), + power(effects.as_ref(), &op[4]), + ); + menu.beacon_update(&env, primary, secondary); + out += &format!("{}\n", state(&menu)); + continue; + } // ServerboundContainerSlotStateChangedPacket. "SLOT_STATE" => { if (0..9).contains(&slot) { 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/place_recipe_fixture.rs b/crates/horizon-client/examples/place_recipe_fixture.rs index 45d763980..1e2b66dbf 100644 --- a/crates/horizon-client/examples/place_recipe_fixture.rs +++ b/crates/horizon-client/examples/place_recipe_fixture.rs @@ -38,12 +38,19 @@ fn main() -> horizon_client::Result<()> { let recipes = Recipes::load(root, &items)?; let brewing = horizon_client::brewing::Brewing::load(root, &items); let banners = horizon_client::banner::Banners::default(); + let station_recipes = horizon_client::stations::StationRecipes::default(); + let enchantments = horizon_client::enchant::Enchantments::default(); + let names = horizon_client::creative::Names::default(); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, + station_recipes: &station_recipes, + enchantments: &enchantments, + names: &names, trade: None, + maps: None, }; let mut out = String::new(); for (line, order) in cases.lines().zip(orders.lines()) { diff --git a/crates/horizon-client/examples/streaming_bench.rs b/crates/horizon-client/examples/streaming_bench.rs index 9f8e99899..b8c56b28c 100644 --- a/crates/horizon-client/examples/streaming_bench.rs +++ b/crates/horizon-client/examples/streaming_bench.rs @@ -3,6 +3,7 @@ //! what the render thread pays for it in `Streaming::update`. //! //! streaming_bench RESOURCES [--threads N] [--radius R] [--seed S] [--fly CHUNKS_PER_S] [--seconds T] [--hz F] +//! [--dimension overworld|the_nether|the_end] [--center-x X] [--center-z Z] //! //! First the area around (0, 0) fills; then, with `--fly`, the centre moves along +x //! at that speed for T seconds while frames run at F per second. Each phase reports @@ -72,14 +73,33 @@ static ALLOCATOR: CountingAllocator = CountingAllocator; type Result = std::result::Result>; +fn cpu_seconds() -> f64 { + std::fs::read_to_string("/proc/self/stat") + .ok() + .and_then(|stat| { + let fields = stat + .rsplit_once(')')? + .1 + .split_whitespace() + .collect::>(); + Some((fields[11].parse::().ok()? + fields[12].parse::().ok()?) / 100.0) + }) + .unwrap_or(0.0) +} + #[derive(Default)] struct Phase { updates: Vec, local: (u64, u64), uploads: usize, + stage_samples: [u64; 7], + cpu_start: f64, } impl Phase { fn update(&mut self, streaming: &mut Streaming, world: &mut World) { + if self.updates.is_empty() { + self.cpu_start = cpu_seconds(); + } let before = LOCAL.with(Cell::get); let started = Instant::now(); let (uploads, _) = streaming.update(world); @@ -89,6 +109,9 @@ impl Phase { self.local.1 += after.1 - before.1; self.uploads += uploads.len(); drop(uploads); + for (sum, (_, count)) in self.stage_samples.iter_mut().zip(streaming.stages()) { + *sum += count as u64; + } } fn report(&self, name: &str, wall: Duration, streaming: &Streaming, generated: u64) { let mut sorted = self.updates.clone(); @@ -106,6 +129,16 @@ impl Phase { at(0.99), sorted.last().copied().unwrap_or(0.0), ); + println!( + "BENCH {}", + serde_json::json!({ + "phase": name, "wall_s": wall.as_secs_f64(), + "cpu_s": cpu_seconds() - self.cpu_start, + "chunks": streaming.generated_total - generated, "sections": self.uploads, + "updates": self.updates.len(), "update_ms": total, + "mean_stages": self.stage_samples.map(|n| n as f64 / self.updates.len() as f64), + }) + ); if TRACK { println!( " update allocations: {} ({:.1} MiB)", @@ -142,6 +175,22 @@ fn main() -> Result<()> { let fly = flag("--fly", 0.0); let seconds = flag("--seconds", 10.0); let hz = flag("--hz", 240.0); + let dimension = args + .iter() + .position(|a| a == "--dimension") + .and_then(|i| args.get(i + 1)) + .map(|d| { + if d.contains(':') { + d.clone() + } else { + format!("minecraft:{d}") + } + }) + .unwrap_or_else(|| "minecraft:overworld".into()); + let center = ( + flag("--center-x", 0.0) as i32, + flag("--center-z", 0.0) as i32, + ); let assets = Arc::new(Assets::load(&root)?); let render = Arc::new(assets.reload(&root)?); @@ -154,11 +203,12 @@ fn main() -> Result<()> { models::load_visibility(&root, assets.registry)?, )?); let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?); - let terrain = Arc::new(VanillaTerrain::new( + let terrain = Arc::new(VanillaTerrain::for_dimension( &root.join("worldgen"), assets.registry, &biomes, seed, + &dimension, )?); let context = Arc::new(WorkerContext { assets, @@ -170,8 +220,12 @@ fn main() -> Result<()> { let mut world = World::new(facts.air, seed); let mut streaming = Streaming::new(terrain, context, threads); streaming.radius = radius; - streaming.center = (0, 0); - println!("{threads} workers, radius {radius}, seed {seed}"); + streaming.center = center; + streaming.nether_shading = dimension == "minecraft:the_nether"; + streaming.sky_light = dimension != "minecraft:the_nether"; + println!( + "{threads} workers, radius {radius}, seed {seed}, dimension {dimension}, center {center:?}" + ); let (allocations, bytes) = (ALLOCATIONS.load(Relaxed), BYTES.load(Relaxed)); // Fill: update as often as the game would uncapped, until settled. @@ -198,12 +252,12 @@ fn main() -> Result<()> { let mut behind = Vec::new(); while started.elapsed().as_secs_f64() < seconds { let next = Instant::now() + frame; - let x = (started.elapsed().as_secs_f64() * fly) as i32; - streaming.center = (x, 0); + let x = center.0 + (started.elapsed().as_secs_f64() * fly) as i32; + streaming.center = (x, center.1); phase.update(&mut streaming, &mut world); // Columns within 2 chunks of the player still missing their meshes. let near = (-2..=2) - .flat_map(|dz| (-2..=2).map(move |dx| (x + dx, dz))) + .flat_map(|dz| (-2..=2).map(move |dx| (x + dx, center.1 + dz))) .filter(|&(cx, cz)| !streaming.is_lit(cx, cz)) .count(); behind.push(near); diff --git a/crates/horizon-client/examples/trading_fixture.rs b/crates/horizon-client/examples/trading_fixture.rs index a560b1c06..58824257c 100644 --- a/crates/horizon-client/examples/trading_fixture.rs +++ b/crates/horizon-client/examples/trading_fixture.rs @@ -239,10 +239,12 @@ fn main() -> horizon_client::Result<()> { let vanilla = fs::read_to_string(args.get(3).ok_or(usage)?)?; let items = Items::catalog(root)?; let enchantments = Enchantments::load(root); + let names = horizon_client::creative::Names::default(); let trades = Trades::load(root); let recipes = horizon_client::crafting::Recipes::load(root, &items)?; let brewing = horizon_client::brewing::Brewing::load(root, &items); let banners = horizon_client::banner::Banners::load(root); + let station_recipes = horizon_client::stations::StationRecipes::default(); let types: HashMap<_, _> = horizon_client::mobs::MobTypes::load(root)? .types .into_iter() @@ -378,7 +380,11 @@ fn main() -> horizon_client::Result<()> { recipes: &recipes, brewing: &brewing, banners: &banners, + station_recipes: &station_recipes, + enchantments: &enchantments, + names: &names, trade: Some(&env_trade), + maps: None, }; trade(&mut out, name, &kv, &mut world, &env, origin)?; } 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/creative.rs b/crates/horizon-client/src/creative.rs index 80445d541..55e4eb28e 100644 --- a/crates/horizon-client/src/creative.rs +++ b/crates/horizon-client/src/creative.rs @@ -44,6 +44,7 @@ pub struct Creative { search_index: Vec, } /// Display names from the pinned en_us language file. +#[derive(Default)] pub struct Names { map: HashMap, } diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs index a988eeb55..ca2ea6f5c 100644 --- a/crates/horizon-client/src/enchant.rs +++ b/crates/horizon-client/src/enchant.rs @@ -60,6 +60,7 @@ pub struct ItemProps { /// `minecraft:brewing_fuel` present. pub brewing_fuel: bool, } +#[derive(Default)] pub struct Enchantments { pub list: Vec, index: HashMap, usize>, @@ -192,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/first_person.rs b/crates/horizon-client/src/first_person.rs index a25d9f537..463d51437 100644 --- a/crates/horizon-client/src/first_person.rs +++ b/crates/horizon-client/src/first_person.rs @@ -21,6 +21,8 @@ pub enum ItemPose { Trident { ticks_used: f32, }, + /// Riptide's spin (`isAutoSpinAttack`): the item held up like a fork. + SpinAttack, Bow { ticks_used: f32, }, @@ -67,6 +69,12 @@ pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) - if matches!(pose, ItemPose::Using) { return m; } + if matches!(pose, ItemPose::SpinAttack) { + return m + * Mat4::from_translation(Vec3::new(invert * -0.4, 0.8, 0.3)) + * Mat4::from_rotation_y((invert * 65.0f32).to_radians()) + * Mat4::from_rotation_z((invert * -85.0f32).to_radians()); + } let charging = match pose { ItemPose::Bow { ticks_used } => { let power = ticks_used / 20.0; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 02d31b494..9e06e12bb 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -74,6 +74,7 @@ mod lan_entities; mod lan_mobs; mod lan_pvp; mod lan_screen; +mod lan_stations; mod lan_trading; mod lan_waypoints; mod leads; @@ -119,6 +120,7 @@ mod recipe_book; mod remote; mod remote_objects; mod remote_projectiles; +mod remote_stations; mod render_control; mod render_tick; mod respawn_anchor; @@ -213,6 +215,7 @@ use horizon_world::{ registry::BlockStateId, }; use std::{ + cell::RefCell, collections::{HashMap, HashSet}, path::PathBuf, sync::{ @@ -271,9 +274,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, @@ -330,7 +334,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, }; @@ -340,7 +344,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); @@ -905,6 +909,8 @@ struct WorldRest { behaviours: Behaviours, player_arm: Option, player_type: Option>, + /// `SpinAttackEffectModel` (Riptide's spinning boxes). + spin_attack: Option, stations: horizon_client::stations::StationData, } @@ -980,6 +986,9 @@ impl Resources { fn player_type(&self) -> &Option> { &self.rest().player_type } + fn spin_attack(&self) -> &Option { + &self.rest().spin_attack + } fn stations(&self) -> &horizon_client::stations::StationData { &self.rest().stations } @@ -1385,7 +1394,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. @@ -1415,6 +1424,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, @@ -2562,14 +2573,23 @@ impl Game<'_> { 1029 => Some(("minecraft:block.anvil.destroy", 1.0)), 1031 => Some(("minecraft:block.anvil.land", 0.3)), 1505 => Some(("minecraft:item.bone_meal.use", 1.0)), + 1042 => Some(("minecraft:block.grindstone.use", 1.0)), + 1044 => Some(("minecraft:block.smithing_table.use", 1.0)), + // LevelEvent.SOUND_PAGE_TURN (a lectern's page). + 1043 => Some(("minecraft:item.book.page_turn", 1.0)), _ => None, }; if let Some((name, volume)) = sound { - let pitch = if id == 1009 { - 2.6 + (self.world.random.next_float() - self.world.random.next_float()) - * 0.8 - } else { - 1.0 + let pitch = match id { + 1009 => { + 2.6 + (self.world.random.next_float() + - self.world.random.next_float()) + * 0.8 + } + 1029 | 1030 | 1042 | 1043 | 1044 => { + self.world.random.next_float() * 0.1 + 0.9 + } + _ => 1.0, }; self.audio.play(name, c, volume, pitch); } @@ -3925,6 +3945,7 @@ impl Game<'_> { } let riding = self.riding.is_some(); let ghast_collisions = self.happy_ghast_player_collisions(); + let spin_targets = self.spin_targets(); let Some(player) = self.player.as_mut() else { // A dedicated server has no local player: the world still runs. if self.options.dedicated.is_some() { @@ -4002,6 +4023,7 @@ impl Game<'_> { .any(|s| immune.is_some_and(|t| t.contains(&*s.item))); // The dimension's FAST_LAVA: the Nether's lava pushes harder. player.fluids.fast_lava = self.dim == Dim::Nether; + player.spin_targets = spin_targets; let grounded = player.ground.on_ground; let before = ( grounded, @@ -4024,6 +4046,7 @@ impl Game<'_> { } } let events = std::mem::take(&mut player.events); + let spin_hit = player.spin_hit.take(); let glider_wear = std::mem::take(&mut player.glider_wear); if glider_wear > 0 && !self.creative @@ -4042,6 +4065,7 @@ impl Game<'_> { self.eye += (camera_eye.unwrap_or(eye_height) - self.eye) * 0.5; let crouching = player.pose == horizon_client::pose::Pose::Crouching; self.tick_avatar(before, riding); + self.end_spin_attack(spin_hit); self.record_combat(&events); for event in events { match event { @@ -4474,10 +4498,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); } @@ -4831,6 +4862,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. @@ -5446,6 +5480,17 @@ impl Game<'_> { .station .as_ref() .is_some_and(|s| s.kind == stations::Kind::Merchant); + let stonecutter_open = self + .station + .as_ref() + .is_some_and(|s| s.kind == stations::Kind::Stonecutter); + let station_kind = self.station.as_ref().map(|s| s.kind); + let grindstone_open = station_kind == Some(stations::Kind::Grindstone); + let cartography_open = station_kind == Some(stations::Kind::Cartography); + let anvil_open = station_kind == Some(stations::Kind::Anvil); + let smithing_open = station_kind == Some(stations::Kind::Smithing); + let enchanting_open = station_kind == Some(stations::Kind::Enchanting); + let beacon_open = station_kind == Some(stations::Kind::Beacon); let (kind, game_of): (Kind, Vec>) = if self.creative_tab_open() { // ItemPickerMenu: the display slots (clicked by the screen), then the hotbar. let mut v = vec![None; 45]; @@ -5472,6 +5517,51 @@ impl Game<'_> { v.push(Some(stations::RESULT)); v.extend((9..36).chain(0..9).map(Some)); (Kind::Loom, v) + } else if stonecutter_open { + // StonecutterMenu: the input, the result, then the inventory. + let mut v = vec![Some(stations::INPUT), Some(stations::RESULT)]; + v.extend((9..36).chain(0..9).map(Some)); + (Kind::Stonecutter, v) + } else if grindstone_open || cartography_open { + // GrindstoneMenu and CartographyTableMenu: the two inputs, the + // result, then the inventory. + let mut v = vec![ + Some(stations::INPUT), + Some(stations::INPUT + 1), + Some(stations::RESULT), + ]; + v.extend((9..36).chain(0..9).map(Some)); + let kind = if grindstone_open { + Kind::Grindstone + } else { + Kind::Cartography + }; + (kind, v) + } else if enchanting_open { + // EnchantmentMenu: the item, the lapis, then the inventory. + let mut v = vec![Some(stations::INPUT), Some(stations::INPUT + 1)]; + v.extend((9..36).chain(0..9).map(Some)); + (Kind::Enchanting, v) + } else if beacon_open { + // BeaconMenu: the payment, then the inventory. + let mut v = vec![Some(stations::INPUT)]; + v.extend((9..36).chain(0..9).map(Some)); + (Kind::Beacon, v) + } else if anvil_open || smithing_open { + // ItemCombinerMenu: the inputs, the result, then the inventory. + let inputs = if anvil_open { 2 } else { 3 }; + let mut v: Vec> = + (0..inputs).map(|i| Some(stations::INPUT + i)).collect(); + v.push(Some(stations::RESULT)); + v.extend((9..36).chain(0..9).map(Some)); + ( + if anvil_open { + Kind::Anvil + } else { + Kind::Smithing + }, + v, + ) } else { let (kind, map) = if self.container.is_some() { let size = self.container_size(); @@ -5554,6 +5644,10 @@ impl Game<'_> { s.loom.patterns.clone(), ) }); + let stone = self + .station + .as_ref() + .map(|s| (s.selected.map_or(-1, |i| i as i32), s.stone.clone())); let crafter_data = match self.container_kind() { Some(BlockEntity::Crafter(c)) => Some((c.disabled, c.triggered)), _ => None, @@ -5567,6 +5661,18 @@ impl Game<'_> { if let Some((s, mob)) = session.as_mut() { self.merchant_sync_in(s, *mob); } + // The cartography table reads and makes the level's maps; a + // server's (the client menu's ContainerLevelAccess.NULL) doesn't. + let level_maps = (kind == Kind::Cartography && self.remote.is_none()).then(|| { + let held: Vec = before + .iter() + .flatten() + .chain(self.inventory.iter().flatten()) + .chain(self.carried.iter()) + .cloned() + .collect(); + self.level_maps(&held) + }); let next_map = if merchant_open { self.peek_map_id() } else { 0 }; let tag = |t: &str| self.structure_tag(t); let maps = trading::GameMaps { @@ -5585,10 +5691,21 @@ impl Game<'_> { recipes: self.res.recipes(), brewing: &self.res.stations().brewing, banners: &self.res.stations().banners, + station_recipes: &self.res.stations().recipes, + enchantments: &self.res.stations().enchantments, + names: &self.pack.names, trade: Some(&trade_env), + maps: level_maps + .as_ref() + .map(|m| m as &dyn horizon_client::menu::Maps), }; menu.creative = creative; menu.selected = self.selected; + menu.levels = self.experience.level; + if anvil_open { + // The rename box as AnvilScreen.onNameChanged gives it to the menu. + menu.anvil.name = self.station.as_ref().map(|s| self.anvil_item_name(s)); + } for (i, stack) in before.iter().enumerate() { menu.set_slot(&env, i, stack.clone()); } @@ -5606,6 +5723,25 @@ impl Game<'_> { menu.loom_patterns = patterns; menu.set_slot(&env, 3, before[3].clone()); } + if kind == Kind::Stonecutter + && let Some((selected, state)) = stone + { + // The same: the list and selection between clicks, then the result. + menu.data[0] = selected; + menu.stone = state; + menu.set_slot(&env, 1, before[1].clone()); + } + if kind == Kind::Enchanting + && let Some(s) = self.station.as_ref() + { + // The offers between clicks (what copying the slots in flagged is not a change). + menu.enchant_changed = false; + for i in 0..3 { + menu.data[i] = s.offers.costs[i]; + menu.data[7 + i] = s.offers.clues[i].as_ref().map_or(-1, |(_, l)| *l as i32); + } + menu.data[3] = self.level.xp_seed; + } if let Some((disabled, triggered)) = crafter_data { for (i, d) in disabled.iter().enumerate() { menu.data[i] = i32::from(*d); @@ -5660,10 +5796,37 @@ impl Game<'_> { s.loom.selected = usize::try_from(menu.data[0]).ok(); s.loom.patterns = std::mem::take(&mut menu.loom_patterns); } - for sound in sounds { - self.loom_sound(sound); + // A server's loom plays its own sounds (the client's menu has no level). + for sound in sounds.into_iter().filter(|_| !predicting) { + self.station_sound(sound); } self.loom_screen_changed(); + } else if kind == Kind::Cartography { + for sound in sounds.into_iter().filter(|_| !predicting) { + self.station_sound(sound); + } + } else if kind == Kind::Stonecutter { + if let Some(s) = self.station.as_mut() { + s.selected = usize::try_from(menu.data[0]).ok(); + s.stone = std::mem::take(&mut menu.stone); + s.stonecutter_changed(); + } + for sound in sounds.into_iter().filter(|_| !predicting) { + self.station_sound(sound); + } + } + if let Some(amount) = menu.ground.take().filter(|_| !predicting) + && let Some(pos) = self.station.as_ref().map(|s| s.pos) + { + self.grindstone_taken(pos, amount); + } + if kind == Kind::Anvil || kind == Kind::Smithing { + self.combiner_session_end(&menu, predicting); + } + if kind == Kind::Enchanting && (menu.enchant_changed || before[0] != menu.slot(0).cloned()) + { + // EnchantmentMenu.slotsChanged: new offers for the item. + self.station_changed(); } if kind == Kind::CrafterBlock && let Some(BlockEntity::Crafter(c)) = self @@ -5691,6 +5854,9 @@ impl Game<'_> { } } self.apply_equipment(); + if let Some(maps) = level_maps { + self.register_made_maps(maps); + } true } /// Number keys, F and Q over a slot of the open menu: SWAP with a hotbar @@ -6774,7 +6940,13 @@ impl Game<'_> { /// enchantments. pub(super) fn melee_damage(&mut self, target_kind: &str) -> (f32, f32, bool) { let hand_damage = 1.0 + self.attack_item_info().map_or(0.0, |i| i.attack_damage); - let damage = hand_damage + self.effect_attack_bonus(); + // Riptide's spin replaces the attack damage attribute. + let spin = self.player.as_ref().map_or(0.0, |p| p.auto_spin_attack_dmg); + let damage = if spin > 0.0 { + spin + } else { + hand_damage + self.effect_attack_bonus() + }; let scale = self.attack_strength_scale(); let mut amount = damage * (0.2 + scale * scale * 0.8); // Item.getAttackDamageBonus (a mace's smash), before the critical hit. @@ -6902,6 +7074,14 @@ impl Game<'_> { return false; } } + self.attack_mob(index); + // Minecraft.startAttack swings after the attack. + self.swing_arm(); + true + } + /// `Player.attack` on a mob: the damage, knockback, sweep, particles and + /// sounds. + pub(super) fn attack_mob(&mut self, index: usize) { let target_kind = self.mobs[index].kind.id.clone(); let target_kind = format!("minecraft:{}", target_kind.trim_start_matches("minecraft:")); let (amount, scale, crit) = self.melee_damage(&target_kind); @@ -6919,7 +7099,6 @@ impl Game<'_> { self.audio .play("minecraft:entity.player.attack.knockback", from, 1.0, 1.0); } - self.swing_arm(); // LivingEntity.setLastHurtMob (tamed wolves join in). self.combat.last_hurt_mob = Some((self.mobs[index].id, self.world.game_time)); let old_health = self.mobs[index].health; @@ -7012,7 +7191,6 @@ impl Game<'_> { self.audio .play("minecraft:entity.player.attack.nodamage", from, 1.0, 1.0); } - true } /// ServerExplosion: rays from a 16^3 grid lose (resistance + 0.3) * 0.3 per step. /// A mob explosion (`Level.ExplosionInteraction.MOB`: drop decay with the @@ -8512,6 +8690,10 @@ impl Game<'_> { } let shown = self.hands_to_render(); let used_hand = self.used_hand(); + let spinning = self + .player + .as_ref() + .is_some_and(|p| p.auto_spin_attack_ticks > 0); for (i, (hand, item)) in Hand::BOTH .into_iter() .zip(self.visible_hand_items()) @@ -8631,6 +8813,7 @@ impl Game<'_> { ItemPose::Using } } + _ if spinning => ItemPose::SpinAttack, _ => ItemPose::Swing, }; let m = to_world @@ -9626,15 +9809,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`. @@ -9656,8 +9841,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) }; @@ -9704,6 +9889,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, @@ -9746,6 +9937,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 { @@ -9851,9 +10049,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() @@ -9861,7 +10058,10 @@ impl Game<'_> { || self.title.as_ref().is_some_and(|t| { matches!(self.screen, Screen::Options | Screen::Win) || !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) } @@ -10968,6 +11168,10 @@ impl ApplicationHandler for Game<'_> { WindowEvent::RedrawRequested => { self.observe_fullscreen(); let now = Instant::now(); + let frame_cpu = self + .options + .spikes + .and_then(|_| horizon_client::spans::thread_cpu()); let elapsed = now.duration_since(self.previous); self.frame_ticks = elapsed.as_secs_f32() * 20.0; self.previous = now; @@ -10997,6 +11201,8 @@ impl ApplicationHandler for Game<'_> { } let updated = Instant::now(); self.track_toggle_screens(); + // For the "I'm playing" ping: an atomic, sent on when it changes. + horizon_client::heartbeat::set_lan(self.is_published()); let steps = self.clock.advance(elapsed); for _ in 0..steps { let started = Instant::now(); @@ -11035,15 +11241,16 @@ impl ApplicationHandler for Game<'_> { let cpu = now.elapsed().saturating_sub(r.last_wait).as_secs_f32() * 1000.0; let spans = horizon_client::spans::take(); if cpu > threshold { - let list: Vec = spans - .iter() - .filter(|(_, ms)| *ms >= 0.5) - .map(|(n, ms)| format!("{n} {ms:.1}")) - .collect(); + // The render thread's own CPU time in the frame: + // far below the wall time, the frame waited. + let worked = horizon_client::spans::thread_cpu() + .zip(frame_cpu) + .map_or_else(String::new, |(end, start)| { + format!(", cpu {:.1} ms", (end - start).as_secs_f32() * 1000.0) + }); log::info!( - "Horizon: slow frame {cpu:.1} ms ({} ticks): {}", - steps, - list.join(", ") + "Horizon: slow frame {cpu:.1} ms{worked} ({steps} ticks): {}", + horizon_client::spans::describe(&spans) ); } } @@ -11472,11 +11679,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, @@ -11496,6 +11703,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(), @@ -12091,6 +12299,7 @@ fn load_world_rest( player_type: perspective::player_type(root), player_arm: horizon_client::mobs::load_model(root, "minecraft:player#main") .and_then(|m| m.children.into_iter().find(|c| c.name == "right_arm")), + spin_attack: horizon_client::mobs::load_model(root, "minecraft:spin_attack#main"), }) } @@ -12207,6 +12416,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, @@ -12221,6 +12431,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> { entities: &[], dynamic_lights: &[], clouds: None, + lightning: Default::default(), additive: &[], see_through: &[], celestial: &[], @@ -12793,9 +13004,26 @@ pub fn run() -> Result<()> { if options.dedicated.is_some() && !dedicated::preflight(&mut options)? { return Ok(()); } - if options.dedicated.is_some() { - // Before any worker starts: on Linux they go behind the server thread. - horizon_threads::put_helpers_behind(); + // Before any worker starts: on Linux they go behind the server thread + // and the render thread. + horizon_threads::put_helpers_behind(); + if options.dedicated.is_none() { + // The render thread, like the server thread, ahead of the workers on + // macOS and Windows. While terrain loads, the worker pools (two with + // single player's server thread) and other programs outnumber the + // cores, and a frame that gave its core up (in a GPU submit) waited + // 10 to 200 ms to get one back. + horizon_threads::favour_current(); + } + // Someone is playing: the anonymous ping behind the launcher's "N playing now". Not for a + // server, a benchmark or a run that quits by itself. + if options.dedicated.is_none() + && options.benchmark.is_none() + && !options.offscreen + && options.frames.is_none() + && options.world_frames.is_none() + { + horizon_client::heartbeat::start(); } let started = Instant::now(); horizon_client::spans::enable(options.spikes.is_some()); 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/beacon.rs b/crates/horizon-client/src/game/beacon.rs index 79cf14541..c8a0bcba6 100644 --- a/crates/horizon-client/src/game/beacon.rs +++ b/crates/horizon-client/src/game/beacon.rs @@ -15,6 +15,7 @@ use horizon_client::{ mesher::Vertex, mobs::render::{DYE, DYE_NAMES}, }; +use horizon_protocol::packets::play::{self, Serverbound as S}; /// The beacon screen is 54 px wider than the 176-px menus it shares an origin with. pub(super) const SHIFT: f32 = -27.0; @@ -35,9 +36,6 @@ const PAYMENT: [&str; 5] = [ "minecraft:diamond", "minecraft:netherite_ingot", ]; -pub(super) fn is_payment(item: &str) -> bool { - PAYMENT.contains(&item) -} /// `BeaconMenu.PaymentSlot` and the player inventory, relative to the 176 origin. pub(super) fn slot_position(i: usize) -> Option<(f32, f32)> { Some(match i { @@ -171,7 +169,7 @@ impl Game<'_> { } } } - fn beacon_sound(&mut self, p: [i32; 3], sound: &str) { + pub(super) fn beacon_sound(&mut self, p: [i32; 3], sound: &str) { let at = [ f64::from(p[0]) + 0.5, f64::from(p[1]) + 0.5, @@ -255,9 +253,13 @@ impl Game<'_> { } } fn beacon_levels(&self) -> i32 { - let Some(pos) = self.station.as_ref().map(|s| s.pos) else { + let Some(s) = self.station.as_ref() else { return 0; }; + if let Some(levels) = s.beacon_levels { + return levels; + } + let pos = s.pos; match self.world.block_entities.get(&(pos[0], pos[1], pos[2])) { Some(BlockEntity::Beacon(b)) => b.levels, _ => 0, @@ -346,8 +348,16 @@ impl Game<'_> { self.screen = super::Screen::Playing; self.capture(true); } - /// `BeaconMenu.updateEffects`: spend the payment and set the powers. + /// `BeaconMenu.updateEffects`: spend the payment and set the powers. On + /// a server, `BeaconScreen`'s confirm button sends them + /// (`ServerboundSetBeaconPacket`) and the server's menu does it. fn confirm_beacon(&mut self, sel: [Option; 2]) { + if self.remote.is_some() { + let id = |e: Option| e.and_then(|e| self.remote_effect_network_id(EFFECTS[e].0)); + let (primary, secondary) = (id(sel[0]), id(sel[1])); + self.send(S::SetBeacon(play::SetBeacon { primary, secondary })); + return; + } let Some(s) = self.station.as_mut() else { return; }; 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/books.rs b/crates/horizon-client/src/game/books.rs index 3dd49c005..ccc1c6e19 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -9,6 +9,7 @@ use horizon_client::{ hud::{HudBatch, rgba}, item_data::WrittenBook, items::ItemStack, + menu::{Kind, Menu}, text::Text, ui, }; @@ -89,6 +90,17 @@ impl Game<'_> { self.capture(false); } pub(super) fn close_book(&mut self) { + // A server's lectern: LecternScreen's menu closes (closeContainer). + if matches!( + self.book, + Some(BookScreen::View { + lectern: Some(_), + .. + }) + ) && self.remote.is_some() + { + self.remote_close_container(); + } self.book = None; self.capture(true); } @@ -319,38 +331,25 @@ impl Game<'_> { } } Some(BookScreen::View { - pages, - page, - lectern, - }) => { - let before = *page; + lectern: Some(key), .. + }) => lectern_page = Some(*key), + Some(BookScreen::View { pages, page, .. }) => { if forward && *page + 1 < pages.len() { *page += 1; } else if !forward && *page > 0 { *page -= 1; } - if *page != before - && let Some(pos) = *lectern - { - lectern_page = Some((pos, *page)); - } } None => return, } + // LecternScreen's page buttons click the menu's (1 back, 2 forward); + // the page turns with the server's data slot and level event 1043. + if let Some(key) = lectern_page { + self.lectern_button(key, if forward { 2 } else { 1 }); + return; + } self.audio .play("minecraft:item.book.page_turn", None, 1.0, 1.0); - if let Some((pos, page)) = lectern_page { - self.set_lectern_page(pos, page as i32); - } - } - /// `LecternBlockEntity.setPage` and `LecternBlock.signalPageChange`. - fn set_lectern_page(&mut self, key: (i32, i32, i32), page: i32) { - if let Some(BlockEntity::Lectern(l)) = self.world.block_entities.get_mut(&key) { - l.page = page; - } - self.set_lectern_powered(key, true); - self.lectern_pulses.push((key, 2)); - self.container_changed(key); } fn set_lectern_powered(&mut self, key: (i32, i32, i32), powered: bool) { self.set_lectern_property(key, "powered", powered); @@ -380,6 +379,7 @@ impl Game<'_> { } /// The 2-tick pulses of turned lecterns. pub(super) fn tick_lecterns(&mut self) { + self.follow_lectern(); let mut done = Vec::new(); for (key, left) in &mut self.lectern_pulses { *left -= 1; @@ -452,6 +452,7 @@ impl Game<'_> { .or_else(|| data.map(|d| d.writable_pages.clone())) .unwrap_or_default(); let page = (l.page.max(0) as usize).min(pages.len().saturating_sub(1)); + self.stats.custom("interact_with_lectern", 1); self.open_book(BookScreen::View { pages, page, @@ -459,24 +460,189 @@ impl Game<'_> { }); true } - /// `LecternMenu` "Take Book". - fn take_lectern_book(&mut self, key: (i32, i32, i32)) { - let book = match self.world.block_entities.get_mut(&key) { - Some(BlockEntity::Lectern(l)) => { - l.page = 0; - l.book.take() + /// A `LecternMenu` button of the open lectern screen: on a server it is + /// sent (`handleInventoryButtonClick`); here the lectern's menu takes it + /// with the player's inventory, and the screen follows the block entity. + fn lectern_button(&mut self, key: (i32, i32, i32), id: i32) { + if self.remote.is_some() { + if let Some((container, _)) = self.remote.as_ref().and_then(|r| r.menu.as_ref()) { + self.send( + horizon_protocol::packets::play::Serverbound::ContainerButtonClick( + horizon_protocol::packets::play::ContainerButtonClick { + container: *container, + button: id, + }, + ), + ); } - _ => None, - }; - if let Some(book) = book - && let Some(rest) = self.give(book) - && let Some(eye) = self.eye_position() - { - self.spawn_item(rest, [eye[0], eye[1] - 0.3, eye[2]], [0.0, 0.1, 0.0], 40); + return; + } + let Some(mut menu) = self.lectern_menu(key) else { + return; + }; + for i in 0..36 { + menu.set_player_item(i, self.inventory[i].clone()); + } + menu.set_player_item(40, self.offhand.clone()); + menu.creative = self.creative; + menu.selected = self.selected; + menu.may_build = self.may_build(); + if !menu.button(&self.menu_env(), id) { + return; + } + for i in 0..36 { + self.inventory[i] = menu.player_item(i).cloned(); + } + self.offhand = menu.player_item(40).cloned(); + for stack in std::mem::take(&mut menu.dropped) { + self.player_drop(stack); + } + self.lectern_menu_done(key, &menu); + self.follow_lectern(); + } + /// The `book` control command: a button of the open book or lectern + /// screen (the page arrows, Take Book, Done), then its page. + pub(super) fn book_control( + &mut self, + action: Option<&str>, + ) -> horizon_client::Result { + let lectern = match &self.book { + Some(BookScreen::View { lectern, .. }) => *lectern, + Some(BookScreen::Edit { .. }) => None, + None => return Err("no book is open".into()), + }; + match action { + None => {} + Some("next") => self.turn_page(true), + Some("back") => self.turn_page(false), + Some("take") => match lectern { + Some(key) => self.lectern_button(key, 3), + None => return Err("not a lectern".into()), + }, + Some("done") => self.close_book(), + Some(other) => return Err(format!("unknown book button {other}").into()), + } + Ok(match &self.book { + Some(BookScreen::View { + pages, + page, + lectern, + }) => serde_json::json!({ + "page": page, "pages": pages.len(), "lectern": lectern.map(|k| [k.0, k.1, k.2]), + }), + Some(BookScreen::Edit { pages, page, .. }) => { + serde_json::json!({ "page": page, "pages": pages.len(), "lectern": null }) + } + None => serde_json::json!({ "closed": true }), + }) + } + /// A server's `minecraft:lectern` menu: LecternScreen, its book and + /// page to come (`remote_lectern_book`, `remote_lectern_page`). + pub(super) fn remote_open_lectern(&mut self, key: (i32, i32, i32)) { + self.open_book(BookScreen::View { + pages: Vec::new(), + page: 0, + lectern: Some(key), + }); + } + /// `LecternScreen.bookChanged`: the menu's book slot. + pub(super) fn remote_lectern_book(&mut self, book: Option) { + if let Some(BookScreen::View { + lectern: Some(_), + pages, + page, + }) = self.book.as_mut() + { + let data = book.as_ref().and_then(ItemStack::data); + *pages = data + .and_then(|d| d.written.as_ref().map(|w| w.pages.clone())) + .or_else(|| data.map(|d| d.writable_pages.clone())) + .unwrap_or_default(); + *page = (*page).min(pages.len().saturating_sub(1)); + } + } + /// `LecternScreen.pageChanged`: the menu's page data slot. + pub(super) fn remote_lectern_page(&mut self, value: i32) { + if let Some(BookScreen::View { + lectern: Some(_), + pages, + page, + }) = self.book.as_mut() + { + *page = (value.max(0) as usize).min(pages.len().saturating_sub(1)); + } + } + /// The server closed its lectern menu; false when none is open. + pub(super) fn remote_lectern_closed(&mut self) -> bool { + if !matches!( + self.book, + Some(BookScreen::View { + lectern: Some(_), + .. + }) + ) { + return false; + } + if let Some(r) = self.remote.as_mut() { + r.menu = None; + r.menu_title = None; + } + self.book = None; + self.capture(true); + true + } + /// `LecternMenu` over the lectern at `key` (the menu engine, for the + /// local player and LAN guests alike): its book and page. + pub(super) fn lectern_menu(&self, key: (i32, i32, i32)) -> Option { + let Some(BlockEntity::Lectern(l)) = self.world.block_entities.get(&key) else { + return None; + }; + let mut menu = Menu::new(Kind::Lectern); + menu.set_slot(&self.menu_env(), 0, l.book.clone()); + menu.data[0] = l.page; + Some(menu) + } + /// The lectern menu's book and page back in the block entity: a new page + /// is `LecternBlock.signalPageChange` (the 2-tick pulse, level event + /// 1043), a book gone `onBookItemRemove` (`resetBookState`). + pub(super) fn lectern_menu_done(&mut self, key: (i32, i32, i32), menu: &Menu) { + let Some(BlockEntity::Lectern(l)) = self.world.block_entities.get_mut(&key) else { + return; + }; + let (had, before) = (l.book.is_some(), l.page); + l.book = menu.slot(0).cloned(); + l.page = menu.data[0]; + if had && l.book.is_none() { + self.set_lectern_powered(key, false); + self.set_lectern_property(key, "has_book", false); + self.container_changed(key); + } else if menu.data[0] != before { + self.set_lectern_powered(key, true); + self.lectern_pulses.push((key, 2)); + self.level_event_at(1043, [key.0, key.1, key.2], 0); + self.container_changed(key); + } + } + /// The open lectern screen follows its block entity (`LecternScreen`'s + /// menu listener): the page, and closing once the book is gone. + pub(super) fn follow_lectern(&mut self) { + let Some(BookScreen::View { + lectern: Some(key), + page, + pages, + }) = self.book.as_mut() + else { + return; + }; + if self.remote.is_some() { + return; + } + match self.world.block_entities.get(key) { + Some(BlockEntity::Lectern(l)) if l.book.is_some() => { + *page = (l.page.max(0) as usize).min(pages.len().saturating_sub(1)); + } + _ => self.close_book(), } - self.set_lectern_property(key, "has_book", false); - self.container_changed(key); - self.close_book(); } pub(super) fn book_click(&mut self, size: [u32; 2]) { let b = HudBatch::new(size); @@ -537,7 +703,8 @@ impl Game<'_> { self.close_book(); } else if inside(w / 2.0 + 2.0, 196.0, 98.0, 20.0) { click(self); - self.take_lectern_book(key); + // LecternScreen's Take Book: the menu's button 3. + self.lectern_button(key, 3); } } else if inside((w - 200.0) / 2.0, 196.0, 200.0, 20.0) { click(self); diff --git a/crates/horizon-client/src/game/cartography.rs b/crates/horizon-client/src/game/cartography.rs index 4a5738f6e..b8b57666a 100644 --- a/crates/horizon-client/src/game/cartography.rs +++ b/crates/horizon-client/src/game/cartography.rs @@ -1,70 +1,80 @@ -//! The cartography table (`CartographyTableMenu`, `CartographyTableScreen`): -//! zooming a map out with paper, cloning it with an empty map, locking it -//! with a glass pane, the post-processing on take (`MapItem.scaleMap`, -//! `lockMap`) and the preview with its error and lock sprites. +//! The cartography table (`CartographyTableMenu` on the menu engine, +//! `CartographyTableScreen`): zooming a map out with paper, cloning it with +//! an empty map, locking it with a glass pane. The engine reads the level's +//! maps through `LevelMaps`; the scaled and locked copies a take makes +//! (`MapItem.scaleMap`, `lockMap`) are registered after the click. The +//! screen draws the preview with its error and lock sprites. use super::{ Game, maps::{MapData, map_id}, - stations::Station, }; -use horizon_client::{hud::HudBatch, items::ItemStack}; +use horizon_client::{hud::HudBatch, items::ItemStack, menu::Maps}; +use std::{ + cell::{Cell, RefCell}, + collections::HashMap, +}; + +/// The level's maps as a menu sees them (`ContainerLevelAccess`): the +/// states of the maps the click can reach, and the copies it makes. +pub(super) struct LevelMaps { + states: RefCell>, + next_id: Cell, + /// (new id, source id, scaled) for each copy made. + made: RefCell>, +} + +impl Maps for LevelMaps { + fn state(&self, id: i32) -> Option<(bool, u8)> { + self.states.borrow().get(&id).copied() + } + + fn derive(&self, id: i32, scale: bool) -> Option { + let (_, s) = self.state(id)?; + let new = self.next_id.get(); + self.next_id.set(new + 1); + let made = if scale { + (false, (s + 1).min(4)) + } else { + (true, s) + }; + self.states.borrow_mut().insert(new, made); + self.made.borrow_mut().push((new, id, scale)); + Some(new) + } +} impl Game<'_> { - /// `setupResultSlot`. - pub(super) fn cartography_result(&self, s: &Station) -> Option { - let (map, extra) = (s.inputs[0].as_ref()?, s.inputs[1].as_ref()?); - let data = self.maps.data.get(&map_id(map)?)?; - match &*extra.item { - "minecraft:paper" if !data.locked && data.scale < 4 => Some(ItemStack { - count: 1, - ..map.clone() - }), - "minecraft:glass_pane" if !data.locked => Some(ItemStack { - count: 1, - ..map.clone() - }), - "minecraft:map" => Some(ItemStack { - count: 2, - ..map.clone() - }), - _ => None, + /// The maps of `stacks` (loaded as needed) for a menu over this level. + pub(super) fn level_maps<'s>( + &mut self, + stacks: impl IntoIterator, + ) -> LevelMaps { + let ids: Vec = stacks.into_iter().filter_map(map_id).collect(); + let mut states = HashMap::new(); + for id in ids { + if let Some(m) = self.map(id) { + states.insert(id, (m.locked, m.scale)); + } + } + LevelMaps { + states: RefCell::new(states), + next_id: Cell::new(self.peek_map_id()), + made: RefCell::new(Vec::new()), } } - /// `onCraftedPostProcess` for the taken result: a scaled or locked copy - /// under a new map id. Also spends the inputs' extra item kind check. - pub(super) fn cartography_post(&mut self, mut result: ItemStack) -> ItemStack { - let extra = self - .station - .as_ref() - .and_then(|s| s.inputs[1].as_ref()) - .map(|e| e.item.clone()); - let Some(id) = map_id(&result) else { - return result; - }; - let new = match extra.as_deref() { - Some("minecraft:paper") => self.map(id).map(|m| m.scaled()), - Some("minecraft:glass_pane") => self.map(id).map(|m| m.locked_copy()), - _ => None, - }; - if let Some(data) = new { - let new_id = self.new_map_id(data); - result.data_mut().map_id = Some(new_id); + + /// The scaled and locked copies a menu made (`level.setMapData`). + pub(super) fn register_made_maps(&mut self, maps: LevelMaps) { + for (id, source, scale) in maps.made.into_inner() { + let Some(data) = self + .map(source) + .map(|m| if scale { m.scaled() } else { m.locked_copy() }) + else { + continue; + }; + let new = self.new_map_id(data); + debug_assert_eq!(new, id, "map ids follow peek_map_id"); } - result - } - /// The take sound (once per tick). - pub(super) fn cartography_taken(&mut self, pos: [i32; 3]) { - let at = [ - f64::from(pos[0]) + 0.5, - f64::from(pos[1]) + 0.5, - f64::from(pos[2]) + 0.5, - ]; - self.audio.play( - "minecraft:ui.cartography_table.take_result", - Some(at), - 1.0, - 1.0, - ); } /// `CartographyTableScreen.extractBackground` after the background. pub(super) fn draw_cartography(&mut self, batch: &mut HudBatch, ox: f32, oy: f32) { diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 6a79419a1..dd0b2fcc1 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -524,13 +524,22 @@ impl Game<'_> { Screen::Inventory if self.recipe_search_focused() => { self.recipe_text(Some(text), false) } + // The anvil's rename box. + Screen::Inventory + if self + .station + .as_ref() + .is_some_and(|s| s.kind == super::stations::Kind::Anvil) => + { + self.station_text(Some(text), false) + } Screen::Creative if self.creative_screen.tab().search => { // As typed: replaces a selected query, keeps the length limit. self.creative_search_edit(Some(text), false) } _ => { return Err( - "type needs the chat screen (key t tap), the language search, the creative search or World Options".into(), + "type needs the chat screen (key t tap), the language search, the creative search, the anvil or World Options".into(), ); } } @@ -913,7 +922,7 @@ impl Game<'_> { "chunks": self.world.chunks.len(), "mobs": self.mobs.len(), "block_entities": self.world.block_entities.len(), - "pending_chunks": self.streaming.pending() + self.pending_uploads.len(), + "pending_chunks": self.streaming.pending() + self.pending_uploads.len() + self.remote_backlog(), "generated_chunks": self.streaming.generated_total, "meshed_sections": self.streaming.meshed_total, "streaming": self.streaming.stages().into_iter().map(|(k, v)| (k.to_string(), v.into())).collect::>(), diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 78efc708d..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); @@ -2107,15 +2125,22 @@ impl Game<'_> { let from = pl.position; self.spawn_mob("minecraft:endermite", [from.x, from.y, from.z], false); } + // To where the pearl started its last tick (oldPosition). + let to = p.previous; if let Some(pl) = self.player.as_mut() { - pl.position = at; + pl.position = to; pl.velocity = Vec3::ZERO; pl.fall_distance = 0.0; + pl.teleported = true; } - self.previous_position = at; + self.previous_position = to; self.hurt_player_by("minecraft:ender_pearl", 5.0); - self.audio - .play("minecraft:entity.player.teleport", Some(atp), 1.0, 1.0); + self.audio.play( + "minecraft:entity.player.teleport", + Some([to.x, to.y, to.z]), + 1.0, + 1.0, + ); } } (ProjectileKind::SmallFireball, hit) => match hit { @@ -2922,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 f5ddf537b..e30cc3d81 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.rs b/crates/horizon-client/src/game/lan.rs index f9ea1262b..548a69e3f 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -10,7 +10,7 @@ use horizon_client::{ self, Lan, MAX_PLAYERS, NetConfig, chunks::ChunkEncoder, data::SyncData, - entity::EntityState, + entity::{EntityState, States}, hub::{HostEvent, HostState, Hub, HubConfig, TickCtx}, playerdata, }, @@ -69,6 +69,9 @@ pub(super) struct LanHost { /// Guests' commands waiting for the hub to be back in `self.lan`, where /// a command can reach every player (game/lan_actions.rs). pub commands: Vec, + /// The entities the guests track, described again every tick + /// (`lan_entities`) over last tick's states. + states: lan::entity::States, } /// The player who owns an integrated server's world: a guest whose state is @@ -136,8 +139,7 @@ fn baby_index(kind: &str) -> Option { /// A mob's synched data as ServerEntity sends it (only the values that differ /// from the defaults the client constructs), with vanilla's entry indices: /// Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses. -fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> { - let mut meta = Vec::new(); +fn mob_meta(m: &Mob, hub: &Hub, meta: &mut Vec<(u8, i32, Value)>) { let kind = m.kind.id.as_str(); if m.fire_ticks > 0 { meta.push((0, serializer::BYTE, Value::Byte(1))); @@ -280,14 +282,16 @@ fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> { } _ => {} } - meta } /// The equipment a mob shows (ClientboundSetEquipmentPacket slots: main hand, /// off hand, feet, legs, chest, head, body, saddle). -fn mob_equipment(m: &Mob, hub: &mut Hub) -> Vec<(u8, Option)> { +fn mob_equipment( + m: &Mob, + hub: &mut Hub, + out: &mut Vec<(u8, Option)>, +) { let e = &m.extra; - let mut out = Vec::new(); let slots = [ (0u8, &e.main_hand), (1, &e.off_hand), @@ -316,7 +320,6 @@ fn mob_equipment(m: &Mob, hub: &mut Hub) -> Vec<(u8, Option { waypoints: Default::default(), waypoint_dead: Default::default(), commands: Vec::new(), + states: Default::default(), }); self.audio.capture = Some(Vec::new()); Ok(()) @@ -740,77 +744,44 @@ impl Game<'_> { equipment, health: p.health.health(), attributes: horizon_client::lan::attributes::syncable(&p.attributes), - living_flags: living_flags(self.using), + // Bit 4: Riptide's spin (LivingEntity.isAutoSpinAttack). + living_flags: living_flags(self.using) + | if p.auto_spin_attack_ticks > 0 { 4 } else { 0 }, bed: self.sleeping, }) } /// The entities guests track: mobs, items and the rest (game/lan_entities.rs). - fn lan_entities(&self, host_entity: Option, hub: &mut Hub) -> Vec { - let mut out = Vec::with_capacity(self.mobs.len() + self.dropped.len() + self.orbs.len()); + fn lan_entities(&self, host_entity: Option, hub: &mut Hub, out: &mut States) { + out.clear(); for m in self.mobs.iter().filter(|m| !m.removed) { - let kind = m.kind.id.as_str(); - let meta = mob_meta(m, hub); - let equipment = mob_equipment(m, hub); - let attributes = self.mob_attributes(m); - let (yaw, pitch) = (m.yaw, m.head_pitch); - out.push(EntityState { - id: m.id as i32, - uuid: entity_uuid(m.id), - kind: kind.to_owned(), - position: [m.position.x, m.position.y, m.position.z], - yaw, - pitch, - head_yaw: m.head_yaw, - on_ground: m.on_ground, - velocity: [m.velocity.x, m.velocity.y, m.velocity.z], - data: 0, - meta, - equipment, - attributes, - precise: false, - }); + let e = out.add(m.id as i32, entity_uuid(m.id), m.kind.id.as_str()); + e.position = [m.position.x, m.position.y, m.position.z]; + (e.yaw, e.pitch, e.head_yaw) = (m.yaw, m.head_pitch, m.head_yaw); + e.on_ground = m.on_ground; + e.velocity = [m.velocity.x, m.velocity.y, m.velocity.z]; + mob_meta(m, hub, &mut e.meta); + mob_equipment(m, hub, &mut e.equipment); + self.mob_attributes(m, &mut e.attributes); } for d in &self.dropped { let stack = hub.stack(&Some(d.stack.clone())); - out.push(EntityState { - id: d.id as i32, - uuid: entity_uuid(d.id), - kind: "minecraft:item".to_owned(), - position: [d.position.x, d.position.y, d.position.z], - yaw: 0.0, - pitch: 0.0, - head_yaw: 0.0, - on_ground: d.on_ground, - velocity: [d.velocity.x, d.velocity.y, d.velocity.z], - data: 0, - meta: vec![(8, serializer::ITEM_STACK, Value::Item(stack))], - equipment: Vec::new(), - attributes: Vec::new(), - precise: false, - }); + let e = out.add(d.id as i32, entity_uuid(d.id), "minecraft:item"); + e.position = [d.position.x, d.position.y, d.position.z]; + e.on_ground = d.on_ground; + e.velocity = [d.velocity.x, d.velocity.y, d.velocity.z]; + e.meta.push((8, serializer::ITEM_STACK, Value::Item(stack))); } for o in &self.orbs { - out.push(EntityState { - id: o.id as i32, - uuid: entity_uuid(o.id), - kind: "minecraft:experience_orb".to_owned(), - position: [o.position.x, o.position.y, o.position.z], - yaw: 0.0, - pitch: 0.0, - head_yaw: 0.0, - on_ground: o.on_ground, - velocity: [o.velocity.x, o.velocity.y, o.velocity.z], - data: 0, - // ExperienceOrb.DATA_VALUE. - meta: vec![(8, serializer::INT, Value::Int(o.value as i32))], - equipment: Vec::new(), - attributes: Vec::new(), - precise: false, - }); + let e = out.add(o.id as i32, entity_uuid(o.id), "minecraft:experience_orb"); + e.position = [o.position.x, o.position.y, o.position.z]; + e.on_ground = o.on_ground; + e.velocity = [o.velocity.x, o.velocity.y, o.velocity.z]; + // ExperienceOrb.DATA_VALUE. + e.meta + .push((8, serializer::INT, Value::Int(o.value as i32))); } - self.lan_object_states(host_entity, hub, &mut out); - out + self.lan_object_states(host_entity, hub, out); } /// Run the hub for this tick and apply what the guests did. @@ -832,21 +803,23 @@ impl Game<'_> { // A dedicated server runs the hub without a host player. if state.is_some() || host.hub.config.dedicated { let has_guests = !host.hub.guests.is_empty(); - let entities = if has_guests { + let mut states = std::mem::take(&mut host.states); + if has_guests { let host_entity = state.as_ref().map(|s| s.entity_id); self.lan_assign_ids(); self.lan_riding(host_entity, &mut host.hub.riding); - self.lan_entities(host_entity, &mut host.hub) + self.lan_entities(host_entity, &mut host.hub, &mut states); } else { - Vec::new() - }; + states.clear(); + } + let entities = states.as_slice(); let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]); let events = { let clock_rate = self.network_clock_rate(); let mut ctx = TickCtx { world: &mut self.world, host: state.as_ref(), - entities: &entities, + entities, next_entity: &mut self.next_entity, spawn, difficulty: i32::from(self.ui.difficulty), @@ -887,7 +860,7 @@ impl Game<'_> { self.lan_log_event(event); } HostEvent::Joined(conn) => { - self.lan_guest_joined(&mut host, conn, state.as_ref(), &entities, spawn); + self.lan_guest_joined(&mut host, conn, state.as_ref(), entities, spawn); if self.options.dedicated.is_some() && let Some(g) = host.hub.guest(conn) { @@ -952,6 +925,7 @@ impl Game<'_> { } } } + host.states = states; } self.lan_flush_effects(&mut host); self.tick_guests(&mut host); @@ -1011,15 +985,15 @@ impl Game<'_> { g.dimension = in_place; } self.load_guest_records(host, conn); - let theirs; + let mut theirs = States::default(); let entities = if elsewhere { if let Err(e) = self.enter_level(Some(host), level) { log::error!("could not open {}: {e}", level.id()); return; } // A dedicated server has no host player. - theirs = self.lan_entities(None, &mut host.hub); - &theirs[..] + self.lan_entities(None, &mut host.hub, &mut theirs); + theirs.as_slice() } else { entities }; diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index b261e8ad2..7028c2eca 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -53,6 +53,10 @@ pub(super) struct GuestPlay { pub(super) merchant: Option, /// The inventory menu and the crafting table the guest crafts in. pub(super) crafting: super::lan_crafting::GuestCrafting, + /// The workstation menu the guest has open (game/lan_stations.rs). + pub(super) station: Option, + /// The lectern the guest reads (game/lan_stations.rs). + pub(super) lectern: Option, /// What the guest's body was given for its effects and enchantments. potions: super::potions::BodyPotions, /// `ServerPlayer.getStats` and the inventory `inventory_changed` last saw. @@ -476,7 +480,13 @@ impl Game<'_> { self.container = container; self.screen = screen; self.sign_edit = host_sign; - self.book = host_book; + // A lectern the guest's use opened (LecternBlock.openScreen). + let guest_lectern = match std::mem::replace(&mut self.book, host_book) { + Some(super::books::BookScreen::View { + lectern: Some(key), .. + }) => Some(key), + _ => None, + }; self.command_block_screen = host_command_block; self.mount_menu = host_mount_menu; self.keys = host_keys; @@ -532,12 +542,14 @@ impl Game<'_> { g.health = m.health.health(); g.food = m.health.food.food; g.saturation = m.health.food.saturation; - // A teleport (commands) moves the guest. + // A teleport (commands, a pearl) moves the guest; a pearl's is + // sent even to where they stand (ServerPlayer.teleport). let at = [m.position.x, m.position.y, m.position.z]; m.sprinting = false; + let teleported = std::mem::take(&mut m.teleported); let moved: f64 = (0..3).map(|k| (at[k] - g.position[k]).powi(2)).sum(); g.motion = Some(Box::new(m)); - if moved > 0.0001 || turned { + if moved > 0.0001 || turned || teleported { host.hub.teleport(i, Some(at)); } } @@ -571,6 +583,9 @@ impl Game<'_> { if let Some(station) = opened_station { self.lan_station_opened(host, conn, station); } + if let Some(key) = guest_lectern { + self.lan_open_lectern(host, conn, key); + } if opened_table { self.lan_open_crafting(host, conn); } @@ -637,6 +652,13 @@ impl Game<'_> { _ => ("minecraft:furnace", "container.furnace"), }; (menu, title, Slots::Block(pos)) + } else if let Some(BlockEntity::Crafter(_)) = self.world.block_entities.get(&pos) { + // CrafterBlock.useWithoutItem: CrafterMenu over the block entity. + ( + "minecraft:crafter_3x3", + "container.crafter", + Slots::Block(pos), + ) } else if let Some(BlockEntity::Brewing(_)) = self.world.block_entities.get(&pos) { // BrewingStandBlock.useWithoutItem: BrewingStandMenu. ( @@ -679,6 +701,7 @@ impl Game<'_> { }; // ServerPlayer.openMenu closes the menu that was open. self.guest_container_closed(host, conn); + self.lan_station_closed(host, conn, None); host.hub.open_container( conn, menu, @@ -913,6 +936,16 @@ impl Game<'_> { S::ContainerClick(p) if self.lan_inventory_click(host, conn, &p) => {} S::ContainerClick(p) if self.lan_crafting_click(host, conn, &p) => {} S::ContainerClick(p) if self.lan_machine_click(host, conn, &p) => {} + S::ContainerClick(p) if self.lan_station_click(host, conn, &p) => {} + S::ContainerClick(p) if self.lan_lectern_click(host, conn, &p) => {} + S::ContainerButtonClick(p) => { + self.lan_station_button(host, conn, p.container, p.button); + } + S::RenameItem(p) => self.lan_station_rename(host, conn, &p.name), + S::ContainerSlotStateChanged(p) => { + self.lan_crafter_slot_state(host, conn, p.container, p.slot, p.enabled); + } + S::SetBeacon(p) => self.lan_station_beacon(host, conn, p.primary, p.secondary), S::SelectTrade(p) => self.lan_select_trade(host, conn, p.item), S::ContainerClose(p) if self.lan_merchant_closed(host, conn, Some(p.container)) => { let g = &mut host.hub.guests[gi]; @@ -920,7 +953,10 @@ impl Game<'_> { self.drop_guest_items(host, gi, vec![c]); } } - S::ContainerClose(p) if self.lan_crafting_closed(host, conn, Some(p.container)) => { + S::ContainerClose(p) + if self.lan_crafting_closed(host, conn, Some(p.container)) + || self.lan_station_closed(host, conn, Some(p.container)) => + { let g = &mut host.hub.guests[gi]; if let Some(c) = g.carried.take() { self.drop_guest_items(host, gi, vec![c]); @@ -1438,6 +1474,7 @@ impl Game<'_> { /// Per tick, for every guest: dig, use items, pick up drops, die. pub(super) fn tick_guests(&mut self, host: &mut LanHost) { self.lan_merchant_tick(host); + self.lan_stations_tick(host); self.announce_guest_advancements(host); let conns: Vec = host .hub @@ -1693,6 +1730,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/lan_attributes.rs b/crates/horizon-client/src/game/lan_attributes.rs index 72d06c2ef..73942e770 100644 --- a/crates/horizon-client/src/game/lan_attributes.rs +++ b/crates/horizon-client/src/game/lan_attributes.rs @@ -83,17 +83,16 @@ impl Game<'_> { /// `LivingEntity.removeFrost`), what finalizeSpawn set, the baby speed /// modifier, its effects' modifiers, its equipment's, and what /// `/attribute` changed. - pub(super) fn mob_attributes(&self, m: &Mob) -> Vec { + pub(super) fn mob_attributes(&self, m: &Mob, out: &mut Vec) { let kind = m.kind.id.as_str(); - let mut out = Vec::new(); if let Some(a) = self.synced_attribute(kind, "minecraft:movement_speed") { - instance(&mut out, a, finalize::base_value(m, Attr::MovementSpeed)); + instance(out, a, finalize::base_value(m, Attr::MovementSpeed)); } if let Some(s) = m.extra.attributes.as_deref() { for (attr, v) in &s.bases { if let Some(a) = self.synced_attribute(kind, &format!("minecraft:{}", attr.name())) { - instance(&mut out, a, *v).base = *v; + instance(out, a, *v).base = *v; } } for x in &s.modifiers { @@ -101,7 +100,7 @@ impl Game<'_> { self.synced_attribute(kind, &format!("minecraft:{}", x.attr.name())) { add_modifier( - &mut out, + out, a, finalize::base_value(m, x.attr), AttributeModifier { @@ -122,7 +121,7 @@ impl Game<'_> { finalize::transient(m, Attr::MovementSpeed), ) { add_modifier( - &mut out, + out, a, finalize::base_value(m, Attr::MovementSpeed), AttributeModifier { @@ -150,7 +149,7 @@ impl Game<'_> { }; let start = base(attribute).unwrap_or_else(|| self.attribute_default(kind, attribute)); add_modifier( - &mut out, + out, a, start, AttributeModifier { @@ -172,10 +171,9 @@ impl Game<'_> { ("chest", e.chest.as_ref()), ("head", e.head.as_ref()), ], - &mut out, + out, ); - self.generic_attributes_of(Target::Mob(m.id), &mut out); - out + self.generic_attributes_of(Target::Mob(m.id), out); } /// An armor stand's synced instances: movement speed (its first diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index 6101ce99e..cb3b0a2c9 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -55,6 +55,7 @@ fn load_player(menu: &mut Menu, g: &Guest) { menu.set_player_item(OFFHAND, g.offhand.clone()); menu.selected = g.selected; menu.creative = g.creative(); + menu.levels = g.xp_level; menu.carried = g.carried.clone(); } @@ -83,27 +84,47 @@ fn place_back(menu: &mut Menu, env: &Env, stacks: Vec) { } impl Game<'_> { - fn menu_env(&self) -> Env<'_> { + pub(super) fn menu_env(&self) -> Env<'_> { Env { items: self.res.items(), recipes: self.res.recipes(), brewing: &self.res.stations().brewing, banners: &self.res.stations().banners, + station_recipes: &self.res.stations().recipes, + enchantments: &self.res.stations().enchantments, + names: &self.pack.names, trade: None, + maps: None, } } /// Runs `op` on the guest's menu with their inventory copied in and back. - fn guest_menu_op( + pub(super) fn guest_menu_op( &mut self, host: &mut LanHost, gi: usize, menu: &mut Menu, op: impl FnOnce(&mut Menu, &Env) -> R, ) -> R { - let env = self.menu_env(); + // The cartography table reads and makes the host level's maps. + let maps = (menu.kind() == Kind::Cartography).then(|| { + let g = &host.hub.guests[gi]; + let held: Vec = (0..menu.slot_count()) + .filter_map(|s| menu.slot(s).cloned()) + .chain(g.inventory.iter().flatten().cloned()) + .chain(g.carried.clone()) + .collect(); + self.level_maps(&held) + }); + let env = Env { + maps: maps.as_ref().map(|m| m as &dyn horizon_client::menu::Maps), + ..self.menu_env() + }; load_player(menu, &host.hub.guests[gi]); let result = op(menu, &env); + if let Some(maps) = maps { + self.register_made_maps(maps); + } let dropped = std::mem::take(&mut menu.dropped); let equipped = std::mem::take(&mut menu.equipped); menu.drops.clear(); @@ -201,8 +222,14 @@ impl Game<'_> { (Kind::Furnace(recipe), f.items.to_vec()) } Some(BlockEntity::Brewing(b)) => (Kind::Brewing, b.items.to_vec()), + Some(BlockEntity::Crafter(c)) => (Kind::CrafterBlock, c.items.to_vec()), _ => return false, }; + // CrafterBlockEntity.containerData: the disabled slots, then triggered. + let crafter_data = match self.world.block_entities.get(&pos) { + Some(BlockEntity::Crafter(c)) => Some((c.disabled, c.triggered)), + _ => None, + }; if host.hub.guests[gi].spectator() { return true; } @@ -219,6 +246,13 @@ impl Game<'_> { for (k, s) in items.iter().enumerate() { menu.set_slot(env, k, s.clone()); } + // After the slots: setting a disabled slot (CrafterBlockEntity.setItem) enables it. + if let Some((disabled, triggered)) = crafter_data { + for (k, d) in disabled.iter().enumerate() { + menu.data[k] = i32::from(*d); + } + menu.data[9] = i32::from(triggered); + } let before: Vec<_> = (0..menu.slot_count()) .map(|s| menu.slot(s).cloned()) .collect(); @@ -241,6 +275,13 @@ impl Game<'_> { b.items[k] = menu.slot(k).cloned(); } } + // CrafterBlockEntity.setItem: filling a disabled slot enables it. + Some(BlockEntity::Crafter(c)) => { + for k in 0..9 { + c.items[k] = menu.slot(k).cloned(); + c.disabled[k] = menu.data[k] == 1; + } + } _ => {} } host.play.entry(conn).or_default().crafting.machine = Some((p.container, menu)); @@ -248,6 +289,39 @@ impl Game<'_> { true } + /// `ServerGamePacketListenerImpl.handleContainerSlotStateChanged`: a + /// guest's crafter slot toggle (`CrafterBlockEntity.setSlotState`) in + /// their open crafter window. + pub(super) fn lan_crafter_slot_state( + &mut self, + host: &mut LanHost, + conn: u32, + window: i32, + slot: i32, + enabled: bool, + ) { + let Some(pos) = host + .hub + .guest(conn) + .filter(|g| !g.spectator()) + .and_then(|g| g.menu.as_ref()) + .filter(|m| window != 0 && m.window == window) + .and_then(|m| match m.slots { + Slots::Block(pos) => Some(pos), + _ => None, + }) + else { + return; + }; + if let (Some(BlockEntity::Crafter(c)), Ok(slot)) = ( + self.world.block_entities.get_mut(&pos), + usize::try_from(slot), + ) { + c.set_slot_state(slot, enabled); + self.world.modified.insert((pos.0 >> 4, pos.2 >> 4)); + } + } + /// ServerGamePacketListenerImpl.handlePlaceRecipe: the guest's recipe /// book places a known recipe in their inventory grid or crafting table /// (`ServerPlaceRecipe`), and answers with a ghost recipe when the items @@ -331,6 +405,7 @@ impl Game<'_> { /// The guest opened a crafting table (`CraftingTableBlock.getMenuProvider`). pub(super) fn lan_open_crafting(&mut self, host: &mut LanHost, conn: u32) { self.lan_crafting_closed(host, conn, None); + self.lan_station_closed(host, conn, None); // The container it replaces loses its opener. self.guest_container_closed(host, conn); let title = horizon_protocol::text::translatable("container.crafting", &[]); @@ -430,22 +505,35 @@ impl Game<'_> { None => return false, } }; - if grid.is_empty() { - return true; + if !grid.is_empty() { + self.lan_place_back(host, gi, grid); } - let mut menu = Menu::new(Kind::Inventory); - self.guest_menu_op(host, gi, &mut menu, |menu, env| place_back(menu, env, grid)); true } - /// A guest left: what their crafting grids held goes back into their + /// `Inventory.placeItemBackInInventory` of `stacks` for guest `gi`, what + /// doesn't fit dropped (`clearContainer`). + pub(super) fn lan_place_back(&mut self, host: &mut LanHost, gi: usize, stacks: Vec) { + let mut menu = Menu::new(Kind::Inventory); + self.guest_menu_op(host, gi, &mut menu, |menu, env| { + place_back(menu, env, stacks) + }); + } + + /// A guest left: what their crafting grids and workstation held goes back into their /// inventory before it is saved (dropped where they stood if full). pub(super) fn lan_crafting_left(&mut self, host: &mut LanHost, g: &mut Guest) { - let table = host.play.remove(&g.conn).and_then(|p| p.crafting.table); + let play = host.play.remove(&g.conn); let mut grid: Vec = g.craft_grid.iter_mut().filter_map(Option::take).collect(); g.craft_result = None; - if let Some((_, _, menu)) = table { - grid.extend((1..10).filter_map(|s| menu.slot(s).cloned())); + if let Some(play) = play { + if let Some((_, _, menu)) = play.crafting.table { + grid.extend((1..10).filter_map(|s| menu.slot(s).cloned())); + } + // A workstation's inputs too. + if let Some(station) = &play.station { + grid.extend(super::lan_stations::station_inputs(station)); + } } if grid.is_empty() { return; diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 7230e323d..404d00c46 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -5,7 +5,7 @@ //! synched data that differs from the defaults), and who rides what. use super::Game; use horizon_client::lan::{ - entity::{EntityState, Riding}, + entity::{EntityState, Riding, States}, hub::Hub, }; use horizon_protocol::entity_data::{Value, serializer}; @@ -107,7 +107,7 @@ impl Game<'_> { &self, host_entity: Option, hub: &mut Hub, - out: &mut Vec, + out: &mut States, ) { for b in &self.boats { let p = b.position; @@ -268,12 +268,7 @@ impl Game<'_> { /// Primed TNT, falling blocks, projectiles, tridents, firework rockets and /// end crystals, as guests track them. - fn lan_projectile_states( - &self, - host_entity: Option, - hub: &mut Hub, - out: &mut Vec, - ) { + fn lan_projectile_states(&self, host_entity: Option, hub: &mut Hub, out: &mut States) { let owner = |who: Option| match who { Some(horizon_client::mobs::Who::Mob(id)) => id as i32, Some(horizon_client::mobs::Who::Player) => host_entity.unwrap_or(0), diff --git a/crates/horizon-client/src/game/lan_stations.rs b/crates/horizon-client/src/game/lan_stations.rs new file mode 100644 index 000000000..25921f936 --- /dev/null +++ b/crates/horizon-client/src/game/lan_stations.rs @@ -0,0 +1,672 @@ +//! Workstation menus for LAN guests: the screen a guest's use opens runs on +//! the host's menu engine (`horizon_client::menu`), the one single player +//! uses, with vanilla's packets: OpenScreen with the station's `MenuType`, +//! container clicks, `ServerboundContainerButtonClickPacket`, the content and +//! data slot sync after each (`broadcastChanges`), and the inputs back into +//! the inventory when the menu closes (`AbstractContainerMenu.clearContainer`). +use super::{ + Game, + lan::LanHost, + lan_crafting::input, + stations::{Kind as StationKind, Station}, +}; +use horizon_client::{ + containers::BlockEntity, + items::ItemStack, + menu::{Kind, Menu}, +}; +use horizon_core::random::RandomSource; +use horizon_protocol::packets::play::{self, Clientbound as C}; + +/// A guest's open workstation menu. +pub(super) struct GuestStation { + window: i32, + state: i32, + kind: StationKind, + pos: [i32; 3], + menu: Box, + /// The data slots the client was last sent. + sent_data: Vec, + /// The game time of the menu's last sound (`lastSoundTime`). + last_sound: u64, +} + +/// A guest's open lectern: `LecternMenu` over the block entity, made on the +/// menu engine for each click (`Game::lectern_menu`). +pub(super) struct GuestLectern { + window: i32, + state: i32, + key: (i32, i32, i32), + /// The book and page the client was last sent (`broadcastChanges`). + sent: Option<(Option, i32)>, +} + +/// The `MenuType`, the engine's menu and the input slots +/// (`clearContainer`'s container) of a station a guest can use. +fn menu_of(kind: StationKind) -> Option<(&'static str, Kind, std::ops::Range)> { + Some(match kind { + StationKind::Loom => ("minecraft:loom", Kind::Loom, 0..3), + StationKind::Stonecutter => ("minecraft:stonecutter", Kind::Stonecutter, 0..1), + StationKind::Grindstone => ("minecraft:grindstone", Kind::Grindstone, 0..2), + StationKind::Anvil => ("minecraft:anvil", Kind::Anvil, 0..2), + StationKind::Smithing => ("minecraft:smithing", Kind::Smithing, 0..3), + StationKind::Enchanting => ("minecraft:enchantment", Kind::Enchanting, 0..2), + StationKind::Beacon => ("minecraft:beacon", Kind::Beacon, 0..1), + StationKind::Cartography => ("minecraft:cartography_table", Kind::Cartography, 0..2), + _ => return None, + }) +} + +impl Game<'_> { + /// A workstation a guest's use opened (`ServerPlayer.openMenu`); false + /// when guests can't use that one yet. + pub(super) fn lan_open_station( + &mut self, + host: &mut LanHost, + conn: u32, + station: &Station, + ) -> bool { + let Some((menu_type, kind, _)) = menu_of(station.kind) else { + return false; + }; + self.lan_station_closed(host, conn, None); + self.lan_crafting_closed(host, conn, None); + // The container it replaces loses its opener. + self.guest_container_closed(host, conn); + let title = horizon_protocol::text::translatable(station.kind.title_key(), &[]); + let Some(window) = host.hub.open_window(conn, menu_type, title) else { + return true; + }; + let mut menu = Box::new(Menu::new(kind)); + if let Some(g) = host.hub.guests.iter_mut().find(|g| g.conn == conn) + && kind == Kind::Enchanting + { + // Player.enchantmentSeed, made when first needed. + if g.xp_seed == 0 { + g.xp_seed = self.world.random.next_int(); + } + menu.data[3] = g.xp_seed; + } + if kind == Kind::Beacon { + menu.data = self.beacon_data(host, station.pos).to_vec(); + } + host.play.entry(conn).or_default().station = Some(GuestStation { + window, + state: 0, + kind: station.kind, + pos: station.pos, + menu, + sent_data: Vec::new(), + last_sound: 0, + }); + self.lan_send_station(host, conn); + true + } + + /// Runs `op` on the guest's open station (window `window`, any when + /// None) with their inventory in it, then sends what changed. False when + /// no such window is open. + fn lan_station_op( + &mut self, + host: &mut LanHost, + conn: u32, + window: Option, + op: impl FnOnce(&mut Menu, &horizon_client::menu::Env), + ) -> bool { + let Some(mut gs) = host + .play + .get_mut(&conn) + .and_then(|p| p.station.take_if(|s| window.is_none_or(|w| s.window == w))) + else { + return false; + }; + if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) + && !host.hub.guests[gi].spectator() + { + self.guest_menu_op(host, gi, &mut gs.menu, op); + self.lan_station_sounds(&mut gs); + if let Some(amount) = gs.menu.ground.take() { + self.grindstone_taken(gs.pos, amount); + } + self.lan_station_combined(host, conn, &mut gs); + if let Some(button) = gs.menu.enchant_button.take() { + self.lan_enchant(host, gi, &mut gs, button); + } + if std::mem::take(&mut gs.menu.enchant_changed) { + self.lan_enchant_offers(host, gi, &mut gs); + } + } + host.play.entry(conn).or_default().station = Some(gs); + self.lan_send_station(host, conn); + true + } + + /// `LecternBlock.openScreen` for a guest: `minecraft:lectern` over the + /// block entity, with its book and page. + pub(super) fn lan_open_lectern(&mut self, host: &mut LanHost, conn: u32, key: (i32, i32, i32)) { + self.lan_station_closed(host, conn, None); + self.lan_crafting_closed(host, conn, None); + self.guest_container_closed(host, conn); + let title = horizon_protocol::text::translatable("container.lectern", &[]); + let Some(window) = host.hub.open_window(conn, "minecraft:lectern", title) else { + return; + }; + host.play.entry(conn).or_default().lectern = Some(GuestLectern { + window, + state: 0, + key, + sent: None, + }); + self.lan_send_lectern(host, conn, true); + } + + /// The lectern's book and page for the client: everything (`all`), or + /// what changed since it was last sent. + fn lan_send_lectern(&mut self, host: &mut LanHost, conn: u32, all: bool) { + let Some(gl) = host.play.get_mut(&conn).and_then(|p| p.lectern.as_mut()) else { + return; + }; + let (book, page) = match self.world.block_entities.get(&gl.key) { + Some(BlockEntity::Lectern(l)) => (l.book.clone(), l.page), + _ => (None, 0), + }; + let now = Some((book.clone(), page)); + if !all && gl.sent == now { + return; + } + let page_changed = gl.sent.as_ref().is_none_or(|(_, p)| *p != page); + gl.sent = now; + gl.state = (gl.state + 1) & 0x7FFF; + let (window, state) = (gl.window, gl.state); + let carried = host + .hub + .guests + .iter() + .find(|g| g.conn == conn) + .and_then(|g| g.carried.clone()); + let content = C::ContainerSetContent(play::ContainerSetContent { + container: window, + state, + items: vec![host.hub.stack(&book)], + carried: host.hub.stack(&carried), + }); + host.hub.send_to(conn, &content); + if all || page_changed { + host.hub.send_to( + conn, + &C::ContainerSetData(play::ContainerSetData { + container: window, + id: 0, + value: page as i16, + }), + ); + } + } + + /// Runs `op` on the guest's lectern menu (window `window`) with their + /// inventory, the block entity takes the book and page back, and the + /// client gets what changed. False when no such window is open. + fn lan_lectern_op( + &mut self, + host: &mut LanHost, + conn: u32, + window: i32, + op: impl FnOnce(&mut Menu, &horizon_client::menu::Env), + ) -> bool { + let Some(key) = host + .play + .get(&conn) + .and_then(|p| p.lectern.as_ref()) + .filter(|l| l.window == window) + .map(|l| l.key) + else { + return false; + }; + if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) + && !host.hub.guests[gi].spectator() + && let Some(mut menu) = self.lectern_menu(key) + { + // Player.mayBuild: survival and creative. + let may_build = matches!(host.hub.guests[gi].game_mode, 0 | 1); + self.guest_menu_op(host, gi, &mut menu, |menu, env| { + menu.may_build = may_build; + op(menu, env); + }); + self.lectern_menu_done(key, &menu); + } + self.lan_send_lectern(host, conn, true); + true + } + + /// A click on the guest's lectern window; false for other windows. + pub(super) fn lan_lectern_click( + &mut self, + host: &mut LanHost, + conn: u32, + p: &play::ContainerClick, + ) -> bool { + self.lan_lectern_op(host, conn, p.container, |menu, env| { + let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input)); + }) + } + + /// The rest of a taken anvil or smithing result's `onTake`: the guest + /// pays the levels, the anvil wears (level event 1030 or 1029), the + /// smithing table sounds (1044). + fn lan_station_combined(&mut self, host: &mut LanHost, conn: u32, gs: &mut GuestStation) { + let change = std::mem::take(&mut gs.menu.level_change); + if change != 0 { + self.as_guest(host, conn, |g| g.give_levels(change)); + } + if !std::mem::take(&mut gs.menu.combined) { + return; + } + if gs.kind == StationKind::Smithing { + self.level_event_at(1044, gs.pos, 0); + } else { + let creative = gs.menu.creative; + // A broken anvil closes the menu on the next stillValid check. + self.anvil_used(gs.pos, creative); + } + } + + /// `EnchantmentMenu.slotsChanged` with a level: the costs and clues for + /// the guest's seed and the bookshelves around the table. + fn lan_enchant_offers(&mut self, host: &LanHost, gi: usize, gs: &mut GuestStation) { + let seed = host.hub.guests[gi].xp_seed; + let bookcases = self.count_bookshelves(gs.pos); + let offers = horizon_client::stations::enchant_offers( + &self.res.stations().enchantments, + self.res.items(), + seed, + bookcases, + gs.menu.slot(0), + ); + for i in 0..3 { + gs.menu.data[i] = offers.costs[i]; + let clue = offers.clues[i].as_ref(); + gs.menu.data[4 + i] = clue + .and_then(|(e, _)| host.hub.registry_id("minecraft:enchantment", e)) + .unwrap_or(-1); + gs.menu.data[7 + i] = clue.map_or(-1, |(_, l)| *l as i32); + } + gs.menu.data[3] = seed; + } + + /// `EnchantmentMenu.clickMenuButton`'s `access.execute`: the item gets + /// the offer's enchantments, the guest pays its levels and lapis and + /// gets a new seed, the table sounds, and the offers are made again. + fn lan_enchant(&mut self, host: &mut LanHost, gi: usize, gs: &mut GuestStation, button: usize) { + let Some(item) = gs.menu.slot(0).cloned() else { + return; + }; + let g = &host.hub.guests[gi]; + let (seed, creative, conn) = (g.xp_seed, g.creative(), g.conn); + let Some(enchanted) = horizon_client::stations::apply_enchantment( + &self.res.stations().enchantments, + self.res.items(), + seed, + button, + gs.menu.data[button], + &item, + ) else { + return; + }; + let need = button as i32 + 1; + // Player.onEnchantmentPerformed, and EnchantmentMenu's awardStat(ENCHANT_ITEM). + self.as_guest(host, conn, |game| { + game.give_levels(-need); + game.stats.custom("enchant_item", 1); + }); + host.hub.guests[gi].xp_seed = self.world.random.next_int(); + let env = self.menu_env(); + let lapis = gs.menu.slot(1).cloned().filter(|_| !creative).map(|mut l| { + l.count = l.count.saturating_sub(need as u32); + l + }); + gs.menu.set_slot(&env, 0, Some(enchanted)); + if !creative { + gs.menu.set_slot(&env, 1, lapis.filter(|l| l.count > 0)); + } + gs.menu.enchant_changed = false; + self.lan_enchant_offers(host, gi, gs); + let pitch = self.world.random.next_float() * 0.1 + 0.9; + let at = gs.pos.map(|v| f64::from(v) + 0.5); + self.audio.play( + "minecraft:block.enchantment_table.use", + Some(at), + 1.0, + pitch, + ); + } + + /// `ServerGamePacketListenerImpl.handleRenameItem`: the guest's anvil + /// takes the name (`AnvilMenu.setItemName`). + pub(super) fn lan_station_rename(&mut self, host: &mut LanHost, conn: u32, name: &str) { + let anvil = host + .play + .get(&conn) + .and_then(|p| p.station.as_ref()) + .is_some_and(|s| s.kind == StationKind::Anvil); + if anvil { + self.lan_station_op(host, conn, None, |menu, env| { + menu.rename(env, name); + }); + } + } + + /// The sounds the menu played, at the station (heard by everyone around, + /// as `level.playSound(null, pos, ...)`), once per tick. + fn lan_station_sounds(&mut self, gs: &mut GuestStation) { + let sounds = std::mem::take(&mut gs.menu.sounds); + if sounds.is_empty() || gs.last_sound == self.ticks { + return; + } + gs.last_sound = self.ticks; + let at = gs.pos.map(|v| f64::from(v) + 0.5); + for sound in sounds { + self.audio.play(sound, Some(at), 1.0, 1.0); + } + } + + /// A click on the guest's station window; false for other windows. + pub(super) fn lan_station_click( + &mut self, + host: &mut LanHost, + conn: u32, + p: &play::ContainerClick, + ) -> bool { + self.lan_station_op(host, conn, Some(p.container), |menu, env| { + let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input)); + }) + } + + /// `ServerGamePacketListenerImpl.handleContainerButtonClick`: + /// `clickMenuButton`, then `broadcastChanges` when the menu took it. + pub(super) fn lan_station_button( + &mut self, + host: &mut LanHost, + conn: u32, + window: i32, + id: i32, + ) { + // LecternMenu's page buttons and Take Book. + if self.lan_lectern_op(host, conn, window, |menu, env| { + menu.button(env, id); + }) { + return; + } + self.lan_station_op(host, conn, Some(window), |menu, env| { + menu.button(env, id); + }); + } + + /// The whole station menu and its changed data slots for the client + /// (`sendAllDataToRemote` / `broadcastChanges`). + fn lan_send_station(&mut self, host: &mut LanHost, conn: u32) { + let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { + return; + }; + let Some(gs) = host.play.get_mut(&conn).and_then(|p| p.station.as_mut()) else { + return; + }; + gs.state = (gs.state + 1) & 0x7FFF; + let own = gs.menu.slot_count() - 36; + let mut items: Vec> = + (0..own).map(|s| gs.menu.slot(s).cloned()).collect(); + let g = &host.hub.guests[gi]; + items.extend((9..36).chain(0..9).map(|i| g.inventory[i].clone())); + let carried = g.carried.clone(); + let packet = C::ContainerSetContent(play::ContainerSetContent { + container: gs.window, + state: gs.state, + items: items.iter().map(|s| host.hub.stack(s)).collect(), + carried: host.hub.stack(&carried), + }); + gs.sent_data.resize(gs.menu.data.len(), i32::MIN); + let mut data = Vec::new(); + for (k, &v) in gs.menu.data.iter().enumerate() { + if gs.sent_data[k] != v { + gs.sent_data[k] = v; + data.push(C::ContainerSetData(play::ContainerSetData { + container: gs.window, + id: k as i16, + value: v as i16, + })); + } + } + host.hub.send_to(conn, &packet); + for packet in data { + host.hub.send_to(conn, &packet); + } + } + + /// `AbstractContainerMenu.removed` of the guest's station (`window`; + /// None closes it whichever it is): the carried stack and the inputs go + /// back to the inventory, what doesn't fit is dropped. False when no such + /// window is open. + pub(super) fn lan_station_closed( + &mut self, + host: &mut LanHost, + conn: u32, + window: Option, + ) -> bool { + // A lectern's menu keeps nothing of its own (the book is the block entity's). + let lectern = host + .play + .get_mut(&conn) + .and_then(|p| p.lectern.take_if(|l| window.is_none_or(|w| l.window == w))); + if lectern.is_some() { + // AbstractContainerMenu.removed: the carried stack goes back. + if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) + && let Some(carried) = host.hub.guests[gi].carried.take() + { + self.lan_place_back(host, gi, vec![carried]); + } + if window.is_some() { + return true; + } + } + let Some(gs) = host + .play + .get_mut(&conn) + .and_then(|p| p.station.take_if(|s| window.is_none_or(|w| s.window == w))) + else { + return false; + }; + let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { + return true; + }; + // AbstractContainerMenu.removed: the carried stack first, then the inputs. + let mut back: Vec = host.hub.guests[gi].carried.take().into_iter().collect(); + let inputs = station_inputs(&gs); + if gs.kind == StationKind::Beacon { + // BeaconMenu.removed drops the payment (player.drop). + if !back.is_empty() { + self.lan_place_back(host, gi, std::mem::take(&mut back)); + } + self.drop_guest_items(host, gi, inputs); + } else { + back.extend(inputs); + } + if !back.is_empty() { + self.lan_place_back(host, gi, back); + } + true + } + + /// `BeaconBlockEntity.dataAccess`: the pyramid's levels and the powers + /// (`BeaconMenu.encodeEffect`: the `mob_effect` id + 1, 0 for none). + fn beacon_data(&self, host: &LanHost, pos: [i32; 3]) -> [i32; 3] { + let Some(BlockEntity::Beacon(b)) = self.world.block_entities.get(&(pos[0], pos[1], pos[2])) + else { + return [0; 3]; + }; + let encode = |e: &Option| { + e.as_deref() + .and_then(|n| host.hub.registry_id("minecraft:mob_effect", n)) + .map_or(0, |id| id + 1) + }; + [b.levels, encode(&b.primary), encode(&b.secondary)] + } + + /// `ServerGamePacketListenerImpl.handleSetBeaconPacket`: the guest's + /// beacon menu takes the powers (`BeaconMenu.updateEffects`), and they + /// become the block entity's (`dataAccess.set`: the power_select sound + /// while the beam is up). + pub(super) fn lan_station_beacon( + &mut self, + host: &mut LanHost, + conn: u32, + primary: Option, + secondary: Option, + ) { + let Some(pos) = host + .play + .get(&conn) + .and_then(|p| p.station.as_ref()) + .filter(|s| s.kind == StationKind::Beacon) + .map(|s| s.pos) + else { + return; + }; + // An id the registry doesn't have fails the packet's codec. + let mut powers: [Option<(i32, String)>; 2] = [None, None]; + for (k, id) in [primary, secondary].into_iter().enumerate() { + if let Some(id) = id { + let Some(name) = host.hub.registry_name("minecraft:mob_effect", id) else { + return; + }; + powers[k] = Some((id, name.to_owned())); + } + } + let data = self.beacon_data(host, pos); + let mut updated = false; + self.lan_station_op(host, conn, None, |menu, env| { + menu.data.copy_from_slice(&data); + let power = |k: usize| powers[k].as_ref().map(|(id, n)| (*id, n.as_str())); + updated = menu.beacon_update(env, power(0), power(1)); + }); + if !updated { + return; + } + let [primary, secondary] = powers.map(|p| p.map(|(_, n)| n)); + let mut select_sound = false; + if let Some(BlockEntity::Beacon(b)) = + self.world.block_entities.get_mut(&(pos[0], pos[1], pos[2])) + { + b.primary = primary; + b.secondary = secondary; + select_sound = !b.sections.is_empty(); + } + if select_sound { + self.beacon_sound(pos, "minecraft:block.beacon.power_select"); + } + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); + } + + /// `ServerPlayer.doTick`'s `stillValid`: a guest's station closes once its + /// block is gone or the guest is out of reach (`isWithinBlockInteractionRange(pos, 4)`). + pub(super) fn lan_stations_tick(&mut self, host: &mut LanHost) { + self.lan_lecterns_tick(host); + let conns: Vec = host + .play + .iter() + .filter(|(_, p)| p.station.is_some()) + .map(|(c, _)| *c) + .collect(); + for conn in conns { + let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else { + continue; + }; + if !host.hub.here(g) { + continue; + } + let Some(gs) = host.play.get(&conn).and_then(|p| p.station.as_ref()) else { + continue; + }; + let [x, y, z] = gs.pos; + let name = &self.res.facts().get(self.world.block(x, y, z)).name; + let block = StationKind::from_block(name) == Some(gs.kind); + let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]]; + // The block interaction range (4.5, creative 5) and the buffer. + let reach = if g.creative() { 5.0 } else { 4.5 } + 4.0; + let near = (0..3) + .map(|k| { + let lo = f64::from(gs.pos[k]); + (lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2) + }) + .sum::() + < reach * reach; + if !(block && near) { + let window = gs.window; + self.lan_station_closed(host, conn, Some(window)); + host.hub.send_to( + conn, + &C::ContainerClose(play::ContainerClose { container: window }), + ); + } else if gs.kind == StationKind::Beacon { + // The beacon's data slots follow its block entity. + let data = self.beacon_data(host, gs.pos); + if let Some(gs) = host.play.get_mut(&conn).and_then(|p| p.station.as_mut()) + && gs.menu.data[..] != data[..] + { + gs.menu.data.copy_from_slice(&data); + self.lan_send_station(host, conn); + } + } + } + } +} + +impl Game<'_> { + /// The guests' lecterns each tick: `stillValid` (the block entity, its + /// book, the reach) closes them, and `broadcastChanges` sends a book or + /// page another player changed. + fn lan_lecterns_tick(&mut self, host: &mut LanHost) { + let open: Vec<(u32, i32, (i32, i32, i32))> = host + .play + .iter() + .filter_map(|(c, p)| p.lectern.as_ref().map(|l| (*c, l.window, l.key))) + .collect(); + for (conn, window, key) in open { + let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else { + continue; + }; + if !host.hub.here(g) { + continue; + } + let has_book = matches!( + self.world.block_entities.get(&key), + Some(BlockEntity::Lectern(l)) if l.book.is_some() + ); + // Container.stillValidBlockEntity: the interaction range and its buffer. + let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]]; + let reach = if g.creative() { 5.0 } else { 4.5 } + 4.0; + let pos = [key.0, key.1, key.2]; + let near = (0..3) + .map(|k| { + let lo = f64::from(pos[k]); + (lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2) + }) + .sum::() + < reach * reach; + if has_book && near { + self.lan_send_lectern(host, conn, false); + } else { + self.lan_station_closed(host, conn, Some(window)); + host.hub.send_to( + conn, + &C::ContainerClose(play::ContainerClose { container: window }), + ); + } + } + } +} + +/// What `clearContainer` gives back from a station's menu. +pub(super) fn station_inputs(gs: &GuestStation) -> Vec { + menu_of(gs.kind) + .map(|(_, _, inputs)| inputs.filter_map(|s| gs.menu.slot(s).cloned()).collect()) + .unwrap_or_default() +} diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index c7f8a94a6..786399dac 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -55,8 +55,9 @@ impl Game<'_> { state.session.update_special_prices(); } let title = self.merchant_display_name(&state); - // The container the trading screen replaces loses its opener. + // The container or workstation the trading screen replaces is closed. self.guest_container_closed(host, conn); + self.lan_station_closed(host, conn, None); let Some(window) = host.hub.open_merchant_window(conn, title) else { self.merchant_closed(&mut state); return; @@ -254,7 +255,11 @@ impl Game<'_> { recipes: self.res.recipes(), brewing: &self.res.stations().brewing, banners: &self.res.stations().banners, + station_recipes: &self.res.stations().recipes, + enchantments: &self.res.stations().enchantments, + names: &self.pack.names, trade: Some(&trade_env), + maps: None, }; let mut menu = Menu::new(Kind::Merchant); { @@ -393,8 +398,8 @@ impl Game<'_> { }); } } - /// Takes a station a guest's action opened: a trading screen goes to the - /// guest; other stations are not shown to guests yet. + /// Takes a station a guest's action opened: a trading screen or a + /// workstation menu goes to the guest (game/lan_stations.rs). pub(super) fn lan_station_opened( &mut self, host: &mut LanHost, @@ -406,6 +411,8 @@ impl Game<'_> { && let Some(m) = station.merchant.take() { self.lan_open_merchant(host, conn, *m); + return; } + self.lan_open_station(host, conn, &station); } } diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index 31b34a9d0..7df5541b4 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -312,15 +312,10 @@ impl Game<'_> { .map_or_else(String::new, |(end, start)| { format!(", cpu {:.1} ms", (end - start).as_secs_f32() * 1000.0) }); - let list: Vec = spans - .iter() - .filter(|(_, ms)| *ms >= 0.5) - .map(|(n, ms)| format!("{n} {ms:.1}")) - .collect(); log::info!( "Horizon: slow tick {wall:.1} ms{cpu} ({} mobs): {}", self.mobs.len(), - list.join(", ") + horizon_client::spans::describe(&spans) ); } result 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/loom.rs b/crates/horizon-client/src/game/loom.rs index f1ff1a300..ef49c8cf1 100644 --- a/crates/horizon-client/src/game/loom.rs +++ b/crates/horizon-client/src/game/loom.rs @@ -68,8 +68,9 @@ impl Game<'_> { } l.last_inputs = inputs; } - /// A sound the loom menu played: the result's once per tick. - pub(super) fn loom_sound(&mut self, sound: &str) { + /// A sound the loom or stonecutter menu played: the result's once per + /// tick (`lastSoundTime`). + pub(super) fn station_sound(&mut self, sound: &str) { let ticks = self.ticks; let Some(s) = self.station.as_mut() else { return; @@ -98,6 +99,7 @@ impl Game<'_> { if taken { self.audio .play("minecraft:ui.loom.select_pattern", None, 1.0, 1.0); + self.remote_station_button(index as i32); } taken } 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/machines/crafter.rs b/crates/horizon-client/src/game/machines/crafter.rs index d87646fe0..0fe66f7c8 100644 --- a/crates/horizon-client/src/game/machines/crafter.rs +++ b/crates/horizon-client/src/game/machines/crafter.rs @@ -8,6 +8,7 @@ use horizon_client::{ containers::Crafter, hud::{HudBatch, rgba}, }; +use horizon_protocol::packets::play::{self, Serverbound as S}; use serde_json::Value; /// `CrafterBlock`'s crafting animation length. @@ -323,6 +324,15 @@ impl Game<'_> { menu.set_slot_state(i, enabled); Some(true) }); + if let Some((container, _)) = self.remote.as_ref().and_then(|r| r.menu.clone()) { + self.send(S::ContainerSlotStateChanged( + play::ContainerSlotStateChanged { + slot: i as i32, + container, + enabled, + }, + )); + } let pitch = if enabled { 1.0 } else { 0.75 }; self.audio .play("minecraft:ui.button.click", None, 0.4, pitch); 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 0fab09bde..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))) @@ -191,7 +256,13 @@ impl NaturalLevel for GameLevel<'_, '_> { StructureSpawns::shared(&self.game.options.resources) } fn nearest_player_distance_sqr(&self, x: f64, y: f64, z: f64) -> Option { - nearest_player(&self.players, x, y, z).map(|p| p.distance_sqr(x, y, z)) + // The nearest player's distance (`nearest_player`), without finding + // which player it is: every spawn attempt asks. + self.players + .iter() + .filter(|p| !p.spectator) + .map(|p| p.distance_sqr(x, y, z)) + .reduce(f64::min) } fn respawn(&self) -> Option<[i32; 3]> { // The world spawn point lives in the overworld. @@ -218,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() @@ -238,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") @@ -283,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 @@ -305,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/perspective.rs b/crates/horizon-client/src/game/perspective.rs index ec46120dd..bd2721648 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -312,6 +312,7 @@ impl Game<'_> { let crouching = p.pose == Pose::Crouching; let (position, flying) = (p.position, p.flying || p.fall_flying); let (fall_flying, fly_ticks, velocity) = (p.fall_flying, p.fall_fly_ticks, p.velocity); + let spinning = p.auto_spin_attack_ticks > 0; let using = self.using.map(|(_, ticks)| ticks as i32 + 1).unwrap_or(0); let using_off_hand = self .using @@ -397,6 +398,7 @@ impl Game<'_> { m.velocity = velocity; m.extra.fall_flying = fall_flying; m.extra.fall_fly_ticks = fly_ticks; + m.extra.auto_spin_attack = spinning; m.extra.main_hand_left = self.settings.main_hand_left; m.extra.using_item = using; m.extra.using_off_hand = using_off_hand; @@ -451,6 +453,7 @@ impl Game<'_> { out, ); self.player_elytra_geometry(m, camera, alpha as f32, packed, out); + self.spin_attack_geometry(m, camera, alpha as f32, packed, out); self.held_item_geometry(m, camera, alpha, packed, true, out); } /// `extractEntityInInventoryFollowsMouse`: the player in the box @@ -592,6 +595,47 @@ impl Game<'_> { out, ); } + /// `SpinAttackEffectLayer`: Riptide's two boxes turning around a spinning + /// player (`SpinAttackEffectModel.setupAnim`). + fn spin_attack_geometry( + &self, + m: &Mob, + camera: glam::DVec3, + partial: f32, + light: u32, + out: &mut Vec, + ) { + if !m.extra.auto_spin_attack { + return; + } + let (Some(model), Some(rect)) = ( + self.res.spin_attack().as_ref(), + self.gui.atlas.sprites.get("entity/trident/trident_riptide"), + ) else { + return; + }; + let age = m.age as f32 + partial; + horizon_client::mobs::render_model( + model, + horizon_client::mobs::render::base_transform(m, partial, camera), + &|part| { + let mut p = part.pose; + if let Some(i) = part + .name + .strip_prefix("box") + .and_then(|i| i.parse::().ok()) + { + let angle = age * -(45.0 + f32::from(i + 1) * 5.0); + p[4] = wrap(angle).to_radians(); + } + p + }, + [rect.u0, rect.v0, rect.u1, rect.v1], + light, + 0, + out, + ); + } } fn player_preview_quads( 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/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 843c01476..d3c14ffc7 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -279,7 +279,11 @@ impl Game<'_> { recipes: self.res.recipes(), brewing: &self.res.stations().brewing, banners: &self.res.stations().banners, + station_recipes: &self.res.stations().recipes, + enchantments: &self.res.stations().enchantments, + names: &self.pack.names, trade: None, + maps: None, }; for i in 0..36 { menu.set_player_item(i, self.inventory[i].clone()); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index fcc7bee08..398c43050 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}, @@ -41,7 +41,11 @@ use horizon_protocol::{ text::{Language, format_java, plain}, }; use horizon_world::{nbt::Tag, registry::BlockStateId}; -use std::{collections::HashMap, sync::Arc, time::Instant}; +use std::{ + collections::{HashMap, VecDeque}, + sync::Arc, + time::{Duration, Instant}, +}; use winit::{event::MouseButton, keyboard::KeyCode}; /// A text component the server sent, for the HUD. @@ -112,9 +116,9 @@ pub(super) struct Remote { /// only replace the remembered state; then the block takes it. predictions: HashMap<[i32; 3], (i32, i32)>, /// Open container: (window id, menu name). - menu: Option<(i32, String)>, + pub(super) menu: Option<(i32, String)>, /// The open menu's title as the server named it. - menu_title: Option, + pub(super) menu_title: Option, state_id: i32, use_target: Option<[i32; 3]>, entities: HashMap, @@ -136,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, @@ -162,8 +168,22 @@ pub(super) struct Remote { clock_game_time: i64, /// `ClientChunkCache.Storage`'s view centre (ClientboundSetChunkCacheCenterPacket). chunk_center: (i32, i32), + /// Received events a frame left for the next one, in order, and when + /// the oldest of them first waited (`poll_remote`). + backlog: VecDeque, + backlog_since: Option, } +/// The time a frame spends on chunk packets before it leaves the rest of +/// the received events for the next frame. A batch of 25 to 60 columns +/// (0.1 ms each on an M4 Pro) all in one frame was a 3 to 8 ms frame every +/// time the player crossed a chunk border at 32 chunks. +const CHUNK_PACKETS_PER_FRAME: Duration = Duration::from_millis(1); +/// Events that have waited this long are all handled in the next frame, +/// whatever their cost: the packets after a slow machine's chunks never +/// wait more than a tick. +const BACKLOG_LIMIT: Duration = Duration::from_millis(50); + fn face_direction(face: [i32; 3]) -> u8 { match face { [0, -1, 0] => 0, @@ -176,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}; @@ -288,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; @@ -337,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(), @@ -355,6 +405,8 @@ impl Game<'_> { clock_partial: 0.0, clock_game_time: 0, chunk_center: (0, 0), + backlog: VecDeque::new(), + backlog_since: None, }); // The level's TickRateManager follows the server's ticking packets. self.clock = horizon_client::clock::FixedStep::client(); @@ -451,8 +503,15 @@ impl Game<'_> { .unwrap_or("minecraft:air"), ) } + /// The server's network id of a mob effect (`brewing::EFFECTS` id). + pub(super) fn remote_effect_network_id(&self, effect: &str) -> Option { + let r = self.remote.as_ref()?; + r.builtin + .get("minecraft:mob_effect")? + .id(&format!("minecraft:{effect}")) + } /// A mob effect's network id as the effect (`brewing::EFFECTS` id). - fn remote_effect_id(&self, effect: i32) -> Option<&'static str> { + pub(super) fn remote_effect_id(&self, effect: i32) -> Option<&'static str> { let r = self.remote.as_ref()?; let name = r.builtin.get("minecraft:mob_effect")?.name(effect)?; horizon_client::brewing::effect(name).map(|d| d.id) @@ -488,18 +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); + // 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); @@ -571,12 +730,34 @@ impl Game<'_> { Some(r.chat.iter().rev().take(n).map(|l| l.0.clone()).collect()) } - /// Process everything the network thread received (once per frame, like - /// the client's packet processor). + /// Received events left for the next frame (`poll_remote`): until they + /// are handled, the terrain the server sent is not all there. + pub(super) fn remote_backlog(&self) -> usize { + self.remote.as_ref().map_or(0, |r| r.backlog.len()) + } + /// Process what the network thread received (once per frame, like the + /// client's packet processor), in order. Chunk packets get + /// `CHUNK_PACKETS_PER_FRAME`: once a frame has spent it, the events from + /// the next chunk packet on wait for the next frame, unless they have + /// already waited `BACKLOG_LIMIT`. pub(super) fn poll_remote(&mut self) -> Result<()> { - let Some(r) = &self.remote else { return Ok(()) }; - let events = r.session.poll(); - for event in events { + let Some(r) = self.remote.as_mut() else { + return Ok(()); + }; + let mut events = std::mem::take(&mut r.backlog); + events.extend(r.session.poll()); + let overdue = r + .backlog_since + .is_some_and(|since| since.elapsed() >= BACKLOG_LIMIT); + let mut chunks = Duration::ZERO; + while let Some(event) = events.pop_front() { + let chunk = + matches!(&event, Event::Packet(p) if matches!(**p, C::LevelChunkWithLight(_))); + if chunk && !overdue && chunks >= CHUNK_PACKETS_PER_FRAME { + events.push_front(event); + break; + } + let started = chunk.then(Instant::now); match event { Event::Status(s) => { if let Some(r) = self.remote.as_mut() { @@ -622,10 +803,19 @@ impl Game<'_> { } Event::Packet(packet) => self.handle_packet(*packet)?, } + chunks += started.map_or(Duration::ZERO, |t| t.elapsed()); if self.remote.is_none() { break; } } + if let Some(r) = self.remote.as_mut() { + r.backlog_since = if events.is_empty() { + None + } else { + Some(r.backlog_since.unwrap_or_else(Instant::now)) + }; + r.backlog = events; + } self.send_suggestion_request(); Ok(()) } @@ -1243,9 +1433,39 @@ impl Game<'_> { "minecraft:hopper" => slots(5), "minecraft:generic_3x3" => slots(9), "minecraft:brewing_stand" => slots(5), - _ => None, + // CrafterMenu: the grid, the inventory, then the result (the + // client's own). + "minecraft:crafter_3x3" => slots(9), + // A workstation: its inputs, its result, then the inventory. + m => { + let kind = Self::remote_station_kind(m)?; + let inputs = kind.inputs(); + let own = inputs + usize::from(kind.has_result()); + match s { + _ if s < inputs => Some(super::stations::INPUT + s), + _ if s < own => Some(super::stations::RESULT), + _ if s < own + 27 => Some(9 + s - own), + _ if s < own + 36 => Some(s - own - 27), + _ => None, + } + } } } + /// The workstation screen of a menu type a server opens. + pub(super) fn remote_station_kind(menu: &str) -> Option { + use super::stations::Kind; + Some(match menu { + "minecraft:loom" => Kind::Loom, + "minecraft:stonecutter" => Kind::Stonecutter, + "minecraft:grindstone" => Kind::Grindstone, + "minecraft:anvil" => Kind::Anvil, + "minecraft:smithing" => Kind::Smithing, + "minecraft:enchantment" => Kind::Enchanting, + "minecraft:beacon" => Kind::Beacon, + "minecraft:cartography_table" => Kind::Cartography, + _ => return None, + }) + } fn open_menu_name(&self, container: i32) -> String { match self.remote.as_ref().and_then(|r| r.menu.as_ref()) { Some((id, name)) if *id == container && container != 0 => name.clone(), @@ -1254,6 +1474,12 @@ impl Game<'_> { } fn set_menu_slot(&mut self, container: i32, slot: i32, item: Option) { let menu = self.open_menu_name(container); + if menu == "minecraft:lectern" { + if slot == 0 { + self.remote_lectern_book(item); + } + return; + } if container != 0 && menu == "inventory" { return; } @@ -1264,6 +1490,9 @@ impl Game<'_> { return; // the result slot is recomputed from the grid } *self.slot_mut(internal) = item; + if internal >= super::stations::INPUT && self.station.is_some() { + self.remote_station_slot_changed(internal); + } } fn handle_packet(&mut self, packet: C) -> Result<()> { @@ -1532,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 { @@ -1913,6 +2165,12 @@ impl Game<'_> { } self.remote_synced(); } + C::ContainerSetData(p) if self.open_menu_name(p.container) == "minecraft:lectern" => { + self.remote_lectern_page(i32::from(p.value)); + } + C::ContainerSetData(p) if self.remote_station_open(p.container) => { + self.remote_station_data(usize::try_from(p.id).unwrap_or(usize::MAX), p.value); + } C::ContainerSetData(p) => { let v = i32::from(p.value); match self @@ -1926,6 +2184,12 @@ impl Game<'_> { 3 => f.cooking_total = v, _ => {} }, + // CrafterBlockEntity.containerData. + Some(BlockEntity::Crafter(c)) => match usize::try_from(p.id) { + Ok(k @ 0..9) => c.disabled[k] = v == 1, + Ok(9) => c.triggered = v == 1, + _ => {} + }, // BrewingStandBlockEntity.dataAccess. Some(BlockEntity::Brewing(b)) => match p.id { 0 => b.brew_time = v, @@ -1943,6 +2207,7 @@ impl Game<'_> { C::RecipeBookSettings(p) => self.remote_recipe_book_settings(p), C::PlaceGhostRecipe(p) => self.remote_ghost_recipe(p), C::MerchantOffers(p) => self.remote_merchant_offers(p), + C::ContainerClose(_) if self.remote_lectern_closed() => {} C::ContainerClose(_) => { if self.screen == Screen::Inventory { self.remote_close_local(); @@ -2160,6 +2425,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); @@ -2305,33 +2571,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 @@ -2344,9 +2597,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() @@ -3155,10 +3467,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() { @@ -3335,7 +3645,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; @@ -3393,7 +3711,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 { @@ -3408,26 +3730,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 @@ -3682,23 +4031,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 => { @@ -3789,6 +4141,10 @@ impl Game<'_> { /// engine doesn't model sends the clicks unpredicted. False when a click's /// slot isn't one of the menu's. pub(super) fn remote_menu_ops(&mut self, ops: &[(Option, i32, Input)]) -> bool { + // CrafterScreen.slotClicked: a slot toggle goes out before the click. + if let [(Some(slot), button, input)] = ops { + self.crafter_slot_clicked(*slot, *button, *input); + } let (container, menu) = self.remote_menu(); let mut clicks = Vec::with_capacity(ops.len()); for &(slot, button, input) in ops { @@ -3941,13 +4297,8 @@ impl Game<'_> { r.menu = None; r.menu_title = None; } - if self - .station - .as_ref() - .is_some_and(|s| s.kind == super::stations::Kind::Merchant) - { - self.station = None; - } + // The client's menu has no level access: what it holds is the server's. + self.station = None; self.craft_size = 2; if let Some(key) = self.container.take() { // Server containers stay renderable but lose their copied slots. @@ -4021,6 +4372,27 @@ impl Game<'_> { .as_ref() .and_then(|r| r.use_target) .map(|t| (t[0], t[1], t[2])); + if menu == "minecraft:lectern" { + // LecternScreen: the book and page come in the menu's content and data. + if let Some(r) = self.remote.as_mut() { + r.menu = Some((p.container, menu)); + } + self.remote_open_lectern(target.unwrap_or_default()); + return; + } + if let Some(kind) = Self::remote_station_kind(&menu) { + let title = plain( + &p.title, + &self + .remote + .as_ref() + .map(|r| r.lang.clone()) + .unwrap_or_default(), + ); + let pos = target.map_or([0, 0, 0], |t| [t.0, t.1, t.2]); + self.remote_open_station(p.container, menu, kind, title, pos); + return; + } if menu == "minecraft:merchant" { // A trading window: its offers follow in a MerchantOffers packet. let title = plain( @@ -4060,6 +4432,8 @@ impl Game<'_> { horizon_client::brewing::BrewingStand::new(), ))), "minecraft:generic_3x3" => Some(BlockEntity::Chest(vec![None; 9])), + // CrafterMenu: the disabled slots and triggered come in ContainerSetData. + "minecraft:crafter_3x3" => Some(BlockEntity::Crafter(Default::default())), m if m.starts_with("minecraft:generic_9x") || m == "minecraft:shulker_box" => { let rows = m .strip_prefix("minecraft:generic_9x") @@ -4353,7 +4727,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). @@ -4383,6 +4757,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 { @@ -4399,7 +4784,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, @@ -4411,13 +4796,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() } } @@ -4533,6 +4936,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/remote_stations.rs b/crates/horizon-client/src/game/remote_stations.rs new file mode 100644 index 000000000..b46725345 --- /dev/null +++ b/crates/horizon-client/src/game/remote_stations.rs @@ -0,0 +1,156 @@ +//! A server's workstation menus on this client: the server opens the menu +//! (`ClientboundOpenScreenPacket` with the station's `MenuType`), the +//! station screen draws it, and its clicks and buttons are predicted on the +//! menu engine (`Game::menu_session`) and sent, as +//! `MultiPlayerGameMode.handleContainerInput` and `handleInventoryButtonClick` +//! do. The menu's client-side `slotsChanged` follows the server's slots, and +//! its data slots come in `ClientboundContainerSetDataPacket`. +use super::{ + Game, Screen, + stations::{Kind, Station}, +}; +use horizon_protocol::packets::play::{self, Serverbound as S}; + +impl Game<'_> { + /// The server opened workstation menu `menu` in window `container`. + pub(super) fn remote_open_station( + &mut self, + container: i32, + menu: String, + kind: Kind, + title: String, + pos: [i32; 3], + ) { + if let Some(r) = self.remote.as_mut() { + r.menu = Some((container, menu)); + r.menu_title = Some(title); + } + self.craft_size = 2; + self.container = None; + self.station = Some(Station::new_kind(kind, pos)); + self.screen = Screen::Inventory; + self.capture(false); + } + + /// Window `container` is the server's workstation menu, open here. + pub(super) fn remote_station_open(&self, container: i32) -> bool { + self.station.is_some() + && self + .remote + .as_ref() + .and_then(|r| r.menu.as_ref()) + .is_some_and(|(id, name)| { + *id == container && Self::remote_station_kind(name).is_some() + }) + } + + /// The server set station slot `internal`: the client menu's + /// `Slot.set` runs its container's `setChanged`, so the loom lists the + /// patterns its inputs allow and the stonecutter the recipes of its input. + pub(super) fn remote_station_slot_changed(&mut self, internal: usize) { + if !self.station.as_ref().is_some_and(|s| { + matches!( + s.kind, + Kind::Loom + | Kind::Stonecutter + | Kind::Grindstone + | Kind::Anvil + | Kind::Smithing + | Kind::Cartography + ) + }) { + return; + } + self.menu_session(|menu, env, to_menu| { + let i = to_menu(internal)?; + let stack = menu.slot(i).cloned(); + menu.set_slot(env, i, stack); + Some(true) + }); + // AnvilScreen.slotChanged: the box shows the new input's name, which + // its responder sends. + self.remote_anvil_rename(); + } + + /// `AbstractContainerMenu.setData` from the server. + pub(super) fn remote_station_data(&mut self, id: usize, value: i16) { + let Some(s) = self.station.as_mut() else { + return; + }; + match (s.kind, id) { + // LoomMenu.selectedBannerPatternIndex. + (Kind::Loom, 0) => s.loom.selected = usize::try_from(value).ok(), + // StonecutterMenu.selectedRecipeIndex. + (Kind::Stonecutter, 0) => s.selected = usize::try_from(value).ok(), + // AnvilMenu.cost. + (Kind::Anvil, 0) => s.anvil.cost = i32::from(value), + // EnchantmentMenu: costs, the seed (the screen's glyph names), + // the clues' enchantments and levels. + (Kind::Enchanting, 0..3) => s.offers.costs[id] = i32::from(value), + (Kind::Enchanting, 3) => self.level.xp_seed = i32::from(value), + (Kind::Enchanting, 4..7) => { + let name = self.remote.as_ref().and_then(|r| { + r.registries + .name("minecraft:enchantment", i32::from(value)) + .map(std::sync::Arc::::from) + }); + let level = s.offers.clues[id - 4].as_ref().map_or(1, |(_, l)| *l); + s.offers.clues[id - 4] = name.map(|n| (n, level)); + } + (Kind::Enchanting, 7..10) => { + if let Some((_, level)) = s.offers.clues[id - 7].as_mut() { + *level = value.max(0) as u32; + } + } + // BeaconMenu: the levels, then the powers (BeaconScreen's + // dataChanged shows the menu's). + (Kind::Beacon, 0) => s.beacon_levels = Some(i32::from(value)), + (Kind::Beacon, 1 | 2) => { + let effect = self.remote_effect_id(i32::from(value) - 1); + let index = + effect.and_then(|e| super::beacon::EFFECTS.iter().position(|(n, _)| *n == e)); + if let Some(s) = self.station.as_mut() { + s.beacon[id - 1] = index; + } + } + _ => {} + } + } + + /// `AnvilScreen.onNameChanged` on a server: the rename box's text (blank + /// when it is the input's own name) goes to the server when the menu's + /// `setItemName` takes it. + pub(super) fn remote_anvil_rename(&mut self) { + if self.remote.is_none() { + return; + } + let Some(s) = self + .station + .as_ref() + .filter(|s| s.kind == Kind::Anvil && s.inputs[0].is_some()) + else { + return; + }; + let name = self.anvil_item_name(s); + if s.anvil_sent.as_deref() == Some(&name) { + return; + } + if let Some(s) = self.station.as_mut() { + s.anvil_sent = Some(name.clone()); + } + self.send(S::RenameItem(play::RenameItem { name })); + } + + /// `MultiPlayerGameMode.handleInventoryButtonClick`: the screen already + /// ran `clickMenuButton` on its own menu. + pub(super) fn remote_station_button(&self, button: i32) { + if let Some((container, _)) = self.remote.as_ref().and_then(|r| r.menu.as_ref()) + && self.remote_station_open(*container) + { + self.send(S::ContainerButtonClick(play::ContainerButtonClick { + container: *container, + button, + })); + } + } +} 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/station_control.rs b/crates/horizon-client/src/game/station_control.rs index 75ad9225e..ecbbad0b8 100644 --- a/crates/horizon-client/src/game/station_control.rs +++ b/crates/horizon-client/src/game/station_control.rs @@ -10,6 +10,7 @@ pub(super) const HELP: &[&str] = &[ "use X Y Z open the block's menu as if right-clicked", "click-slot ID [right] [shift] click a menu slot (0-35 inventory, 300+ container, 600+ station, 650 result)", "click-gui X Y [right] [shift] click at GUI pixel X Y relative to the menu's top-left corner", + "book [next|back|take|done] the open book or lectern: its page, or press one of its buttons", "type TEXT | type-back type into the anvil name box / delete one character", "enchant ID LEVEL enchant the held item (books store the enchantment)", "potion ITEM POTION give a potion item (potion, splash_potion, lingering_potion, tipped_arrow)", @@ -136,6 +137,7 @@ impl Game<'_> { self.apply_equipment(); ok() } + "book" => Ok(Some(self.book_control(words.get(1).copied())?)), "potion" => { let stack = ItemStack::new(&id(arg(1)?), 1).with_potion(&id(arg(2)?)); let rest = self.give(stack); diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index c19f6165c..ffe56d699 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -13,7 +13,6 @@ use horizon_client::{ stations::{self, AnvilResult, EnchantOffers}, }; use horizon_core::random::{LegacyRandom, RandomSource}; -use std::sync::Arc; /// Slot ids of the open station: inputs from 600, the result at 650. pub(super) const INPUT: usize = 600; @@ -36,7 +35,7 @@ pub(super) enum Kind { Loom, } impl Kind { - fn from_block(name: &str) -> Option { + pub(super) fn from_block(name: &str) -> Option { Some(match name { "minecraft:enchanting_table" => Self::Enchanting, "minecraft:anvil" | "minecraft:chipped_anvil" | "minecraft:damaged_anvil" => { @@ -51,7 +50,7 @@ impl Kind { _ => return None, }) } - fn inputs(self) -> usize { + pub(super) fn inputs(self) -> usize { match self { Self::Smithing | Self::Loom => 3, Self::Stonecutter | Self::Beacon => 1, @@ -71,7 +70,7 @@ impl Kind { Self::Loom => "gui/container/loom", } } - fn title_key(self) -> &'static str { + pub(super) fn title_key(self) -> &'static str { match self { Self::Enchanting => "container.enchant", Self::Anvil => "container.repair", @@ -108,6 +107,10 @@ impl Kind { }; table[i.min(table.len() - 1)] } + /// Whether the menu has a result slot after its inputs. + pub(super) fn has_result(self) -> bool { + self.result_pos().is_some() + } fn result_pos(self) -> Option<(f32, f32)> { match self { Self::Enchanting => None, @@ -128,18 +131,20 @@ pub(super) struct Station { pub(super) pos: [i32; 3], pub(super) inputs: Vec>, pub(super) result: Option, - offers: EnchantOffers, + pub(super) offers: EnchantOffers, bookcases: i32, - anvil: AnvilResult, + pub(super) anvil: AnvilResult, /// Anvil rename box text. pub(super) name: String, - /// Stonecutter: recipe indices for the input, selection and first shown index. - recipes: Vec, - selected: Option, + /// Stonecutter: the menu's recipe list (horizon_client::menu), its + /// `selectedRecipeIndex` and the screen's first shown index. + pub(super) stone: horizon_client::menu::Stonecutter, + pub(super) selected: Option, start: usize, - input_item: Option>, /// Anvil: the input the rename box was last filled from. anvil_last: Option, + /// Anvil on a server: the name last sent (the client menu's `itemName`). + pub(super) anvil_sent: Option, /// When the screen opened: the rename box has the focus from then. opened: std::time::Instant, pub(super) last_sound: u64, @@ -147,6 +152,8 @@ pub(super) struct Station { pub(super) merchant: Option>, /// Beacon menu: the selected primary and secondary power (EFFECTS index). pub(super) beacon: [Option; 2], + /// A server's beacon menu: the pyramid's levels (its data slot 0). + pub(super) beacon_levels: Option, /// The loom's patterns, selection and scroller (game/loom.rs). pub(super) loom: super::loom::LoomState, } @@ -161,21 +168,29 @@ impl Station { bookcases: 0, anvil: AnvilResult::default(), name: String::new(), - recipes: Vec::new(), + stone: Default::default(), selected: None, start: 0, - input_item: None, anvil_last: None, + anvil_sent: None, opened: std::time::Instant::now(), last_sound: 0, merchant: None, beacon: [None; 2], + beacon_levels: None, loom: Default::default(), } } pub(super) fn new_kind(kind: Kind, pos: [i32; 3]) -> Self { Self::new(kind, pos) } + /// `StonecutterScreen.containerChanged`: without recipes to show, the + /// list scrolls back to the top. + pub(super) fn stonecutter_changed(&mut self) { + if self.inputs[0].is_none() || self.stone.recipes.is_empty() { + self.start = 0; + } + } } /// The 108x19 enchantment button `i` (relative to the GUI origin). @@ -323,6 +338,10 @@ impl Game<'_> { let Some(mut station) = self.station.take() else { return; }; + if self.remote.is_some() && station.kind != Kind::Merchant { + // A server's workstation: its removed() gives the inputs back. + return; + } if let Some(m) = station.merchant.as_mut() { self.merchant_closed(m); } @@ -375,7 +394,7 @@ impl Game<'_> { _ => &mut self.scratch_slot, } } - fn count_bookshelves(&self, pos: [i32; 3]) -> i32 { + pub(super) fn count_bookshelves(&self, pos: [i32; 3]) -> i32 { let tags = &self.res.items().block_tags; let is = |p: [i32; 3], tag: &str| { let name = &self @@ -399,7 +418,7 @@ impl Game<'_> { .count() as i32 } /// The anvil name the menu works with (`AnvilScreen.onNameChanged`). - fn anvil_item_name(&self, s: &Station) -> String { + pub(super) fn anvil_item_name(&self, s: &Station) -> String { match &s.inputs[0] { Some(input) if input.custom_name().is_none() && s.name == self.pack.names.item(&input.item) => @@ -419,6 +438,16 @@ impl Game<'_> { let data = self.res.stations(); let items = self.res.items(); match s.kind { + // A server's table: its data slots carry the offers, and its + // client menu only clears them without an enchantable item. + Kind::Enchanting if self.remote.is_some() => { + let enchantable = s.inputs[0].as_ref().is_some_and(|i| { + data.enchantments.enchantable(&i.item) > 0 && i.enchantments().is_empty() + }); + if !enchantable { + s.offers = Default::default(); + } + } Kind::Enchanting => { s.bookcases = self.count_bookshelves(s.pos); s.offers = stations::enchant_offers( @@ -465,35 +494,9 @@ impl Game<'_> { // The menu engine keeps the merchant's result (Game::menu_session). Kind::Merchant => {} Kind::Beacon => {} - Kind::Cartography => s.result = self.cartography_result(&s), - // The menu engine keeps the loom's state (Game::menu_session). - Kind::Loom => {} - Kind::Stonecutter => { - let item = s.inputs[0].as_ref().map(|i| i.item.clone()); - if item != s.input_item { - s.input_item = item; - s.selected = None; - s.start = 0; - s.recipes = match &s.inputs[0] { - Some(input) => data - .recipes - .stonecutting - .iter() - .enumerate() - .filter(|(_, r)| r.input.test(input)) - .map(|(i, _)| i) - .collect(), - None => Vec::new(), - }; - } - s.result = match (s.selected, &s.inputs[0]) { - (Some(i), Some(_)) => s - .recipes - .get(i) - .map(|&r| data.recipes.stonecutting[r].result.clone()), - _ => None, - }; - } + // The menu engine keeps the cartography table's, the loom's and + // the stonecutter's state (Game::menu_session). + Kind::Cartography | Kind::Loom | Kind::Stonecutter => {} } self.station = Some(s); } @@ -505,7 +508,6 @@ impl Game<'_> { } /// `Slot.mayPlace` and `getMaxStackSize` for station slots. fn slot_rules(&self, slot: usize, stack: &ItemStack) -> (bool, u32) { - let data = self.data(); if slot >= super::mount_menu::SADDLE { return self.mount_slot_rules(slot, stack); } @@ -528,24 +530,7 @@ impl Game<'_> { if slot == RESULT { return (false, 64); } - let i = slot - INPUT; - match s.kind { - Kind::Enchanting if i == 0 => (true, 1), - Kind::Beacon => (super::beacon::is_payment(&stack.item), 1), - Kind::Loom => (false, 64), - Kind::Cartography if i == 0 => (super::maps::map_id(stack).is_some(), 64), - Kind::Cartography => ( - matches!( - &*stack.item, - "minecraft:paper" | "minecraft:map" | "minecraft:glass_pane" - ), - 64, - ), - Kind::Enchanting => (&*stack.item == "minecraft:lapis_lazuli", 64), - Kind::Grindstone => (stations::grindstone_accepts(self.res.items(), stack), 64), - Kind::Smithing => (data.recipes.smithing_accepts(i, stack), 64), - _ => (true, 64), - } + (s.kind != Kind::Loom, 64) } /// `AbstractContainerMenu.doClick` PICKUP on a filtered slot. pub(super) fn click_filtered(&mut self, slot: usize, right: bool) { @@ -644,112 +629,80 @@ impl Game<'_> { } stack.count != start } - /// The player inventory in menu order: main rows, then the hotbar. - fn player_slots() -> Vec { - (9..36).chain(0..9).collect() + /// After an anvil or smithing click on the menu engine: the anvil's cost + /// and state back into the station and the rename box following the + /// input (`AnvilScreen.slotChanged`), then the rest of a taken result's + /// `onTake` (the levels, the anvil's wear, the use sound) unless a + /// server does it. + pub(super) fn combiner_session_end( + &mut self, + menu: &horizon_client::menu::Menu, + predicting: bool, + ) { + let Some(s) = self.station.as_mut() else { + return; + }; + let (pos, kind) = (s.pos, s.kind); + if kind == Kind::Anvil { + s.anvil.cost = menu.data[0]; + s.anvil.repair_item_count_cost = menu.anvil.repair_count; + s.anvil.only_renaming = menu.anvil.only_renaming; + s.anvil.result = s.result.clone(); + } + self.station_after_input(); + if !menu.combined || predicting { + return; + } + if kind == Kind::Smithing { + self.level_event_at(1044, pos, 0); + return; + } + self.give_levels(menu.level_change); + if self.anvil_used(pos, self.creative) { + self.close_station(); + self.screen = Screen::Playing; + self.capture(true); + } } - /// A shift-click: `AbstractContainerMenu.doClick`'s QUICK_MOVE repeats - /// `quickMoveStack` while it moves something and the slot still holds the - /// same item. - fn quick_move(&mut self, slot: usize) { - while let Some(item) = self.slot_mut(slot).as_ref().map(|s| s.item.clone()) - && self.quick_move_once(slot) - && self.slot_mut(slot).as_ref().is_some_and(|s| s.item == item) - {} - } - /// The station menu's `quickMoveStack` for one slot (`EnchantmentMenu`, - /// `BeaconMenu`, `GrindstoneMenu`, `StonecutterMenu`, - /// `CartographyTableMenu`, and `ItemCombinerMenu` with `SmithingMenu`'s - /// `canMoveIntoInputSlots`); whether the stack's count changed. Each - /// rule that names its target slots moves nowhere else when they are full. - fn quick_move_once(&mut self, slot: usize) -> bool { - let Some(kind) = self.station.as_ref().map(|s| s.kind) else { - return false; - }; - let Some(mut stack) = self.slot_mut(slot).take() else { - return false; - }; - let start = stack.count; - let empty = |game: &mut Self, i: usize| game.station_slot_mut(INPUT + i).is_none(); - // The other half of the inventory: main rows to the hotbar and back. - let halves: Vec = if slot < 9 { - (9..36).collect() - } else { - (0..9).collect() - }; - if slot >= INPUT { - // An input slot: into the inventory, the hotbar's last slot first - // where vanilla moves in reverse. - let reverse = matches!(kind, Kind::Enchanting | Kind::Beacon); - self.move_to(&mut stack, &Self::player_slots(), reverse); - } else { - match kind { - Kind::Enchanting => { - if &*stack.item == "minecraft:lapis_lazuli" { - self.move_to(&mut stack, &[INPUT + 1], true); - } else if empty(self, 0) { - *self.station_slot_mut(INPUT) = Some(ItemStack { - count: 1, - ..stack.clone() - }); - stack.count -= 1; - } + /// `AnvilMenu.onTake`'s level part: out of creative a 12% chance + /// (`AnvilBlock.damage`) to wear the anvil a stage, or break a damaged one + /// (level event 1029); otherwise level event 1030. True when it broke. + pub(super) fn anvil_used(&mut self, pos: [i32; 3], creative: bool) -> bool { + let state = self.world.block(pos[0], pos[1], pos[2]); + let name = self.res.facts().get(state).name.clone(); + let anvil = matches!( + &*name, + "minecraft:anvil" | "minecraft:chipped_anvil" | "minecraft:damaged_anvil" + ); + if !creative && anvil && self.world.random.next_float() < 0.12 { + match &*name { + "minecraft:anvil" => { + let _ = self.set_state_named(pos, "minecraft:chipped_anvil", &["facing"]); } - Kind::Beacon => { - if empty(self, 0) && super::beacon::is_payment(&stack.item) && stack.count == 1 - { - self.move_to(&mut stack, &[INPUT], false); - } else { - self.move_to(&mut stack, &halves, false); - } + "minecraft:chipped_anvil" => { + let _ = self.set_state_named(pos, "minecraft:damaged_anvil", &["facing"]); } - Kind::Grindstone => { - if empty(self, 0) || empty(self, 1) { - self.move_to(&mut stack, &[INPUT, INPUT + 1], false); - } else { - self.move_to(&mut stack, &halves, false); - } + _ => { + let _ = self.world.set(pos[0], pos[1], pos[2], self.world.air); + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); + self.level_event_at(1029, pos, 0); + return true; } - Kind::Stonecutter => { - if self.data().recipes.stonecutter(&stack).is_empty() { - self.move_to(&mut stack, &halves, false); - } else { - self.move_to(&mut stack, &[INPUT], false); - } - } - Kind::Cartography => { - if super::maps::map_id(&stack).is_some() { - self.move_to(&mut stack, &[INPUT], false); - } else if matches!( - &*stack.item, - "minecraft:paper" | "minecraft:map" | "minecraft:glass_pane" - ) { - self.move_to(&mut stack, &[INPUT + 1], false); - } else { - self.move_to(&mut stack, &halves, false); - } - } - Kind::Anvil | Kind::Smithing => { - let inputs: Vec = (0..kind.inputs()).map(|i| INPUT + i).collect(); - // ItemCombinerMenu.canMoveIntoInputSlots: always for the - // anvil; the smithing table needs an empty slot whose - // ingredient test takes the stack. - let into_inputs = kind == Kind::Anvil - || (0..3).any(|i| { - empty(self, i) && self.data().recipes.smithing_accepts(i, &stack) - }); - let targets = if into_inputs { &inputs } else { &halves }; - self.move_to(&mut stack, targets, false); - } - // Their clicks run on the menu engine. - Kind::Merchant | Kind::Loom => {} } } - let moved = stack.count != start; - if stack.count > 0 { - *self.slot_mut(slot) = Some(stack); + self.level_event_at(1030, pos, 0); + false + } + /// The grindstone result's `onTake` with a level (`amount`: the menu's + /// `getExperienceAmount` sum): the orbs at the block's centre + /// (`ExperienceOrb.award`), then level event 1042, the grindstone's sound + /// for everyone around. + pub(super) fn grindstone_taken(&mut self, pos: [i32; 3], amount: i32) { + let xp = stations::grindstone_xp_roll(amount, &mut self.world.random); + if xp > 0 { + self.spawn_orbs(pos.map(|v| f64::from(v) + 0.5), xp); } - moved + self.level_event_at(1042, pos, 0); } fn play_at(&mut self, sound: &str, pos: [i32; 3], volume: f32, pitch: f32) { let at = [ @@ -788,185 +741,6 @@ impl Game<'_> { _ => true, } } - /// The result slot's `onTake`. - fn take_result(&mut self) { - let Some(mut s) = self.station.take() else { - return; - }; - let pos = s.pos; - match s.kind { - Kind::Anvil => { - let cost = s.anvil.cost; - let repair = s.anvil.repair_item_count_cost; - if repair > 0 { - if let Some(a) = s.inputs[1].as_mut() - && a.count > repair - { - a.count -= repair; - } else { - s.inputs[1] = None; - } - } else if !s.anvil.only_renaming { - s.inputs[1] = None; - } - s.inputs[0] = None; - s.name.clear(); - if !self.creative { - self.give_levels(-cost); - } - let pitch = self.world.random.next_float() * 0.1 + 0.9; - if !self.creative && self.world.random.next_float() < 0.12 { - // AnvilBlock.damage - let state = self.world.block(pos[0], pos[1], pos[2]); - let name = self.res.facts().get(state).name.clone(); - let next = match &*name { - "minecraft:anvil" => Some("minecraft:chipped_anvil"), - "minecraft:chipped_anvil" => Some("minecraft:damaged_anvil"), - _ => None, - }; - match next { - Some(next) => { - let _ = self.set_state_named(pos, next, &["facing"]); - self.play_at("minecraft:block.anvil.use", pos, 1.0, pitch); - } - None => { - let _ = self.world.set(pos[0], pos[1], pos[2], self.world.air); - self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); - self.play_at("minecraft:block.anvil.destroy", pos, 1.0, pitch); - self.station = Some(s); - self.close_station(); - self.screen = Screen::Playing; - self.capture(true); - return; - } - } - } else { - self.play_at("minecraft:block.anvil.use", pos, 1.0, pitch); - } - } - Kind::Grindstone => { - let (a, b) = (s.inputs[0].take(), s.inputs[1].take()); - let mut random = LegacyRandom::new(self.world.random.next_long()); - let xp = stations::grindstone_experience( - &self.res.stations().enchantments, - &mut random, - a.as_ref(), - b.as_ref(), - ); - if xp > 0 { - self.spawn_orbs( - [ - f64::from(pos[0]) + 0.5, - f64::from(pos[1]) + 0.5, - f64::from(pos[2]) + 0.5, - ], - xp, - ); - } - let pitch = self.world.random.next_float() * 0.1 + 0.9; - self.play_at("minecraft:block.grindstone.use", pos, 1.0, pitch); - } - Kind::Smithing => { - for slot in s.inputs.iter_mut() { - if let Some(x) = slot.as_mut() { - x.count -= 1; - if x.count == 0 { - *slot = None; - } - } - } - let pitch = self.world.random.next_float() * 0.1 + 0.9; - self.play_at("minecraft:block.smithing_table.use", pos, 1.0, pitch); - } - Kind::Stonecutter => { - if let Some(x) = s.inputs[0].as_mut() { - x.count -= 1; - if x.count == 0 { - s.inputs[0] = None; - } - } - if s.last_sound != self.ticks { - s.last_sound = self.ticks; - self.play_at("minecraft:ui.stonecutter.take_result", pos, 1.0, 1.0); - } - } - Kind::Merchant => {} - Kind::Beacon => {} - Kind::Cartography => { - for slot in &mut s.inputs { - if let Some(x) = slot.as_mut() { - x.count -= 1; - if x.count == 0 { - *slot = None; - } - } - } - if s.last_sound != self.ticks { - s.last_sound = self.ticks; - self.cartography_taken(pos); - } - } - Kind::Loom => {} - Kind::Enchanting => {} - } - self.station = Some(s); - self.station_changed(); - } - fn click_result(&mut self, shift: bool) { - loop { - let Some(result) = self.station.as_ref().and_then(|s| s.result.clone()) else { - return; - }; - if !self.may_take_result() { - return; - } - let result = if self - .station - .as_ref() - .is_some_and(|s| s.kind == Kind::Cartography) - { - self.cartography_post(result) - } else { - result - }; - if shift { - let mut stack = result.clone(); - let player = Self::player_slots(); - // Simulate first so nothing is lost when the inventory is full. - let saved: Vec> = self.inventory.clone(); - self.move_to(&mut stack, &player, true); - if stack.count > 0 { - self.inventory = saved; - return; - } - } else { - match &mut self.carried { - None => self.carried = Some(result.clone()), - Some(c) - if c.same_item_same_components(&result) - && c.count + result.count - <= self.res.items().get(&c.item).map_or(64, |i| i.max_stack) => - { - c.count += result.count - } - _ => return, - } - } - if let Some(s) = self.station.as_mut() { - s.result = None; - } - self.take_result(); - let again = shift - && self - .station - .as_ref() - .and_then(|s| s.result.as_ref()) - .is_some_and(|r| r.item == result.item); - if !again { - return; - } - } - } /// `EnchantmentMenu.clickMenuButton`. fn click_enchant(&mut self, button: usize) { let Some(s) = self.station.as_ref() else { @@ -987,6 +761,11 @@ impl Game<'_> { { return; } + if self.remote.is_some() { + // EnchantmentScreen.mouseClicked: the client menu took it, the server enchants. + self.remote_station_button(button as i32); + return; + } let Some(enchanted) = stations::apply_enchantment( &self.res.stations().enchantments, self.res.items(), @@ -1036,7 +815,7 @@ impl Game<'_> { }) .collect(), Kind::Stonecutter if s.inputs[0].is_some() => (s.start - ..(s.start + 12).min(s.recipes.len())) + ..(s.start + 12).min(s.stone.recipes.len())) .map(|index| { let p = index - s.start; [ @@ -1089,64 +868,21 @@ impl Game<'_> { } } } - if kind == Kind::Stonecutter - && let Some(s) = self.station.as_ref() - && s.inputs[0].is_some() - { - for index in s.start..(s.start + 12).min(s.recipes.len()) { - let p = index - s.start; - let (x, y) = (52.0 + (p % 4) as f32 * 16.0, 14.0 + (p / 4) as f32 * 18.0); - if inside(local, x, y, 16.0, 18.0) { - if s.selected != Some(index) { - if let Some(st) = self.station.as_mut() { - st.selected = Some(index); - } - self.audio.play( - "minecraft:ui.stonecutter.select_recipe", - None, - 1.0, - 1.0, - ); - self.station_changed(); - } - return true; - } - } + if kind == Kind::Stonecutter && self.stonecutter_click(local) { + return true; } } let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return true; }; - if self - .station - .as_ref() - .is_none_or(|s| matches!(s.kind, Kind::Loom | Kind::Merchant)) - { - // LoomMenu, MerchantMenu and the brewing stand's BrewingStandMenu - // clicks run on the verified menu engine. - let input = if shift { - horizon_client::menu::Input::QuickMove - } else { - horizon_client::menu::Input::Pickup - }; - self.menu_click(Some(slot), i32::from(right), input); - return true; - } - if slot == RESULT { - self.click_result(shift); - return true; - } - if shift { - self.quick_move(slot); - } else if slot >= INPUT { - self.click_filtered(slot, right); + // Every station's clicks (and the brewing stand's) run on the + // verified menu engine. + let input = if shift { + horizon_client::menu::Input::QuickMove } else { - return false; - } - if let Some(key) = self.container { - self.world.modified.insert((key.0 >> 4, key.2 >> 4)); - } - self.station_after_input(); + horizon_client::menu::Input::Pickup + }; + self.menu_click(Some(slot), i32::from(right), input); true } /// Recompute after slot changes; the anvil box follows its input item. @@ -1164,16 +900,49 @@ impl Game<'_> { } self.station_changed(); } + /// `StonecutterScreen.mouseClicked` on its recipe grid: `clickMenuButton` + /// with the cell's index (an empty cell's too), and the select sound when + /// the menu took it. + fn stonecutter_click(&mut self, local: (f32, f32)) -> bool { + let Some(start) = self + .station + .as_ref() + .filter(|s| s.inputs[0].is_some() && !s.stone.recipes.is_empty()) + .map(|s| s.start) + else { + return false; + }; + for index in start..start + 12 { + let p = index - start; + let (x, y) = (52.0 + (p % 4) as f32 * 16.0, 14.0 + (p / 4) as f32 * 18.0); + if !inside(local, x, y, 16.0, 18.0) { + continue; + } + let mut taken = false; + let flag = &mut taken; + self.menu_session(|menu, env, _| { + *flag = menu.button(env, index as i32); + Some(*flag) + }); + if taken { + self.audio + .play("minecraft:ui.stonecutter.select_recipe", None, 1.0, 1.0); + self.remote_station_button(index as i32); + return true; + } + } + false + } pub(super) fn station_scroll(&mut self, d: f32) { self.merchant_scroll(d); self.loom_scroll(d); let Some(s) = self.station.as_mut() else { return; }; - if s.kind != Kind::Stonecutter || s.recipes.len() <= 12 { + if s.kind != Kind::Stonecutter || s.stone.recipes.len() <= 12 { return; } - let rows = s.recipes.len().div_ceil(4) - 3; + let rows = s.stone.recipes.len().div_ceil(4) - 3; let first_row = (s.start / 4) as i32 - d.signum() as i32; s.start = first_row.clamp(0, rows as i32) as usize * 4; } @@ -1207,6 +976,7 @@ impl Game<'_> { } } self.station_changed(); + self.remote_anvil_rename(); } /// Ctrl+A/C/V/X in the anvil's rename box (an `EditBox` of 50) or the /// recipe book's search box. @@ -1227,6 +997,7 @@ impl Game<'_> { ANVIL_NAME_CHARS, ) { self.station_changed(); + self.remote_anvil_rename(); } } @@ -1740,9 +1511,9 @@ impl Game<'_> { } Kind::Merchant | Kind::Beacon | Kind::Cartography | Kind::Loom => {} Kind::Stonecutter => { - let display = s.inputs[0].is_some() && !s.recipes.is_empty(); - let active = display && s.recipes.len() > 12; - let rows = s.recipes.len().div_ceil(4).saturating_sub(3).max(1); + let display = s.inputs[0].is_some() && !s.stone.recipes.is_empty(); + let active = display && s.stone.recipes.len() > 12; + let rows = s.stone.recipes.len().div_ceil(4).saturating_sub(3).max(1); let offs = if active { (s.start / 4) as f32 / rows as f32 } else { @@ -1763,13 +1534,14 @@ impl Game<'_> { let (start, selected) = (s.start, s.selected); // graphics.item: the icon only, without the count. let shown: Vec<(usize, ItemStack)> = (start - ..(start + 12).min(s.recipes.len())) + ..(start + 12).min(s.stone.recipes.len())) .map(|i| { ( i, ItemStack { count: 1, - ..self.res.stations().recipes.stonecutting[s.recipes[i]] + ..self.res.stations().recipes.stonecutting + [s.stone.recipes[i]] .result .clone() }, @@ -2082,7 +1854,7 @@ impl Game<'_> { "bookcases": s.bookcases, "anvil_cost": s.anvil.cost, "result": s.result.as_ref().map(|r| format!("{} x{}", r.item, r.count)), - "recipes": s.recipes.iter().map(|&i| recipes[i].id.clone()).collect::>(), + "recipes": s.stone.recipes.iter().map(|&i| recipes[i].id.clone()).collect::>(), "selected": s.selected, }) } diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index b24f4540e..c31094596 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -122,6 +122,38 @@ impl Game<'_> { let sky = self.world.light(x, y + 1, z) >> 4 == 15; water || (self.world.weather.raining && sky) } + /// The living entities a spinning player can touch this tick, for + /// `LivingEntity.checkAutoSpinAttack` (none when not spinning). + pub(super) fn spin_targets(&self) -> Vec<(u32, Aabb)> { + let Some(p) = self + .player + .as_ref() + .filter(|p| p.auto_spin_attack_ticks > 0) + else { + return Vec::new(); + }; + // A spin moves a few blocks a tick at most. + let near = p.bounds().inflate(Vec3::new(16.0, 16.0, 16.0)); + self.mobs + .iter() + .filter(|m| m.alive() && m.bounds().intersects(near)) + .map(|m| (m.id, m.bounds())) + .collect() + } + /// `Player.doAutoAttackOnTouch`: the touched entity takes `Player.attack` + /// with the spin's damage; once the spin is over its damage is cleared. + pub(super) fn end_spin_attack(&mut self, hit: Option) { + if let Some(id) = hit + && let Some(index) = self.mobs.iter().position(|m| m.id == id) + { + self.attack_mob(index); + } + if let Some(p) = self.player.as_mut() + && p.auto_spin_attack_ticks <= 0 + { + p.auto_spin_attack_dmg = 0.0; + } + } /// `TridentItem.releaseUsing`. pub(super) fn release_trident(&mut self, ticks: u32) { if ticks < 10 { @@ -152,6 +184,9 @@ impl Game<'_> { p.velocity.y + d[1] * f64::from(strength), p.velocity.z + d[2] * f64::from(strength), ); + // Player.startAutoSpinAttack(20, 8, stack). + p.auto_spin_attack_ticks = 20; + p.auto_spin_attack_dmg = 8.0; if p.ground.on_ground { p.position.y += 1.2; } 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 da53c42ed..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); @@ -4167,6 +4235,34 @@ mod tests { ); assert_eq!(surface_format(&[Rgba16Float], Bgra8UnormSrgb), Rgba16Float); } + /// A Wayland surface on a compositor with colour management, as wgpu lists it (Mesa 26.2 + /// ANV on an Intel HD 620 under weston 16): wide formats first. The pre-#1075 choice, + /// the first non-sRGB format, took `Rgba16Float` and the window looked washed out, as if + /// under a white overlay (#1007); XWayland lists no such format, which is why it looked fine. + #[test] + fn a_colour_managed_wayland_surface_still_gets_8_bit() { + use super::surface_format; + use wgpu::TextureFormat::*; + let wayland = [ + Rgba16Float, + Rgba16Unorm, + Rgb10a2Unorm, + Bgra8UnormSrgb, + Bgra8Unorm, + Rgba8UnormSrgb, + Rgba8Unorm, + ]; + assert_eq!(surface_format(&wayland, Bgra8UnormSrgb), Bgra8Unorm); + // Without Bgra8: Rgba8, still not a 16- or 10-bit format. + let without_bgra = [ + Rgba16Float, + Rgba16Unorm, + Rgb10a2Unorm, + Rgba8UnormSrgb, + Rgba8Unorm, + ]; + assert_eq!(surface_format(&without_bgra, Rgba8UnormSrgb), Rgba8Unorm); + } #[test] fn special_material_batches_preserve_quad_order_and_offsets() { let quad = |layer, id| { 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/heartbeat.rs b/crates/horizon-client/src/heartbeat.rs new file mode 100644 index 000000000..f73c7131f --- /dev/null +++ b/crates/horizon-client/src/heartbeat.rs @@ -0,0 +1,74 @@ +//! The anonymous "I'm playing" ping (`horizon_telemetry::live`, docs/telemetry.md) behind the +//! launcher's "N playing now". While the game runs, a thread of its own sends a random session +//! ID made here and kept only in memory, the version, the platform and whether a LAN or +//! play-with-friends world is open, every minute and at once when that last one changes. +//! It sends nothing when there is no server (`HORIZON_TELEMETRY_URL`, none by default) or +//! with `HORIZON_NO_HEARTBEAT=1` (automated runs). +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::thread::Thread; +use std::time::Duration; + +use horizon_telemetry::live::{self, Ping}; + +/// A world is open to LAN or to friends. +static LAN: AtomicBool = AtomicBool::new(false); +static PINGER: OnceLock = OnceLock::new(); + +/// After a failure the next ping waits longer, doubling up to this. +const MAX_WAIT: Duration = Duration::from_secs(600); + +/// Starts the pings, once. Call when the game itself starts (not a dedicated server, not a +/// benchmark or an automated run). +pub fn start() { + if PINGER.get().is_some() || std::env::var_os("HORIZON_NO_HEARTBEAT").is_some() { + return; + } + let Some(endpoint) = horizon_telemetry::endpoint() else { + return; + }; + let spawned = std::thread::Builder::new() + .name("Heartbeat".into()) + .spawn(move || run(&endpoint)); + match spawned { + Ok(handle) => { + let _ = PINGER.set(handle.thread().clone()); + } + Err(e) => log::warn!("Horizon: no live count ping: {e}"), + } +} + +/// Whether a world is open to LAN or friends; a change is sent at once. +pub fn set_lan(open: bool) { + if LAN.swap(open, Ordering::Relaxed) != open + && let Some(pinger) = PINGER.get() + { + pinger.unpark(); + } +} + +fn run(endpoint: &str) { + let session = live::session_id(); + let version = crate::telemetry::version(); + let mut wait = live::INTERVAL; + let mut failed = false; + loop { + let ping = Ping::new(&session, &version, LAN.load(Ordering::Relaxed)); + match live::send(endpoint, &ping) { + Ok(()) => { + wait = live::INTERVAL; + failed = false; + } + Err(e) => { + // Said once, not every minute the server is away. + if !failed { + log::info!("Horizon: the live count ping failed ({e}); trying again later"); + } + failed = true; + wait = (wait * 2).min(MAX_WAIT); + } + } + // Woken early by `set_lan`; a spurious wake only sends one ping more. + std::thread::park_timeout(wait); + } +} diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 29faf5a2a..8025a72e4 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. @@ -365,6 +367,8 @@ pub struct HudBatch { pub blends: Vec<(std::ops::Range, Blend)>, /// The textures and time of the `Blend::EndPortal` runs. pub end_portal: EndPortalFill, + /// 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)] @@ -414,6 +418,7 @@ impl HudBatch { patches: Vec::new(), blends: Vec::new(), end_portal: EndPortalFill::default(), + blur_at: 0, } } /// Draw the vertices added since `start` with the inverting blend. @@ -466,6 +471,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) { ( @@ -1143,7 +1156,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 { @@ -1155,7 +1187,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 { @@ -1416,6 +1448,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. @@ -1428,6 +1487,7 @@ mod tests { patches: Vec::new(), blends: Vec::new(), end_portal: EndPortalFill::default(), + 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 adc4e0f18..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, } } @@ -594,12 +597,8 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { ), )); } - if let Some(mode) = d.map_post_processing { - entries.push(( - "minecraft:map_post_processing", - Tag::String(if mode == 0 { "lock" } else { "scale" }.into()), - )); - } + // minecraft:map_post_processing is transient: ItemStack.CODEC never + // saves it (only the network carries it). if !d.charged.is_empty() { entries.push(( "minecraft:charged_projectiles", @@ -864,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/conn.rs b/crates/horizon-client/src/lan/conn.rs index 7a92040f2..a8ec46dad 100644 --- a/crates/horizon-client/src/lan/conn.rs +++ b/crates/horizon-client/src/lan/conn.rs @@ -778,7 +778,7 @@ fn play(c: Connection, shared: &Arc, parts: Parts, address: std::net::So std::thread::Builder::new() .name(format!("horizon-lan-out-{conn_id}")) .spawn(move || { - // A dedicated server's tick comes first (horizon_threads). + // Ticks and frames come first (horizon_threads). horizon_threads::behind_server(); write_loop(writer, rx, alive, latency, pending) }) diff --git a/crates/horizon-client/src/lan/containers.rs b/crates/horizon-client/src/lan/containers.rs index 66fbfe4b6..88f50aa3b 100644 --- a/crates/horizon-client/src/lan/containers.rs +++ b/crates/horizon-client/src/lan/containers.rs @@ -455,18 +455,30 @@ impl Hub { let Slots::Block(pos) = m.slots else { return; }; - // AbstractFurnaceBlockEntity.dataAccess, BrewingStandBlockEntity.dataAccess. + // AbstractFurnaceBlockEntity.dataAccess, BrewingStandBlockEntity.dataAccess, + // CrafterBlockEntity.containerData. let data = match world.block_entities.get(&pos) { - Some(BlockEntity::Furnace(f)) => [ + Some(BlockEntity::Furnace(f)) => vec![ f.lit_remaining, f.lit_total, f.cooking_timer, f.cooking_total, ], - Some(BlockEntity::Brewing(b)) => [b.brew_time, b.fuel, b.total_brew_time, b.total_fuel], + Some(BlockEntity::Brewing(b)) => { + vec![b.brew_time, b.fuel, b.total_brew_time, b.total_fuel] + } + // CrafterBlockEntity.containerData: the disabled slots, then triggered. + Some(BlockEntity::Crafter(c)) => c + .disabled + .iter() + .chain([&c.triggered]) + .map(|&d| i32::from(d)) + .collect(), _ => return, } - .map(|v| v as i16); + .into_iter() + .map(|v| v as i16) + .collect::>(); m.sent_data.resize(data.len(), i16::MIN); let window = m.window; let changed: Vec<(usize, i16)> = data diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index c1156001c..c4e8052c0 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -34,7 +34,7 @@ pub fn changed_attributes( } /// What the game says about one entity this tick. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default, PartialEq)] pub struct EntityState { pub id: i32, pub uuid: u128, @@ -61,6 +61,72 @@ pub struct EntityState { pub precise: bool, } +impl EntityState { + /// The entity `id` of type `kind` as a fresh state has it: at the origin, + /// at rest, with no data, equipment or attributes. Keeps the allocations + /// of the strings and vectors it held. + pub fn reset(&mut self, id: i32, uuid: u128, kind: &str) { + self.id = id; + self.uuid = uuid; + self.kind.clear(); + self.kind.push_str(kind); + self.position = [0.0; 3]; + (self.yaw, self.pitch, self.head_yaw) = (0.0, 0.0, 0.0); + self.on_ground = false; + self.velocity = [0.0; 3]; + self.data = 0; + self.meta.clear(); + self.equipment.clear(); + self.attributes.clear(); + self.precise = false; + } +} + +/// The states a level describes its entities with, kept from tick to tick: +/// each tick's are written over the last tick's in place, so the strings and +/// vectors in them are reused instead of being made and freed again for every +/// entity on every tick. +#[derive(Default)] +pub struct States { + list: Vec, + len: usize, +} + +impl States { + /// Start a new tick's states. + pub fn clear(&mut self) { + self.len = 0; + } + /// The next entity's state, reset (`EntityState::reset`). + pub fn add(&mut self, id: i32, uuid: u128, kind: &str) -> &mut EntityState { + if self.len == self.list.len() { + self.list.push(EntityState::default()); + } + let e = &mut self.list[self.len]; + self.len += 1; + e.reset(id, uuid, kind); + e + } + pub fn push(&mut self, e: EntityState) { + match self.list.get_mut(self.len) { + Some(slot) => *slot = e, + None => self.list.push(e), + } + self.len += 1; + } + pub fn as_slice(&self) -> &[EntityState] { + &self.list[..self.len] + } +} + +impl Extend for States { + fn extend>(&mut self, states: I) { + for e in states { + self.push(e); + } + } +} + /// `AbstractArrow`: every update sends its position and rotation. fn is_arrow(kind: &str) -> bool { matches!( @@ -792,6 +858,31 @@ mod tests { } } + #[test] + fn states_are_written_over_last_ticks_in_place() { + let mut states = States::default(); + let e = states.add(1, 1, "minecraft:zombie"); + e.position = [1.0, 2.0, 3.0]; + e.meta.push((9, serializer::FLOAT, Value::Float(20.0))); + e.equipment.push((0, None)); + let (kind, meta) = (e.kind.as_ptr(), e.meta.as_ptr()); + states.push(state(2.0)); + states.clear(); + let e = states.add(3, 3, "minecraft:husk"); + // Nothing of the last tick's state is left, but its allocations are. + let fresh = EntityState { + id: 3, + uuid: 3, + kind: "minecraft:husk".into(), + ..EntityState::default() + }; + assert_eq!(*e, fresh); + assert_eq!((e.kind.as_ptr(), e.meta.as_ptr()), (kind, meta)); + assert_eq!(states.as_slice(), std::slice::from_ref(&fresh)); + states.extend([state(5.0), state(6.0)]); + assert_eq!(states.as_slice(), [fresh, state(5.0), state(6.0)]); + } + /// The entity as added this tick, then its updates (one a tick). fn added(e: &EntityState) -> ServerEntity { ServerEntity::new(e, Some(100), &Riding::default()) diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index f46e37abc..4be5aa29f 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -147,6 +147,8 @@ pub struct Guest { pub xp_level: i32, pub xp_progress: f32, pub xp_total: i32, + /// `Player.enchantmentSeed` (the enchanting table's offers). + pub xp_seed: i32, /// Active status effects (`LivingEntity.activeEffects`). pub effects: crate::effects::PlayerEffects, /// What the client was told of each effect: id, amplifier, flags, and @@ -273,6 +275,7 @@ impl Guest { xp_level: 0, xp_progress: 0.0, xp_total: 0, + xp_seed: 0, effects: Default::default(), sent_effects: Vec::new(), menu_sent: vec![None; 46], @@ -418,6 +421,43 @@ pub fn stack_to_network( horizon_protocol::item::Component::Int(id), )); } + if d.repair_cost > 0 { + stack.added.push(( + horizon_protocol::item::component::REPAIR_COST, + horizon_protocol::item::Component::Int(d.repair_cost as i32), + )); + } + if let Some(mode) = d.map_post_processing { + stack.added.push(( + horizon_protocol::item::component::MAP_POST_PROCESSING, + horizon_protocol::item::Component::Int(i32::from(mode)), + )); + } + // The books a lectern shows and a guest reads. + if !d.writable_pages.is_empty() { + stack.added.push(( + horizon_protocol::item::component::WRITABLE_BOOK_CONTENT, + horizon_protocol::item::Component::WritableBook(d.writable_pages.clone()), + )); + } + if let Some(w) = &d.written { + stack.added.push(( + horizon_protocol::item::component::WRITTEN_BOOK_CONTENT, + horizon_protocol::item::Component::WrittenBook( + horizon_protocol::item::WrittenBook { + title: w.title.clone(), + author: w.author.clone(), + generation: i32::from(w.generation), + pages: w + .pages + .iter() + .map(|p| horizon_protocol::text::literal(p)) + .collect(), + resolved: true, + }, + ), + )); + } } if let Some(name) = s.custom_name() { stack.added.push(( diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 4e8269e80..bb24940f4 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 { @@ -311,6 +335,11 @@ impl Hub { self.sync.id(registry, name) } + /// The name of a network id in a built-in registry. + pub fn registry_name(&self, registry: &str, id: i32) -> Option<&str> { + self.sync.builtin.get(registry)?.name(id) + } + pub fn item_id(&mut self, item: &Arc) -> i32 { if let Some(id) = self.item_ids.get(item) { return *id; @@ -1290,20 +1319,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, @@ -2480,3 +2496,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/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index d7dc097dd..8797f25a2 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -66,6 +66,7 @@ pub fn apply(guest: &mut Guest, level: &Level) { guest.xp_level = level.xp_level; guest.xp_progress = level.xp_progress; guest.xp_total = level.xp_total; + guest.xp_seed = level.xp_seed; guest.effects = crate::effects::PlayerEffects::from_saved(&level.active_effects); guest.game_mode = level.mode(); guest.flying = level.flying; @@ -127,6 +128,7 @@ pub fn store(guest: &Guest, level: &mut Level) { level.xp_level = guest.xp_level; level.xp_progress = guest.xp_progress; level.xp_total = guest.xp_total; + level.xp_seed = guest.xp_seed; level.active_effects = guest.effects.saved(); level.game_mode = guest.game_mode; level.creative = guest.game_mode == 1; diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 25be4a0c4..d48a242a6 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -80,6 +80,7 @@ pub mod graphics; pub mod graphics_style; pub mod graphics_ui; pub mod health; +pub mod heartbeat; pub mod hotbar; pub mod hud; pub mod hud_layout; diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 6dc8d7b7f..cb804e15b 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -3,8 +3,8 @@ //! craft drags, pickup all) for the player inventory, the crafting table, the //! chest family, hoppers, dispensers, shulker boxes, the furnaces, the brewing //! stand, the crafter (its client menu and the block entity's server menu with -//! `setSlotState`), the loom (`clickMenuButton`, `slotsChanged`) and the -//! merchant (`MerchantMenu` over a `merchant::Session`: payment slots, the +//! `setSlotState`), the loom (`clickMenuButton`, `slotsChanged`), the +//! stonecutter (its recipe buttons and result) and the merchant (`MerchantMenu` over a `merchant::Session`: payment slots, the //! result slot's trade, `tryMoveItems`). //! `tools/test_menu_click_parity.py` compares every click with vanilla's menu //! classes. @@ -24,8 +24,29 @@ pub struct Env<'a> { pub recipes: &'a Recipes, pub brewing: &'a Brewing, pub banners: &'a Banners, + /// The stonecutter's recipes. + pub station_recipes: &'a crate::stations::StationRecipes, + /// The grindstone's and the anvil's enchantment rules. + pub enchantments: &'a crate::enchant::Enchantments, + /// Item display names: the anvil compares the rename box with the + /// input's hover name. + pub names: &'a crate::creative::Names, /// What a merchant menu needs for offers made while it is open (level-ups). pub trade: Option<&'a crate::merchant::TradeEnv<'a>>, + /// The level's maps (`ContainerLevelAccess`): the cartography table reads + /// and makes them. None is a client's menu (`ContainerLevelAccess.NULL`): + /// it makes no result, and a taken result keeps its map id. + pub maps: Option<&'a dyn Maps>, +} + +/// The maps of the level a menu is in. +pub trait Maps { + /// `MapItem.getSavedData`: whether map `id` is locked, and its scale; + /// None when the level has no such map. + fn state(&self, id: i32) -> Option<(bool, u8)>; + /// `MapItem.scaleMap` (`scale`) or `lockMap`: the copy of map `id` the + /// level makes under a new id (`getFreeMapId`), None without the map. + fn derive(&self, id: i32, scale: bool) -> Option; } #[derive(Clone, Copy, PartialEq, Eq, Debug)] @@ -71,6 +92,26 @@ pub enum Kind { /// result follows the grid, and filling a disabled slot enables it. CrafterBlock, Loom, + /// `StonecutterMenu`: the input, the result, then the inventory. + Stonecutter, + /// `GrindstoneMenu`: two inputs, the result, then the inventory. + Grindstone, + /// `AnvilMenu`: two inputs, the result, then the inventory. + Anvil, + /// `SmithingMenu`: template, base, addition, the result, then the inventory. + Smithing, + /// `EnchantmentMenu`: the item, the lapis, then the inventory; its data + /// slots are the three costs, the seed and the clues. + Enchanting, + /// `BeaconMenu`: the payment slot, then the inventory; its data slots are + /// the pyramid's levels and the two powers (`encodeEffect`: id + 1). + Beacon, + /// `CartographyTableMenu`: the map, the paper / map / glass pane, the + /// result, then the inventory. + Cartography, + /// `LecternMenu` over the `LecternBlockEntity`: the book's one slot (no + /// inventory slots); its data slot is the open page. + Lectern, /// `MerchantMenu`: two payment slots, the result, then the inventory. Merchant, /// `CreativeModeInventoryScreen.ItemPickerMenu`: an item tab's 45 @@ -96,6 +137,14 @@ impl Kind { "crafter" => Self::Crafter, "crafter_be" => Self::CrafterBlock, "loom" => Self::Loom, + "stonecutter" => Self::Stonecutter, + "grindstone" => Self::Grindstone, + "anvil" => Self::Anvil, + "smithing" => Self::Smithing, + "enchanting" => Self::Enchanting, + "beacon" => Self::Beacon, + "cartography" => Self::Cartography, + "lectern" => Self::Lectern, "merchant" => Self::Merchant, "item_picker" => Self::ItemPicker, _ => return None, @@ -133,6 +182,28 @@ enum Role { LoomResult, /// `MerchantResultSlot`. MerchantResult, + /// The stonecutter's result slot (`onTake` uses up one input). + StoneResult, + /// The grindstone's inputs: damageable or enchanted items. + GrindInput, + /// The grindstone's result slot (`onTake` clears both inputs). + GrindResult, + /// A smithing table input: its recipe property set (template, base, addition). + SmithInput(usize), + /// `ItemCombinerMenu`'s result slot (the anvil's and the smithing table's). + CombineResult, + /// The enchanting table's item slot (one item). + EnchantItem, + /// The enchanting table's lapis slot. + Lapis, + /// `BeaconMenu.PaymentSlot`: one beacon payment item. + BeaconPay, + /// The cartography table's map slot (anything with a map id). + CartoMap, + /// Its paper, empty map or glass pane slot. + CartoExtra, + /// Its result (`onTake`: one of each input, the map post-processed). + CartoResult, /// `CustomCreativeSlot`: a creative tab's display slot, which the /// screen clicks itself; drags and PICKUP_ALL pass it by. CreativeDisplay, @@ -145,6 +216,26 @@ struct Slot { role: Role, } +/// `BeaconBlockEntity.BEACON_EFFECTS`: the powers of each pyramid level. +pub const BEACON_EFFECTS: [&[&str]; 4] = [ + &["minecraft:speed", "minecraft:haste"], + &["minecraft:resistance", "minecraft:jump_boost"], + &["minecraft:strength"], + &["minecraft:regeneration"], +]; + +/// `BeaconBlockEntity.getRequiredLevelsFor`: 0 for no power, `i32::MAX` +/// for one no level gives. +pub fn beacon_required_levels(effect: Option<&str>) -> i32 { + let Some(effect) = effect else { + return 0; + }; + BEACON_EFFECTS + .iter() + .position(|tier| tier.contains(&effect)) + .map_or(i32::MAX, |i| i as i32 + 1) +} + /// The containers a menu spans. const PLAYER: usize = 0; const MAIN: usize = 1; @@ -182,6 +273,53 @@ pub struct Menu { pub equipped: Vec<(&'static str, Option)>, /// The merchant a merchant menu trades with. pub merchant: Option>, + /// The stonecutter's recipe list (`recipesForInput`). + pub stone: Stonecutter, + /// The grindstone result's `getExperienceAmount` sum before its roll, + /// set when the result was taken: the caller (with a level) awards the + /// orbs and plays level event 1042. + pub ground: Option, + /// `Player.experienceLevel`, which the anvil's result needs. + pub levels: i32, + /// The levels the menu gave the player (`giveExperienceLevels`), for the caller. + pub level_change: i32, + /// `AnvilMenu`'s state besides its slots and its cost data slot. + pub anvil: Anvil, + /// The anvil's or the smithing table's result was taken: the caller (with + /// a level) runs the rest of its `onTake` (the anvil's wear and level + /// event 1030 or 1029, the smithing table's 1044). + pub combined: bool, + /// The enchanting table's item changed to an enchantable one: the caller + /// (with a level) fills the costs and clues (`slotsChanged`'s + /// `access.execute`). + pub enchant_changed: bool, + /// An enchanting button the menu took (`clickMenuButton` passed its + /// checks): the caller (with a level) enchants. + pub enchant_button: Option, + /// `Player.mayBuild` (not adventure mode): the lectern's Take Book. + pub may_build: bool, +} + +/// `AnvilMenu`'s state besides its slots and `cost`. +#[derive(Clone, Default, Debug, PartialEq)] +pub struct Anvil { + /// `itemName`: the rename box's text (`ServerboundRenameItemPacket`). + pub name: Option, + /// `repairItemCountCost`. + pub repair_count: u32, + /// `onlyRenaming`. + pub only_renaming: bool, +} + +/// `StonecutterMenu`'s state besides its slots and `selectedRecipeIndex`. +#[derive(Clone, Default, Debug, PartialEq)] +pub struct Stonecutter { + /// `recipesForInput`: indices into `StationRecipes.stonecutting`. + pub recipes: Vec, + /// The item the list was made for (`input`; None for nothing). + pub input: Option>, + /// `ResultContainer.recipeUsed`. + pub used: Option, } fn same_item(a: &ItemStack, b: &ItemStack) -> bool { @@ -196,6 +334,15 @@ fn split(stack: &mut ItemStack, amount: u32) -> ItemStack { out } +/// `LecternBlockEntity.getPageCount`: a written book's pages, else a +/// writable book's. +pub fn book_pages(stack: &ItemStack) -> usize { + stack.data().map_or(0, |d| match &d.written { + Some(w) => w.pages.len(), + None => d.writable_pages.len(), + }) +} + fn tidy(slot: &mut Option) { if slot.as_ref().is_some_and(|s| s.count == 0) { *slot = None; @@ -318,6 +465,101 @@ impl Menu { player(&mut slots); data = 1; } + Kind::Stonecutter => { + containers[MAIN] = vec![None; 1]; + slots.extend(main(1, Role::Plain)); + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::StoneResult, + }); + player(&mut slots); + // selectedRecipeIndex: DataSlot.standalone() starts at 0. + data = 1; + } + Kind::Grindstone => { + containers[MAIN] = vec![None; 2]; + slots.extend(main(2, Role::GrindInput)); + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::GrindResult, + }); + player(&mut slots); + } + Kind::Anvil => { + containers[MAIN] = vec![None; 2]; + slots.extend(main(2, Role::Plain)); + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::CombineResult, + }); + player(&mut slots); + // cost: DataSlot.standalone() starts at 0. + data = 1; + } + Kind::Smithing => { + containers[MAIN] = vec![None; 3]; + slots.extend((0..3).map(|index| Slot { + container: MAIN, + index, + role: Role::SmithInput(index), + })); + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::CombineResult, + }); + player(&mut slots); + // hasRecipeError. + data = 1; + } + Kind::Enchanting => { + containers[MAIN] = vec![None; 2]; + slots.push(Slot { + container: MAIN, + index: 0, + role: Role::EnchantItem, + }); + slots.push(Slot { + container: MAIN, + index: 1, + role: Role::Lapis, + }); + player(&mut slots); + // costs[3], enchantmentSeed, enchantClue[3], levelClue[3]. + data = 10; + } + Kind::Beacon => { + containers[MAIN] = vec![None; 1]; + slots.extend(main(1, Role::BeaconPay)); + player(&mut slots); + // levels, primary, secondary. + data = 3; + } + Kind::Cartography => { + containers[MAIN] = vec![None; 2]; + for (index, role) in [Role::CartoMap, Role::CartoExtra].into_iter().enumerate() { + slots.push(Slot { + container: MAIN, + index, + role, + }); + } + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::CartoResult, + }); + player(&mut slots); + } + Kind::Lectern => { + containers[MAIN] = vec![None; 1]; + slots.extend(main(1, Role::Plain)); + // The open page (LecternBlockEntity.dataAccess). + data = 1; + } Kind::ItemPicker => { containers[MAIN] = vec![None; 45]; slots.extend(main(45, Role::CreativeDisplay)); @@ -403,15 +645,51 @@ impl Menu { crafted: Vec::new(), equipped: Vec::new(), merchant: None, + stone: Stonecutter::default(), + ground: None, + levels: 0, + level_change: 0, + anvil: Anvil::default(), + combined: false, + enchant_changed: false, + enchant_button: None, + may_build: true, } + .with_initial_data() + } + + /// Data slots that do not start at 0: the enchanting table's clues are -1. + fn with_initial_data(mut self) -> Self { + if self.kind == Kind::Enchanting { + self.data[4..].fill(-1); + } + self } pub fn kind(&self) -> Kind { self.kind } - /// `clickMenuButton`: the loom's pattern buttons. False when refused. + /// `clickMenuButton`: the loom's pattern buttons and the stonecutter's + /// recipes. False when refused. pub fn button(&mut self, env: &Env, id: i32) -> bool { + if self.kind == Kind::Lectern { + return self.lectern_button(env, id); + } + if self.kind == Kind::Enchanting { + return self.enchant_click(id); + } + if self.kind == Kind::Stonecutter { + // StonecutterMenu.clickMenuButton: an invalid index is taken too. + if self.data[0] == id { + return false; + } + if id >= 0 && (id as usize) < self.stone.recipes.len() { + self.data[0] = id; + self.stone_setup_result(env, id); + } + return true; + } if self.kind != Kind::Loom || id < 0 || id as usize >= self.loom_patterns.len() { return false; } @@ -421,6 +699,41 @@ impl Menu { true } + /// `LecternMenu.clickMenuButton`: the page buttons (1 back, 2 forward, + /// 100 + n to page n) and Take Book (3), which puts the book in the + /// inventory or drops it. + fn lectern_button(&mut self, env: &Env, id: i32) -> bool { + match id { + 100.. => self.set_data(0, id - 100), + 1 => self.set_data(0, self.data[0] - 1), + 2 => self.set_data(0, self.data[0] + 1), + 3 if self.may_build => { + // removeItemNoUpdate: the whole book, and onBookItemRemove. + let book = self.containers[MAIN][0].take(); + self.data[0] = 0; + if let Some(mut book) = book + && !self.inventory_add(env, &mut book) + { + self.drop_stack(&book); + } + } + _ => return false, + } + true + } + + /// `AbstractContainerMenu.setData`: the lectern's is + /// `LecternBlockEntity.setPage`, kept within the book's pages. + pub fn set_data(&mut self, id: usize, value: i32) { + if self.kind == Kind::Lectern && id == 0 { + // Mth.clamp(page, 0, pageCount - 1). + let count = self.containers[MAIN][0].as_ref().map_or(0, book_pages) as i32; + self.data[0] = value.max(0).min(count - 1); + return; + } + self.data[id] = value; + } + /// `CrafterBlockEntity.setSlotState` (the slot state packet): only an /// empty slot can be disabled or enabled. pub fn set_slot_state(&mut self, slot: usize, enabled: bool) { @@ -510,24 +823,278 @@ impl Menu { } } + /// `StonecutterMenu.slotsChanged`: a new input item lists its recipes + /// (`setupRecipeList`), with none selected and no result. + fn stone_changed(&mut self, env: &Env) { + let input = self.containers[MAIN][0].as_ref().map(|s| s.item.clone()); + if input == self.stone.input { + return; + } + self.stone.input = input; + self.data[0] = -1; + self.containers[RESULT][0] = None; + self.stone.recipes = match &self.containers[MAIN][0] { + Some(stack) => env + .station_recipes + .stonecutting + .iter() + .enumerate() + .filter(|(_, r)| r.input.test(stack)) + .map(|(i, _)| i) + .collect(), + None => Vec::new(), + }; + } + + /// `StonecutterMenu.setupResultSlot`. + fn stone_setup_result(&mut self, env: &Env, index: i32) { + let recipe = usize::try_from(index) + .ok() + .and_then(|i| self.stone.recipes.get(i).copied()); + self.stone.used = recipe; + self.containers[RESULT][0] = + recipe.map(|r| env.station_recipes.stonecutting[r].result.clone()); + } + /// `Slot.setChanged` on slot `s`: the loom recomputes from its inputs, - /// the block crafter refreshes its result. + /// the stonecutter lists its recipes, the block crafter refreshes its + /// result. fn slot_changed(&mut self, env: &Env, s: usize) { // MerchantContainer.setChanged: every slot of it, the result too. if self.kind == Kind::Merchant && self.slots[s].container != PLAYER { self.merchant_update(env); return; } + // SmithingMenu.slotsChanged runs for its result container too. + if self.kind == Kind::Smithing && self.slots[s].container == RESULT { + self.smith_error(); + return; + } + // CartographyTableMenu: its result container calls slotsChanged too. + if self.kind == Kind::Cartography && self.slots[s].container != PLAYER { + self.carto_changed(env); + return; + } if self.slots[s].container != MAIN { return; } match self.kind { Kind::Loom => self.loom_changed(env), + Kind::Stonecutter => self.stone_changed(env), + // GrindstoneMenu.createResult. + Kind::Grindstone => { + self.containers[RESULT][0] = crate::stations::grindstone_result( + env.enchantments, + env.items, + self.containers[MAIN][0].as_ref(), + self.containers[MAIN][1].as_ref(), + ); + } Kind::CrafterBlock => self.crafter_result(env), + Kind::Anvil => self.anvil_result(env), + Kind::Enchanting => self.enchant_changed(env), + Kind::Smithing => { + self.smith_result(env); + self.smith_error(); + } _ => {} } } + /// `EnchantmentMenu.clickMenuButton`'s checks: the lapis, the cost and + /// the levels (creative pays nothing). The enchanting itself needs a + /// level and is the caller's (`enchant_button`). + fn enchant_click(&mut self, id: i32) -> bool { + let Some(i) = usize::try_from(id).ok().filter(|&i| i < 3) else { + return false; + }; + let need = id + 1; + let lapis = self.containers[MAIN][1] + .as_ref() + .map_or(0, |l| l.count as i32); + if lapis < need && !self.creative { + return false; + } + if self.data[i] <= 0 + || self.containers[MAIN][0].is_none() + || (self.levels < need || self.levels < self.data[i]) && !self.creative + { + return false; + } + self.enchant_button = Some(i); + true + } + + /// `EnchantmentMenu.slotsChanged`: no costs or clues without an + /// enchantable item; with one, a level fills them (`enchant_changed`). + fn enchant_changed(&mut self, env: &Env) { + let enchantable = self.containers[MAIN][0].as_ref().is_some_and(|s| { + env.enchantments.enchantable(&s.item) > 0 && s.enchantments().is_empty() + }); + if enchantable { + self.enchant_changed = true; + } else { + self.data[..3].fill(0); + self.data[4..].fill(-1); + } + } + + /// `AnvilMenu.createResult`. + fn anvil_result(&mut self, env: &Env) { + let hover = self.containers[MAIN][0] + .as_ref() + .map(|i| crate::stations::hover_name(&|id| env.names.item(id), i)) + .unwrap_or_default(); + let out = crate::stations::anvil_result( + env.enchantments, + env.items, + self.containers[MAIN][0].as_ref(), + self.containers[MAIN][1].as_ref(), + self.anvil.name.as_deref(), + &hover, + self.creative, + ); + // onlyRenaming is reset, repairItemCountCost only where an input is. + self.anvil.only_renaming = out.only_renaming; + if self.containers[MAIN][0].is_some() { + self.anvil.repair_count = out.repair_item_count_cost; + } + self.data[0] = out.cost; + self.containers[RESULT][0] = out.result; + } + + /// `AnvilMenu.setItemName` (`ServerboundRenameItemPacket`): false when + /// the name is refused or unchanged. + /// `BeaconMenu.updateEffects` (`ServerboundSetBeaconPacket`): with a + /// payment, powers `BeaconBlockEntity.validateEffects` allows for the + /// pyramid's levels (data 0) become data 1 and 2 and the payment is used. + /// Each power is its `mob_effect` id and name. False when refused. + pub fn beacon_update( + &mut self, + env: &Env, + primary: Option<(i32, &str)>, + secondary: Option<(i32, &str)>, + ) -> bool { + if self.kind != Kind::Beacon || self.containers[MAIN][0].is_none() { + return false; + } + let levels = self.data[0]; + let (p, s) = ( + beacon_required_levels(primary.map(|e| e.1)), + beacon_required_levels(secondary.map(|e| e.1)), + ); + let valid = !(secondary.is_some() && levels < 4) + && p <= levels + && s <= levels + && p < 4 + && !(s != 0 && s < 4 && primary.map(|e| e.0) != secondary.map(|e| e.0)); + if !valid { + return false; + } + self.data[1] = primary.map_or(0, |e| e.0 + 1); + self.data[2] = secondary.map_or(0, |e| e.0 + 1); + self.remove(env, 0, 1); + true + } + + pub fn rename(&mut self, env: &Env, name: &str) -> bool { + // StringUtil.filterText, then validateName's length limit. + let name: String = name + .chars() + .filter(|&c| c != '\u{a7}' && c >= ' ' && c != '\u{7f}') + .collect(); + if self.kind != Kind::Anvil + || name.encode_utf16().count() > 50 + || self.anvil.name.as_deref() == Some(&name) + { + return false; + } + if let Some(result) = self.containers[RESULT][0].as_mut() { + result.data_mut().custom_name = (!name.trim().is_empty()).then(|| name.clone()); + result.tidy(); + } + self.anvil.name = Some(name); + self.anvil_result(env); + true + } + + /// `SmithingMenu.createResult`. + fn smith_result(&mut self, env: &Env) { + let [a, b, c] = [0, 1, 2].map(|i| self.containers[MAIN][i].as_ref()); + self.containers[RESULT][0] = env + .station_recipes + .smithing_result(env.enchantments, a, b, c); + } + + /// `SmithingMenu.slotsChanged`'s `hasRecipeError`: every input filled and no result. + fn smith_error(&mut self) { + let error = self.containers[MAIN].iter().all(Option::is_some) + && self.containers[RESULT][0].is_none(); + self.data[0] = i32::from(error); + } + + /// `CartographyTableMenu.slotsChanged` and `setupResultSlot`: a result + /// only where the level has the map (`access.execute`), with the post + /// processing its take runs (`MAP_POST_PROCESSING`: 0 lock, 1 scale). + fn carto_changed(&mut self, env: &Env) { + let [map, extra] = [0, 1].map(|i| self.containers[MAIN][i].clone()); + if self.containers[RESULT][0].is_some() && (map.is_none() || extra.is_none()) { + self.containers[RESULT][0] = None; + return; + } + let (Some(map), Some(extra), Some(maps)) = (map, extra, env.maps) else { + return; + }; + let Some((locked, scale)) = map + .data() + .and_then(|d| d.map_id) + .and_then(|id| maps.state(id)) + else { + return; + }; + let extendable = env + .items + .item_tags + .get("minecraft:extendable_maps") + .is_some_and(|t| t.contains(&*map.item)); + let copy = |count: u32, post: Option| { + let mut out = ItemStack { + count, + ..map.clone() + }; + if post.is_some() { + out.data_mut().map_post_processing = post; + } + out + }; + self.containers[RESULT][0] = match &*extra.item { + "minecraft:paper" if extendable && !locked && scale < 4 => Some(copy(1, Some(1))), + "minecraft:glass_pane" if !locked => Some(copy(1, Some(0))), + "minecraft:map" => Some(copy(2, None)), + _ => None, + }; + } + + /// `Item.onCraftedBy` of a taken cartography result + /// (`MapItem.onCraftedPostProcess`): the post processing goes, and on a + /// level with maps the stack names the scaled or locked copy. + fn map_crafted(env: &Env, stack: &mut ItemStack) { + if &*stack.item != "minecraft:filled_map" { + return; + } + let Some(post) = stack.data().and_then(|d| d.map_post_processing) else { + return; + }; + stack.data_mut().map_post_processing = None; + let id = stack.data().and_then(|d| d.map_id); + if let (Some(maps), Some(id)) = (env.maps, id) + && let Some(new) = maps.derive(id, post == 1) + { + stack.data_mut().map_id = Some(new); + } + stack.tidy(); + } + pub fn slot_count(&self) -> usize { self.slots.len() } @@ -539,6 +1106,11 @@ impl Menu { /// Sets a slot as a test fixture does (`Slot.set`). pub fn set_slot(&mut self, env: &Env, i: usize, stack: Option) { + if self.kind == Kind::Lectern { + // LecternBlockEntity.setBook: the book its slot can't set. + self.containers[MAIN][0] = stack; + return; + } self.put(env, i, stack); } @@ -634,10 +1206,34 @@ impl Menu { Role::LoomBanner => Self::is_banner(stack), Role::LoomDye => env.banners.loom_dye(env.items, stack).is_some(), Role::LoomPattern => env.banners.is_pattern_item(env.items, stack), - Role::LoomResult | Role::MerchantResult => false, + Role::GrindInput => crate::stations::grindstone_accepts(env.items, stack), + Role::SmithInput(i) => env.station_recipes.smithing_accepts(i, stack), + Role::EnchantItem => true, + Role::Lapis => &*stack.item == "minecraft:lapis_lazuli", + Role::BeaconPay => env + .items + .item_tags + .get("minecraft:beacon_payment_items") + .is_some_and(|t| t.contains(&*stack.item)), + Role::CartoMap => stack.data().is_some_and(|d| d.map_id.is_some()), + Role::CartoExtra => Self::is_carto_extra(stack), + Role::LoomResult + | Role::MerchantResult + | Role::StoneResult + | Role::GrindResult + | Role::CombineResult + | Role::CartoResult => false, } } + /// What the cartography table's second slot takes. + fn is_carto_extra(stack: &ItemStack) -> bool { + matches!( + &*stack.item, + "minecraft:paper" | "minecraft:map" | "minecraft:glass_pane" + ) + } + /// `BannerItem`. fn is_banner(stack: &ItemStack) -> bool { stack.item.ends_with("_banner") @@ -646,6 +1242,10 @@ impl Menu { fn may_pickup(&self, env: &Env, s: usize) -> bool { match self.slots[s].role { Role::Inert => false, + // AnvilMenu.mayPickup: the levels to pay, and a price. + Role::CombineResult if self.kind == Kind::Anvil => { + (self.creative || self.levels >= self.data[0]) && self.data[0] > 0 + } Role::MerchantResult => self .merchant .as_ref() @@ -670,7 +1270,9 @@ impl Menu { /// `Slot.getMaxStackSize(stack)`. fn slot_max(&self, env: &Env, s: usize, stack: &ItemStack) -> u32 { let own = match self.slots[s].role { - Role::Armor(_) | Role::Potion => 1, + Role::Armor(_) | Role::Potion | Role::EnchantItem | Role::BeaconPay => 1, + // The lectern's bookAccess holds one. + Role::Plain if self.kind == Kind::Lectern && self.slots[s].container == MAIN => 1, Role::Fuel if Self::is_bucket(stack) => return 1, _ => CONTAINER_MAX, }; @@ -681,12 +1283,20 @@ impl Menu { fn put(&mut self, env: &Env, s: usize, mut stack: Option) { tidy(&mut stack); let slot = self.slots[s]; + // LecternBlockEntity's bookAccess.setItem does nothing. + if self.kind == Kind::Lectern && slot.container == MAIN { + return; + } // SimpleContainer / BaseContainerBlockEntity.setItem: limitSize to // getMaxStackSize(stack). The loom's result is a SimpleContainer too. if (slot.container == MAIN || slot.role == Role::LoomResult) && let Some(st) = stack.as_mut() { st.count = st.count.min(CONTAINER_MAX.min(Self::max_stack(env, st))); + // The beacon's container holds one item (getMaxStackSize 1). + if self.kind == Kind::Beacon { + st.count = st.count.min(1); + } } // CrafterBlockEntity.setItem: filling a disabled (empty) slot enables it. if self.kind == Kind::CrafterBlock @@ -758,17 +1368,63 @@ impl Menu { .filter(|c| c.count > 0) .map(|c| split(c, amount)); tidy(cell); + // LecternBlockEntity: an emptied book slot is onBookItemRemove (page 0). + if self.kind == Kind::Lectern && slot.container == MAIN && cell.is_none() { + self.data[0] = 0; + } if out.is_some() && slot.container == GRID { self.recompute(env); } // SimpleContainer.removeItem calls setChanged when it took something; // MerchantContainer.removeItem updates the result after a payment slot. - if out.is_some() && matches!(self.kind, Kind::Loom | Kind::Merchant) { + if out.is_some() + && matches!( + self.kind, + Kind::Loom + | Kind::Merchant + | Kind::Stonecutter + | Kind::Grindstone + | Kind::Anvil + | Kind::Smithing + | Kind::Enchanting + | Kind::Cartography + ) + { self.slot_changed(env, s); } out } + /// `AnvilMenu.onTake`: the levels, the material used up, then the input. + fn anvil_take(&mut self, env: &Env) { + let cost = self.data[0]; + if !self.creative { + // Player.giveExperienceLevels(-cost). + self.level_change -= cost; + self.drops.push(format!( + "levels{}{}", + if cost <= 0 { "+" } else { "" }, + -cost + )); + } + let repair = self.anvil.repair_count; + if repair > 0 { + let addition = self.containers[MAIN][1] + .clone() + .filter(|a| a.count > repair) + .map(|mut a| { + a.count -= repair; + a + }); + self.put(env, 1, addition); + } else if !self.anvil.only_renaming { + self.put(env, 1, None); + } + self.data[0] = 0; + self.put(env, 0, None); + self.combined = true; + } + /// `CraftingMenu.slotChangedCraftingGrid`. fn recompute(&mut self, env: &Env) { if self.grid_size == 0 { @@ -787,6 +1443,57 @@ impl Menu { self.merchant_take(env); return; } + if self.slots[s].role == Role::StoneResult { + // StonecutterMenu's result onTake: awardUsedRecipes, one input + // used up, the result again for the selected recipe. + if let Some(r) = self.stone.used { + self.crafted + .push(env.station_recipes.stonecutting[r].id.clone()); + } + if self.remove(env, 0, 1).is_some() { + self.stone_setup_result(env, self.data[0]); + } + self.sounds.push("minecraft:ui.stonecutter.take_result"); + return; + } + if self.slots[s].role == Role::GrindResult { + // GrindstoneMenu's result onTake: the experience (from the inputs + // before they go), then both inputs cleared. + self.ground = Some(crate::stations::grindstone_xp_base( + env.enchantments, + self.containers[MAIN][0].as_ref(), + self.containers[MAIN][1].as_ref(), + )); + self.put(env, 0, None); + self.put(env, 1, None); + return; + } + if self.slots[s].role == Role::CombineResult && self.kind == Kind::Anvil { + self.anvil_take(env); + return; + } + if self.slots[s].role == Role::CombineResult { + // SmithingMenu.onTake: awardUsedRecipes, then one of each input. + for i in 0..3 { + if let Some(mut stack) = self.containers[MAIN][i].clone() { + stack.count -= 1; + self.put(env, i, Some(stack)); + } + } + self.combined = true; + return; + } + if self.slots[s].role == Role::CartoResult { + // CartographyTableMenu's result onTake: one of each input, the + // take sound, then Slot.onTake's setChanged. The taken stack's + // onCraftedBy is the caller's (map_crafted). + self.remove(env, 0, 1); + self.remove(env, 1, 1); + self.sounds + .push("minecraft:ui.cartography_table.take_result"); + self.slot_changed(env, s); + return; + } if self.slots[s].role == Role::LoomResult { // LoomMenu's result onTake: one banner and one dye are used up. self.remove(env, 0, 1); @@ -897,8 +1604,11 @@ impl Menu { amount: u32, max_amount: u32, ) -> Option { - let result = self.try_remove(env, s, amount, max_amount)?; + let mut result = self.try_remove(env, s, amount, max_amount)?; self.on_take(env, s); + if self.slots[s].role == Role::CartoResult { + Self::map_crafted(env, &mut result); + } Some(result) } @@ -1231,6 +1941,177 @@ impl Menu { return None; } } + Kind::Stonecutter => { + after_take = true; + if index == 1 { + if !self.move_to(env, &mut stack, 2, 38, true) { + return None; + } + } else if index == 0 { + if !self.move_to(env, &mut stack, 2, 38, false) { + return None; + } + } else if env + .station_recipes + .stonecutting + .iter() + .any(|r| r.input.test(&stack)) + { + if !self.move_to(env, &mut stack, 0, 1, false) { + return None; + } + } else if (2..29).contains(&index) { + if !self.move_to(env, &mut stack, 29, 38, false) { + return None; + } + } else if (29..38).contains(&index) && !self.move_to(env, &mut stack, 2, 29, false) + { + return None; + } + } + Kind::Grindstone => { + after_take = true; + let full = self.containers[MAIN].iter().all(Option::is_some); + if index == 2 { + if !self.move_to(env, &mut stack, 3, 39, true) { + return None; + } + } else if index == 0 || index == 1 { + if !self.move_to(env, &mut stack, 3, 39, false) { + return None; + } + } else if full { + if (3..30).contains(&index) { + if !self.move_to(env, &mut stack, 30, 39, false) { + return None; + } + } else if (30..39).contains(&index) + && !self.move_to(env, &mut stack, 3, 30, false) + { + return None; + } + } else if !self.move_to(env, &mut stack, 0, 2, false) { + return None; + } + } + Kind::Cartography => { + after_take = true; + if index == 2 { + // onCraftedBy edits the result in its slot first. + Self::map_crafted(env, &mut stack); + self.containers[RESULT][0] = Some(stack.clone()); + if !self.move_to(env, &mut stack, 3, 39, true) { + return None; + } + } else if index == 0 || index == 1 { + if !self.move_to(env, &mut stack, 3, 39, false) { + return None; + } + } else if stack.data().is_some_and(|d| d.map_id.is_some()) { + if !self.move_to(env, &mut stack, 0, 1, false) { + return None; + } + } else if Self::is_carto_extra(&stack) { + if !self.move_to(env, &mut stack, 1, 2, false) { + return None; + } + } else if (3..30).contains(&index) { + if !self.move_to(env, &mut stack, 30, 39, false) { + return None; + } + } else if (30..39).contains(&index) && !self.move_to(env, &mut stack, 3, 30, false) + { + return None; + } + } + // LecternMenu.quickMoveStack moves nothing. + Kind::Lectern => return None, + Kind::Beacon => { + // BeaconMenu.quickMoveStack. + after_take = true; + if index == 0 { + if !self.move_to(env, &mut stack, 1, 37, true) { + return None; + } + } else if self.containers[MAIN][0].is_none() + && self.may_place(env, 0, &stack) + && stack.count == 1 + { + if !self.move_to(env, &mut stack, 0, 1, false) { + return None; + } + } else if (1..28).contains(&index) { + if !self.move_to(env, &mut stack, 28, 37, false) { + return None; + } + } else if (28..37).contains(&index) { + if !self.move_to(env, &mut stack, 1, 28, false) { + return None; + } + } else if !self.move_to(env, &mut stack, 1, 37, false) { + return None; + } + } + Kind::Enchanting => { + after_take = true; + if index < 2 { + if !self.move_to(env, &mut stack, 2, 38, true) { + return None; + } + } else if &*stack.item == "minecraft:lapis_lazuli" { + if !self.move_to(env, &mut stack, 1, 2, true) { + return None; + } + } else { + // One item into the empty item slot (setByPlayer). + if self.containers[MAIN][0].is_some() { + return None; + } + let single = ItemStack { + count: 1, + ..stack.clone() + }; + stack.count -= 1; + // The source slot keeps the rest while the item slot changes. + let slot = self.slots[index]; + self.containers[slot.container][slot.index] = + (stack.count > 0).then(|| stack.clone()); + self.set_by_player(env, 0, Some(single)); + } + } + Kind::Anvil | Kind::Smithing => { + // ItemCombinerMenu.quickMoveStack. + after_take = true; + let result = if self.kind == Kind::Anvil { 2 } else { 3 }; + let (start, use_row) = (result + 1, result + 28); + let end = result + 37; + let into_inputs = self.kind == Kind::Anvil + || (0..3).any(|i| { + self.containers[MAIN][i].is_none() + && env.station_recipes.smithing_accepts(i, &stack) + }); + if index == result { + if !self.move_to(env, &mut stack, start, end, true) { + return None; + } + } else if index < result { + if !self.move_to(env, &mut stack, start, end, false) { + return None; + } + } else if into_inputs && (start..end).contains(&index) { + if !self.move_to(env, &mut stack, 0, result, false) { + return None; + } + } else if (start..use_row).contains(&index) { + if !self.move_to(env, &mut stack, use_row, end, false) { + return None; + } + } else if (use_row..end).contains(&index) + && !self.move_to(env, &mut stack, start, use_row, false) + { + return None; + } + } Kind::Merchant => { after_take = true; if index == 2 { @@ -1369,7 +2250,10 @@ impl Menu { if after_take || matches!(self.kind, Kind::Inventory | Kind::Crafting) { self.on_take(env, index); } - if index == 0 && matches!(self.kind, Kind::Inventory | Kind::Crafting) { + // What the result slot's move left over is dropped. + if (index == 0 && matches!(self.kind, Kind::Inventory | Kind::Crafting)) + || (index == 1 && self.kind == Kind::Stonecutter) + { self.drop_stack(&stack); } Some(clicked) @@ -1537,6 +2421,10 @@ impl Menu { if let Some(stack) = self.slot(slot_index as usize) { let mut copy = stack.clone(); copy.count = Self::max_stack(env, stack); + // The cartography result's safeClone runs onCraftedBy. + if self.slots[slot_index as usize].role == Role::CartoResult { + Self::map_crafted(env, &mut copy); + } self.carried = Some(copy); } } else if input == Input::Throw && self.carried.is_none() && slot_index >= 0 { @@ -1604,9 +2492,14 @@ impl Menu { } else { clicked.count.div_ceil(2) }; - if let Some(taken) = self.try_remove(env, s, amount, u32::MAX) { - self.carried = Some(taken); + if let Some(mut taken) = self.try_remove(env, s, amount, u32::MAX) { + self.carried = Some(taken.clone()); self.on_take(env, s); + if self.slots[s].role == Role::CartoResult { + // onTake's onCraftedBy edits the carried stack. + Self::map_crafted(env, &mut taken); + self.carried = Some(taken); + } } } Some(mut carried) => { @@ -1631,11 +2524,15 @@ impl Menu { } else if clicked.same_item_same_components(&carried) { let room = Self::max_stack(env, &carried).saturating_sub(carried.count); self.carried = Some(carried.clone()); - if let Some(taken) = self.try_remove(env, s, clicked.count, room) { + if let Some(mut taken) = self.try_remove(env, s, clicked.count, room) { if let Some(c) = self.carried.as_mut() { c.count += taken.count; } self.on_take(env, s); + if self.slots[s].role == Role::CartoResult { + // onCraftedBy edits the taken stack, not the carried one. + Self::map_crafted(env, &mut taken); + } } } else { self.carried = Some(carried); @@ -1660,6 +2557,11 @@ impl Menu { self.containers[PLAYER][inv_slot] = Some(taken.clone()); self.set_by_player(env, target, None); self.on_take(env, target); + if self.slots[target].role == Role::CartoResult + && let Some(stack) = self.containers[PLAYER][inv_slot].as_mut() + { + Self::map_crafted(env, stack); + } } } (Some(mut source), None) => { @@ -1698,12 +2600,14 @@ impl Menu { } /// The PICKUP_ALL branch (double click). - /// `canTakeItemForPickAll`: never the result slots (the loom's is a - /// plain slot), MerchantMenu's or an item tab's display slots. + /// `canTakeItemForPickAll`: never the result slots of the menus that + /// override it (crafting, smithing, stonecutter, cartography), MerchantMenu's + /// or an item tab's display slots. fn can_take_for_pick_all(&self, t: usize) -> bool { self.kind != Kind::Merchant && self.slots[t].role != Role::CreativeDisplay - && (self.slots[t].container != RESULT || self.kind == Kind::Loom) + && (self.slots[t].container != RESULT + || matches!(self.kind, Kind::Loom | Kind::Grindstone | Kind::Anvil)) } /// `AbstractContainerScreen.mouseReleased` on a Shift double click: @@ -2023,12 +2927,19 @@ pub(crate) mod tests { let recipes = Recipes::load(&root, &items).unwrap(); let brewing = Brewing::load(&root, &items); let banners = Banners::load(&root); + let station_recipes = crate::stations::StationRecipes::load(&root, &items); + let enchantments = crate::enchant::Enchantments::default(); + let names = crate::creative::Names::default(); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, + station_recipes: &station_recipes, + enchantments: &enchantments, + names: &names, trade: None, + maps: None, }; let mut menu = Menu::new(kind); menu.creative = true; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 28bcadeed..db2ebeb60 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -690,6 +690,8 @@ pub struct Extra { pub blocking: bool, pub fall_flying: bool, pub fall_fly_ticks: i32, + /// `LivingEntity.isAutoSpinAttack` (Riptide). + pub auto_spin_attack: bool, pub main_hand_left: bool, pub elytra: ElytraAnimation, pub swim: SwimAnimation, @@ -805,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, @@ -844,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)] @@ -1308,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 @@ -1404,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, @@ -1418,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, @@ -1436,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(), } } } @@ -1513,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, @@ -2137,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 99548ec3f..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 => { @@ -771,6 +774,11 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4 .sqrt() .min(1.0); base *= glam::Mat4::from_rotation_z(f * flip_degrees(m).to_radians()); + } else if m.extra.auto_spin_attack { + // Riptide: lying along the look direction, spinning 75 degrees a tick. + let pitch = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha; + base *= glam::Mat4::from_rotation_x((-90.0 - pitch).to_radians()) + * glam::Mat4::from_rotation_y(((m.age as f32 + alpha) * -75.0).to_radians()); } else if matches!(m.custom_name.as_deref(), Some("Dinnerbone" | "Grumm")) { // isEntityUpsideDown base *= glam::Mat4::from_translation(glam::Vec3::new(0.0, m.height() + 0.1, 0.0)) @@ -781,7 +789,9 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4 let ticks = m.extra.fall_fly_ticks as f32 + alpha; let scale = (ticks * ticks / 100.0).min(1.0); let pitch = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha; - base *= glam::Mat4::from_rotation_x((scale * (-90.0 - pitch)).to_radians()); + if !m.extra.auto_spin_attack { + base *= glam::Mat4::from_rotation_x((scale * (-90.0 - pitch)).to_radians()); + } let yaw = m.previous_head_yaw + wrap(m.head_yaw - m.previous_head_yaw) * alpha; let (look_x, look_z) = (-(yaw.to_radians()).msin(), (yaw.to_radians()).mcos()); let v = m.velocity; diff --git a/crates/horizon-client/src/mobs/spawn_selection.rs b/crates/horizon-client/src/mobs/spawn_selection.rs index c87c3d97a..614a2b2b5 100644 --- a/crates/horizon-client/src/mobs/spawn_selection.rs +++ b/crates/horizon-client/src/mobs/spawn_selection.rs @@ -691,33 +691,37 @@ pub struct StructureAt { } /// `NetherFortressStructure.FORTRESS_ENEMIES`. -pub fn fortress_enemies() -> Vec { - let e = |entity: &str, weight, min, max, constant| SpawnEntry { - entity: entity.to_owned(), - weight, - min, - max, - constant, - }; - vec![ - e("minecraft:blaze", 10, 2, 3, false), - e("minecraft:zombified_piglin", 5, 4, 4, true), - e("minecraft:wither_skeleton", 8, 5, 5, true), - e("minecraft:skeleton", 2, 5, 5, true), - e("minecraft:magma_cube", 3, 4, 4, true), - ] +pub fn fortress_enemies() -> &'static [SpawnEntry] { + static ENEMIES: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + let e = |entity: &str, weight, min, max, constant| SpawnEntry { + entity: entity.to_owned(), + weight, + min, + max, + constant, + }; + vec![ + e("minecraft:blaze", 10, 2, 3, false), + e("minecraft:zombified_piglin", 5, 4, 4, true), + e("minecraft:wither_skeleton", 8, 5, 5, true), + e("minecraft:skeleton", 2, 5, 5, true), + e("minecraft:magma_cube", 3, 4, 4, true), + ] + }); + &ENEMIES } /// `NaturalSpawner.mobsAt`: the fortress bounds on nether bricks, then /// `ChunkGenerator.getMobsAt` (the first referenced structure whose override -/// for the category holds the position), else the biome's list. +/// for the category holds the position), else the biome's list. Borrowed from +/// the level: a spawn attempt looks it up up to twice. pub fn mobs_at( l: &L, category: Category, x: i32, y: i32, z: i32, -) -> Vec { +) -> &[SpawnEntry] { // Only a fortress or a structure overriding this category's spawns can // change the list, so only theirs are looked up (the references reaching // most chunks are mineshafts, which override nothing). @@ -738,13 +742,12 @@ pub fn mobs_at( if let Some(o) = overrides.get(&s.id, category.name()) && (if o.piece { s.in_piece } else { s.in_bounds }) { - return o.spawns.clone(); + return &o.spawns; } } l.biome_spawns(x, y, z) .and_then(|b| b.get(category.name())) - .cloned() - .unwrap_or_default() + .map_or(&[], Vec::as_slice) } /// `WeightedList.getRandom`. @@ -1103,7 +1106,7 @@ pub fn spawn_category_for_position( { None } else { - weighted_pick(&mobs_at(l, category, x, y, z), random) + weighted_pick(mobs_at(l, category, x, y, z), random) }; let Some(entry) = list else { break; 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 7bdaea785..1920026b9 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -247,6 +247,14 @@ pub struct PlayerMotion { pub glide_ending: bool, /// Glider durability to take this tick (updateFallFlying). pub glider_wear: u32, + /// `LivingEntity.autoSpinAttackTicks` and `autoSpinAttackDmg`: Riptide's + /// spin. The damage stays until the game has dealt the hit. + pub auto_spin_attack_ticks: i32, + pub auto_spin_attack_dmg: f32, + /// The living entities the game put near a spinning player (id, box). + pub spin_targets: Vec<(u32, Aabb)>, + /// The entity the spin touched this tick (`doAutoAttackOnTouch`). + pub spin_hit: Option, pub sprinting: bool, pub sprint_input: crate::sprint::SprintState, pub shift_key_down: bool, @@ -262,6 +270,10 @@ pub struct PlayerMotion { pub steps: MovementDistances, pub needs_sync: bool, pub sync_position: bool, + /// Moved by an ender pearl (`ServerPlayer.teleport`): a server sends the + /// position packet even when the player lands where they stood. The + /// server takes it at the end of a guest's turn. + pub teleported: bool, pub events: Vec, pub attributes: LiveAttributes i32>>, pub impulse: ImpulseContext, @@ -409,6 +421,10 @@ impl PlayerMotion { fall_fly_ticks: 0, glide_ending: false, glider_wear: 0, + auto_spin_attack_ticks: 0, + auto_spin_attack_dmg: 0.0, + spin_targets: Vec::new(), + spin_hit: None, sprinting: false, sprint_input: crate::sprint::SprintState::default(), shift_key_down: false, @@ -428,6 +444,7 @@ impl PlayerMotion { }, needs_sync: false, sync_position: false, + teleported: false, events: Vec::new(), attributes, fluids: PlayerFluids::default(), @@ -699,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); } @@ -919,6 +937,7 @@ impl MotionWorld<'_, '_, '_> { input.z = 0.0; } self.jump_phase()?; + let before_travel = self.player.bounds(); // Player.travel: swim steering, then LivingEntity.travel (fluids // first, then gliding, then air), keeping 0.6 of the vertical speed // while flying. @@ -973,8 +992,26 @@ impl MotionWorld<'_, '_, '_> { { self.freeze_damage()?; } + if self.player.auto_spin_attack_ticks > 0 { + self.player.auto_spin_attack_ticks -= 1; + self.check_auto_spin_attack(before_travel); + } Ok(()) } + /// `LivingEntity.checkAutoSpinAttack`: the first living entity in the + /// box swept this tick takes the hit and ends the spin, bouncing the + /// player back at a fifth of its speed; a wall ends it too. + fn check_auto_spin_attack(&mut self, before: Aabb) { + let swept = before.union_bounds(self.player.bounds()); + let p = &mut self.player; + if let Some(&(id, _)) = p.spin_targets.iter().find(|(_, b)| b.intersects(swept)) { + p.spin_hit = Some(id); + p.auto_spin_attack_ticks = 0; + p.velocity = p.velocity.scale(-0.2); + } else if p.collision.horizontal { + p.auto_spin_attack_ticks = 0; + } + } /// `hurtServer(damageSources().freeze(), 1)` for a fully frozen player. fn freeze_damage(&mut self) -> Result<()> { let id = self @@ -2659,6 +2696,49 @@ mod tests { } } #[test] + fn a_riptide_spin_lies_flat_and_ends_on_the_first_entity_it_touches() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + let mut scene = World::test_scene(&assets, &render, 2).unwrap(); + let ahead = Aabb::new(Vec3::new(20.2, 9.0, 21.5), Vec3::new(20.8, 11.0, 22.1)); + for target in [None, Some(ahead)] { + let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 10.0, 20.5)).unwrap(); + player.auto_spin_attack_ticks = 20; + player.auto_spin_attack_dmg = 8.0; + player.velocity = Vec3::new(0.0, 0.0, 1.0); + player.spin_targets = target.map(|b| (7, b)).into_iter().collect(); + let mut w = MotionWorld { + entities: &[], + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + }; + w.simulation_tick([0.0, 0.0], false).unwrap(); + if target.is_some() { + // Touched: the hit, no more spin, bounced back at a fifth. + assert_eq!(w.player.spin_hit, Some(7)); + assert_eq!(w.player.auto_spin_attack_ticks, 0); + assert!(w.player.velocity.z < 0.0, "{:?}", w.player.velocity); + assert_eq!(w.player.pose, crate::pose::Pose::Standing); + } else { + assert_eq!(w.player.spin_hit, None); + assert_eq!(w.player.auto_spin_attack_ticks, 19); + assert_eq!(w.player.pose, crate::pose::Pose::SpinAttack); + assert_eq!(w.player.dimensions.height, 0.6); + } + } + } + #[test] fn a_landing_glide_lasts_a_tick_so_a_jump_keeps_its_speed() { let root = Path::new(env!("CARGO_MANIFEST_DIR")) .join("../../.local/horizon-client") diff --git a/crates/horizon-client/src/pose.rs b/crates/horizon-client/src/pose.rs index 9c8124b0e..e34b1f1fc 100644 --- a/crates/horizon-client/src/pose.rs +++ b/crates/horizon-client/src/pose.rs @@ -14,6 +14,7 @@ pub enum Pose { Crouching, Swimming, FallFlying, + SpinAttack, } impl Pose { pub fn name(self) -> &'static str { @@ -22,13 +23,14 @@ impl Pose { Self::Crouching => "CROUCHING", Self::Swimming => "SWIMMING", Self::FallFlying => "FALL_FLYING", + Self::SpinAttack => "SPIN_ATTACK", } } pub fn dimensions(self, scale: f32) -> Dimensions { let (height, eye_height) = match self { Self::Standing => (1.8, 1.62), Self::Crouching => (1.5, 1.27), - Self::Swimming | Self::FallFlying => (0.6, 0.4), + Self::Swimming | Self::FallFlying | Self::SpinAttack => (0.6, 0.4), }; Dimensions { width: 0.6 * scale, @@ -98,11 +100,13 @@ impl MotionWorld<'_, '_, '_> { if !self.can_fit_pose(Pose::Swimming)? { return Ok(()); } - // Player.getDesiredPose: swimming before gliding. + // Player.getDesiredPose: swimming, gliding, Riptide's spin. let desired = if self.player.swimming { Pose::Swimming } else if self.player.fall_flying { Pose::FallFlying + } else if self.player.auto_spin_attack_ticks > 0 { + Pose::SpinAttack } else if self.player.shift_key_down && !self.player.flying { Pose::Crouching } else { diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 0428670f4..191509780 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>>>>; @@ -3896,6 +3961,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/spans.rs b/crates/horizon-client/src/spans.rs index 5c37f2bfc..ce69be8ce 100644 --- a/crates/horizon-client/src/spans.rs +++ b/crates/horizon-client/src/spans.rs @@ -1,8 +1,10 @@ //! Named timings within a frame, for finding what makes a frame slow: //! `HORIZON_SPIKES=MS` prints the spans of every frame whose CPU time //! exceeds MS milliseconds, and of every server tick (dedicated or -//! integrated) longer than MS. Costs one clock read per span when enabled -//! and a relaxed load otherwise. +//! integrated) longer than MS. Each span keeps its wall time and the +//! thread's CPU time inside it, so a span that waited (for a lock, the GPU +//! or a core on a busy machine) shows apart from one that worked. Costs two +//! clock reads per span when enabled and a relaxed load otherwise. use std::{ cell::RefCell, sync::atomic::{AtomicBool, Ordering}, @@ -11,7 +13,15 @@ use std::{ static ENABLED: AtomicBool = AtomicBool::new(false); thread_local! { - static SPANS: RefCell> = const { RefCell::new(Vec::new()) }; + static SPANS: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// A named timing: wall milliseconds and the thread's CPU milliseconds in it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Span { + pub name: &'static str, + pub ms: f32, + pub cpu_ms: f32, } pub fn enable(on: bool) { @@ -23,10 +33,13 @@ pub fn time(name: &'static str, f: impl FnOnce() -> T) -> T { if !ENABLED.load(Ordering::Relaxed) { return f(); } - let started = Instant::now(); + let (started, cpu) = (Instant::now(), thread_cpu()); let out = f(); let ms = started.elapsed().as_secs_f32() * 1000.0; - SPANS.with(|s| s.borrow_mut().push((name, ms))); + let cpu_ms = thread_cpu() + .zip(cpu) + .map_or(ms, |(end, start)| (end - start).as_secs_f32() * 1000.0); + SPANS.with(|s| s.borrow_mut().push(Span { name, ms, cpu_ms })); out } /// The CPU time this thread has used, where the platform tells it: a tick @@ -42,21 +55,84 @@ pub fn thread_cpu() -> Option { None } /// The frame's spans, summed by name, slowest first; clears them. -pub fn take() -> Vec<(&'static str, f32)> { +pub fn take() -> Vec { let spans = SPANS.with(|s| std::mem::take(&mut *s.borrow_mut())); - let mut sums: Vec<(&'static str, f32)> = Vec::new(); - for (name, ms) in spans { - match sums.iter_mut().find(|(n, _)| *n == name) { - Some(entry) => entry.1 += ms, - None => sums.push((name, ms)), + let mut sums: Vec = Vec::new(); + for span in spans { + match sums.iter_mut().find(|s| s.name == span.name) { + Some(sum) => { + sum.ms += span.ms; + sum.cpu_ms += span.cpu_ms; + } + None => sums.push(span), } } - sums.sort_by(|a, b| b.1.total_cmp(&a.1)); + sums.sort_by(|a, b| b.ms.total_cmp(&a.ms)); sums } +/// `name wall` for spans of at least 0.5 ms, with `/cpu` when the thread +/// worked for less than nine tenths of it: the slow-frame and slow-tick lines. +pub fn describe(spans: &[Span]) -> String { + let list: Vec = spans + .iter() + .filter(|s| s.ms >= 0.5) + .map(|s| { + if s.cpu_ms < s.ms * 0.9 { + format!("{} {:.1}/{:.1}", s.name, s.ms, s.cpu_ms) + } else { + format!("{} {:.1}", s.name, s.ms) + } + }) + .collect(); + list.join(", ") +} #[cfg(test)] mod tests { + use super::Span; + + /// Spans of one name add up; a span the thread spent mostly waiting + /// shows its CPU time after the wall time, short ones are left out. + #[test] + fn spans_sum_by_name_and_show_waits() { + super::SPANS.with(|s| { + s.borrow_mut().extend([ + Span { + name: "tick", + ms: 2.0, + cpu_ms: 2.0, + }, + Span { + name: "submit", + ms: 30.0, + cpu_ms: 0.2, + }, + Span { + name: "tick", + ms: 3.0, + cpu_ms: 2.9, + }, + Span { + name: "hud", + ms: 0.3, + cpu_ms: 0.3, + }, + ]); + }); + let spans = super::take(); + assert_eq!( + spans[0], + Span { + name: "submit", + ms: 30.0, + cpu_ms: 0.2 + } + ); + assert_eq!((spans[1].name, spans[1].ms), ("tick", 5.0)); + assert_eq!(super::describe(&spans), "submit 30.0/0.2, tick 5.0"); + assert!(super::take().is_empty()); + } + /// The thread's CPU clock moves with work done on it, not with time /// spent asleep. #[cfg(unix)] diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index 20750d6fe..715c2663e 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -198,8 +198,10 @@ pub fn anvil_result( let mut repair_item_count_cost = 0; let mut naming_cost = 0; if let Some(addition) = addition { - // addition.has(STORED_ENCHANTMENTS): only enchanted books carry that component. - let using_book = &*addition.item == "minecraft:enchanted_book"; + // addition.has(STORED_ENCHANTMENTS): an enchanted book (its default + // component), or any item given stored enchantments. + let using_book = &*addition.item == "minecraft:enchanted_book" + || !addition.stored_enchantments().is_empty(); if is_damageable(items, &result) && is_valid_repair_item(e, items, input, addition) { let max = max_damage(items, &result); let mut repair = (result.damage as i32).min(max / 4); @@ -401,13 +403,13 @@ pub fn grindstone_result( (None, None) => None, } } -/// Experience from the grindstone result slot's `getExperienceAmount`. -pub fn grindstone_experience( +/// The grindstone result slot's `getExperienceAmount` before its roll: the +/// minimum costs of the inputs' non-curse enchantments. +pub fn grindstone_xp_base( e: &Enchantments, - random: &mut LegacyRandom, input: Option<&ItemStack>, additional: Option<&ItemStack>, -) -> u32 { +) -> i32 { let from = |s: Option<&ItemStack>| -> i32 { s.map_or(0, |s| { s.crafting_enchantments() @@ -417,7 +419,10 @@ pub fn grindstone_experience( .sum() }) }; - let amount = from(input) + from(additional); + from(input) + from(additional) +} +/// `getExperienceAmount`'s roll of the sum: `half + nextInt(half)`. +pub fn grindstone_xp_roll(amount: i32, random: &mut LegacyRandom) -> u32 { if amount > 0 { let half = (f64::from(amount) / 2.0).ceil() as i32; (half + random.next_int_bound(half).unwrap_or(0)) as u32 @@ -425,6 +430,15 @@ pub fn grindstone_experience( 0 } } +/// Experience from the grindstone result slot's `getExperienceAmount`. +pub fn grindstone_experience( + e: &Enchantments, + random: &mut LegacyRandom, + input: Option<&ItemStack>, + additional: Option<&ItemStack>, +) -> u32 { + grindstone_xp_roll(grindstone_xp_base(e, input, additional), random) +} // ---------------------------------------------------------------- smithing & stonecutting @@ -450,6 +464,7 @@ pub struct Stonecutting { pub input: Ingredient, pub result: ItemStack, } +#[derive(Default)] pub struct StationRecipes { pub smithing: Vec, /// Sorted by recipe id, the registry order vanilla lists them in. diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 858d05d30..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 { @@ -436,7 +439,7 @@ impl Streaming { thread::Builder::new() .name(format!("horizon-worker-{i}")) .spawn(move || { - // A dedicated server's tick comes first (horizon_threads). + // Ticks and frames come first (horizon_threads). horizon_threads::behind_server(); let mut worker = generator.worker(); // The face visibility table and its occlusion cache stay with @@ -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/telemetry.rs b/crates/horizon-client/src/telemetry.rs index 2010df04a..ec67fe7f7 100644 --- a/crates/horizon-client/src/telemetry.rs +++ b/crates/horizon-client/src/telemetry.rs @@ -1,6 +1,7 @@ //! The game's part in opt-in data collection (`horizon_telemetry`, docs/telemetry.md). When the //! player allows it, the game keeps a scrubbed crash report, or a play session's performance -//! summary, in the outbox. It never sends anything itself: the launcher does, at its next start. +//! summary, in the outbox. It never sends those itself: the launcher does, at its next start (the +//! game's only sending is the anonymous "I'm playing" ping, `heartbeat.rs`). //! Without the player's yes for that kind nothing is kept, and crash-reports/ stays local. use std::path::Path; use std::sync::atomic::{AtomicU32, Ordering}; 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-port-pack/src/carry.rs b/crates/horizon-port-pack/src/carry.rs index dd6b148f3..e6056e519 100644 --- a/crates/horizon-port-pack/src/carry.rs +++ b/crates/horizon-port-pack/src/carry.rs @@ -707,7 +707,8 @@ pub fn carry( let mut biome_conventions = BTreeSet::new(); let set_tags = crate::worldgen::structure_set_tags(&mut zip); let piece_counts = crate::worldgen::piece_counts(&mut zip); - let processor_data = crate::processors::ProcessorData::read(&mut zip); + let mut processor_data = crate::processors::ProcessorData::read(&mut zip); + processor_data.mark_loaded(loaded); report.namespaces = extra_namespaces(&mut zip, id, pack.mods); let owned: Vec<&str> = std::iter::once(id.as_str()) .chain(report.namespaces.iter().map(String::as_str)) diff --git a/crates/horizon-port-pack/src/processors.rs b/crates/horizon-port-pack/src/processors.rs index 7f26282bf..e6c0fe7d8 100644 --- a/crates/horizon-port-pack/src/processors.rs +++ b/crates/horizon-port-pack/src/processors.rs @@ -16,6 +16,12 @@ //! `condition` become the game's `horizon:apply_random` and //! `horizon:condition`, with the lists inside them carried the same way, //! and its `set_block` (simple or weighted states) `horizon:set_block`. +//! - Repurposed Structures' mineshaft sky view becomes the game's +//! `horizon:mineshaft_sky_view`. +//! - Choice Theorem's Overhauled Village's `modular_compat` runs another +//! list only when the mod it names is loaded: that list is written in its +//! place when the mod is ported along, and it is taken out (a no-op, as in +//! the mod) when it is not. //! //! What is not here is taken out of its list later and counted //! (`worldgen::upgrade`). The entity NBT is written in 26.3's shape (an @@ -37,9 +43,37 @@ pub struct ProcessorData { pub replace_vanilla: BTreeSet<(String, String)>, /// The mod's processor lists by id, for Lithostitched's references. pub lists: BTreeMap, + /// The mods named by its `ctov:modular_compat` processors that are + /// ported along ([`Self::mark_loaded`]). + pub compat_loaded: BTreeSet, } +/// Choice Theorem's Overhauled Village's processor that runs the list +/// `reference` when mod `modid` is loaded (ModularCompatProcessor). +const MODULAR_COMPAT: &str = "ctov:modular_compat"; + impl ProcessorData { + /// Notes which mods its compat processors name are `loaded`. + pub fn mark_loaded(&mut self, loaded: &dyn Fn(&str) -> bool) { + fn walk(v: &Value, out: &mut BTreeSet) { + match v { + Value::Object(o) => { + if o.get("processor_type").and_then(Value::as_str) == Some(MODULAR_COMPAT) { + if let Some(id) = o.get("modid").and_then(Value::as_str) { + out.insert(id.to_owned()); + } + } + o.values().for_each(|v| walk(v, out)); + } + Value::Array(a) => a.iter().for_each(|v| walk(v, out)), + _ => {} + } + } + let mut named = BTreeSet::new(); + self.lists.values().for_each(|l| walk(l, &mut named)); + self.compat_loaded = named.into_iter().filter(|m| loaded(m)).collect(); + } + pub fn read(zip: &mut zip::ZipArchive) -> Self { let mut out = Self::default(); for i in 0..zip.len() { @@ -408,6 +442,17 @@ fn references( let mut out = Vec::with_capacity(list.len()); let mut changed = false; for p in list { + if p["processor_type"] == MODULAR_COMPAT && depth < 8 { + *carried.entry(MODULAR_COMPAT.into()).or_default() += 1; + changed = true; + let loaded = p["modid"] + .as_str() + .is_some_and(|m| data.compat_loaded.contains(m)); + if let Some(inner) = loaded.then(|| referenced(&p["reference"], data)).flatten() { + out.extend(references(inner, data, carried, depth + 1).0); + } + continue; + } let named = (p["processor_type"] == "lithostitched:reference" && depth < 8) .then(|| referenced(&p["processor_lists"], data)) .flatten(); @@ -491,6 +536,10 @@ fn as_data(kind: &str, p: &Value, data: &ProcessorData) -> Option> { "repurposed_structures:waterlogging_when_replacing_water_processor" => { vec![json!({"processor_type": "horizon:waterlog_in_world_water"})] } + // Its mineshafts: nothing above the ocean floor but grounded rails. + "repurposed_structures:mineshaft_sky_view_processor" => { + vec![json!({"processor_type": "horizon:mineshaft_sky_view"})] + } "moogs_structures:vanilla_loot_swap_processor" => { let key = ( p["modid"].as_str()?.to_owned(), @@ -1344,7 +1393,8 @@ mod tests { #[test] fn repurposed_waterlogging_follows_the_world() { let mut list = json!({"processors": [{"processor_type": - "repurposed_structures:waterlogging_when_replacing_water_processor"}]}); + "repurposed_structures:waterlogging_when_replacing_water_processor"}, + {"processor_type": "repurposed_structures:mineshaft_sky_view_processor"}]}); let mut carried = BTreeMap::new(); assert!(carry( "processor_list", @@ -1354,7 +1404,8 @@ mod tests { )); assert_eq!( list["processors"], - json!([{"processor_type": "horizon:waterlog_in_world_water"}]) + json!([{"processor_type": "horizon:waterlog_in_world_water"}, + {"processor_type": "horizon:mineshaft_sky_view"}]) ); } @@ -1391,6 +1442,27 @@ mod tests { assert_eq!(p[1]["processor_type"], "lithostitched:block_swap"); } + #[test] + fn modular_compat_runs_its_list_only_with_its_mod() { + let mut data = ProcessorData::default(); + let swap = json!({"processor_type": "minecraft:rule", "rules": []}); + data.lists + .insert("v:house_ns".into(), json!({"processors": [swap.clone()]})); + let compat = |m: &str| json!({"processor_type": "ctov:modular_compat", "modid": m, "reference": "v:house_ns"}); + let gravity = json!({"processor_type": "minecraft:gravity"}); + data.lists.insert( + "v:house".into(), + json!({"processors": [compat("ns"), compat("absent"), gravity.clone()]}), + ); + data.mark_loaded(&|m| m == "ns"); + assert_eq!(data.compat_loaded, BTreeSet::from(["ns".to_owned()])); + let mut v = json!({"processors": [compat("ns"), compat("absent"), gravity.clone()]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut v, &data, &mut carried)); + assert_eq!(v, json!({"processors": [swap, gravity]})); + assert_eq!(carried["ctov:modular_compat"], 2); + } + #[test] fn lithostitched_references_are_written_in() { let mut data = data(); diff --git a/crates/horizon-port-pack/src/worldgen.rs b/crates/horizon-port-pack/src/worldgen.rs index 918dbf05e..91b659217 100644 --- a/crates/horizon-port-pack/src/worldgen.rs +++ b/crates/horizon-port-pack/src/worldgen.rs @@ -86,6 +86,31 @@ const YUNG_REPLACES: [(&str, &str); 7] = [ ("betterfortresses:fortress", "minecraft:fortress"), ("bettermineshafts:mineshaft_", "minecraft:mineshaft"), ]; +/// Mo' Structures' placement (`mostructures:type`) takes its spacing and +/// separation from the mod's config, not its files: the defaults it writes +/// (MoStructuresConfig), by config key, as (spacing, separation). +const MO_SPREADS: [(&str, i64, i64); 17] = [ + ("abandoned_church", 33, 20), + ("air_balloon", 22, 12), + ("barn_house", 32, 16), + ("big_pyramid", 32, 25), + ("ice_tower", 28, 20), + ("jungle_pyramid", 25, 22), + ("killer_bunny_castle", 32, 22), + ("lighthouse", 24, 14), + ("moai", 17, 15), + ("pillager_factory", 34, 16), + ("pillager_mines", 40, 27), + ("pirate_ship", 32, 16), + ("tavern", 26, 16), + ("the_castle_in_the_sky", 32, 22), + ("villager_market", 32, 16), + ("villager_tower", 26, 16), + ("sphinx", 24, 16), +]; +/// Mo' Structures keeps a start out of this many chunks around a start of +/// each set in its `structure_set_to_avoid`. +const MO_AVOID_CHUNKS: i64 = 3; /// Moog's Structure Lib spreads its structures 1.65 times as far apart as /// its files say (AdvancedRandomSpread's constructor). const MOOGS_SPACING: f64 = 1.65; @@ -510,12 +535,44 @@ fn upgrade_types( v["type"] = "minecraft:jigsaw".into(); true } + // Mo' Structures' ModStructure: vanilla's jigsaw that starts only + // where the terrain under the 5×5 chunks around varies by no + // more than `heightRange` blocks (-1: anywhere). + Some("mostructures:generic") => { + let range = v + .as_object_mut() + .and_then(|o| o.remove("heightRange")) + .and_then(|r| r.as_i64()) + .unwrap_or(-1); + if range >= 0 { + v["horizon:start_checks"] = + serde_json::json!({"terrain_radius": 2, "terrain_range": range}); + } + v["type"] = "minecraft:jigsaw".into(); + true + } // Formations' SimpleStructure: its pool and placement, laid out // by the game (`horizon_world::worldgen::structure::formations`). Some("formations:simple") => { v["type"] = "horizon:formations".into(); true } + // Its PiecedStructure: the same start, then vanilla's jigsaw + // (`horizon:pieced`). + Some("formations:pieced") => { + let Some(o) = v.as_object_mut() else { + return false; + }; + let pool = o.remove("start_pool").unwrap_or_default(); + let mut pieced = serde_json::Map::new(); + for k in ["max_depth", "max_distance_from_center"] { + pieced.insert(k.into(), o.remove(k).unwrap_or_default()); + } + o.insert("template".into(), pool); + o.insert("horizon:pieced".into(), pieced.into()); + o.insert("type".into(), "horizon:formations".into()); + true + } Some(t) if !t.starts_with("minecraft:") => { unsupported(t); false @@ -533,6 +590,7 @@ fn upgrade_types( p["type"] = "minecraft:random_spread".into(); true } + Some("mostructures:type") => mo_placement(&mut v["placement"], lost), Some(t) if YUNG_SPREADS.contains(&t) => { let t = t.to_owned(); yung_placement(&t, &mut v["placement"], set_tags, lost); @@ -1022,6 +1080,41 @@ fn placement_rules( } } +/// Mo' Structures' placement as vanilla's random spread: the spacing and +/// separation of its config key, and its sets to avoid as +/// `horizon:exclusion_zone` tested by their spread alone +/// (ModStructurePlacement.exclusionZoneCheck). A key the config does not +/// have fails the mod's codec, and the set stays as it is. +fn mo_placement(p: &mut Value, lost: &mut BTreeMap) -> bool { + let key = p["config_key"].as_str().unwrap_or_default(); + let Some(&(_, spacing, separation)) = MO_SPREADS.iter().find(|(k, ..)| *k == key) else { + *lost.entry("config_key".into()).or_default() += 1; + return false; + }; + let Some(o) = p.as_object_mut() else { + return false; + }; + o.remove("config_key"); + o.insert("spacing".into(), spacing.into()); + o.insert("separation".into(), separation.into()); + let avoid = o.remove("structure_set_to_avoid"); + let sets: Vec = avoid + .iter() + .flat_map(|a| a.as_array().into_iter().flatten()) + .filter(|s| s.is_string()) + .cloned() + .collect(); + if !sets.is_empty() { + o.insert( + "horizon:exclusion_zone".into(), + serde_json::json!({"other_sets": sets, "chunk_count": MO_AVOID_CHUNKS, + "their_zones": false}), + ); + } + o.insert("type".into(), "minecraft:random_spread".into()); + true +} + /// One of YUNG's placements as vanilla's random spread with `horizon:` keys: /// the enhanced exclusion zone as `horizon:exclusion_zone`; the temples' /// ocean and river search (findBiomeHorizontal around the chunk's middle @@ -1222,6 +1315,21 @@ mod tests { const NO_TAGS: BTreeMap> = BTreeMap::new(); + #[test] + fn formations_pieced_structure_keeps_its_jigsaw() { + let mut v = json!({"type": "formations:pieced", "start_pool": "fo:fountain/fountains", + "max_depth": 2, "max_distance_from_center": 116, "placement": "surface"}); + let mut report = Upgrade::default(); + assert!(upgrade("structure", &mut v, &mut report, &BTreeMap::new())); + assert_eq!( + v, + json!({"type": "horizon:formations", "template": "fo:fountain/fountains", + "placement": "surface", + "horizon:pieced": {"max_depth": 2, "max_distance_from_center": 116}}) + ); + assert!(report.unsupported.is_empty()); + } + #[test] fn formations_become_the_games() { let mut report = Upgrade::default(); @@ -1247,12 +1355,7 @@ mod tests { (json!(6), json!(1)) ); assert!(e(0).get("ground_level").is_none()); - // The pieced structure stays out. - let mut pieced = json!({"type": "formations:pieced", "start_pool": "f:p", "max_depth": 2, - "max_distance_from_center": 40, "placement": "surface", "biomes": "#f:x"}); - assert!(!upgrade("structure", &mut pieced, &mut report, &NO_TAGS)); - assert_eq!(report.unsupported.get("formations:pieced"), Some(&1)); - assert_eq!(report.unsupported.len(), 1); + assert!(report.unsupported.is_empty()); } #[test] @@ -1385,6 +1488,71 @@ mod tests { ); } + #[test] + fn mo_structures_become_vanillas_jigsaw_and_spread() { + let mut report = Upgrade::default(); + let mut s = json!({"type": "mostructures:generic", "start_pool": "mostructures:a/base", + "size": 7, "heightRange": 25, "use_expansion_hack": true, + "start_height": {"absolute": 0}, "max_distance_from_center": 80}); + assert!(upgrade("structure", &mut s, &mut report, &BTreeMap::new())); + assert_eq!(s["type"], "minecraft:jigsaw"); + assert!(s.get("heightRange").is_none()); + assert_eq!( + s["horizon:start_checks"], + json!({"terrain_radius": 2, "terrain_range": 25}) + ); + let mut anywhere = json!({"type": "mostructures:generic", "heightRange": -1}); + assert!(upgrade( + "structure", + &mut anywhere, + &mut report, + &BTreeMap::new() + )); + assert!(anywhere.get("horizon:start_checks").is_none()); + + // The config's spacing and separation, not the file's. + let mut set = json!({"placement": {"type": "mostructures:type", "config_key": "moai", + "salt": 12994829, "spacing": 17, "separation": 15, + "structure_set_to_avoid": ["minecraft:villages", "mostructures:lighthouse"]}}); + assert!(upgrade( + "structure_set", + &mut set, + &mut report, + &BTreeMap::new() + )); + assert_eq!( + set["placement"], + json!({"type": "minecraft:random_spread", "salt": 12994829, "spacing": 17, + "separation": 15, "horizon:exclusion_zone": {"chunk_count": 3, + "other_sets": ["minecraft:villages", "mostructures:lighthouse"], + "their_zones": false}}) + ); + let mut set = json!({"placement": {"type": "mostructures:type", + "config_key": "jungle_pyramid", "salt": 1, "spacing": 16, "separation": 14}}); + assert!(upgrade( + "structure_set", + &mut set, + &mut report, + &BTreeMap::new() + )); + assert_eq!( + ( + &set["placement"]["spacing"], + &set["placement"]["separation"] + ), + (&json!(25), &json!(22)) + ); + assert!(set["placement"].get("horizon:exclusion_zone").is_none()); + let mut unknown = json!({"placement": {"type": "mostructures:type", "config_key": "x"}}); + assert!(!upgrade( + "structure_set", + &mut unknown, + &mut report, + &BTreeMap::new() + )); + assert_eq!(report.rules_lost["config_key"], 1); + } + #[test] fn super_exclusion_zones_name_their_sets() { let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); 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 90ea5b6cd..6f59228b5 100644 --- a/crates/horizon-protocol/src/item.rs +++ b/crates/horizon-protocol/src/item.rs @@ -25,9 +25,27 @@ 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; + pub const WRITABLE_BOOK_CONTENT: i32 = 56; + pub const WRITTEN_BOOK_CONTENT: i32 = 57; +} + +/// A written book's content (`WrittenBookContent.STREAM_CODEC`): the +/// filtered variants of the title and pages are read and dropped. +#[derive(Clone, Debug, PartialEq)] +pub struct WrittenBook { + pub title: String, + pub author: String, + pub generation: i32, + /// Each page's text component. + pub pages: Vec, + pub resolved: bool, } /// The value of one patched data component. Components whose stream codec @@ -42,6 +60,8 @@ pub enum Component { Ident(String), Lore(Vec), Enchantments(Vec<(i32, i32)>), + AttackRange([f32; 6]), + Profile(Profile), CustomModelData { floats: Vec, flags: Vec, @@ -52,13 +72,58 @@ pub enum Component { hide: bool, hidden: Vec, }, + /// `WritableBookContent`: the pages (raw text). + WritableBook(Vec), + WrittenBook(WrittenBook), +} + +/// `Filterable.streamCodec`: the raw value, then an optional filtered one +/// (dropped). +fn filterable(r: &mut Reader, value: impl Fn(&mut Reader) -> Result) -> Result { + let raw = value(r)?; + if r.bool()? { + value(r)?; + } + 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::*; Ok(match kind { - MAX_STACK_SIZE | MAX_DAMAGE | DAMAGE | RARITY | REPAIR_COST | MAP_ID => { - Self::Int(r.varint()?) + MAX_STACK_SIZE | MAX_DAMAGE | DAMAGE | RARITY | REPAIR_COST | MAP_ID + | MAP_POST_PROCESSING => Self::Int(r.varint()?), + WRITABLE_BOOK_CONTENT => { + let n = r.count(100)?; + Self::WritableBook( + (0..n) + .map(|_| filterable(r, |r| r.string(1024))) + .collect::>()?, + ) + } + WRITTEN_BOOK_CONTENT => { + let title = filterable(r, |r| r.string(32))?; + let author = r.string(32767)?; + let generation = r.varint()?; + let n = r.count(r.remaining())?; + let pages = (0..n) + .map(|_| filterable(r, |r| r.nbt())) + .collect::>()?; + Self::WrittenBook(WrittenBook { + title, + author, + generation, + pages, + resolved: r.bool()?, + }) } DYED_COLOR => Self::Int(r.i32()?), UNBREAKABLE | CREATIVE_SLOT_LOCK => Self::Unit, @@ -78,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::>()?; @@ -124,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, @@ -144,6 +283,25 @@ impl Component { w.varint(hidden.len() as i32); hidden.iter().for_each(|h| w.varint(*h)); } + Self::WritableBook(pages) => { + w.varint(pages.len() as i32); + for page in pages { + w.string(page); + w.bool(false); + } + } + Self::WrittenBook(b) => { + w.string(&b.title); + w.bool(false); + w.string(&b.author); + w.varint(b.generation); + w.varint(b.pages.len() as i32); + for page in &b.pages { + w.nbt(page); + w.bool(false); + } + w.bool(b.resolved); + } } } } @@ -349,12 +507,43 @@ mod tests { Component::Lore(vec![literal("a"), literal("b")]), )); sword.removed.push(component::REPAIR_COST); + let mut book = Stack::new(1100, 1); + book.added.push(( + component::WRITTEN_BOOK_CONTENT, + Component::WrittenBook(WrittenBook { + title: "Notes".into(), + author: "Guest".into(), + generation: 1, + pages: vec![literal("one"), literal("two")], + resolved: true, + }), + )); + book.added + .push((component::MAP_POST_PROCESSING, Component::Int(1))); + round::, Slot>(Some(book)); + let mut quill = Stack::new(1099, 1); + quill.added.push(( + component::WRITABLE_BOOK_CONTENT, + Component::WritableBook(vec!["a".into(), String::new()]), + )); + round::, Slot>(Some(quill)); assert_eq!(sword.damage(), 17); round::, Slot>(Some(sword.clone())); round::, HashedSlot>(Some(Hashed::of(&sword))); round::, HashedSlot>(None); } + #[test] + fn filtered_book_pages_are_read_and_dropped() { + // A writable book with one page "hi" and its filtered "**". + let bytes = [1, 7, 1, 0, 56, 1, 2, b'h', b'i', 1, 2, b'*', b'*']; + let stack = Slot::read(&mut Reader::new(&bytes)).unwrap().unwrap(); + assert_eq!( + stack.component(component::WRITABLE_BOOK_CONTENT), + Some(&Component::WritableBook(vec!["hi".into()])) + ); + } + #[test] fn empty_stack_is_a_zero_count() { let mut w = Writer::new(); @@ -370,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 c5d5eb68c..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, @@ -1712,6 +1775,25 @@ packet!( } ); packet!(SelectTrade { item: i32 => VarInt }); +packet!( + /// ServerboundContainerButtonClickPacket: `AbstractContainerMenu.clickMenuButton` + /// (the loom's patterns, the stonecutter's recipes, the enchanting table's offers). + ContainerButtonClick { container: i32 => VarInt, button: i32 => VarInt } +); +packet!( + /// ServerboundContainerSlotStateChangedPacket: the crafter's slot toggle + /// (`CrafterBlockEntity.setSlotState`). + ContainerSlotStateChanged { slot: i32 => VarInt, container: i32 => VarInt, enabled: bool => Bool } +); +packet!( + /// ServerboundRenameItemPacket: `AnvilMenu.setItemName`. + RenameItem { name: String => Str } +); +packet!( + /// ServerboundSetBeaconPacket: `BeaconMenu.updateEffects`, each power an + /// optional `mob_effect` id. + SetBeacon { primary: Option => Opt, secondary: Option => Opt } +); packet!(Interact { id: i32 => VarInt, hand: i32 => VarInt, location: [f64; 3] => LpVec3, secondary: bool => Bool }); packet!( /// ServerboundMovePlayerPacket flags: 1 on ground, 2 horizontal collision. @@ -1777,6 +1859,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { ClientInformation(ClientInformation) = CLIENT_INFORMATION, ClientTickEnd(Empty) = CLIENT_TICK_END, ConfigurationAcknowledged(Empty) = CONFIGURATION_ACKNOWLEDGED, + ContainerButtonClick(ContainerButtonClick) = CONTAINER_BUTTON_CLICK, ContainerClick(ContainerClick) = CONTAINER_CLICK, ContainerClose(ContainerClose) = CONTAINER_CLOSE, CustomPayload(CustomPayload) = CUSTOM_PAYLOAD, @@ -1794,9 +1877,12 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { PlayerInput(PlayerInput) = PLAYER_INPUT, PlayerLoaded(Empty) = PLAYER_LOADED, Pong(Ping) = PONG, + RenameItem(RenameItem) = RENAME_ITEM, + ContainerSlotStateChanged(ContainerSlotStateChanged) = CONTAINER_SLOT_STATE_CHANGED, Punch(Empty) = PUNCH, ResourcePack(ResourcePackResponse) = RESOURCE_PACK, SelectTrade(SelectTrade) = SELECT_TRADE, + SetBeacon(SetBeacon) = SET_BEACON, SetCarriedItem(SetCarriedItem) = SET_CARRIED_ITEM, SetCreativeModeSlot(SetCreativeModeSlot) = SET_CREATIVE_MODE_SLOT, UseItem(UseItem) = USE_ITEM, @@ -2374,6 +2460,34 @@ mod tests { Serverbound::encode, Serverbound::decode, ); + // CONTAINER_ID and the button, both VarInts. + let button = Serverbound::ContainerButtonClick(ContainerButtonClick { + container: 3, + button: 200, + }); + assert_eq!(&button.encode()[1..], &[3, 0xC8, 1]); + round_trip(button, Serverbound::encode, Serverbound::decode); + // The name, a UTF-8 string with its VarInt length. + let rename = Serverbound::RenameItem(RenameItem { + name: "Blade".into(), + }); + assert_eq!(&rename.encode()[1..], &[5, b'B', b'l', b'a', b'd', b'e']); + round_trip(rename, Serverbound::encode, Serverbound::decode); + // The slot, the container id (VarInts), then the new state. + let toggle = Serverbound::ContainerSlotStateChanged(ContainerSlotStateChanged { + slot: 4, + container: 2, + enabled: false, + }); + assert_eq!(&toggle.encode()[1..], &[4, 2, 0]); + round_trip(toggle, Serverbound::encode, Serverbound::decode); + // Two optional mob effect ids: a presence byte, then the VarInt. + let beacon = Serverbound::SetBeacon(SetBeacon { + primary: Some(2), + secondary: None, + }); + assert_eq!(&beacon.encode()[1..], &[1, 2, 0]); + round_trip(beacon, Serverbound::encode, Serverbound::decode); } #[test] @@ -2439,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-telemetry-server/README.md b/crates/horizon-telemetry-server/README.md index cf2d52393..dc1f51248 100644 --- a/crates/horizon-telemetry-server/README.md +++ b/crates/horizon-telemetry-server/README.md @@ -1,6 +1,6 @@ # horizon-telemetry-server -This server receives what players choose to send (performance summaries, crash and bug reports, benchmark uploads: [docs/telemetry.md](../../docs/telemetry.md)) and stores it in one SQLite file. It serves anonymous totals to the website. It is one small Rust process, about 7 MB of memory when idle. +This server receives what players choose to send (performance summaries, crash and bug reports, benchmark uploads: [docs/telemetry.md](../../docs/telemetry.md)) and stores it in one SQLite file. It serves anonymous totals to the website. It also keeps the live player count from the games' anonymous "I'm playing" pings, in memory only. It is one small Rust process, about 7 MB of memory when idle. cargo run --release # in this folder: its own workspace, like the launcher's PORT=8080 HORIZON_TELEMETRY_DB=/data/telemetry.sqlite3 horizon-telemetry-server @@ -14,6 +14,8 @@ The launcher sends to it when `HORIZON_TELEMETRY_URL` is set (and to `DEFAULT_EN | `POST /v1/batch` | A zstd batch (`Content-Encoding: zstd`, at most 256 KiB, 1 MiB inflated, 64 items). Returns 204. Returns 400 for a bad batch, 413 for one too large, 415 if it is not zstd, 429 when over a limit. | | `DELETE /v1/installs/` | Deletes everything that install sent. Its share of the daily totals is rebuilt at once. | | `GET /v1/aggregate?days=30` | The totals the website reads. Cached 10 minutes, with `Access-Control-Allow-Origin` set to the website. | +| `POST /v1/live` | A game's "I'm playing" ping (JSON, at most 512 bytes). Returns 204. Returns 400 for a bad ping, 413 for one too large, 429 over the address's limit, 503 when it holds `LIVE_MAX_SESSIONS` already. | +| `GET /v1/live` | How many play now, rounded: `playing`, `lan`, `versions`, `platforms`. Made again at most every 15 seconds, with the same `Access-Control-Allow-Origin`. | | `GET /healthz` | `ok` | The totals are grouped per version, OS, GPU vendor and render distance. Each group has its sessions, install-days, hours played, the 14 frame-time buckets summed, and the mean p50 and p99 frame times. Groups with fewer than 5 install-days are left out. The totals also list crash counts per version and the newest 50 benchmark uploads. @@ -27,6 +29,8 @@ The totals are grouped per version, OS, GPU vendor and render distance. Each gro Measured: **about 190 bytes per play session** on disk, indexes included (`tests/server.rs`, 10 000 sessions). 1 000 players playing twice a day for 180 days is about 70 MB. +The live count is a table in memory: a session ID, when it last pinged, its version, platform and LAN flag, about 100 bytes a session. A session counts while its last ping is under 2 minutes old and is forgotten after that. Nothing of it reaches the disk, so a restart empties it; it is whole again a minute later. + The day stored is the day the server received an item. The sender's IP address is never written down. The per-address rate limit keeps addresses in memory for an hour at most. Raw rows are deleted after `HORIZON_TELEMETRY_RETENTION_DAYS` (180). The daily totals stay; they hold no install ID. @@ -43,6 +47,9 @@ All are environment variables: - `HORIZON_TELEMETRY_ITEMS_PER_DAY` per install (100) - `HORIZON_TELEMETRY_TRUST_PROXY=1` behind a proxy (the client's address is then the first of `X-Forwarded-For`) - `HORIZON_TELEMETRY_ALLOW_ORIGIN` (`https://playhorizon.dev`) +- `HORIZON_TELEMETRY_LIVE_PER_HOUR` per address, pings and reads (600, bursts of 60: ten players behind one address) +- `HORIZON_TELEMETRY_LIVE_WINDOW_SECONDS` (120) +- `HORIZON_TELEMETRY_LIVE_MAX_SESSIONS` (200 000) ## Hosting diff --git a/crates/horizon-telemetry-server/src/lib.rs b/crates/horizon-telemetry-server/src/lib.rs index b1521a714..061a9ca37 100644 --- a/crates/horizon-telemetry-server/src/lib.rs +++ b/crates/horizon-telemetry-server/src/lib.rs @@ -3,12 +3,15 @@ //! - `POST /v1/batch`: a zstd batch from the launcher, checked by `horizon_telemetry::batch`. //! - `DELETE /v1/installs/`: everything an install sent goes. //! - `GET /v1/aggregate?days=30`: the anonymous totals the website reads, cached. +//! - `POST /v1/live`: a game's anonymous "I'm playing" ping (`live`, in memory only). +//! - `GET /v1/live`: how many play now, rounded, cached briefly. //! - `GET /healthz`. //! //! Abuse limits: a token bucket per IP address (kept in memory for an hour, never stored), a -//! daily item cap per install, and the batch size limits. Raw rows expire after -//! `retention_days`; the daily totals stay. One small process and one SQLite file: see -//! `README.md` for running it. +//! daily item cap per install, and the batch size limits. The live count has its own, larger +//! bucket per address (several players can share one) and a cap on the sessions it holds. Raw +//! rows expire after `retention_days`; the daily totals stay. One small process and one SQLite +//! file: see `README.md` for running it. use std::collections::HashMap; use std::net::{IpAddr, SocketAddr}; use std::sync::{Arc, Mutex}; @@ -21,8 +24,11 @@ use axum::response::{IntoResponse, Response}; use axum::routing::{delete, get, post}; use horizon_telemetry::batch; +pub mod live; pub mod store; +use horizon_telemetry::live::{MAX_PING_BYTES, Ping}; +use live::Live; use store::Store; pub struct Config { @@ -38,6 +44,13 @@ pub struct Config { pub trust_proxy: bool, /// The website allowed to read the totals from a browser. pub allow_origin: String, + /// Live count requests (pings and reads) an IP address may make an hour, with a burst of a + /// tenth of it. A game pings once a minute, so the default lets ten play behind one address. + pub live_per_hour: f64, + /// How long a session counts after its last ping. + pub live_window: Duration, + /// Sessions the live count holds at most; a new one past that is refused. + pub live_max_sessions: usize, } impl Default for Config { @@ -49,13 +62,17 @@ impl Default for Config { items_per_day: 100, trust_proxy: false, allow_origin: "https://playhorizon.dev".into(), + live_per_hour: 600.0, + live_window: horizon_telemetry::live::WINDOW, + live_max_sessions: 200_000, } } } impl Config { /// The defaults, with `HORIZON_TELEMETRY_RETENTION_DAYS`, `…_MIN_INSTALL_DAYS`, - /// `…_REQUESTS_PER_HOUR`, `…_ITEMS_PER_DAY`, `…_TRUST_PROXY` (1) and `…_ALLOW_ORIGIN`. + /// `…_REQUESTS_PER_HOUR`, `…_ITEMS_PER_DAY`, `…_TRUST_PROXY` (1), `…_ALLOW_ORIGIN`, + /// `…_LIVE_PER_HOUR`, `…_LIVE_WINDOW_SECONDS` and `…_LIVE_MAX_SESSIONS`. pub fn from_env() -> Self { let var = |k: &str| std::env::var(format!("HORIZON_TELEMETRY_{k}")).ok(); let d = Self::default(); @@ -74,6 +91,15 @@ impl Config { .unwrap_or(d.items_per_day), trust_proxy: var("TRUST_PROXY").is_some_and(|v| v == "1"), allow_origin: var("ALLOW_ORIGIN").unwrap_or(d.allow_origin), + live_per_hour: var("LIVE_PER_HOUR") + .and_then(|v| v.parse().ok()) + .unwrap_or(d.live_per_hour), + live_window: var("LIVE_WINDOW_SECONDS") + .and_then(|v| v.parse().ok()) + .map_or(d.live_window, Duration::from_secs), + live_max_sessions: var("LIVE_MAX_SESSIONS") + .and_then(|v| v.parse().ok()) + .unwrap_or(d.live_max_sessions), } } } @@ -82,13 +108,21 @@ pub struct App { store: Mutex, config: Config, /// Tokens left and when they were counted, per client address. - buckets: Mutex>, + buckets: Mutex, + /// The same for the live count's requests. + live_buckets: Mutex, + /// Who is playing now (`live`). + live: Mutex, + /// `GET /v1/live`'s answer and when it was made. + live_cache: Mutex>, /// `/v1/aggregate` answers by `days`, with when they were made. cache: Mutex>, /// Today, in days since 1970 (a test moves it). today: Box u32 + Send + Sync>, } +type Buckets = HashMap; + const CACHE_FOR: Duration = Duration::from_secs(600); fn status(code: StatusCode, message: &str) -> Response { @@ -105,10 +139,14 @@ impl App { config: Config, today: Box u32 + Send + Sync>, ) -> Arc { + let live = Live::new(config.live_window, config.live_max_sessions); Arc::new(Self { store: Mutex::new(store), config, buckets: Mutex::default(), + live_buckets: Mutex::default(), + live: Mutex::new(live), + live_cache: Mutex::default(), cache: Mutex::default(), today, }) @@ -120,18 +158,16 @@ impl App { /// Takes a token for `ip`; false when it has none left. fn allow(&self, ip: IpAddr) -> bool { - let rate = self.config.requests_per_hour / 3600.0; - let burst = (self.config.requests_per_hour / 10.0).max(1.0); - let mut buckets = self.buckets.lock().unwrap_or_else(|e| e.into_inner()); - let now = Instant::now(); - let (tokens, at) = buckets.entry(ip).or_insert((burst, now)); - *tokens = (*tokens + now.duration_since(*at).as_secs_f64() * rate).min(burst); - *at = now; - if *tokens < 1.0 { - return false; - } - *tokens -= 1.0; - true + take(&self.buckets, self.config.requests_per_hour, ip) + } + + /// [`Self::allow`] for the live count's requests. + fn allow_live(&self, ip: IpAddr) -> bool { + take(&self.live_buckets, self.config.live_per_hour, ip) + } + + fn live(&self) -> std::sync::MutexGuard<'_, Live> { + self.live.lock().unwrap_or_else(|e| e.into_inner()) } fn client(&self, headers: &HeaderMap, peer: Option) -> IpAddr { @@ -160,14 +196,18 @@ impl App { self.store().newest_day(install).ok().flatten() } - /// Daily upkeep: totals rebuilt, expired rows removed, idle rate-limit entries forgotten. + /// Daily upkeep: totals rebuilt, expired rows removed, idle rate-limit entries and live + /// sessions forgotten. pub fn maintain(&self) -> rusqlite::Result { let oldest = (self.today)().saturating_sub(self.config.retention_days); let removed = self.store().expire(oldest)?; - self.buckets - .lock() - .unwrap_or_else(|e| e.into_inner()) - .retain(|_, (_, at)| at.elapsed() < Duration::from_secs(3600)); + for buckets in [&self.buckets, &self.live_buckets] { + buckets + .lock() + .unwrap_or_else(|e| e.into_inner()) + .retain(|_, (_, at)| at.elapsed() < Duration::from_secs(3600)); + } + self.live().forget_expired(Instant::now()); if removed > 0 { self.cache.lock().unwrap_or_else(|e| e.into_inner()).clear(); } @@ -175,6 +215,23 @@ impl App { } } +/// Takes a token for `ip` from its bucket in `buckets` (`per_hour`, bursts of a tenth of it); +/// false when it has none left. +fn take(buckets: &Mutex, per_hour: f64, ip: IpAddr) -> bool { + let rate = per_hour / 3600.0; + let burst = (per_hour / 10.0).max(1.0); + let mut buckets = buckets.lock().unwrap_or_else(|e| e.into_inner()); + let now = Instant::now(); + let (tokens, at) = buckets.entry(ip).or_insert((burst, now)); + *tokens = (*tokens + now.duration_since(*at).as_secs_f64() * rate).min(burst); + *at = now; + if *tokens < 1.0 { + return false; + } + *tokens -= 1.0; + true +} + fn peer(req: &Request) -> Option { req.extensions() .get::>() @@ -278,18 +335,65 @@ async fn aggregate(State(app): State>, Query(window): Query) -> } } }; + json_response(&app, json, CACHE_FOR.as_secs()) +} + +/// `POST /v1/live`: one "I'm playing". 204, or 400 for a bad ping, 413 for one too large, 429 +/// over the address's limit, 503 when the table is full. +async fn ping(State(app): State>, req: Request) -> Response { + if !app.allow_live(app.client(req.headers(), peer(&req))) { + return status(StatusCode::TOO_MANY_REQUESTS, "too many requests"); + } + let Ok(body) = axum::body::to_bytes(req.into_body(), MAX_PING_BYTES).await else { + return status(StatusCode::PAYLOAD_TOO_LARGE, "a ping is at most 512 bytes"); + }; + let ping: Ping = match serde_json::from_slice(&body) { + Ok(ping) => ping, + Err(e) => return status(StatusCode::BAD_REQUEST, &e.to_string()), + }; + if let Err(e) = ping.check() { + return status(StatusCode::BAD_REQUEST, e); + } + match app.live().ping(&ping, Instant::now()) { + Ok(()) => StatusCode::NO_CONTENT.into_response(), + Err(live::Full) => status(StatusCode::SERVICE_UNAVAILABLE, "try again later"), + } +} + +/// `GET /v1/live`: the rounded live count (`horizon_telemetry::live::Count`), made again at +/// most every eighth of the window. +async fn playing(State(app): State>, req: Request) -> Response { + if !app.allow_live(app.client(req.headers(), peer(&req))) { + return status(StatusCode::TOO_MANY_REQUESTS, "too many requests"); + } + let fresh_for = app.config.live_window / 8; + let json = { + let mut cache = app.live_cache.lock().unwrap_or_else(|e| e.into_inner()); + match &*cache { + Some((at, json)) if at.elapsed() < fresh_for => json.clone(), + _ => { + let json = + serde_json::to_string(&app.live().count(Instant::now())).unwrap_or_default(); + *cache = Some((Instant::now(), json.clone())); + json + } + } + }; + json_response(&app, json, fresh_for.as_secs()) +} + +fn json_response(app: &App, json: String, max_age: u64) -> Response { let origin = HeaderValue::from_str(&app.config.allow_origin).unwrap_or(HeaderValue::from_static("*")); + let cache = HeaderValue::from_str(&format!("public, max-age={max_age}")) + .unwrap_or(HeaderValue::from_static("no-cache")); ( [ ( header::CONTENT_TYPE, HeaderValue::from_static("application/json"), ), - ( - header::CACHE_CONTROL, - HeaderValue::from_static("public, max-age=600"), - ), + (header::CACHE_CONTROL, cache), (header::ACCESS_CONTROL_ALLOW_ORIGIN, origin), ], json, @@ -300,6 +404,7 @@ async fn aggregate(State(app): State>, Query(window): Query) -> pub fn router(app: Arc) -> Router { Router::new() .route("/v1/batch", post(receive)) + .route("/v1/live", post(ping).get(playing)) .route("/v1/installs/{id}", delete(forget)) .route("/v1/aggregate", get(aggregate)) .route("/healthz", get(|| async { "ok" })) diff --git a/crates/horizon-telemetry-server/src/live.rs b/crates/horizon-telemetry-server/src/live.rs new file mode 100644 index 000000000..f28165da5 --- /dev/null +++ b/crates/horizon-telemetry-server/src/live.rs @@ -0,0 +1,201 @@ +//! Who is playing now, from the games' "I'm playing" pings (`horizon_telemetry::live`). Kept in +//! memory only: a session ID, when it last pinged, its version, platform and LAN flag. A +//! session counts while its last ping is under the window old and is forgotten after it. No +//! address is kept, and nothing is written to disk, so a restart starts the count again (it +//! is whole again a minute later). +use std::collections::{BTreeMap, HashMap}; +use std::time::{Duration, Instant}; + +use horizon_telemetry::live::{Count, PLATFORMS, Ping, round}; + +/// Versions listed by name in a count; the rest are summed under `other`. +const VERSIONS_SHOWN: usize = 12; + +struct Seen { + at: Instant, + version: Box, + platform: u8, + lan: bool, +} + +pub struct Live { + sessions: HashMap, + window: Duration, + max_sessions: usize, +} + +/// The table is full and this session is new. +#[derive(Debug, PartialEq, Eq)] +pub struct Full; + +impl Live { + pub fn new(window: Duration, max_sessions: usize) -> Self { + Self { + sessions: HashMap::new(), + window, + max_sessions, + } + } + + /// Records `ping` (already checked) as seen at `now`. + pub fn ping(&mut self, ping: &Ping, now: Instant) -> Result<(), Full> { + let Ok(id) = u128::from_str_radix(&ping.session, 16) else { + return Ok(()); + }; + if !self.sessions.contains_key(&id) && self.sessions.len() >= self.max_sessions { + self.forget_expired(now); + if self.sessions.len() >= self.max_sessions { + return Err(Full); + } + } + let platform = PLATFORMS + .iter() + .position(|p| *p == ping.platform) + .unwrap_or(PLATFORMS.len() - 1) as u8; + self.sessions.insert( + id, + Seen { + at: now, + version: ping.version.as_str().into(), + platform, + lan: ping.lan, + }, + ); + Ok(()) + } + + /// Drops the sessions whose last ping is older than the window. + pub fn forget_expired(&mut self, now: Instant) { + let window = self.window; + self.sessions + .retain(|_, s| now.saturating_duration_since(s.at) < window); + } + + /// Who is playing at `now`, rounded. + pub fn count(&mut self, now: Instant) -> Count { + self.forget_expired(now); + let mut versions: HashMap<&str, u64> = HashMap::new(); + let mut platforms = [0u64; PLATFORMS.len()]; + let mut lan = 0; + for s in self.sessions.values() { + *versions.entry(&s.version).or_default() += 1; + platforms[usize::from(s.platform)] += 1; + lan += u64::from(s.lan); + } + let mut by_count: Vec<(&str, u64)> = versions.into_iter().collect(); + by_count.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0))); + let mut shown = BTreeMap::new(); + let mut other = 0; + for (i, (version, n)) in by_count.into_iter().enumerate() { + if i < VERSIONS_SHOWN { + shown.insert(version.to_owned(), round(n)); + } else { + other += n; + } + } + if other > 0 { + *shown.entry("other".to_owned()).or_default() += round(other); + } + Count { + playing: round(self.sessions.len() as u64), + lan: round(lan), + versions: shown, + platforms: PLATFORMS + .iter() + .zip(platforms) + .filter(|(_, n)| *n > 0) + .map(|(p, n)| ((*p).to_owned(), round(n))) + .collect(), + } + } + + /// Sessions held now, counted or not yet forgotten. + pub fn len(&self) -> usize { + self.sessions.len() + } + + pub fn is_empty(&self) -> bool { + self.sessions.is_empty() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ping(n: u32, version: &str, platform: &str, lan: bool) -> Ping { + Ping { + session: format!("{n:032x}"), + version: version.into(), + platform: platform.into(), + lan, + } + } + + #[test] + fn sessions_count_until_the_window_passes() { + let t = Instant::now(); + let mut live = Live::new(Duration::from_secs(120), 100); + live.ping(&ping(1, "0.2.0", "linux", false), t).unwrap(); + live.ping(&ping(2, "0.2.0", "macos", true), t).unwrap(); + // The same session again is still one. + live.ping( + &ping(1, "0.2.0", "linux", false), + t + Duration::from_secs(60), + ) + .unwrap(); + let count = live.count(t + Duration::from_secs(61)); + assert_eq!((count.playing, count.lan), (2, 1)); + assert_eq!(count.versions, BTreeMap::from([("0.2.0".into(), 2)])); + assert_eq!( + count.platforms, + BTreeMap::from([("linux".into(), 1), ("macos".into(), 1)]) + ); + // Session 2 stopped pinging two minutes ago; session 1 pinged a minute later. + let count = live.count(t + Duration::from_secs(150)); + assert_eq!((count.playing, count.lan), (1, 0)); + assert_eq!(live.len(), 1); + assert_eq!(live.count(t + Duration::from_secs(181)), Count::default()); + assert!(live.is_empty()); + } + + #[test] + fn a_full_table_takes_no_new_session_until_one_expires() { + let t = Instant::now(); + let mut live = Live::new(Duration::from_secs(120), 2); + live.ping(&ping(1, "0.2.0", "linux", false), t).unwrap(); + live.ping(&ping(2, "0.2.0", "linux", false), t).unwrap(); + assert_eq!(live.ping(&ping(3, "0.2.0", "linux", false), t), Err(Full)); + // A known session still refreshes. + live.ping( + &ping(1, "0.2.0", "linux", false), + t + Duration::from_secs(100), + ) + .unwrap(); + let later = t + Duration::from_secs(130); + live.ping(&ping(3, "0.2.0", "linux", false), later).unwrap(); + assert_eq!(live.count(later).playing, 2); + } + + #[test] + fn rare_versions_are_summed_and_counts_rounded() { + let t = Instant::now(); + let mut live = Live::new(Duration::from_secs(120), 1000); + for n in 0..40 { + live.ping(&ping(n, "0.2.0", "windows", n % 4 == 0), t) + .unwrap(); + } + for n in 0..(VERSIONS_SHOWN as u32 + 3) { + live.ping(&ping(100 + n, &format!("dev {n}"), "other", false), t) + .unwrap(); + } + let count = live.count(t); + assert_eq!(count.playing, 55); + assert_eq!(count.lan, 10); + assert_eq!(count.versions["0.2.0"], 40); + assert_eq!(count.versions["other"], 4); + assert_eq!(count.versions.len(), VERSIONS_SHOWN + 1); + assert_eq!(count.platforms["windows"], 40); + assert_eq!(count.platforms["other"], 15); + } +} diff --git a/crates/horizon-telemetry-server/tests/live.rs b/crates/horizon-telemetry-server/tests/live.rs new file mode 100644 index 000000000..d8c7f33fe --- /dev/null +++ b/crates/horizon-telemetry-server/tests/live.rs @@ -0,0 +1,190 @@ +//! The live count through its HTTP interface, and end to end with the game's ping and the +//! launcher's read (`horizon_telemetry::live`). +use std::sync::Arc; +use std::time::Duration; + +use axum::body::Body; +use axum::http::{Request, StatusCode, header}; +use horizon_telemetry::live::{self, Count, Ping}; +use horizon_telemetry_server::store::Store; +use horizon_telemetry_server::{App, Config, router}; +use http_body_util::BodyExt; +use tower::ServiceExt; + +fn app(config: Config) -> Arc { + App::new(Store::open(":memory:").unwrap(), config) +} + +fn quick() -> Config { + Config { + live_per_hour: 100_000.0, + live_window: Duration::from_secs(1), + trust_proxy: true, + ..Config::default() + } +} + +fn ping(n: u32, version: &str, lan: bool) -> String { + serde_json::to_string(&Ping { + session: format!("{n:032x}"), + version: version.into(), + platform: "linux".into(), + lan, + }) + .unwrap() +} + +async fn send(app: &Arc, req: Request) -> (StatusCode, axum::http::HeaderMap, String) { + let res = router(app.clone()).oneshot(req).await.unwrap(); + let (code, headers) = (res.status(), res.headers().clone()); + let body = res.into_body().collect().await.unwrap().to_bytes(); + (code, headers, String::from_utf8_lossy(&body).into_owned()) +} + +async fn post(app: &Arc, body: impl Into, from: &str) -> StatusCode { + let req = Request::post("/v1/live") + .header("x-forwarded-for", from) + .body(body.into()) + .unwrap(); + send(app, req).await.0 +} + +async fn count(app: &Arc) -> Count { + let req = Request::get("/v1/live") + .header("x-forwarded-for", "198.51.100.1") + .body(Body::empty()) + .unwrap(); + let (code, headers, body) = send(app, req).await; + assert_eq!(code, StatusCode::OK, "{body}"); + assert_eq!(headers[header::CONTENT_TYPE], "application/json"); + assert_eq!( + headers[header::ACCESS_CONTROL_ALLOW_ORIGIN], + "https://playhorizon.dev" + ); + serde_json::from_str(&body).unwrap() +} + +#[tokio::test] +async fn sessions_count_while_they_ping_and_expire_after() { + let app = app(quick()); + assert_eq!( + post(&app, ping(1, "0.2.0", false), "203.0.113.1").await, + StatusCode::NO_CONTENT + ); + assert_eq!( + post(&app, ping(2, "0.2.0", true), "203.0.113.2").await, + StatusCode::NO_CONTENT + ); + // A second ping from the same session is still one player. + assert_eq!( + post(&app, ping(1, "0.2.0", false), "203.0.113.1").await, + StatusCode::NO_CONTENT + ); + let now = count(&app).await; + assert_eq!((now.playing, now.lan), (2, 1)); + assert_eq!(now.versions["0.2.0"], 2); + assert_eq!(now.platforms["linux"], 2); + + // Session 1 keeps pinging; session 2 stops. + for _ in 0..5 { + tokio::time::sleep(Duration::from_millis(250)).await; + post(&app, ping(1, "0.2.0", false), "203.0.113.1").await; + } + let later = count(&app).await; + assert_eq!((later.playing, later.lan), (1, 0)); + tokio::time::sleep(Duration::from_millis(1200)).await; + assert_eq!(count(&app).await, Count::default()); +} + +#[tokio::test] +async fn bad_pings_are_refused() { + let app = app(quick()); + let from = "203.0.113.3"; + assert_eq!(post(&app, "not json", from).await, StatusCode::BAD_REQUEST); + assert_eq!( + post(&app, ping(1, "0.2", false), from).await, + StatusCode::BAD_REQUEST + ); + let extra = r#"{"session":"00000000000000000000000000000001","version":"0.2.0","platform":"linux","lan":false,"name":"Steve"}"#; + assert_eq!(post(&app, extra, from).await, StatusCode::BAD_REQUEST); + assert_eq!( + post(&app, "x".repeat(4096), from).await, + StatusCode::PAYLOAD_TOO_LARGE + ); + assert_eq!(count(&app).await.playing, 0); +} + +#[tokio::test] +async fn an_address_is_rate_limited_on_its_own_bucket() { + let app = app(Config { + live_per_hour: 60.0, + trust_proxy: true, + ..Config::default() + }); + // A burst of a tenth of the hour's 60, then 429. + let mut codes = Vec::new(); + for n in 0..8 { + codes.push(post(&app, ping(n, "0.2.0", false), "203.0.113.4").await); + } + assert_eq!( + codes + .iter() + .filter(|c| **c == StatusCode::NO_CONTENT) + .count(), + 6 + ); + assert_eq!(codes[7], StatusCode::TOO_MANY_REQUESTS); + // Another address is not held back. + assert_eq!( + post(&app, ping(9, "0.2.0", false), "203.0.113.5").await, + StatusCode::NO_CONTENT + ); +} + +#[tokio::test] +async fn a_full_table_refuses_new_sessions() { + let app = app(Config { + live_max_sessions: 2, + ..quick() + }); + for n in 0..2 { + assert_eq!( + post(&app, ping(n, "0.2.0", false), "203.0.113.6").await, + StatusCode::NO_CONTENT + ); + } + assert_eq!( + post(&app, ping(2, "0.2.0", false), "203.0.113.6").await, + StatusCode::SERVICE_UNAVAILABLE + ); + assert_eq!( + post(&app, ping(1, "0.2.0", false), "203.0.113.6").await, + StatusCode::NO_CONTENT + ); +} + +#[tokio::test] +async fn the_games_ping_and_the_launchers_read_reach_it_end_to_end() { + let app = app(Config { + live_window: Duration::from_secs(120), + ..quick() + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let service = router(app.clone()).into_make_service_with_connect_info::(); + tokio::spawn(async move { axum::serve(listener, service).await.unwrap() }); + + let count = tokio::task::spawn_blocking(move || { + let a = Ping::new(&live::session_id(), "0.2.0", false); + let b = Ping::new(&live::session_id(), "dev 0.1.0", true); + live::send(&url, &a)?; + live::send(&url, &b)?; + live::fetch(&url) + }) + .await + .unwrap() + .unwrap(); + assert_eq!((count.playing, count.lan), (2, 1)); + assert_eq!(count.versions.len(), 2); + assert_eq!(count.platforms[live::platform()], 2); +} diff --git a/crates/horizon-telemetry/Cargo.toml b/crates/horizon-telemetry/Cargo.toml index ea54b079d..913eac453 100644 --- a/crates/horizon-telemetry/Cargo.toml +++ b/crates/horizon-telemetry/Cargo.toml @@ -13,12 +13,14 @@ serde_json = "1" ruzstd = "0.9" # The random install ID and outbox file names. getrandom = "0.3" -# Sending, for the launcher; the ingest server builds without it. +# Sending, for the launcher (and the game's "I'm playing" ping); the ingest server builds without it. ureq = { version = "2", default-features = false, features = ["tls"], optional = true } [features] -default = ["upload"] +default = ["upload", "live"] upload = ["dep:ureq"] +# The "I'm playing" ping and reading the live count (`live`), for the game and the launcher. +live = ["dep:ureq"] [[test]] name = "consent_gating" diff --git a/crates/horizon-telemetry/src/lib.rs b/crates/horizon-telemetry/src/lib.rs index e903936db..8d2840a08 100644 --- a/crates/horizon-telemetry/src/lib.rs +++ b/crates/horizon-telemetry/src/lib.rs @@ -6,11 +6,15 @@ //! connection. Items are small summaries (percentiles and histogram buckets, never raw streams), //! dated to the day, with no account, world, server or address in them ([`scrub`]); they leave //! in zstd batches ([`batch`]). `docs/telemetry.md` lists every field. +//! +//! The one exception is [`live`]: the anonymous "I'm playing" ping the game sends while it +//! runs, for the live player count. It holds no install ID and nothing about the player. use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; pub mod batch; pub mod consent; +pub mod live; pub mod outbox; pub mod payload; pub mod scrub; @@ -29,8 +33,9 @@ pub const SCHEMA: u32 = 1; /// and until the player answers nothing new is kept or sent. pub const CONSENT_VERSION: u32 = 1; -/// The ingest server, or none while there isn't one: then nothing is ever sent and the outbox -/// stays within its caps. `HORIZON_TELEMETRY_URL` overrides it (tests, a local server). +/// The ingest server, or none while there isn't one: then nothing is ever sent (no ping either) +/// and the outbox stays within its caps. `HORIZON_TELEMETRY_URL` overrides it (tests, a local +/// server). pub const DEFAULT_ENDPOINT: Option<&str> = None; /// Where items are sent, if anywhere. diff --git a/crates/horizon-telemetry/src/live.rs b/crates/horizon-telemetry/src/live.rs new file mode 100644 index 000000000..b1df57320 --- /dev/null +++ b/crates/horizon-telemetry/src/live.rs @@ -0,0 +1,215 @@ +//! The anonymous "I'm playing" ping, and the live count it feeds ("N playing now" in the +//! launcher). +//! +//! Unlike everything else in this crate it does not wait for consent: Ludovic decided +//! (2026-10-22) to count every player and tell them, in the launcher's first-run question, its +//! Settings and the privacy page. So a ping holds only what the count needs: a random session ID +//! made when the game starts and kept only in its memory (not the install ID), the Horizon +//! version, the platform and whether a LAN or play-with-friends world is open. The game sends +//! one every [`INTERVAL`]; the server counts a session while its last ping is under +//! [`WINDOW`] old, keeps nothing on disk and serves the counts rounded ([`round`]). +use std::collections::BTreeMap; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; + +/// How often the game pings while it runs. +pub const INTERVAL: Duration = Duration::from_secs(60); + +/// How long a session counts after its last ping: two pings, so one lost on the way doesn't +/// drop it. +pub const WINDOW: Duration = Duration::from_secs(120); + +/// The platforms a ping may name; anything else is `other`. +pub const PLATFORMS: [&str; 4] = ["linux", "macos", "windows", "other"]; + +/// The largest ping body the server reads. +pub const MAX_PING_BYTES: usize = 512; + +const MAX_VERSION: usize = 40; + +/// One "I'm playing", as it is sent: `{"session":"…","version":"…","platform":"…","lan":false}`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Ping { + /// 128 random bits in hex, made when the game starts ([`session_id`]) and never written down. + pub session: String, + /// The release (`v2026.10.15`, `0.2.0`) or `dev 0.1.0` for a build from source. + pub version: String, + /// One of [`PLATFORMS`]. + pub platform: String, + /// A world is open to LAN or to friends over the internet. + pub lan: bool, +} + +impl Ping { + pub fn new(session: &str, version: &str, lan: bool) -> Self { + Self { + session: session.to_owned(), + version: version.to_owned(), + platform: platform().to_owned(), + lan, + } + } + + /// Why the server refuses this ping, if it does. + pub fn check(&self) -> Result<(), &'static str> { + if !crate::consent::is_install_id(&self.session) { + return Err("session: 32 lowercase hex digits"); + } + let version_ok = !self.version.is_empty() + && self.version.len() <= MAX_VERSION + && self + .version + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b" .+-_".contains(&b)); + if !version_ok { + return Err("version: at most 40 letters, digits, spaces and .+-_"); + } + if !PLATFORMS.contains(&self.platform.as_str()) { + return Err("platform: linux, macos, windows or other"); + } + Ok(()) + } +} + +/// A new session ID: 128 random bits in hex. +pub fn session_id() -> String { + crate::random_hex(16) +} + +/// This machine's entry in [`PLATFORMS`]. +pub fn platform() -> &'static str { + match std::env::consts::OS { + os @ ("linux" | "macos" | "windows") => os, + _ => "other", + } +} + +/// The live count, as `GET /v1/live` serves it: every number already [`round`]ed. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Count { + /// Sessions that pinged within the window. + pub playing: u64, + /// Of those, the ones with a LAN or play-with-friends world open. + pub lan: u64, + /// Per version: the most played ones, the rest summed under `other`. + pub versions: BTreeMap, + /// Per platform. + pub platforms: BTreeMap, +} + +/// Rounds a count for showing: exact under 10, then to the nearest 5 under 100, the nearest 10 +/// under 1000 and the nearest 100 above. Small numbers stay true; large ones don't pretend to +/// a precision a two-minute window doesn't have. +pub fn round(n: u64) -> u64 { + let step = match n { + 0..10 => return n, + 10..100 => 5, + 100..1000 => 10, + _ => 100, + }; + (n + step / 2) / step * step +} + +/// Sends `ping` to `endpoint` (`https://host`, without a trailing slash). +#[cfg(feature = "live")] +pub fn send(endpoint: &str, ping: &Ping) -> Result<(), String> { + agent() + .post(&format!("{endpoint}/v1/live")) + .set("Content-Type", "application/json") + .send_string(&serde_json::to_string(ping).map_err(|e| e.to_string())?) + .map(drop) + .map_err(|e| e.to_string()) +} + +/// The live count at `endpoint`. +#[cfg(feature = "live")] +pub fn fetch(endpoint: &str) -> Result { + let body = agent() + .get(&format!("{endpoint}/v1/live")) + .call() + .map_err(|e| e.to_string())? + .into_string() + .map_err(|e| e.to_string())?; + serde_json::from_str(&body).map_err(|e| e.to_string()) +} + +#[cfg(feature = "live")] +fn agent() -> ureq::Agent { + ureq::AgentBuilder::new() + .timeout(Duration::from_secs(5)) + .build() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ping() -> Ping { + Ping::new(&session_id(), "v2026.10.15", false) + } + + #[test] + fn a_ping_holds_only_the_four_fields() { + let json = serde_json::to_value(Ping::new(&"a".repeat(32), "0.2.0", true)).unwrap(); + let mut keys: Vec<&str> = json + .as_object() + .unwrap() + .keys() + .map(|k| k.as_str()) + .collect(); + keys.sort_unstable(); + assert_eq!(keys, ["lan", "platform", "session", "version"]); + assert!(serde_json::to_string(&ping()).unwrap().len() < MAX_PING_BYTES); + } + + #[test] + fn session_ids_are_fresh_each_time() { + let (a, b) = (session_id(), session_id()); + assert_ne!(a, b); + assert!(ping().check().is_ok()); + } + + #[test] + fn bad_pings_are_refused() { + let bad = |f: fn(&mut Ping)| { + let mut p = ping(); + f(&mut p); + p.check().is_err() + }; + assert!(bad(|p| p.session = "ABC".into())); + assert!(bad(|p| p.session = "G".repeat(32))); + assert!(bad(|p| p.version = String::new())); + assert!(bad(|p| p.version = "1".repeat(41))); + assert!(bad(|p| p.version = "