diff --git a/AGENTS.md b/AGENTS.md index e1fa9e7fe..489a1466b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,8 @@ Feature → files → harness for the most-changed areas: [docs/architecture.md] `tools/check_public_tree.py` rejects them; `git config core.hooksPath .githooks` runs it on commit. - **Keep your runs away from real player data.** Any game or launcher you start gets fresh `mktemp -d` folders in `HORIZON_HOME` (the game's data), `HORIZON_LAUNCHER_HOME`, `XDG_DATA_HOME` and - `XDG_CONFIG_HOME`, plus `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` and `HORIZON_NO_AUDIO=1`. Never write to + `XDG_CONFIG_HOME`, plus `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` and `HORIZON_NO_AUDIO=1`, and, for the + launcher, `HORIZON_LAUNCHER_TRASH` and `HORIZON_LAUNCHER_CLIPBOARD` pointing into the scratch home. Never write to `~/.local/share/{applications,horizon,horizon-launcher}` or `~/.local/bin`. - **Mark what an agent posts.** A PR body starts with a line naming whose agent opened it and with what. Ludovic's agents write `> 🤖 Opened by Ludovic's AI agent (Claude), not by Ludovic himself.`, and a @@ -34,7 +35,9 @@ Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-se | Crate | Owns | |---|---| -| `horizon-client` | The game: a lib (`src/lib.rs`, ~190 flat modules) and the bin (`src/main.rs` → `game.rs` + `game/`), plus `horizon-ctl` (`src/bin/horizon-ctl/`). Also the dedicated server (`--dedicated`) | +| `horizon-client` | The game: a lib (`src/lib.rs`, ~180 flat modules) and the bin (`src/main.rs` → `game.rs` + `game/`), plus `horizon-ctl` (`src/bin/horizon-ctl/`). Also the dedicated server (`--dedicated`) | +| `horizon-command` | Command parsing (Brigadier): the vanilla tree, argument types, selectors, suggestions, the tree's network form. Re-exported as `horizon_client::command` | +| `horizon-client-core` | The client lib's bottom layer: `text.rs`, `lang.rs`, `snbt.rs`, `nbt_path.rs`, `component.rs`, `scoreboard.rs`, `bossbar.rs`, `gamerules.rs`, `block_entity_nbt.rs`, registry/particle/sound tables. Re-exported under the old paths (`horizon_client::text`...) | | `horizon-world` | Vanilla world data with no gameplay loop: NBT, regions, chunks, `datafix/`, `worldgen/`, `level/` (server-side block behaviour, ticks, redstone), entity physics, items, effects, food, damage | | `horizon-core` | Simulation primitives: Java `Random`s, `jmath` (HotSpot-exact `Math`), positions, noise, density, paletted storage, `version.rs` (the pinned version) | | `horizon-protocol` | Network protocol 777: codecs, framing, encryption, `packets/{handshake,status,login,configuration,play}.rs`, `entity_data.rs` | @@ -118,16 +121,16 @@ python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end | Other entities | L: `entities.rs`, `projectiles.rs`, `arrows.rs`; G: `boats.rs`, `minecarts.rs`, `mounts.rs`, `armor_stands.rs`, `paintings.rs`, `frames.rs`, `fireworks.rs`, `tnt.rs`, `explosion.rs` | | Player actions | game.rs (`fn use_hand`, `fn use_item`, `fn attack`, `fn tick_mining`, `fn break_block`); G: `hand.rs`, `combat.rs`, `consume.rs`, `potions.rs`, `shield.rs`, `crossbow.rs`, `trident.rs`, `fishing.rs`; L: `motion.rs` + `motion/` (movement), `collisions.rs`, `items.rs`, `item_data.rs` | | Inventory and containers | L: `menu.rs` (`AbstractContainerMenu.clicked`), `container_screen.rs`, `containers.rs`, `creative.rs`, `crafting.rs`, `recipe_book*.rs`, `stations.rs`, `merchant.rs`; game.rs `fn menu_ops`, `fn click_inventory`; G: `stations.rs`, `trading.rs`, `recipe_book.rs`, `machines.rs` | -| Commands | parse: L: `command/` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`); run: G: `commands.rs` (dispatch) + `commands/*.rs` (`admin`, `execute`, `items`, `players`, `world_cmds`...); L: `scoreboard_cmd.rs`, `data_cmd.rs`, `nbt_path.rs`; G: `functions.rs`, `command_blocks.rs` | +| Commands | parse: crate `horizon-command` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`); run: G: `commands.rs` (dispatch) + `commands/*.rs` (`admin`, `execute`, `items`, `players`, `world_cmds`...); L: `scoreboard_cmd.rs`, `data_cmd.rs`; `horizon-client-core`: `nbt_path.rs`, `scoreboard.rs`; G: `functions.rs`, `command_blocks.rs` | | UI screens | `Screen` enum in game.rs; L: `title.rs` + `title/`, `options_ui.rs`, `multiplayer.rs`, `pack_screen.rs`, `graphics_ui.rs`, `screen_draw.rs`, `ui.rs` (widgets), `hud.rs`, `hud_layout.rs`, `hud_overlays.rs`, `chat.rs`, `tab_list.rs`; G: `startup_menu.rs`, `screens.rs` (pause, death), `options.rs`, `lan_screen.rs`, `chat.rs`, `sign_edit.rs`, `books.rs` | | Multiplayer client | L: `net.rs` (network thread); G: `remote.rs` (`fn handle_packet`, `fn tick_remote`), `remote_*.rs` (mob data, objects, projectiles, vehicles, stations) | | LAN host / server side | L: `lan/` (`conn.rs` handshake + login threads, `hub.rs` + `hub/` play state, `chunks.rs`, `entity.rs`, `tracking.rs`, `guest.rs`, `playerdata.rs`); G: `lan.rs` (`LanHost`), `lan_actions.rs` (`fn as_guest`, `fn tick_guests`), `lan_*.rs` per feature, `lan_entities.rs` (tracked entities) | | Integrated server | G: `integrated.rs` (the server thread), `levels.rs` (one level per dimension, `fn tick_server`), `server_travel.rs` | | Dedicated server | G: `dedicated.rs`, `dedicated/status.rs`; crates `horizon-server-files`, `horizon-server` | -| Save and load | L: `save.rs` (level.dat, regions, playerdata), `entity_nbt.rs`, `block_entity_nbt.rs`, `options_file.rs`; G: `saving.rs`, `persist.rs` (entities); `crates/horizon-world/src/{region.rs,nbt.rs,datafix/}` | +| Save and load | L: `save.rs` (level.dat, regions, playerdata), `entity_nbt.rs`, `options_file.rs`; `horizon-client-core/src/block_entity_nbt.rs`; G: `saving.rs`, `persist.rs` (entities); `crates/horizon-world/src/{region.rs,nbt.rs,datafix/}` | | Input | game.rs `fn window_event`, `fn key_pressed`, `fn play_mouse`; L: `keybinds.rs`, `keymapping.rs`, `key_names.rs`, `mouse.rs`, `input.rs`, `interaction_input.rs`, `gamepad.rs`, `osk.rs`, `clipboard.rs`; G: `pad.rs`, `pad_menu.rs` | | Audio | L: `audio.rs` (mixer), `sound_engine.rs`, `sound_events.rs`, `music.rs`, `ambience.rs`; G: `music.rs`, `subtitle_hud.rs` | -| Resource packs | L: `packs.rs` + `packs/`, `pack_screen.rs`, `atlas_sources.rs`, `sprites.rs`, `mipmap.rs`, `model_library.rs`, `font.rs`, `lang.rs`; crate `horizon-assets`; G: `packs.rs` | +| Resource packs | L: `packs.rs` + `packs/`, `pack_screen.rs`, `atlas_sources.rs`, `sprites.rs`, `mipmap.rs`, `model_library.rs`, `font.rs`; `horizon-client-core/src/lang.rs`; crate `horizon-assets`; G: `packs.rs` | | Agent control | L: `control.rs` (socket), `bin/horizon-ctl/`; G: `control.rs`, `agent.rs`, `events.rs`, `ui_control.rs` ([docs/agent-control.md](docs/agent-control.md)) | | Mods | crate `horizon-mods`; G: `mods.rs`; L: `mod_content.rs`, `mod_list.rs` | | Horizon extras, settings | L: `extras.rs`, `graphics.rs`, `settings.rs`, `minimap.rs`; G: `extras.rs`, `tweaks.rs`, `options.rs` | diff --git a/Cargo.lock b/Cargo.lock index 46ee9c316..0e0a39038 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1372,6 +1372,8 @@ dependencies = [ "glam", "horizon-assets", "horizon-bench", + "horizon-client-core", + "horizon-command", "horizon-core", "horizon-dualsense", "horizon-friends", @@ -1403,6 +1405,23 @@ dependencies = [ "zip", ] +[[package]] +name = "horizon-client-core" +version = "0.1.0" +dependencies = [ + "horizon-world", + "serde_json", +] + +[[package]] +name = "horizon-command" +version = "0.1.0" +dependencies = [ + "horizon-client-core", + "horizon-protocol", + "horizon-world", +] + [[package]] name = "horizon-core" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index f0529d098..933901dce 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,45 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"] -members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-hdr", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "crates/horizon-mod-sdk/examples/beacons", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask", "mods/official/recipes"] +members = [ + "crates/horizon-core", + "crates/horizon-dualsense", + "crates/horizon-threads", + "crates/horizon-hdr", + "crates/horizon-world", + "crates/horizon-client", + "crates/horizon-client-core", + "crates/horizon-command", + "crates/horizon-server-files", + "crates/horizon-server", + "crates/horizon-bots", + "crates/horizon-assets", + "crates/horizon-protocol", + "crates/horizon-theme", + "crates/horizon-prepare", + "crates/horizon-telemetry", + "crates/horizon-bench", + "crates/horizon-friends", + "crates/horizon-relay", + "crates/horizon-mod-sdk", + "crates/horizon-mods", + "crates/horizon-mods/tests/guest", + "crates/horizon-mods/tests/ui_guest", + "crates/cargo-horizon-mod", + "crates/horizon-port-pack", + "crates/horizon-shaders", + "crates/horizon-shader-api", + "crates/horizon-release-sign", + "crates/horizon-mod-sdk/examples/coords-hud", + "crates/horizon-mod-sdk/examples/predator-missile", + "crates/horizon-mod-sdk/examples/welcome", + "crates/horizon-mod-sdk/examples/beacons", + "mods/official/fps-overlay", + "mods/official/keystrokes", + "mods/official/minimap", + "mods/official/zoom", + "xtask", + "mods/official/recipes", +] resolver = "2" [workspace.package] diff --git a/crates/cargo-horizon-mod/src/check.rs b/crates/cargo-horizon-mod/src/check.rs index f95fbe4dc..988ba826d 100644 --- a/crates/cargo-horizon-mod/src/check.rs +++ b/crates/cargo-horizon-mod/src/check.rs @@ -200,7 +200,7 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> { return Err(format!("it didn't start: {reason}")); } let client: Vec = mods.commands().map(str::to_owned).collect(); - let server: Vec = mods.server_commands().map(str::to_owned).collect(); + let server: Vec = mods.server_commands().map(|c| c.name.clone()).collect(); report.commands = [client.clone(), server.clone()].concat(); // A server mod plays with one player on, who joins, chats and leaves. let steve = ServerPlayer { diff --git a/crates/horizon-client-core/Cargo.toml b/crates/horizon-client-core/Cargo.toml new file mode 100644 index 000000000..8809a5216 --- /dev/null +++ b/crates/horizon-client-core/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "horizon-client-core" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version = "1.90" +description = "The client's lowest layer: chat text and translations, SNBT and NBT paths, the scoreboard, boss bars, game rules and the registry and particle tables commands name" + +[dependencies] +horizon-world = { path = "../horizon-world" } +serde_json = { version = "1.0.151", features = ["raw_value"] } + +[lints] +workspace = true diff --git a/crates/horizon-client/src/block_entity_nbt.rs b/crates/horizon-client-core/src/block_entity_nbt.rs similarity index 99% rename from crates/horizon-client/src/block_entity_nbt.rs rename to crates/horizon-client-core/src/block_entity_nbt.rs index a4c02ba3b..6e214fd61 100644 --- a/crates/horizon-client/src/block_entity_nbt.rs +++ b/crates/horizon-client-core/src/block_entity_nbt.rs @@ -259,7 +259,7 @@ fn is_pos(tag: &Tag) -> bool { matches!(tag, Tag::IntArray(v) if v.len() == 3) } /// The loaded `SignText` of one side, or the empty text. -pub(crate) fn sign_side(tag: Option<&Tag>) -> Tag { +pub fn sign_side(tag: Option<&Tag>) -> Tag { let empty = || string(""); let mut messages: Vec = match tag.and_then(|t| t.get("messages")) { Some(Tag::List(list)) => list.iter().filter_map(component).collect(), diff --git a/crates/horizon-client/src/bossbar.rs b/crates/horizon-client-core/src/bossbar.rs similarity index 100% rename from crates/horizon-client/src/bossbar.rs rename to crates/horizon-client-core/src/bossbar.rs diff --git a/crates/horizon-client/src/component.rs b/crates/horizon-client-core/src/component.rs similarity index 99% rename from crates/horizon-client/src/component.rs rename to crates/horizon-client-core/src/component.rs index fced49898..5b828b305 100644 --- a/crates/horizon-client/src/component.rs +++ b/crates/horizon-client-core/src/component.rs @@ -252,7 +252,7 @@ pub fn to_text_with( } else if let Some(sel) = o.get("selector").and_then(Value::as_str) { resolve(sel) } else if let Some(key) = o.get("keybind").and_then(Value::as_str) { - crate::keybinds::display_name(key) + crate::key_display::display_name(key) } else { Text::empty() }; diff --git a/crates/horizon-client/src/fastutil_order.rs b/crates/horizon-client-core/src/fastutil_order.rs similarity index 100% rename from crates/horizon-client/src/fastutil_order.rs rename to crates/horizon-client-core/src/fastutil_order.rs diff --git a/crates/horizon-client/src/gamerules.rs b/crates/horizon-client-core/src/gamerules.rs similarity index 90% rename from crates/horizon-client/src/gamerules.rs rename to crates/horizon-client-core/src/gamerules.rs index 7198fd202..6715e01ec 100644 --- a/crates/horizon-client/src/gamerules.rs +++ b/crates/horizon-client-core/src/gamerules.rs @@ -292,27 +292,4 @@ mod tests { assert_eq!(GameRules::load(&dir), rules); let _ = fs::remove_dir_all(dir); } - /// The world's save (Level.write) writes the rules as they are now, and a - /// world opened again reads them back (#74). - #[test] - fn level_save_keeps_changed_rules() { - let dir = - std::env::temp_dir().join(format!("horizon-gamerules-level-{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - let mut level = crate::save::Level::default(); - level.write(&dir).unwrap(); - // Rules changed while playing, then saved and loaded again. - let mut rules = GameRules::load(&dir); - assert_eq!(rules, GameRules::default()); - assert!(rules.set("advance_time", Value::Bool(false))); - assert!(rules.set("advance_weather", Value::Bool(false))); - assert!(rules.set("random_tick_speed", Value::Int(0))); - level.game_rules = rules.by_name(); - level.write(&dir).unwrap(); - assert_eq!(GameRules::load(&dir), rules); - let read = crate::save::Level::read(&dir).unwrap(); - assert_eq!(read.game_rules, rules.by_name()); - assert_eq!(read.game_rule("advance_time"), 0); - let _ = fs::remove_dir_all(dir); - } } diff --git a/crates/horizon-client-core/src/identifier.rs b/crates/horizon-client-core/src/identifier.rs new file mode 100644 index 000000000..1e76f7731 --- /dev/null +++ b/crates/horizon-client-core/src/identifier.rs @@ -0,0 +1,18 @@ +//! Resource identifiers (`Identifier`). + +/// Identifier.parse: `ns:path` or `path`, validated. +pub fn parse_identifier(raw: &str) -> Option { + let (ns, path) = match raw.split_once(':') { + Some(("", path)) => ("minecraft", path), + Some((ns, path)) => (ns, path), + None => ("minecraft", raw), + }; + let ns_ok = ns != ".." + && ns + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-')); + let path_ok = path.chars().all(|c| { + c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/') + }); + (ns_ok && path_ok).then(|| format!("{ns}:{path}")) +} diff --git a/crates/horizon-client-core/src/key_display.rs b/crates/horizon-client-core/src/key_display.rs new file mode 100644 index 000000000..fc57c97bd --- /dev/null +++ b/crates/horizon-client-core/src/key_display.rs @@ -0,0 +1,38 @@ +//! Key display names (`InputConstants.Key.getDisplayName`), shared by key +//! mappings and `keybind` text components. +use crate::text::Text; + +/// InputConstants.Key.getDisplayName: one-character keys as the upper-case +/// character, others by translation. +pub fn display_name(key: &str) -> Text { + if let Some(rest) = key.strip_prefix("key.keyboard.") + && rest.chars().count() == 1 + { + let c = rest.to_uppercase(); + return Text::literal(c); + } + let symbol = match key { + "key.keyboard.minus" => Some("-"), + "key.keyboard.equal" => Some("="), + "key.keyboard.left.bracket" => Some("["), + "key.keyboard.right.bracket" => Some("]"), + "key.keyboard.backslash" => Some("\\"), + "key.keyboard.semicolon" => Some(";"), + "key.keyboard.apostrophe" => Some("'"), + "key.keyboard.grave.accent" => Some("`"), + "key.keyboard.comma" => Some(","), + "key.keyboard.period" => Some("."), + "key.keyboard.slash" => Some("/"), + _ => None, + }; + if let Some(s) = symbol { + return Text::literal(s); + } + if let Some(n) = key.strip_prefix("key.mouse.") + && n.parse::().is_ok() + && !crate::lang::has(key) + { + return Text::translate("key.mouse", &[Text::literal(n)]); + } + Text::translate(key, &[]) +} diff --git a/crates/horizon-client/src/lang.rs b/crates/horizon-client-core/src/lang.rs similarity index 96% rename from crates/horizon-client/src/lang.rs rename to crates/horizon-client-core/src/lang.rs index cb96cc373..6213cedc8 100644 --- a/crates/horizon-client/src/lang.rs +++ b/crates/horizon-client-core/src/lang.rs @@ -42,8 +42,12 @@ struct Bundled; impl ResourceSource for Bundled { fn read(&self, path: &str) -> Option> { let body = match path { - "assets/horizon/lang/en_us.json" => include_str!("../assets/horizon/lang/en_us.json"), - "assets/horizon/lang/ru_ru.json" => include_str!("../assets/horizon/lang/ru_ru.json"), + "assets/horizon/lang/en_us.json" => { + include_str!("../../horizon-client/assets/horizon/lang/en_us.json") + } + "assets/horizon/lang/ru_ru.json" => { + include_str!("../../horizon-client/assets/horizon/lang/ru_ru.json") + } _ => return None, }; Some(body.as_bytes().to_vec()) diff --git a/crates/horizon-client-core/src/lib.rs b/crates/horizon-client-core/src/lib.rs new file mode 100644 index 000000000..ca40141d1 --- /dev/null +++ b/crates/horizon-client-core/src/lib.rs @@ -0,0 +1,23 @@ +//! The client's lowest layer, below commands and gameplay: chat text and +//! translations, SNBT and NBT paths, text components, the scoreboard, boss +//! bars, game rules, block entity NBT tables, and the registry, particle and +//! sound source tables commands name. horizon-client re-exports each module +//! under its old path (`horizon_client::text`, ...). +#![forbid(unsafe_code)] +pub mod block_entity_nbt; +pub mod bossbar; +pub mod component; +pub mod fastutil_order; +pub mod gamerules; +pub mod identifier; +pub mod key_display; +pub mod lang; +pub mod nbt_path; +pub mod particle_type; +pub mod registries; +pub mod scoreboard; +pub mod snbt; +pub mod sound_source; +pub mod text; +pub mod uuid; +pub type Result = std::result::Result>; diff --git a/crates/horizon-client/src/nbt_path.rs b/crates/horizon-client-core/src/nbt_path.rs similarity index 100% rename from crates/horizon-client/src/nbt_path.rs rename to crates/horizon-client-core/src/nbt_path.rs diff --git a/crates/horizon-client-core/src/particle_type.rs b/crates/horizon-client-core/src/particle_type.rs new file mode 100644 index 000000000..98de2380b --- /dev/null +++ b/crates/horizon-client-core/src/particle_type.rs @@ -0,0 +1,209 @@ +//! Particle types (`ParticleTypes`): the vanilla particle types with a client +//! implementation, by registry name, and their per-type flags. + +macro_rules! particle_types { + ($($variant:ident = $name:literal),* $(,)?) => { + /// Vanilla particle types with a client implementation here. + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] + pub enum ParticleType { $($variant),* } + impl ParticleType { + pub const ALL: &'static [ParticleType] = &[$(ParticleType::$variant),*]; + /// Registry path (`minecraft:`), also the sprite-set file name. + pub fn name(self) -> &'static str { + match self { $(ParticleType::$variant => $name),* } + } + pub fn from_name(name: &str) -> Option { + let name = name.strip_prefix("minecraft:").unwrap_or(name); + match name { $($name => Some(ParticleType::$variant),)* _ => None } + } + } + }; +} +particle_types! { + Block = "block", + BlockCrumble = "block_crumble", + Trail = "trail", + DustPillar = "dust_pillar", + FallingDust = "falling_dust", + Smoke = "smoke", + LargeSmoke = "large_smoke", + WhiteSmoke = "white_smoke", + Flame = "flame", + SoulFireFlame = "soul_fire_flame", + CopperFireFlame = "copper_fire_flame", + SmallFlame = "small_flame", + Lava = "lava", + DrippingWater = "dripping_water", + FallingWater = "falling_water", + DrippingLava = "dripping_lava", + FallingLava = "falling_lava", + LandingLava = "landing_lava", + DrippingHoney = "dripping_honey", + FallingHoney = "falling_honey", + LandingHoney = "landing_honey", + FallingNectar = "falling_nectar", + FallingSporeBlossom = "falling_spore_blossom", + SporeBlossomAir = "spore_blossom_air", + DrippingObsidianTear = "dripping_obsidian_tear", + FallingObsidianTear = "falling_obsidian_tear", + LandingObsidianTear = "landing_obsidian_tear", + DrippingDripstoneWater = "dripping_dripstone_water", + FallingDripstoneWater = "falling_dripstone_water", + DrippingDripstoneLava = "dripping_dripstone_lava", + FallingDripstoneLava = "falling_dripstone_lava", + Splash = "splash", + Rain = "rain", + Bubble = "bubble", + SulfurBubbles = "sulfur_bubbles", + BubblePop = "bubble_pop", + BubbleColumnUp = "bubble_column_up", + CurrentDown = "current_down", + Underwater = "underwater", + Portal = "portal", + ReversePortal = "reverse_portal", + Enchant = "enchant", + Nautilus = "nautilus", + VaultConnection = "vault_connection", + Crit = "crit", + EnchantedHit = "enchanted_hit", + DamageIndicator = "damage_indicator", + Heart = "heart", + AngryVillager = "angry_villager", + HappyVillager = "happy_villager", + Composter = "composter", + Mycelium = "mycelium", + Dolphin = "dolphin", + EggCrack = "egg_crack", + Poof = "poof", + Explosion = "explosion", + ExplosionEmitter = "explosion_emitter", + CampfireCosySmoke = "campfire_cosy_smoke", + CampfireSignalSmoke = "campfire_signal_smoke", + Note = "note", + Dust = "dust", + TotemOfUndying = "totem_of_undying", + Firework = "firework", + EndRod = "end_rod", + Ash = "ash", + WhiteAsh = "white_ash", + CrimsonSpore = "crimson_spore", + WarpedSpore = "warped_spore", + CherryLeaves = "cherry_leaves", + PaleOakLeaves = "pale_oak_leaves", + TintedLeaves = "tinted_leaves", + Effect = "effect", + InstantEffect = "instant_effect", + EntityEffect = "entity_effect", + Witch = "witch", + Infested = "infested", + Cloud = "cloud", + Sneeze = "sneeze", + Snowflake = "snowflake", + Soul = "soul", + SculkSoul = "sculk_soul", + DragonBreath = "dragon_breath", + Gust = "gust", + SmallGust = "small_gust", + GustEmitterLarge = "gust_emitter_large", + GustEmitterSmall = "gust_emitter_small", + DustColorTransition = "dust_color_transition", + SculkCharge = "sculk_charge", + SculkChargePop = "sculk_charge_pop", + Shriek = "shriek", + SonicBoom = "sonic_boom", + Vibration = "vibration", + SweepAttack = "sweep_attack", + Glow = "glow", + WaxOn = "wax_on", + WaxOff = "wax_off", + ElectricSpark = "electric_spark", + Scrape = "scrape", + SquidInk = "squid_ink", + GlowSquidInk = "glow_squid_ink", + Item = "item", + ItemSlime = "item_slime", + ItemSnowball = "item_snowball", + ItemCobweb = "item_cobweb", + SulfurCubeGoo = "sulfur_cube_goo", + Flash = "flash", + Firefly = "firefly", + TrialSpawnerDetection = "trial_spawner_detection", + TrialSpawnerDetectionOminous = "trial_spawner_detection_ominous", + TrialOmen = "trial_omen", + RaidOmen = "raid_omen", + OminousSpawning = "ominous_spawning", + Spit = "spit", + Fishing = "fishing", + DustPlume = "dust_plume", + RedPoplarLeaves = "red_poplar_leaves", + OrangePoplarLeaves = "orange_poplar_leaves", + YellowPoplarLeaves = "yellow_poplar_leaves", + PauseMobGrowth = "pause_mob_growth", + ResetMobGrowth = "reset_mob_growth", + BlockMarker = "block_marker", +} +impl ParticleType { + /// `ParticleType.getOverrideLimiter` (`ParticleTypes.register(name, true)`): + /// spawned regardless of distance. + pub fn override_limiter(self) -> bool { + matches!( + self, + Self::BlockMarker + | Self::DamageIndicator + | Self::ExplosionEmitter + | Self::Explosion + | Self::Gust + | Self::GustEmitterLarge + | Self::GustEmitterSmall + | Self::SonicBoom + | Self::SculkCharge + | Self::SculkChargePop + | Self::Vibration + | Self::Poof + | Self::Spit + | Self::SquidInk + | Self::SweepAttack + | Self::CampfireCosySmoke + | Self::CampfireSignalSmoke + | Self::GlowSquidInk + | Self::Glow + | Self::WaxOn + | Self::WaxOff + | Self::ElectricSpark + | Self::Scrape + | Self::TrialSpawnerDetection + | Self::TrialSpawnerDetectionOminous + | Self::VaultConnection + | Self::OminousSpawning + ) + } + /// `SingleQuadParticle.Layer.translucent`: types whose vanilla particle class + /// hardcodes the translucent layer, drawn after translucent terrain. + /// `TerrainParticle`, `BreakingItemParticle` and `BlockMarker` resolve their + /// layer from the sprite instead (`Layer.bySprite`); see the `translucent` + /// sprite set on the engine. + pub fn translucent_layer(self) -> bool { + match self { + // CampfireSmokeParticle. + Self::CampfireCosySmoke | Self::CampfireSignalSmoke + // PlayerCloudParticle. + | Self::Cloud | Self::Sneeze + // SpellParticle. + | Self::Effect | Self::InstantEffect | Self::EntityEffect + | Self::Witch | Self::Infested | Self::TrialOmen | Self::RaidOmen + // EmissiveRisingParticle. + | Self::Soul | Self::SculkSoul + // SculkChargeParticle, SculkChargePopParticle, ShriekParticle, + // VibrationSignalParticle, FireflyParticle, OverlayParticle. + | Self::SculkCharge | Self::SculkChargePop | Self::Shriek + | Self::Vibration | Self::Firefly | Self::Flash + // SimpleAnimatedParticle and its subclasses: EndRodParticle, + // SparkParticle (firework), SquidInkParticle, TotemParticle. + | Self::EndRod | Self::Firework | Self::SquidInk | Self::GlowSquidInk + | Self::TotemOfUndying + // FlyTowardsPositionParticle: its LifetimeAlpha(0, 0.6, 0.25, 1) is not opaque. + | Self::VaultConnection => true, + _ => false, + } + } +} diff --git a/crates/horizon-client-core/src/registries.rs b/crates/horizon-client-core/src/registries.rs new file mode 100644 index 000000000..310115cf8 --- /dev/null +++ b/crates/horizon-client-core/src/registries.rs @@ -0,0 +1,188 @@ +//! Registry contents and source state that commands validate and complete +//! arguments against (what the server's registry access holds). +use std::collections::BTreeMap; + +/// Registry contents and source state used to validate and complete arguments. +#[derive(Clone, Debug, Default)] +pub struct Registries { + /// Permission level of the command source. + pub permission: u8, + pub items: Vec, + pub item_tags: Vec, + /// Block id -> (property, allowed values). + pub blocks: BTreeMap)>>, + pub block_tags: Vec, + /// Entity types that `summon` can create. + pub summonable: Vec, + /// Every entity type (selector `type=`). + pub entity_types: Vec, + pub effects: Vec, + pub enchantments: Vec, + pub structures: Vec, + pub biomes: Vec, + pub dimensions: Vec, + pub clocks: Vec, + pub timelines: Vec, + pub time_markers: Vec, + pub advancements: Vec, + /// Game rule name -> integer-valued. + pub game_rules: Vec<(String, bool)>, + pub players: Vec, + /// Scoreboard objective names, team names and tracked score holders. + pub objectives: Vec, + pub teams: Vec, + pub tracked: Vec, + /// Loaded datapack functions (`ns:path`) and function tags (`ns:path`). + pub functions: Vec, + /// `/data ... storage` ids. + pub storages: Vec, + /// Boss bar ids and datapack predicate ids. + pub bossbars: Vec, + pub predicates: Vec, + pub item_modifiers: Vec, + pub schedules: Vec, + pub stopwatches: Vec, + pub recipes: Vec, + pub sounds: Vec, + pub damage_types: Vec, + pub attributes: Vec, + pub loot_tables: Vec, + pub templates: Vec, + pub random_sequences: Vec, + pub datapacks_enabled: Vec, + pub datapacks_disabled: Vec, + pub function_tags: Vec, + /// The block the source is looking at (relevant coordinates). + pub target_block: Option<[i32; 3]>, + /// Every registry's element and tag ids (`minecraft:item` -> ...), as + /// the server's registry access and reloadable registries hold them. + pub by_registry: BTreeMap, + /// Blocks whose default state has a block entity. + pub block_entities: std::collections::BTreeSet, + /// Block tag -> member blocks. + pub block_tag_members: BTreeMap>, + /// Data component types with a codec (not transient). + pub persistent_components: Vec, + /// Recipes `/recipe` can give (not special). + pub learnable_recipes: Vec, + /// Advancement id -> criterion names. + pub advancement_criteria: BTreeMap>, + /// World clock -> time markers shown in commands. + pub clock_time_markers: BTreeMap>, + /// Trigger objectives the source may use (`/trigger` suggestions). + pub trigger_objectives: Vec, + /// Objectives with the `trigger` criterion -> holder -> whether its score is locked. + pub trigger_scores: BTreeMap>, +} +/// The ids and tag ids of one registry. +#[derive(Clone, Debug, Default)] +pub struct RegistryIds { + pub ids: Vec, + pub tags: Vec, +} +const EMPTY: &[String] = &[]; +impl Registries { + /// Fill what the game did not build itself from vanilla's exported + /// registries (`command-registries.json`, written by + /// `VanillaCommandParseOracle registries`): built-in registries such as + /// mob effects, data component types and dialogs, block entities and tag + /// members. Registries that data packs reload stay with the game. + pub fn fill_from_export(&mut self, r: &serde_json::Value) { + fn strings(v: &serde_json::Value) -> Vec { + v.as_array() + .map(|a| { + a.iter() + .filter_map(|x| x.as_str().map(str::to_owned)) + .collect() + }) + .unwrap_or_default() + } + let fill = |field: &mut Vec, key: &str| { + if field.is_empty() { + *field = strings(&r[key]); + } + }; + fill(&mut self.effects, "effects"); + fill(&mut self.enchantments, "enchantments"); + fill(&mut self.attributes, "attributes"); + fill(&mut self.damage_types, "damage_types"); + fill(&mut self.templates, "templates"); + fill(&mut self.persistent_components, "persistent_components"); + fill(&mut self.learnable_recipes, "learnable_recipes"); + const RELOADED: [&str; 5] = [ + "minecraft:advancement", + "minecraft:recipe", + "minecraft:loot_table", + "minecraft:predicate", + "minecraft:item_modifier", + ]; + for (name, entry) in r["by_registry"].as_object().into_iter().flatten() { + if RELOADED.contains(&name.as_str()) || self.by_registry.contains_key(name) { + continue; + } + self.by_registry.insert( + name.clone(), + RegistryIds { + ids: strings(&entry["ids"]), + tags: strings(&entry["tags"]), + }, + ); + } + if self.block_entities.is_empty() { + self.block_entities = strings(&r["block_entities"]).into_iter().collect(); + } + if self.block_tag_members.is_empty() { + for (tag, members) in r["block_tag_members"].as_object().into_iter().flatten() { + self.block_tag_members.insert(tag.clone(), strings(members)); + } + } + if self.clock_time_markers.is_empty() { + for (clock, markers) in r["clock_time_markers"].as_object().into_iter().flatten() { + self.clock_time_markers + .insert(clock.clone(), strings(markers)); + } + } + if self.advancement_criteria.is_empty() { + for (id, criteria) in r["advancement_criteria"].as_object().into_iter().flatten() { + self.advancement_criteria + .insert(id.clone(), strings(criteria)); + } + } + } + /// The element ids of a registry (sorted). + pub fn ids(&self, registry: &str) -> &[String] { + if let Some(r) = self.by_registry.get(registry) { + return &r.ids; + } + match registry { + "minecraft:item" => &self.items, + "minecraft:entity_type" => &self.entity_types, + "minecraft:mob_effect" => &self.effects, + "minecraft:enchantment" => &self.enchantments, + "minecraft:worldgen/structure" => &self.structures, + "minecraft:worldgen/biome" => &self.biomes, + "minecraft:world_clock" => &self.clocks, + "minecraft:timeline" => &self.timelines, + "minecraft:attribute" => &self.attributes, + "minecraft:damage_type" => &self.damage_types, + "minecraft:sound_event" => &self.sounds, + "minecraft:predicate" => &self.predicates, + "minecraft:item_modifier" => &self.item_modifiers, + "minecraft:loot_table" => &self.loot_tables, + "minecraft:recipe" => &self.recipes, + "minecraft:advancement" => &self.advancements, + _ => EMPTY, + } + } + /// The tag ids of a registry (sorted). + pub fn tags(&self, registry: &str) -> &[String] { + if let Some(r) = self.by_registry.get(registry) { + return &r.tags; + } + match registry { + "minecraft:item" => &self.item_tags, + "minecraft:block" => &self.block_tags, + _ => EMPTY, + } + } +} diff --git a/crates/horizon-client/src/scoreboard.rs b/crates/horizon-client-core/src/scoreboard.rs similarity index 99% rename from crates/horizon-client/src/scoreboard.rs rename to crates/horizon-client-core/src/scoreboard.rs index 4796be51a..3e820e4eb 100644 --- a/crates/horizon-client/src/scoreboard.rs +++ b/crates/horizon-client-core/src/scoreboard.rs @@ -2,9 +2,9 @@ //! `ObjectiveCriteria`, `NumberFormat`) and its saved data //! (`data/minecraft/scoreboard.dat`, `ScoreboardSaveData.Packed`). use crate::{ - command::Registries, component, fastutil_order::{HashSetOrder, OpenOrder}, + registries::Registries, text::{self, Style, Text}, }; use horizon_world::nbt::Tag; @@ -1266,7 +1266,7 @@ fn entity_uuids(tag: &mut Tag) { }) .collect::>>(), Tag::String(s) => { - crate::save::uuid_from_text(&s.to_string_lossy()).map(Vec::from) + crate::uuid::uuid_from_text(&s.to_string_lossy()).map(Vec::from) } _ => None, }; diff --git a/crates/horizon-client/src/snbt.rs b/crates/horizon-client-core/src/snbt.rs similarity index 100% rename from crates/horizon-client/src/snbt.rs rename to crates/horizon-client-core/src/snbt.rs diff --git a/crates/horizon-client-core/src/sound_source.rs b/crates/horizon-client-core/src/sound_source.rs new file mode 100644 index 000000000..d181d6ac5 --- /dev/null +++ b/crates/horizon-client-core/src/sound_source.rs @@ -0,0 +1,7 @@ +//! Sound sources (`SoundSource`), by name. + +/// SoundSource names in vanilla order. +pub const SOUND_SOURCES: [&str; 11] = [ + "master", "music", "record", "weather", "block", "hostile", "neutral", "player", "ambient", + "voice", "ui", +]; diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client-core/src/text.rs similarity index 99% rename from crates/horizon-client/src/text.rs rename to crates/horizon-client-core/src/text.rs index 4c04c9da5..0a2b6eadb 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client-core/src/text.rs @@ -67,7 +67,7 @@ pub struct Style { } /// A style's `font` field: an identifier (`alt` is `minecraft:alt`). pub fn font_id(v: &Value) -> Option { - crate::command::args::parse_identifier(v.as_str()?) + crate::identifier::parse_identifier(v.as_str()?) } impl Style { pub fn color(c: u32) -> Self { diff --git a/crates/horizon-client-core/src/uuid.rs b/crates/horizon-client-core/src/uuid.rs new file mode 100644 index 000000000..4ede9b141 --- /dev/null +++ b/crates/horizon-client-core/src/uuid.rs @@ -0,0 +1,24 @@ +//! UUIDs as vanilla's four-int form, to and from their text form. + +pub fn uuid_text(u: [i32; 4]) -> String { + let hex: String = u.iter().map(|v| format!("{:08x}", *v as u32)).collect(); + format!( + "{}-{}-{}-{}-{}", + &hex[0..8], + &hex[8..12], + &hex[12..16], + &hex[16..20], + &hex[20..32] + ) +} +pub fn uuid_from_text(s: &str) -> Option<[i32; 4]> { + let hex: String = s.chars().filter(|c| *c != '-').collect(); + if hex.len() != 32 { + return None; + } + let mut out = [0i32; 4]; + for (i, v) in out.iter_mut().enumerate() { + *v = u32::from_str_radix(&hex[i * 8..i * 8 + 8], 16).ok()? as i32; + } + Some(out) +} diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index f1011c534..5611edbc9 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -9,6 +9,8 @@ description = "Horizon native development client" [dependencies] horizon-assets = { path = "../horizon-assets" } +horizon-client-core = { path = "../horizon-client-core" } +horizon-command = { path = "../horizon-command" } horizon-core = { path = "../horizon-core" } # The server thread ahead of the workers (MinecraftServer.spin's Thread.setPriority). horizon-threads = { path = "../horizon-threads" } diff --git a/crates/horizon-client/examples/probe/arrow_probe.rs b/crates/horizon-client/examples/probe/arrow_probe.rs index f72e6276e..411561c4e 100644 --- a/crates/horizon-client/examples/probe/arrow_probe.rs +++ b/crates/horizon-client/examples/probe/arrow_probe.rs @@ -163,6 +163,8 @@ pub fn main() -> Result<()> { ArrowSound::HitGround => "hit", ArrowSound::Splash => "splash", ArrowSound::Extinguish => "extinguish", + ArrowSound::TridentHitGround => "trident_hit_ground", + ArrowSound::TridentHit => "trident_hit", }, volume.to_bits(), pitch.to_bits() diff --git a/crates/horizon-client/examples/probe/entity_anim_fixture.rs b/crates/horizon-client/examples/probe/entity_anim_fixture.rs index 4aceb9f6f..4582033fe 100644 --- a/crates/horizon-client/examples/probe/entity_anim_fixture.rs +++ b/crates/horizon-client/examples/probe/entity_anim_fixture.rs @@ -592,6 +592,7 @@ pub fn main() -> horizon_client::Result<()> { pose, num("maxCrossbowChageDuration"), num("ticksUsingItem"), + false, ); } Species::Evoker | Species::Illusioner | Species::Pillager | Species::Vindicator => { diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index 28b28544b..0e0a3319b 100644 --- a/crates/horizon-client/src/animate_tick.rs +++ b/crates/horizon-client/src/animate_tick.rs @@ -35,8 +35,9 @@ enum Animate { Campfire { spawn_particles: bool, }, - /// Leaves: optional falling-leaf particle and chance, tinted by foliage. - Leaves(Option<(T, f32)>), + /// Leaves: optional falling-leaf particle and chance; a tinted leaf takes + /// the biome foliage colour unless a fixed colour is given (azalea). + Leaves(Option<(T, f32)>, Option), NetherPortal, EnchantingTable, EndRod([i32; 3]), @@ -49,6 +50,8 @@ enum Animate { EnderChest, /// FallingBlock with its dust colour. Falling(u32), + /// A beehive or bee nest full of honey (`BeehiveBlock.animateTick`). + Beehive, RedstoneOre, RedstoneWire { power: u8, @@ -104,10 +107,17 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { spawn_particles: false, }, "oak_leaves" | "birch_leaves" | "jungle_leaves" | "acacia_leaves" | "dark_oak_leaves" - | "mangrove_leaves" => Animate::Leaves(Some((T::TintedLeaves, 0.01))), - "cherry_leaves" => Animate::Leaves(Some((T::CherryLeaves, 0.1))), - "pale_oak_leaves" => Animate::Leaves(Some((T::PaleOakLeaves, 0.02))), - "spruce_leaves" | "azalea_leaves" | "flowering_azalea_leaves" => Animate::Leaves(None), + | "mangrove_leaves" => Animate::Leaves(Some((T::TintedLeaves, 0.01)), None), + "cherry_leaves" => Animate::Leaves(Some((T::CherryLeaves, 0.1)), None), + "pale_oak_leaves" => Animate::Leaves(Some((T::PaleOakLeaves, 0.02)), None), + "red_poplar_leaves" => Animate::Leaves(Some((T::RedPoplarLeaves, 0.01)), None), + "orange_poplar_leaves" => Animate::Leaves(Some((T::OrangePoplarLeaves, 0.01)), None), + "yellow_poplar_leaves" => Animate::Leaves(Some((T::YellowPoplarLeaves, 0.01)), None), + // The azalea blocks drop tinted leaves of the fixed colour -9399763. + "azalea_leaves" | "flowering_azalea_leaves" => { + Animate::Leaves(Some((T::TintedLeaves, 0.01)), Some(0x0070_922D)) + } + "spruce_leaves" => Animate::Leaves(None, None), "nether_portal" => Animate::NetherPortal, "enchanting_table" => Animate::EnchantingTable, "end_rod" => Animate::EndRod(facing()), @@ -119,6 +129,14 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { "sand" => Animate::Falling(0xDBD3A0), "red_sand" => Animate::Falling(0xA95821), "gravel" => Animate::Falling(0x807C7B), + // AnvilBlock/ConcretePowderBlock.getDustColor is the map colour; + // DragonEggBlock's is black. + "anvil" | "chipped_anvil" | "damaged_anvil" => Animate::Falling(0xA7A7A7), + "dragon_egg" => Animate::Falling(0x000000), + _ if name.ends_with("_concrete_powder") => Animate::Falling(concrete_powder_color( + name.trim_end_matches("_concrete_powder"), + )), + "beehive" | "bee_nest" if prop("honey_level").as_deref() == Some("5") => Animate::Beehive, "redstone_ore" | "deepslate_redstone_ore" if lit => Animate::RedstoneOre, "redstone_wire" => { let power = prop("power").and_then(|p| p.parse().ok()).unwrap_or(0); @@ -161,6 +179,27 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { _ => Animate::None, } } +/// `DyeColor.getMapColor` of a concrete powder colour. +fn concrete_powder_color(dye: &str) -> u32 { + match dye { + "white" => 0xFFFFFF, + "orange" => 0xD87F33, + "magenta" => 0xB24CD8, + "light_blue" => 0x6699D8, + "yellow" => 0xE5E533, + "lime" => 0x7FCC19, + "pink" => 0xF27FA5, + "gray" => 0x4C4C4C, + "light_gray" => 0x999999, + "cyan" => 0x4C7F99, + "purple" => 0x7F3FB2, + "blue" => 0x334CB2, + "brown" => 0x664C33, + "green" => 0x667F33, + "red" => 0x993333, + _ => 0x191919, + } +} /// `RedstoneWireBlock.COLORS`. fn redstone_color(power: u8) -> [f32; 3] { let f = f32::from(power) / 15.0; @@ -504,6 +543,53 @@ fn try_spawn_drip( } } } +/// `BeehiveBlock.trySpawnDripParticles`. +fn beehive_drip( + tables: &AnimateTables, + engine: &mut ParticleEngine, + ctx: &AnimateContext, + state: BlockStateId, + pos: [i32; 3], +) { + if ctx.facts.get(state).fluid != Fluid::None || engine.random().next_float() < 0.3 { + return; + } + let Some((bottom, top, bounds)) = ctx.shape_y(pos) else { + return; + }; + if top < 1.0 + || tables + .impermeable + .get(state.0 as usize) + .copied() + .unwrap_or(false) + { + return; + } + let y = if bottom > 0.0 { + f64::from(pos[1]) + bottom - 0.05 + } else { + let below = [pos[0], pos[1] - 1, pos[2]]; + let below_top = ctx.shape_y(below).map_or(1.0, |s| s.1); + // `belowTop < 1 || !isCollisionShapeFullBlock` and no fluid below. + if (below_top < 1.0 || !ctx.sturdy(below)) + && ctx.facts.get(ctx.state(below)).fluid == Fluid::None + { + f64::from(pos[1]) - 0.05 + } else { + return; + } + }; + let r = engine.random(); + let (a, b) = (r.next_double(), r.next_double()); + let (fx, fz) = (f64::from(pos[0]), f64::from(pos[2])); + let p = [ + fx + bounds[0] + (bounds[1] - bounds[0]) * a, + y, + fz + bounds[2] + (bounds[3] - bounds[2]) * b, + ]; + add(engine, T::DrippingHoney, p, [0.0; 3]); +} /// `WaterFluid.animateTick` / `LavaFluid.animateTick`. fn fluid_animate_tick( engine: &mut ParticleEngine, @@ -685,7 +771,7 @@ fn block_animate_tick( } } } - Animate::Leaves(falling) => { + Animate::Leaves(falling, fixed_tint) => { let below = [pos[0], pos[1] - 1, pos[2]]; // LeavesBlock.makeDrippingWaterParticles. if (ctx.raining_at)([pos[0], pos[1] + 1, pos[2]]) && next_int(engine.random(), 15) == 1 @@ -705,7 +791,7 @@ fn block_animate_tick( let r = engine.random(); let p = [fx + r.next_double(), fy - 0.05, fz + r.next_double()]; let options = if ty == T::TintedLeaves { - let c = ctx.foliage(pos); + let c = fixed_tint.unwrap_or_else(|| ctx.foliage(pos)); let f = |s: u32| ((c >> s) & 255) as f32 / 255.0; ParticleOptions::colored(ty, [f(16), f(8), f(0), 1.0]) } else { @@ -977,6 +1063,13 @@ fn block_animate_tick( } } } + Animate::Beehive => { + // BeehiveBlock.animateTick: nextInt(1) + 1 attempts. + let attempts = next_int(engine.random(), 1) + 1; + for _ in 0..attempts { + beehive_drip(tables, engine, ctx, state, pos); + } + } Animate::RedstoneOre => { for d in [ [0, -1, 0], @@ -1209,21 +1302,32 @@ fn candle(engine: &mut ParticleEngine, p: [f64; 3]) { } add(engine, T::SmallFlame, p, [0.0; 3]); } -/// `CampfireBlockEntity.particleTick` for every lit campfire (no cooking items). +/// `CampfireBlockEntity.particleTick` for every lit campfire; `cooking` says +/// which of a campfire's four slots hold an item. pub fn campfire_particles<'a>( tables: &AnimateTables, engine: &mut ParticleEngine, ctx: &AnimateContext, blocks: impl Iterator, + cooking: &dyn Fn([i32; 3]) -> [bool; 4], ) { for &(pos, state) in blocks { if !tables.is_lit_campfire(state) { continue; } - let signal = ctx + let properties = ctx .registry .state(BlockStateId(state)) - .is_some_and(|s| s.properties.get("signal_fire").map(String::as_str) == Some("true")); + .map(|s| &s.properties); + let prop = |k: &str| properties.and_then(|p| p.get(k)).map(String::as_str); + let signal = prop("signal_fire") == Some("true"); + // Direction.get2DDataValue: south, west, north, east. + let rotation = match prop("facing") { + Some("west") => 1, + Some("north") => 2, + Some("east") => 3, + _ => 0, + }; let r = engine.random(); if r.next_float() < 0.11 { let count = next_int(r, 2) + 2; @@ -1231,6 +1335,28 @@ pub fn campfire_particles<'a>( make_campfire_smoke(engine, pos, signal, false); } } + // The smoke over each cooking item, at the slot's corner of the fire. + let occupied = cooking(pos); + for (slot, _) in occupied.iter().enumerate().filter(|(_, held)| **held) { + if engine.random().next_float() >= 0.2 { + continue; + } + // Direction.from2DDataValue((slot + rotation) % 4) and its clockwise side. + let (step, clockwise) = match (slot + rotation) % 4 { + 0 => ([0.0, 1.0], [-1.0, 0.0]), + 1 => ([-1.0, 0.0], [0.0, -1.0]), + 2 => ([0.0, -1.0], [1.0, 0.0]), + _ => ([1.0, 0.0], [0.0, 1.0]), + }; + let at = [ + f64::from(pos[0]) + 0.5 - step[0] * 0.3125 + clockwise[0] * 0.3125, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5 - step[1] * 0.3125 + clockwise[1] * 0.3125, + ]; + for _ in 0..4 { + add(engine, T::Smoke, at, [0.0, 5.0e-4, 0.0]); + } + } } } /// `CampfireBlock.makeParticles` (always visible, overriding the limiter); diff --git a/crates/horizon-client/src/arrows.rs b/crates/horizon-client/src/arrows.rs index f3c9c63bd..6d8dc528b 100644 --- a/crates/horizon-client/src/arrows.rs +++ b/crates/horizon-client/src/arrows.rs @@ -9,7 +9,7 @@ use crate::{ collisions::SceneCollisions, mobs::Who, motion::{FluidResources, LAVA, WATER}, - projectiles::{Hit, Projectile}, + projectiles::{Hit, Projectile, ProjectileKind}, world::World, }; use horizon_core::{ @@ -132,6 +132,10 @@ pub enum ArrowSound { HitGround, /// `entity.generic.extinguish_fire`. Extinguish, + /// A thrown trident's `getDefaultHitGroundSoundEvent` (`item.trident.hit_ground`). + TridentHitGround, + /// `ThrownTrident.onHitEntity`'s `item.trident.hit`. + TridentHit, } /// What a burning arrow does to the block it hits (`onProjectileHit`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -169,6 +173,9 @@ pub struct ArrowState { pub was_eye_in_water: bool, pub first_tick: bool, pub has_been_shot: bool, + /// `ThrownTrident.dealtDamage`: it has hit an entity (or sat in a block + /// for over 4 ticks) and hits no more. + pub dealt_damage: bool, pub removed: bool, /// The arrow's own random (`Entity.random`). pub random: LegacyRandom, @@ -211,6 +218,7 @@ impl ArrowState { was_eye_in_water: false, first_tick: true, has_been_shot: false, + dealt_damage: false, removed: false, random, events: Vec::new(), @@ -451,12 +459,14 @@ pub fn finish_entity_hit(p: &mut Projectile, scene: &ArrowScene, outcome: Entity let Some(mut st) = p.arrow.take() else { return false; }; + let trident = matches!(p.kind, ProjectileKind::Trident); let mut ticker = Ticker { p, st: &mut st, scene, }; match outcome { + EntityHit::Hurt | EntityHit::Refused if trident => ticker.trident_bounce(), EntityHit::Hurt => { ticker.hit_sound(); // A piercing arrow flies on (`getPierceLevel() <= 0` discards). @@ -501,7 +511,16 @@ impl Ticker<'_, '_, '_, '_> { p.z, )) } + /// Whether this is a `ThrownTrident` (`AbstractArrow` with its own water + /// inertia, sounds and hit). + fn trident(&self) -> bool { + matches!(self.p.kind, ProjectileKind::Trident) + } fn tick(&mut self, targets: &[(Who, Aabb)]) -> Hit { + // ThrownTrident.tick. + if self.trident() && self.st.in_ground_time > 4 { + self.st.dealt_damage = true; + } let physics = !self.st.no_physics; let movement = self.p.velocity; let block_pos = self.block_position(); @@ -549,8 +568,9 @@ impl Ticker<'_, '_, '_, '_> { self.st.in_ground_time = 0; let original = self.position(); if self.st.was_touching_water { - // getWaterInertia, then the bubbles behind it. - self.p.velocity = self.p.velocity.scale(f64::from(0.6f32)); + // getWaterInertia (0.99 for a trident), then the bubbles behind it. + let inertia = if self.trident() { 0.99f32 } else { 0.6f32 }; + self.p.velocity = self.p.velocity.scale(f64::from(inertia)); let v = self.p.velocity; for _ in 0..4 { self.st.events.push(ArrowEvent::Particle { @@ -687,6 +707,8 @@ impl Ticker<'_, '_, '_, '_> { .expand_towards(self.p.velocity) .inflate(Vec3::new(1.0, 1.0, 1.0)); let mut best: Option<(Who, Vec3, f64)> = None; + // ThrownTrident.findHitEntity: none once it has dealt damage. + let targets = if self.st.dealt_damage { &[] } else { targets }; for (who, b) in targets { if Some(*who) == self.p.owner && !self.p.left_owner || !b.intersects(area) { continue; @@ -757,12 +779,33 @@ impl Ticker<'_, '_, '_, '_> { /// `playSound(soundEvent, 1, 1.2 / (random * 0.2 + 0.9))`. fn hit_sound(&mut self) { let pitch = 1.2 / (self.st.random.next_float() * 0.2 + 0.9); + let sound = if self.trident() { + ArrowSound::TridentHitGround + } else { + ArrowSound::HitGround + }; self.st.events.push(ArrowEvent::Sound { - sound: ArrowSound::HitGround, + sound, volume: 1.0, pitch, }); } + /// `ThrownTrident.onHitEntity` after the hurt, whether it landed or not: + /// the hit sound, then `deflect(REVERSE, ..., (0.02, 0.2, 0.02))`. The + /// trident keeps flying (it has dealt its damage) and falls. + fn trident_bounce(&mut self) { + self.st.dealt_damage = true; + self.st.events.push(ArrowEvent::Sound { + sound: ArrowSound::TridentHit, + volume: 1.0, + pitch: 1.0, + }); + // ProjectileDeflection.REVERSE. + let rotation = 170.0 + self.st.random.next_float() * 20.0; + let v = self.p.velocity; + self.p.velocity = Vec3::new(v.x * (-0.02 * 0.5), v.y * (-0.2 * 0.5), v.z * (-0.02 * 0.5)); + self.p.yaw += rotation; + } /// `onHitEntity` when the entity took no damage: `deflect(REVERSE, 0.2)`, /// a half turn give or take ten degrees at a tenth of the speed; one /// left almost still drops its pickup (ALLOWED) and is discarded. diff --git a/crates/horizon-client/src/blocks.rs b/crates/horizon-client/src/blocks.rs index 27a36396a..8e906e1bc 100644 --- a/crates/horizon-client/src/blocks.rs +++ b/crates/horizon-client/src/blocks.rs @@ -90,7 +90,7 @@ pub const MAP_COLORS: [u32; 62] = [ 14200723, 8365974, ]; /// The 12 edges of the unit cube (outline data predating the export). -fn cube_edges() -> Vec<[f64; 6]> { +pub fn cube_edges() -> Vec<[f64; 6]> { let mut edges = Vec::new(); for a in 0..3 { for (u, v) in [(0., 0.), (1., 0.), (0., 1.), (1., 1.)] { diff --git a/crates/horizon-client/src/bundle.rs b/crates/horizon-client/src/bundle.rs index 42473729f..948e2f4a9 100644 --- a/crates/horizon-client/src/bundle.rs +++ b/crates/horizon-client/src/bundle.rs @@ -1,6 +1,7 @@ //! `BundleContents.Mutable`: what a bundle takes in and gives back, by //! weight. The menus (`menu`, `lan::menu`) run `BundleItem`'s click //! overrides on it. +use crate::item_data::BundleSelected; use crate::items::{ItemStack, Items}; use horizon_world::nbt::Tag; @@ -97,6 +98,8 @@ pub fn can_be_in_bundle(stack: &ItemStack) -> bool { pub struct Contents { items: Vec, weight: Weight, + /// `selectedItem`: an index into `items`, -1 for none. + selected: i32, } impl Contents { @@ -104,9 +107,11 @@ impl Contents { pub fn of(items: &Items, stack: &ItemStack) -> Option { let inside = contents_of(items, stack)?.to_vec(); let weight = contents_weight(items, &inside); + let selected = stack.data().map_or(-1, |d| d.bundle_selected.0); Some(Self { items: inside, weight, + selected, }) } @@ -154,18 +159,26 @@ impl Contents { amount } - /// `removeOne`: the first stack (Horizon keeps no selected item). + /// `removeOne`: the selected stack, else the first; nothing is selected after. pub fn remove_one(&mut self, items: &Items) -> Option { if self.items.is_empty() { return None; } - let stack = self.items.remove(0); + let at = + usize::try_from(self.selected).map_or(0, |i| if i < self.items.len() { i } else { 0 }); + let stack = self.items.remove(at); self.weight = self .weight .sub(item_weight(items, &stack).times(stack.count)); + self.selected = -1; Some(stack) } + /// `getSelectedItemIndex`. + pub fn selected(&self) -> i32 { + self.selected + } + /// The stacks inside, in display order (the first is the next out). pub fn items(&self) -> &[ItemStack] { &self.items @@ -200,11 +213,28 @@ impl Contents { /// `toImmutable`, written back into the bundle's component. pub fn store(self, bundle: &mut ItemStack) { - bundle.data_mut().bundle_contents = self.items; + let data = bundle.data_mut(); + data.bundle_contents = self.items; + data.bundle_selected = BundleSelected(self.selected); bundle.tidy(); } } +/// `BundleItem.toggleSelectedItem`: select `index`, or nothing when it is the +/// selected one already or outside the contents. +pub fn toggle_selected(bundle: &mut ItemStack, index: i32) { + let Some(data) = bundle.extra.as_deref_mut() else { + return; + }; + let inside = (0..data.bundle_contents.len() as i32).contains(&index); + let selected = if data.bundle_selected.0 != index && inside { + index + } else { + -1 + }; + data.bundle_selected = BundleSelected(selected); +} + #[cfg(test)] mod tests { use super::Weight; @@ -232,8 +262,10 @@ pub struct TooltipLayout { /// The component's own width (96) and height, the text's excluded. pub width: f32, pub height: f32, - /// Each slot's top-left and the stack in it, in reading order. + /// Each slot's top-left and the stack in it, in drawing order. pub slots: Vec<([f32; 2], ItemStack)>, + /// The position in `slots` of the selected item, which is drawn highlighted. + pub selected: Option, /// The `+N` of the items past the grid: its top-left and the count. pub overflow: Option<([f32; 2], u32)>, /// The progress bar's top-left, its fill's width out of 94, and whether @@ -266,6 +298,7 @@ pub fn tooltip_layout( width: 96.0, height: description_height + 13.0 + 8.0, slots: Vec::new(), + selected: None, overflow: None, bar: [x + offset, y + description_height + 4.0], fill: 0.0, @@ -282,6 +315,7 @@ pub fn tooltip_layout( let x_start = x + offset + 96.0; let y_start = y + grid_height; let mut slots = Vec::with_capacity(shown.len()); + let mut selected = None; let mut overflow = None; // Rows fill bottom-up and columns right-to-left, as vanilla draws them. let mut slot = 0; @@ -290,8 +324,13 @@ pub fn tooltip_layout( let at = [x_start - column as f32 * 24.0, y_start - row as f32 * 24.0]; if hidden > 0 && row == 1 && column == 1 { overflow = Some((at, hidden)); - } else if let Some(stack) = shown.get(slot) { - slots.push((at, stack.clone())); + } else if slot < shown.len() { + // `extractSlot`: the cell of slot number n holds item `size - n`. + let index = shown.len() - 1 - slot; + if usize::try_from(contents.selected()) == Ok(index) { + selected = Some(slots.len()); + } + slots.push((at, shown[index].clone())); slot += 1; } } @@ -301,6 +340,7 @@ pub fn tooltip_layout( width: 96.0, height: grid_height + 13.0 + 8.0, slots, + selected, overflow, bar: [x + offset, y + grid_height + 4.0], // `Mth.mulAndTruncate(weight, 94)`, kept within the bar. @@ -349,8 +389,8 @@ mod tooltip_tests { assert_eq!(layout.slots.len(), 12); assert_eq!(layout.overflow, None); assert_eq!(layout.height, 3.0 * 24.0 + 13.0 + 8.0); - // Rows fill bottom-up and columns right-to-left: the first item is in - // the bottom-right cell, the twelfth in the top-left. + // Rows fill bottom-up and columns right-to-left: the twelfth item is in + // the bottom-right cell, the first in the top-left. assert_eq!(layout.slots[0].0, [96.0 - 24.0, 3.0 * 24.0 - 24.0]); assert_eq!(&*layout.slots[0].1.item, "minecraft:stone"); assert_eq!(layout.slots[11].0, [0.0, 0.0]); diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs index 2f418ae82..73b9bf090 100644 --- a/crates/horizon-client/src/enchant.rs +++ b/crates/horizon-client/src/enchant.rs @@ -545,6 +545,32 @@ impl Enchantments { } out } + /// `EnchantmentHelper.forEachModifier` as an item's tooltip lists them: the + /// `minecraft:attributes` effects of `stack`'s enchantments as rows of + /// (attribute, id, amount, operation, slot group), one per slot group the + /// enchantment lists. + pub fn modifier_rows(&self, stack: &ItemStack) -> Vec<(String, String, f64, String, String)> { + let mut rows = Vec::new(); + for (id, level) in stack.enchantments() { + let Some(e) = self.get(id) else { continue }; + for a in e.effects["minecraft:attributes"] + .as_array() + .into_iter() + .flatten() + { + for slot in &e.slots { + rows.push(( + a["attribute"].as_str().unwrap_or("").to_owned(), + a["id"].as_str().unwrap_or("").to_owned(), + f64::from(level_value(&a["amount"], *level)), + a["operation"].as_str().unwrap_or("add_value").to_owned(), + slot.clone(), + )); + } + } + } + rows + } /// Sum of `add_value` amounts of one attribute from enchantments on `stack`. pub fn attribute_add(&self, stack: Option<&ItemStack>, attribute: &str) -> f64 { stack.map_or(0.0, |s| { diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 161ca12e9..c49af48c9 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -180,7 +180,6 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { ("Silent", m.silent), ("NoGravity", m.no_gravity), ("Glowing", m.glowing), - ("Invulnerable", m.invulnerable_flag), ] { if on { map.insert(key.into(), Tag::Byte(1)); @@ -188,6 +187,26 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { map.remove(&horizon_world::nbt::JavaString::from(key)); } } + map.insert( + "Invulnerable".into(), + Tag::Byte(i8::from(m.invulnerable_flag)), + ); + map.insert( + "LeftHanded".into(), + Tag::Byte(i8::from(m.extra.left_handed)), + ); + // Keys of older formats that structure templates still carry. + for key in [ + "HandItems", + "ArmorItems", + "HandDropChances", + "ArmorDropChances", + "Dimension", + "HurtByTimestamp", + "Leashed", + ] { + map.remove(&horizon_world::nbt::JavaString::from(key)); + } if m.ticks_frozen > 0 { map.insert("TicksFrozen".into(), Tag::Int(m.ticks_frozen)); } else { @@ -197,7 +216,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { ("AbsorptionAmount", Tag::Float(0)), ("FallFlying", Tag::Byte(0)), ("CanPickUpLoot", Tag::Byte(i8::from(m.can_pick_up_loot()))), - ("LeftHanded", Tag::Byte(0)), + ("current_impulse_context_reset_grace_time", Tag::Int(0)), ( "Brain", Tag::compound([("memories", Tag::Compound(Compound::new()))]), @@ -209,7 +228,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { // Only breedable animals have an age; a loaded creature that was saved without // one (a frog) stays without. let aged = raw.is_none_or(|r| r.get("Age").is_some()); - if m.kind.category == "creature" && aged { + if (m.kind.category == "creature" || m.species() == crate::mobs::Species::Hoglin) && aged { map.insert("Age".into(), Tag::Int(m.extra.age)); map.insert("AgeLocked".into(), Tag::Byte(i8::from(m.extra.age_locked))); map.insert("ForcedAge".into(), Tag::Int(m.extra.forced_age)); @@ -260,6 +279,10 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { .or_insert_with(|| string("minecraft:classic")); } "minecraft:piglin" | "minecraft:piglin_brute" | "minecraft:hoglin" => { + // Only Piglin.addAdditionalSaveData writes CannotHunt. + if id == "minecraft:piglin_brute" { + map.remove(&"CannotHunt".into()); + } map.insert( "IsImmuneToZombification".into(), Tag::Byte(i8::from(m.extra.flag2)), @@ -498,8 +521,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { )]) }); } - "minecraft:zombie" => { - map.insert("IsBaby".into(), Tag::Byte(i8::from(m.is_baby()))); + "minecraft:zombie" | "minecraft:husk" | "minecraft:drowned" => { for (key, value) in [ ("DrownedConversionTime", Tag::Int(-1)), ("InWaterTime", Tag::Int(-1)), @@ -532,6 +554,21 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { Tag::Byte(i8::from(m.extra.can_break_doors)), ); } + if matches!( + id, + "minecraft:zombie" + | "minecraft:husk" + | "minecraft:drowned" + | "minecraft:zombie_villager" + | "minecraft:zombified_piglin" + | "minecraft:piglin" + | "minecraft:zoglin" + ) { + map.insert("IsBaby".into(), Tag::Byte(i8::from(m.is_baby()))); + } + if let Some(a) = m.extra.attributes.as_deref() { + put_attributes(map, m, a); + } crate::mobs::raider::write_nbt(m, map); crate::mobs::riders::write_nbt(m, map); // LivingEntity equipment: what the mob holds now. @@ -614,6 +651,89 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } tag } +/// `AttributeMap.pack` for the attributes with a base or permanent modifier +/// finalizeSpawn set, over the saved list. +fn put_attributes(map: &mut Compound, m: &Mob, a: &crate::mobs::finalize::Attributes) { + use crate::mobs::finalize::{self, Attr, Op}; + let mut list = match map.get(&"attributes".into()) { + Some(Tag::List(l)) => l.clone(), + _ => Vec::new(), + }; + for attr in Attr::ALL { + let modifiers: Vec = a + .modifiers + .iter() + .filter(|x| x.attr == attr) + .map(|x| { + let op = match x.op { + Op::AddValue => "add_value", + Op::AddMultipliedBase => "add_multiplied_base", + Op::AddMultipliedTotal => "add_multiplied_total", + }; + Tag::compound([ + ("id", string(x.id)), + ("amount", Tag::Double(x.amount.to_bits())), + ("operation", string(op)), + ]) + }) + .collect(); + if modifiers.is_empty() && !a.bases.iter().any(|(b, _)| *b == attr) { + continue; + } + let id = format!("minecraft:{}", attr.name()); + let mut entry = vec![ + ("id", string(&id)), + ("base", Tag::Double(finalize::base_value(m, attr).to_bits())), + ]; + if !modifiers.is_empty() { + entry.push(("modifiers", Tag::List(modifiers))); + } + let entry = Tag::compound(entry); + match list + .iter_mut() + .find(|t| text(t.get("id")).as_deref() == Some(id.as_str())) + { + Some(t) => *t = entry, + None => list.push(entry), + } + } + map.insert("attributes".into(), Tag::List(list)); +} +/// `Brain.Packed`: the memories finalizeSpawn set, over the saved ones. +pub fn put_brain(map: &mut Compound, m: &Mob, dimension: &str) { + if m.extra.memories.is_empty() { + return; + } + let mut memories = match map.get(&"Brain".into()).and_then(|b| b.get("memories")) { + Some(Tag::Compound(c)) => c.clone(), + _ => Compound::new(), + }; + for &(name, value, ttl) in &m.extra.memories { + let value = match name { + "hunted_recently" => Tag::Byte(value as i8), + "home" => match m.extra.home { + Some(p) => Tag::compound([ + ("dimension", string(dimension)), + ("pos", Tag::IntArray(p.to_vec())), + ]), + None => continue, + }, + _ => Tag::Int(value as i32), + }; + let mut memory = vec![("value", value)]; + if ttl != i64::MAX { + memory.push(("ttl", Tag::Long(ttl))); + } + memories.insert( + format!("minecraft:{name}").as_str().into(), + Tag::compound(memory), + ); + } + map.insert( + "Brain".into(), + Tag::compound([("memories", Tag::Compound(memories))]), + ); +} /// `CustomName`: a text component saved as a string or a `{text: ..}` compound. fn custom_name(tag: &Tag) -> Option { match tag.get("CustomName")? { @@ -633,6 +753,22 @@ pub fn name_text(tag: &Tag) -> Text { t => crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t)), } } +/// Mob.finalizeSpawn's follow range bonus in the saved attributes. +pub(crate) fn spawn_bonus(tag: &Tag) -> Option { + let Some(Tag::List(attrs)) = tag.get("attributes") else { + return None; + }; + let range = attrs + .iter() + .find(|a| text(a.get("id")).as_deref() == Some("minecraft:follow_range"))?; + let Some(Tag::List(modifiers)) = range.get("modifiers") else { + return None; + }; + let bonus = modifiers + .iter() + .find(|x| text(x.get("id")).as_deref() == Some("minecraft:random_spawn_bonus"))?; + float(bonus.get("amount")) +} pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) -> Option { let kind = types.get(&self::kind(tag)?)?.clone(); let position = position(tag)?; @@ -658,6 +794,11 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - } } } + if let Some(bonus) = spawn_bonus(tag) { + use crate::mobs::finalize::{Attr, Op, add_modifier}; + let id = "minecraft:random_spawn_bonus"; + add_modifier(&mut m, Attr::FollowRange, id, bonus, Op::AddMultipliedBase); + } m.health = float(tag.get("Health")).map_or(m.attrs.max_health, |h| h as f32); m.hurt_time = number(tag.get("HurtTime")).unwrap_or(0) as i32; // What it holds (equipment.mainhand / offhand), when saved. @@ -699,7 +840,8 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - 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.left_handed = flag(tag, "LeftHanded"); + if m.kind.category == "creature" || m.species() == crate::mobs::Species::Hoglin { 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; m.extra.age_locked = flag(tag, "AgeLocked"); diff --git a/crates/horizon-client/src/falling_block.rs b/crates/horizon-client/src/falling_block.rs index 79ca28f7a..4faf105b9 100644 --- a/crates/horizon-client/src/falling_block.rs +++ b/crates/horizon-client/src/falling_block.rs @@ -35,6 +35,18 @@ impl Damage { ..Self::default() } } + /// A block that starts to fall: anvils hurt, and a brushable block + /// breaks where it lands (BrushableBlock.tick: disableDrop). + pub fn falling(block: &str) -> Self { + if block.ends_with("anvil") { + Self::anvil() + } else { + Self { + cancel_drop: block.starts_with("minecraft:suspicious_"), + ..Self::default() + } + } + } pub fn from_nbt(tag: &Tag, anvil: bool) -> Self { Self { hurt_entities: number(tag.get("HurtEntities")).map_or(anvil, |v| v != 0), @@ -181,6 +193,14 @@ pub fn hurt_mobs(mobs: &mut [Mob], position: Vec3, amount: f32) { #[cfg(test)] mod tests { use super::*; + #[test] + fn only_brushable_blocks_break_where_they_land() { + assert!(Damage::falling("minecraft:suspicious_gravel").cancel_drop); + assert!(Damage::falling("minecraft:suspicious_sand").cancel_drop); + assert!(!Damage::falling("minecraft:gravel").cancel_drop); + assert!(Damage::falling("minecraft:chipped_anvil").hurt_entities); + } + #[test] fn impact_uses_ceil_distance_capped_damage_and_positive_damage_wear() { let damage = Damage::anvil(); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index db49087b2..7699e83d7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -18,6 +18,7 @@ mod boats; mod books; mod bossbars; mod breezes; +mod bundles; mod campfire; mod campfire_douse; mod cartography; @@ -375,7 +376,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 --width N, --height N Window size (default 1280 x 720)\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 --in-frame Run single player's world in the frame, not on its server thread\n --pregen Add Horizon's /pregen command (docs/pregeneration.md)\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 --width N, --height N Window size (default 1280 x 720)\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 --quickPlaySingleplayer WORLD Open this world of saves/ at start, only if it exists (vanilla's)\n --quickPlayMultiplayer HOST[:PORT] The same as --server (vanilla's name)\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 --in-frame Run single player's world in the frame, not on its server thread\n --pregen Add Horizon's /pregen command (docs/pregeneration.md)\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); @@ -430,6 +431,16 @@ impl Options { "--width" => o.window_size[0] = value.parse::()?.max(1), "--height" => o.window_size[1] = value.parse::()?.max(1), "--world" => o.world = Some(value), + // Vanilla's quick play (Main, QuickPlay.joinSingleplayerWorld): only a + // world that exists opens; else the title screen. --world also creates one. + "--quickPlaySingleplayer" => { + let folder = std::env::current_dir()?.join("saves").join(&value); + if folder.join("level.dat").is_file() { + o.world = Some(value); + } else { + eprintln!("Quick play: there is no world {value} in saves/"); + } + } "--dev-mod" => o.dev_mods.push(std::path::absolute(&value)?), "--benchmark" => { if horizon_client::benchmark::scenes(&value).is_none() { @@ -440,7 +451,7 @@ impl Options { } o.benchmark = Some(value); } - "--server" => o.server = Some(value), + "--server" | "--quickPlayMultiplayer" => o.server = Some(value), "--name" => o.player_name = Some(value), "--session-file" => session_file = Some(value), "--control-socket" => o.control = Some(value.into()), @@ -1265,6 +1276,8 @@ struct Game<'a> { inv_clicks: horizon_client::container_screen::Clicks, /// The Mouse Tweaks extra's drag and wheel (`tweaks`). tweaks: tweaks::Tweaks, + /// The wheel and hovered slot of `BundleMouseActions`. + bundle_mouse: bundles::BundleMouse, /// The last inventory click, for the double click that gathers a stack. last_inv_click: Option<(std::time::Instant, usize, bool)>, /// `lastQuickMoved`: what the last Shift click moved, which a Shift @@ -1432,6 +1445,10 @@ struct Game<'a> { titles: titles::Titles, /// `Hud.toolHighlightTimer`: the selected item name. tool_highlight: horizon_client::hud_overlays::ToolHighlight, + /// `Hud.autosaveIndicatorValue`. + saving_indicator: horizon_client::hud_overlays::SavingIndicator, + /// This game's world is autosaving this tick (`MinecraftServer.isSaving`). + autosaving: bool, applied_modifiers: Vec<(String, String)>, experience: Experience, orbs: Vec, @@ -1663,7 +1680,7 @@ struct Game<'a> { lan_block_events: Vec<([i32; 3], i32, i32, u32)>, lan_entity_events: Vec<(i32, i8, [f64; 3])>, /// Successful crits (attacking guest, hit entity), queued while the hub is taken. - lan_critical_hits: Vec<(Option, i32)>, + lan_critical_hits: Vec<(Option, i32, bool)>, /// Global level events for every guest (`ServerLevel.globalLevelEvent`). lan_global_events: Vec<(i32, [i32; 3], i32)>, /// `ContainerOpenersCounter`: how many players (the host and the guests) @@ -1811,9 +1828,46 @@ impl Game<'_> { fn reach(&self) -> f64 { if self.creative { 5.0 } else { 4.5 } } + /// Outline shapes that depend on more than the block state, as one box + /// in block space: `LightBlock` and `ScaffoldingBlock.getShape` are a full + /// block while the main hand holds the block's own item + /// (`CollisionContext.isHoldingItem`), and `ShulkerBoxBlock.getShape` + /// grows with the lid (`ShulkerBoxBlockEntity.getBoundingBox`). + fn context_outline(&self, pos: [i32; 3], state: BlockStateId) -> Option<[f64; 6]> { + let name = &self.res.facts().get(state).name; + if matches!(&**name, "minecraft:light" | "minecraft:scaffolding") { + return self + .held() + .is_some_and(|s| *s.item == **name) + .then_some([0.0, 0.0, 0.0, 1.0, 1.0, 1.0]); + } + if !name.ends_with("shulker_box") { + return None; + } + let progress = self.be_anims.shulkers.get(&pos).map_or(0.0, |s| s.progress); + let facing = self + .pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("facing").cloned()); + let d = facing_offset(facing.as_deref().unwrap_or("up")); + let mut b = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0]; + for a in 0..3 { + match d[a] { + 1 => b[a + 3] += 0.5 * f64::from(progress), + -1 => b[a] -= 0.5 * f64::from(progress), + _ => {} + } + } + Some(b) + } /// A block's outline boxes in world space (`getShape` plus the random offset). fn outline_boxes(&self, pos: [i32; 3]) -> Vec<[f64; 6]> { let state = self.world.block(pos[0], pos[1], pos[2]); + if let Some(b) = self.context_outline(pos, state) { + return vec![std::array::from_fn(|i| f64::from(pos[i % 3]) + b[i])]; + } let f = self.res.facts().get(state); let o = if f.outline_offset { self.pack @@ -2108,6 +2162,33 @@ impl Game<'_> { } /// `TerrainParticle` at `pos`: the model's particle sprite and tint source /// 0's `colorAsTerrainParticle` (white when the block has none). + /// `HoneyBlock.showSlideParticles` (entity event 53): five honey block + /// particles at the entity. + fn honey_slide_particles(&mut self, at: [f64; 3]) { + use horizon_client::particles::{ParticleOptions, ParticleType}; + let Some(honey) = self + .pack + .assets + .registry + .default_state("minecraft:honey_block") + else { + return; + }; + let block = [ + at[0].floor() as i32, + at[1].floor() as i32, + at[2].floor() as i32, + ]; + if let Some((sprite, tint)) = self.particle_sprite(honey, block) { + for _ in 0..5 { + self.particles.add( + &ParticleOptions::block(ParticleType::Block, sprite.clone(), tint), + at, + [0.0; 3], + ); + } + } + } fn particle_sprite(&self, state: BlockStateId, pos: [i32; 3]) -> Option<(String, u32)> { let sprite = Self::block_particle_sprite(&self.pack, state)?; let chunks = &self.world.chunks; @@ -2325,11 +2406,18 @@ impl Game<'_> { yaw.cos() * pitch.cos() * 0.3 + spread.sin() * strength, ]; self.spawn_item(thrown, [eye[0], eye[1] - 0.3, eye[2]], v, 40); - if thrown_from_hand && self.lan_acting.is_none() { - let uuid = self.level.ensure_player_uuid(); + if thrown_from_hand { + let uuid = self.acting_player_uuid(); self.dropped.last_mut().unwrap().thrower = Some(uuid); } } + /// The UUID of the player acting: the guest whose turn it is, else the host. + pub(super) fn acting_player_uuid(&mut self) -> [i32; 4] { + match self.lan_acting_uuid { + Some(guest) => horizon_client::lan::playerdata::uuid_ints(guest), + None => self.level.ensure_player_uuid(), + } + } fn tick_items(&mut self) { let mut items = std::mem::take(&mut self.dropped); // ServerLevel.tick: only entities in entity-ticking chunks tick. @@ -2934,6 +3022,17 @@ impl Game<'_> { pos, data, } => self.smash_dust(pos, data), + // LevelEventHandler 2002 and 2007: a potion's splash. + LevelEvent::LevelEvent { + id: 2002, + pos, + data, + } => self.potion_splash_particles(pos, data, false), + LevelEvent::LevelEvent { + id: 2007, + pos, + data, + } => self.potion_splash_particles(pos, data, true), LevelEvent::LevelEvent { id: id @ 3002..=3005, pos, @@ -2969,6 +3068,8 @@ impl Game<'_> { 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)), + // LevelEvent.SOUND_SPLASH_POTION and its instant twin. + 1053 | 1054 => Some(("minecraft:entity.splash_potion.break", 1.0)), _ => None, }; if let Some((name, volume)) = sound { @@ -2978,7 +3079,7 @@ impl Game<'_> { - self.world.random.next_float()) * 0.8 } - 1029 | 1030 | 1042 | 1043 | 1044 => { + 1029 | 1030 | 1042 | 1043 | 1044 | 1053 | 1054 => { self.world.random.next_float() * 0.1 + 0.9 } 1019 | 1021 => { @@ -2988,7 +3089,7 @@ impl Game<'_> { } _ => 1.0, }; - if matches!(id, 1019 | 1021 | 1029 | 1030) { + if matches!(id, 1019 | 1021 | 1029 | 1030 | 1053 | 1054) { // Clients play the anvil sound from its level event; // capturing it also sends a duplicate sound packet. self.audio.play_unshared(name, c, volume, pitch); @@ -3037,11 +3138,9 @@ impl Game<'_> { drop_item: true, fall_distance: 0.0, stuck: Vec3::ZERO, - damage: if self.res.facts().get(state).name.ends_with("anvil") { - horizon_client::falling_block::Damage::anvil() - } else { - Default::default() - }, + damage: horizon_client::falling_block::Damage::falling( + &self.res.facts().get(state).name, + ), saved: None, }); } @@ -3144,6 +3243,31 @@ impl Game<'_> { LevelEvent::BlockEntityEvent { pos, a, b, .. } => { self.block_entity_event([pos.x, pos.y, pos.z], a, b) } + // NoteBlock.triggerEvent: a NOTE particle above, coloured by + // the note (`note / 24.0` in the x speed). + LevelEvent::BlockEvent { + pos, + state, + kind: "note_particle", + } => { + use horizon_client::particles::{ParticleOptions, ParticleType}; + let note = self + .pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("note")?.parse::().ok()) + .unwrap_or(0.0); + self.particles.add( + &ParticleOptions::simple(ParticleType::Note), + [ + f64::from(pos.x) + 0.5, + f64::from(pos.y) + 1.2, + f64::from(pos.z) + 0.5, + ], + [note / 24.0, 0.0, 0.0], + ); + } LevelEvent::GrowTree { .. } | LevelEvent::PlaceFeature { .. } | LevelEvent::BlockEvent { .. } => {} @@ -3519,7 +3643,7 @@ impl Game<'_> { } else if let Some(tag) = spill::saved_entity(&self.world, pos) { self.pending.record_saved(pos, &tag); } - self.creaking_heart_broken(pos); + self.creaking_heart_broken(pos, true); let hive = match self.world.block_entities.get(&key) { Some(BlockEntity::Beehive(h)) => self.hive_state(pos).map(|s| ((**h).clone(), s)), _ => None, @@ -4311,6 +4435,12 @@ impl Game<'_> { // The world's spawn from the start, not only once saved: a bed set // before the first save must not become it. self.level.world_spawn.get_or_insert([x, y, z]); + // The "Bonus Chest" create-world option, placed once with the spawn. + if horizon_client::save::WorldGen::read(&self.world_root) + .is_some_and(|g| g.bonus_chest) + { + self.place_bonus_chest([x, y, z])?; + } } let s = self .level @@ -4414,7 +4544,11 @@ impl Game<'_> { self.world.weather.tick_levels(); self.tick_weather_effects(); } - if self.ticks.is_multiple_of(6000) { + self.autosaving = self.ticks.is_multiple_of(6000); + if let Some(serving) = &self.serving { + serving.set_saving(self.autosaving); + } + if self.autosaving { self.save_game_with(false)?; } if running { @@ -4625,9 +4759,32 @@ impl Game<'_> { }; self.audio.play(name, Some(feet), volume, pitch); } + // LivingEntity.checkFallDamage: the block's crumbs where the fall landed. + MotionEvent::Fall(horizon_client::landing::FallEvent::Particles { + state, + position, + count, + speed, + }) => self.landing_dust(None, state, position, count, speed), MotionEvent::Fall(event) => self.landing_block_updates(&event), MotionEvent::Snowflake { position, velocity } => self.snowflake(position, velocity), MotionEvent::EnterBlock { state } => self.trigger_enter_block(state), + MotionEvent::HoneySlide { + sound, particles, .. + } => { + if sound { + self.audio + .play("minecraft:block.honey_block.slide", Some(feet), 1.0, 1.0); + } + if particles { + self.honey_slide_particles(feet); + // The server's event 53 reaches the guests too. + let id = self.lan.as_ref().map(|h| h.host_entity); + if let Some(id) = id { + self.lan_entity_event(id, 53, feet); + } + } + } MotionEvent::InsidePortal { pos } => self.player_inside_nether_portal(pos), MotionEvent::CauldronExtinguish { pos } => self.cauldron_extinguish(pos), MotionEvent::InsideWitherRose => self.wither_rose_contact(), @@ -4730,6 +4887,7 @@ impl Game<'_> { /// What the tick runs after the local player's own update: effects, the /// world's entities and blocks, and the network hub. fn tick_world(&mut self, running: bool) -> Result<()> { + self.share_spawn_conditions(); self.update_chunk_tickets(); horizon_client::spans::time("tick_effects", || self.tick_effects(running)); // Player.tick's ItemCooldowns.tick for the window's player (a @@ -4737,6 +4895,7 @@ impl Game<'_> { self.shield_cooldown = self.shield_cooldown.saturating_sub(1); self.cooldowns.tick(); horizon_client::spans::time("tick_using", || self.tick_using()); + self.tick_bundle_hover(); horizon_client::spans::time("tick_hud", || self.tick_hud()); // The player's digging comes in with its packets, before the level // ticks; ServerLevel.tick then runs the scheduled and random block @@ -5434,6 +5593,7 @@ impl Game<'_> { Screen::Mod => self.draw_mod_screen(&mut batch), Screen::Playing | Screen::Options | Screen::Win => {} } + self.draw_saving_indicator(&mut batch); self.draw_toasts(&mut batch); self.draw_pack_toasts(&mut batch); self.remote_hud(&mut batch); @@ -5934,6 +6094,12 @@ impl Game<'_> { /// Several clicks on one menu instance (a quick craft drag is three). fn menu_ops(&mut self, ops: &[(Option, i32, horizon_client::menu::Input)]) -> bool { use horizon_client::menu::Input; + // BundleMouseActions.onSlotClicked: a Shift click or a swap clears the bundle's selection. + for &(slot, _, input) in ops { + if let (Some(slot), Input::QuickMove | Input::Swap) = (slot, input) { + self.unselect_bundle(slot); + } + } if self.remote.is_some() && self.screen == Screen::Inventory { // On a server the clicks are the server's: predicted and sent. return self.remote_menu_ops(ops); @@ -7259,7 +7425,12 @@ impl Game<'_> { self.see_through_vertices = see_through; // Entity shadows (EntityRenderer.extractShadow). self.mark_translucent_entity(out.len(), "minecraft:entity_shadow"); - if let Some(sprite) = self.gui.atlas.sprites.get("misc/shadow").copied() { + let shadow_sprite = self + .settings + .entity_shadows + .then(|| self.gui.atlas.sprites.get("misc/shadow").copied()) + .flatten(); + if let Some(sprite) = shadow_sprite { let ambient = if self.dim == Dim::Nether { 0.1 } else { 0.0 }; let darken = self.sky_darken(); let a = alpha; @@ -7658,7 +7829,7 @@ impl Game<'_> { /// strength and whether it is a critical hit): the weapon and effects /// scaled by the attack strength, a mace's smash, the critical hit, then /// enchantments. - pub(super) fn melee_damage(&mut self, target_kind: &str) -> (f32, f32, bool) { + pub(super) fn melee_damage(&mut self, target_kind: &str) -> (f32, f32, bool, bool) { let hand_damage = 1.0 + self.attack_item_info().map_or(0.0, |i| i.attack_damage); // Riptide's spin replaces the attack damage attribute. let spin = self.player.as_ref().map_or(0.0, |p| p.auto_spin_attack_dmg); @@ -7686,8 +7857,9 @@ impl Game<'_> { amount *= 1.5; } // Enchantment damage (sharpness, smite, bane) scaled by the attack strength. - amount += self.enchant_damage_bonus(target_kind) * scale; - (amount, scale, crit) + let magic_boost = self.enchant_damage_bonus(target_kind) * scale; + amount += magic_boost; + (amount, scale, crit, magic_boost > 0.0) } /// `Player.getAttackStrengthScale(0.5)`. fn attack_strength_scale(&self) -> f32 { @@ -7874,7 +8046,7 @@ impl Game<'_> { 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); + let (amount, scale, crit, magic) = self.melee_damage(&target_kind); let sweep = self.sweep_attack_position(scale, crit); let (knockback, knockback_attack) = self.extra_knockback(&target_kind, scale); self.attack_ticks = 0; @@ -7937,6 +8109,18 @@ impl Game<'_> { feet, width, height, + false, + ); + } + // Player.attackVisualEffects: magicCrit when the enchantments added damage. + if magic { + self.critical_hit( + self.lan_acting, + self.mobs[index].id as i32, + feet, + width, + height, + true, ); } if actual > 2.0 { @@ -8165,6 +8349,7 @@ impl Game<'_> { ); self.session_lock = Some(session_lock); self.end.set_locator(locator); + self.share_spawn_conditions(); self.score = Default::default(); self.fns = Default::default(); self.bosses = Default::default(); @@ -8303,6 +8488,7 @@ impl Game<'_> { seed, )?; self.end.set_locator(locator); + self.share_spawn_conditions(); Ok((streaming, save)) } /// Change dimension through a portal (Entity.changeDimension with @@ -10787,6 +10973,17 @@ impl Game<'_> { [0.0; 3] }; let p = h.pos.map(f64::from); + if let Some(b) = self.context_outline(h.pos, state) { + return horizon_client::blocks::cube_edges() + .iter() + .map(|e| { + std::array::from_fn(|i| { + let k = i % 3; + p[k] + b[k] + e[i] * (b[k + 3] - b[k]) + }) + }) + .collect(); + } f.outline_edges .iter() .map(|e| std::array::from_fn(|i| p[i % 3] + o[i % 3] + e[i])) @@ -11847,6 +12044,7 @@ impl ApplicationHandler for Game<'_> { } if self.screen == Screen::Inventory && d != 0.0 + && !self.bundle_scroll(scaled(raw_x), scaled(raw_y)) && !self.tweak_scroll(d, self.inventory_target().0) { self.station_scroll(d); @@ -12636,6 +12834,7 @@ impl<'a> Game<'a> { craft_table: None, inv_drag: None, tweaks: Default::default(), + bundle_mouse: Default::default(), inv_clicks: Default::default(), last_inv_click: None, last_quick_moved: None, @@ -12697,7 +12896,14 @@ impl<'a> Game<'a> { level, session_lock: None, audio, - music: Default::default(), + music: { + // The manager starts with the saved option (MusicManager's constructor). + let mut music = horizon_client::music::MusicManager::default(); + music.frequency = horizon_client::music::MusicFrequency::parse( + &settings.file.name("musicFrequency"), + ); + music + }, ambience: Default::default(), sound_paused: false, cart_sounds: HashSet::new(), @@ -12741,6 +12947,8 @@ impl<'a> Game<'a> { command_source: None, titles: Default::default(), tool_highlight: Default::default(), + saving_indicator: Default::default(), + autosaving: false, applied_modifiers: Vec::new(), experience: Experience::default(), orbs: Vec::new(), diff --git a/crates/horizon-client/src/game/bundles.rs b/crates/horizon-client/src/game/bundles.rs new file mode 100644 index 000000000..198964803 --- /dev/null +++ b/crates/horizon-client/src/game/bundles.rs @@ -0,0 +1,103 @@ +//! `BundleMouseActions`: the wheel over a bundle in a container screen selects +//! one of the items it shows, which a click that takes one out of it then takes +//! (`BundleContents.Mutable.removeOne`). Moving off the bundle clears the +//! selection. On a server the selection is sent to it (`ServerboundSelectBundleItemPacket`). +use super::{Game, Screen}; +use horizon_client::{ + bundle::{Contents, toggle_selected}, + mouse::ScrollWheelHandler, +}; +use horizon_protocol::packets::play::{self, Serverbound as S}; + +#[derive(Default)] +pub(super) struct BundleMouse { + wheel: ScrollWheelHandler, + /// The slot under the cursor at the last tick (`AbstractContainerScreen.hoveredSlot`). + hovered: Option, +} + +impl Game<'_> { + /// A slot a bundle can be selected in: the player's inventory, the off hand and a + /// container's own slots. A server only knows these in the inventory and chest-like menus. + fn bundle_slot(&mut self, slot: usize) -> bool { + (slot < 36 || slot == 504 || (300..500).contains(&slot)) + && (self.remote.is_none() || self.remote_storage_open()) + && (slot < 36 || slot == 504 || self.slots().contains(&slot)) + } + + /// `BundleMouseActions.onMouseScrolled`: the wheel over a bundle moves the selection + /// through the items its tooltip shows. True when the bundle took the wheel. + pub(super) fn bundle_scroll(&mut self, x: f64, y: f64) -> bool { + let Some(slot) = self.inventory_target().0 else { + return false; + }; + if !self.bundle_slot(slot) { + return false; + } + let stack = self.slot_mut(slot).clone(); + let items = self.res.items(); + let Some(bundle) = stack.filter(|s| items.get(&s.item).is_some_and(|i| i.bundle)) else { + return false; + }; + let shown = Contents::of(items, &bundle).map_or(0, |c| c.shown_count()); + if shown == 0 { + return false; + } + let (wheel_x, wheel_y) = self.bundle_mouse.wheel.on_mouse_scroll(x, y); + let wheel = if wheel_y == 0 { -wheel_x } else { wheel_y }; + if wheel != 0 { + let selected = bundle.data().map_or(-1, |d| d.bundle_selected.0); + let next = ScrollWheelHandler::next_selection(f64::from(wheel), selected, shown as i32); + if next != selected { + self.select_bundle(slot, next); + } + } + true + } + + /// `BundleMouseActions.toggleSelectedBundleItem`: the stack here and, on a server, there. + fn select_bundle(&mut self, slot: usize, index: i32) { + if let Some(stack) = self.slot_mut(slot) { + toggle_selected(stack, index); + } + if self.remote.is_some() { + let (_, menu) = self.remote_menu(); + if let Some(menu_slot) = Self::menu_slot_index(&menu, slot) { + self.send(S::SelectBundleItem(play::SelectBundleItem { + slot: menu_slot as i32, + index, + })); + } + } + } + + /// `BundleMouseActions.unselectedBundleItem` for the bundle in `slot`, if it has a selection. + pub(super) fn unselect_bundle(&mut self, slot: usize) { + if !self.bundle_slot(slot) { + return; + } + let selected = self + .slot_mut(slot) + .as_ref() + .and_then(|s| s.data()) + .is_some_and(|d| d.bundle_selected.0 >= 0); + if selected { + self.select_bundle(slot, -1); + } + } + + /// `AbstractContainerScreen.onStopHovering` (and `onClose`): leaving a slot, or the + /// screen, clears the bundle's selection. + pub(super) fn tick_bundle_hover(&mut self) { + let now = if self.screen == Screen::Inventory { + self.inventory_target().0 + } else { + None + }; + if let Some(left) = std::mem::replace(&mut self.bundle_mouse.hovered, now) + && Some(left) != now + { + self.unselect_bundle(left); + } + } +} diff --git a/crates/horizon-client/src/game/client_ambient.rs b/crates/horizon-client/src/game/client_ambient.rs index a10c6da49..1cf59733d 100644 --- a/crates/horizon-client/src/game/client_ambient.rs +++ b/crates/horizon-client/src/game/client_ambient.rs @@ -4,8 +4,12 @@ //! on the game that has the window, in-frame or following a server, never on //! a server: nothing of them goes over the network. use super::Game; +use horizon_client::blocks::RenderShape; use horizon_client::mobs::{MobEvent, ambient}; -use horizon_client::particles::{ParticleOptions, ParticleType}; +use horizon_client::motion::{LAVA, WATER}; +use horizon_client::particles::{ParticleEngine, ParticleOptions, ParticleType}; +use horizon_client::pose::Pose; +use horizon_core::{geometry::Vec3, random::RandomSource}; impl Game<'_> { pub(super) fn tick_client_ambient(&mut self) { @@ -33,5 +37,209 @@ impl Game<'_> { } } self.eye_particles(); + self.sprint_dust(); + self.effect_swirls(); + } + + /// `Entity.baseTick`'s `spawnSprintParticle` on a client: dust of the + /// block under a sprinting player's feet streams back from them every + /// tick, for the window's own player and for the other players it sees. + fn sprint_dust(&mut self) { + // Each runner's feet, movement and supporting block. + let mut runners: Vec<(Vec3, Vec3, Option<[i32; 3]>)> = Vec::new(); + // Entity.canSpawnSprintParticle. + if let Some(p) = self.player.as_ref() + && p.sprinting + && !p.spectator + && p.pose != Pose::Crouching + && !p.health.dead_or_dying() + && !p.fluids.was_touching_water + && !p.is_in_lava() + && p.fluid_height(WATER) <= 0.0 + && p.fluid_height(LAVA) <= 0.0 + { + let support = p.ground.supporting_block.map(|b| [b.x, b.y, b.z]); + runners.push((p.position, p.velocity, support)); + } + let guests = self.lan.iter().flat_map(|host| host.models.values()); + for m in self.mobs.iter().chain(guests) { + // Another player's fluids aren't known here: none where they stand. + let feet = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + if m.extra.sprinting + && !m.extra.crouching + && m.alive() + && &*m.kind.id == "minecraft:player" + && self + .res + .facts() + .get(self.world.block(feet[0], feet[1], feet[2])) + .fluid_level + == 0 + { + runners.push((m.position, m.position.subtract(m.previous), None)); + } + } + for (position, movement, support) in runners { + // Entity.getOnPosLegacy: getOnPos(0.2). + let below = (position.y - f64::from(0.2f32)).floor() as i32; + let tall = |game: &Self, s: [i32; 3]| { + let name = game.block_name(s); + [ + "minecraft:fences", + "minecraft:walls", + "minecraft:fence_gates", + ] + .iter() + .any(|tag| game.block_in_tag(tag, &name)) + }; + let at = match support { + Some(s) if tall(self, s) => s, + Some(s) => [s[0], below, s[2]], + None => [position.x.floor() as i32, below, position.z.floor() as i32], + }; + let state = self.world.block(at[0], at[1], at[2]); + if self.res.facts().get(state).render_shape == RenderShape::Invisible { + continue; + } + let Some((sprite, tint)) = self.particle_sprite(state, at) else { + continue; + }; + let width = f64::from(0.6f32); + let r = self.particles.random(); + let mut x = position.x + (r.next_double() - 0.5) * width; + let mut z = position.z + (r.next_double() - 0.5) * width; + // Clamped into the block when the feet are in another column. + if position.x.floor() as i32 != at[0] { + x = x.clamp(f64::from(at[0]), f64::from(at[0]) + 1.0); + } + if position.z.floor() as i32 != at[2] { + z = z.clamp(f64::from(at[2]), f64::from(at[2]) + 1.0); + } + self.particles.add( + &ParticleOptions::block(ParticleType::Block, sprite, tint), + [x, position.y + 0.1, z], + [movement.x * -4.0, 1.5, movement.z * -4.0], + ); + } + } + + /// `LivingEntity.tickEffects` on a client: the swirls around an entity + /// with visible effects, from the particles its synched data lists. The + /// window's player has its own effects, a server's mobs and players the + /// list the server sent, and the mobs and guests of a game in the frame + /// theirs. + fn effect_swirls(&mut self) { + if let Some(p) = self.player.as_ref() { + let effects = &self.potions.effects.list; + let list: Vec<_> = effects + .iter() + .filter(|e| e.visible) + .filter_map(|e| effect_particle(e.id, e.ambient)) + .collect(); + let ambient = effects.iter().filter(|e| e.visible).all(|e| e.ambient); + let invisible = effects.iter().any(|e| e.id == "invisibility"); + let size = ( + f64::from(p.dimensions.width), + f64::from(p.dimensions.height), + ); + swirl( + &mut self.particles, + p.position, + size, + &list, + ambient, + invisible, + ); + } + let guests = self.lan.iter().flat_map(|host| host.models.values()); + for m in self.mobs.iter().chain(guests) { + if !m.alive() { + continue; + } + let size = (f64::from(m.width()), f64::from(m.height())); + let invisible = m.invisible || m.has_effect("minecraft:invisibility"); + if m.extra.effect_particles.is_empty() { + // A mob of this game: its own effects, visible and not ambient. + if m.extra.effects.is_empty() { + continue; + } + let list: Vec<_> = m + .extra + .effects + .iter() + .filter(|e| !m.extra.hidden_effects.contains(&e.0)) + .filter_map(|e| effect_particle(e.0, false)) + .collect(); + swirl( + &mut self.particles, + m.position, + size, + &list, + false, + invisible, + ); + } else { + let list = &m.extra.effect_particles; + let ambient = m.extra.effect_ambient; + swirl( + &mut self.particles, + m.position, + size, + list, + ambient, + invisible, + ); + } + } } } + +/// `MobEffect.particleFactory`: the omens have particles of their own, any +/// other effect an entity effect in its colour, faint when ambient. +pub(super) fn effect_particle(effect: &str, ambient: bool) -> Option { + Some(match effect.trim_start_matches("minecraft:") { + "trial_omen" => ParticleOptions::simple(ParticleType::TrialOmen), + "raid_omen" => ParticleOptions::simple(ParticleType::RaidOmen), + other => { + let color = horizon_client::brewing::effect(other)?.color; + let channel = |shift: u32| ((color >> shift) & 255) as f32 / 255.0; + // MobEffect.AMBIENT_ALPHA is 38 of 255. + let alpha = if ambient { 38.0 / 255.0 } else { 1.0 }; + ParticleOptions::colored( + ParticleType::EntityEffect, + [channel(16), channel(8), channel(0), alpha], + ) + } + }) +} + +/// One tick of `LivingEntity.tickEffects`' client branch: a one in four +/// chance (one in fifteen while invisible, a fifth of either when all the +/// effects are ambient) of one of the particles at a random spot of the box. +fn swirl( + particles: &mut ParticleEngine, + feet: Vec3, + size: (f64, f64), + list: &[ParticleOptions], + ambient: bool, + invisible: bool, +) { + if list.is_empty() { + return; + } + let bound = if invisible { 15 } else { 4 } * if ambient { 5 } else { 1 }; + let r = particles.random(); + let Ok(0) = r.next_int_bound(bound) else { + return; + }; + // Util.getRandom, then getRandomX(0.5), getRandomY and getRandomZ. + let pick = r.next_int_bound(list.len() as i32).unwrap_or_default() as usize; + let x = feet.x + size.0 * (2.0 * r.next_double() - 1.0) * 0.5; + let y = feet.y + size.1 * r.next_double(); + let z = feet.z + size.0 * (2.0 * r.next_double() - 1.0) * 0.5; + particles.add(&list[pick], [x, y, z], [1.0; 3]); +} diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs index 6e1d5d82b..2d6b75902 100644 --- a/crates/horizon-client/src/game/combat.rs +++ b/crates/horizon-client/src/game/combat.rs @@ -10,6 +10,9 @@ struct Entry { fall_distance: f32, /// The causing entity: its id (for comparisons) and display name. attacker: Option<(u32, Text)>, + /// The direct entity's display name when no entity caused the damage + /// (`DamageSource.directEntity`: a potion with no thrower, a cloud). + direct: Option, } #[derive(Default)] pub(super) struct CombatTracker { @@ -19,6 +22,8 @@ pub(super) struct CombatTracker { /// Attackers of damage dealt this tick, claimed by the matching /// `RecordedDamage` event. pending: Vec<(String, (u32, Text))>, + /// `pending` for a direct entity with no causing entity: only its name. + pending_direct: Vec<(String, Text)>, /// `LivingEntity.lastHurtByMob` and its timestamp (the kill credit). last_hurt_by: Option<((u32, Text), i64)>, /// The mob the player last hurt (`getLastHurtMob`) and when. @@ -66,6 +71,14 @@ impl Game<'_> { .pending .push((damage_type.to_owned(), (id, name))); } + /// The `DamageSource.directEntity` of the next `damage_type` damage when + /// nothing caused it (a splash potion nobody threw): the death message + /// names it instead (`getLocalizedDeathMessage`). It is no kill credit. + pub(super) fn note_direct_entity(&mut self, damage_type: &str, name: Text) { + self.combat + .pending_direct + .push((damage_type.to_owned(), name)); + } /// `LivingEntity.handleDamageEvent` for the player: the hurt sound of the /// source's `DamageEffects` (`Player.getHurtSound`). pub(super) fn player_hurt_sound(&mut self, sound: &str, at: [f64; 3]) { @@ -94,6 +107,15 @@ impl Game<'_> { .iter() .position(|(t, _)| *t == name) .map(|i| self.combat.pending.remove(i).1); + let direct = match attacker { + Some(_) => None, + None => self + .combat + .pending_direct + .iter() + .position(|(t, _)| *t == name) + .map(|i| self.combat.pending_direct.remove(i).1), + }; let (fall_location, fall_distance) = self.fall_location(); let now = self.world.game_time; if let Some(a) = &attacker { @@ -111,10 +133,12 @@ impl Game<'_> { fall_location, fall_distance, attacker, + direct, }); self.combat.last_damage = now; } self.combat.pending.clear(); + self.combat.pending_direct.clear(); self.combat.fall_before = self.player.as_ref().map_or(0.0, |p| p.fall_distance); } /// `FallLocation.getCurrentFallLocation` and the fall distance so far. @@ -224,6 +248,7 @@ impl Game<'_> { let entries = std::mem::take(&mut self.combat.entries); let killing = entries.last().expect("checked above"); let killer = killing.attacker.clone(); + let direct = killing.direct.clone(); if def.1 == "fall_variants" && let Some(knock) = knock.and_then(|i| entries.get(i)) { @@ -248,15 +273,22 @@ impl Game<'_> { .append(Text::literal("]")); return Text::translate(&format!("{key}.message"), &[me, link]); } + // `getLocalizedDeathMessage`: the causing entity's name, or the + // direct entity's when nothing caused the damage. if let Some((_, name)) = killer { return Text::translate(&key, &[me, name]); } + if let Some(name) = direct { + return Text::translate(&key, &[me, name]); + } // getKillCredit: the last mob that hurt the player in the past 100 ticks. if let Some(((_, name), at)) = &self.combat.last_hurt_by && self.world.game_time - at <= 100 { return Text::translate(&format!("{key}.player"), &[me, name.clone()]); } + // No entity at all: the one-argument message, as vanilla sends it (a + // template that names a killer then shows as written). Text::translate(&key, &[me]) } } diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 22041c3b2..f308cfec6 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -541,8 +541,7 @@ impl Game<'_> { .enumerate() // The kinds /data can write (entity_nbt). .filter(|(_, p)| { - p.arrow.is_some() - || matches!(p.kind, K::LargeFireball { .. } | K::SmallFireball) + p.is_arrow() || matches!(p.kind, K::LargeFireball { .. } | K::SmallFireball) }) .map(|(i, _)| Target::Projectile(i)), ); diff --git a/crates/horizon-client/src/game/commands/effects.rs b/crates/horizon-client/src/game/commands/effects.rs index 65d6592f7..6516bfe6c 100644 --- a/crates/horizon-client/src/game/commands/effects.rs +++ b/crates/horizon-client/src/game/commands/effects.rs @@ -91,7 +91,12 @@ impl Game<'_> { } Target::Mob(id) => match self.mobs.iter_mut().find(|m| m.id == id) { Some(m) => { - m.add_effect(namespaced(effect.id), duration, amplifier); + let name = namespaced(effect.id); + m.add_effect(name, duration, amplifier); + m.extra.hidden_effects.retain(|h| *h != name); + if !particles { + m.extra.hidden_effects.push(name); + } true } None => false, @@ -154,6 +159,10 @@ impl Game<'_> { m.extra .effects .retain(|x| e.is_some_and(|e| x.0 != namespaced(e.id))); + let left = &m.extra.effects; + m.extra + .hidden_effects + .retain(|h| left.iter().any(|x| x.0 == *h)); m.extra.effects.len() != before } None => false, diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index 3f7e4c2a0..eb4d4b157 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -145,9 +145,42 @@ impl Game<'_> { .iter() .find(|m| m.id == id) .map_or(0.0, |m| m.eye_y() - m.position.y), - _ => 0.0, + // ArmorStand.getDefaultDimensions: a marker's are empty, a small + // stand's are BABY_DIMENSIONS, whose eye height is 0.9875F. + Target::Stand(id) => match self.armor_stands.iter().find(|a| a.id == id) { + Some(a) if a.marker => 0.0, + Some(a) if a.small => f64::from(0.9875f32), + _ => self.type_eye_height(&self.target_type(t)), + }, + // Entity.getEyeHeight: the type's dimensions. + _ => self.type_eye_height(&self.target_type(t)), } } + /// `EntityType.getDimensions().eyeHeight()` from `entity-types.json`, + /// read once: a float, widened as `Entity.getEyeY` does. + fn type_eye_height(&self, ty: &str) -> f64 { + static EYE_HEIGHTS: std::sync::OnceLock> = + std::sync::OnceLock::new(); + EYE_HEIGHTS + .get_or_init(|| { + std::fs::read(self.options.resources.join("entity-types.json")) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .and_then(|v| { + v.as_object().map(|o| { + o.iter() + .filter_map(|(k, t)| { + Some((k.clone(), f64::from(t["eye_height"].as_f64()? as f32))) + }) + .collect() + }) + }) + .unwrap_or_default() + }) + .get(ty) + .copied() + .unwrap_or(0.0) + } /// EntityAnchorArgument.Anchor.apply. pub(super) fn anchor_position(&self, s: &Source) -> [f64; 3] { match s.entity { @@ -467,9 +500,10 @@ impl Game<'_> { "positioned" if c.has("as") => targets(self)? .into_iter() .filter_map(|t| { + // withPosition keeps the anchor (only `positioned ` + // resets it to the feet). Some(Source { pos: self.target_position(t)?, - eyes: false, ..s }) }) @@ -606,6 +640,72 @@ impl Game<'_> { .collect(), _ => Vec::new(), }, + // Leashable.getLeashHolder: a fence knot is not an entity here. + Some("leasher") => match entity { + Target::Mob(id) => self + .mobs + .iter() + .find(|m| m.id == id) + .and_then(|m| m.extra.leash.map(|holder| (holder, m.extra.leash_player))) + .and_then(|(holder, player)| match holder { + // The player who tied it (the host's when unrecorded). + horizon_client::mobs::leash::Holder::Player => { + let uuid = player.or(self.level.player_uuid)?; + self.target_by_uuid(horizon_client::lan::playerdata::ints_uuid(uuid)) + } + horizon_client::mobs::leash::Holder::Mob(i) => Some(Target::Mob(i)), + horizon_client::mobs::leash::Holder::Knot(_) => None, + }) + .into_iter() + .collect(), + _ => Vec::new(), + }, + // TraceableEntity.getOwner: who shot a projectile, who threw an + // item, who summoned a vex. + Some("origin") => match entity { + Target::Projectile(i) => self + .creatures + .projectiles + .get(i) + .and_then(|p| match (p.owner?, p.guest) { + // A guest's shot: `Who::Player` is them. + (horizon_client::mobs::Who::Player, Some(conn)) + if self.lan_acting == Some(conn) => + { + Some(Target::Player) + } + (horizon_client::mobs::Who::Player, Some(conn)) => { + Some(Target::Guest(conn)) + } + (horizon_client::mobs::Who::Player, None) => Some(Target::Player), + (horizon_client::mobs::Who::Mob(id), _) => Some(Target::Mob(id)), + }) + .into_iter() + .collect(), + Target::Item(id) => self + .dropped + .iter() + .find(|d| d.id == id) + .and_then(|d| d.thrower) + .and_then(|words| { + let uuid = words + .iter() + .fold(0u128, |all, w| all << 32 | u128::from(*w as u32)); + self.target_by_uuid(uuid) + }) + .into_iter() + .collect(), + Target::Mob(id) => self + .mobs + .iter() + .find(|m| m.id == id && m.kind.id == "minecraft:vex") + .map(|m| m.extra.counter2 as u32) + .filter(|owner| *owner != 0) + .map(Target::Mob) + .into_iter() + .collect(), + _ => Vec::new(), + }, Some("vehicle") => self.ride_vehicle(entity).into_iter().collect(), Some("controller") | Some("passengers") => match entity { Target::Mob(id) if self.mobs.iter().any(|m| m.id == id && m.rider.is_some()) => { diff --git a/crates/horizon-client/src/game/commands/pregen.rs b/crates/horizon-client/src/game/commands/pregen.rs index d497e2734..eb3c37688 100644 --- a/crates/horizon-client/src/game/commands/pregen.rs +++ b/crates/horizon-client/src/game/commands/pregen.rs @@ -244,7 +244,11 @@ impl Game<'_> { /// hand them the next jobs as soon as each one is done, rather than once /// a tick. pub(in crate::game) fn pump_pregen(&mut self, until: Instant) { - while self.pregen_runs_here() { + // Force-loaded chunks too: decorating in vanilla's order, a chunk + // waits for its neighbours far more often than once a tick allows. + while self.pregen_runs_here() + || (!self.streaming.forced.is_empty() && self.streaming.busy()) + { let now = Instant::now(); if now >= until { break; diff --git a/crates/horizon-client/src/game/commands/terrain_cmds.rs b/crates/horizon-client/src/game/commands/terrain_cmds.rs index d4b1c125c..824ca4d60 100644 --- a/crates/horizon-client/src/game/commands/terrain_cmds.rs +++ b/crates/horizon-client/src/game/commands/terrain_cmds.rs @@ -120,6 +120,9 @@ impl Game<'_> { tracker.track(&holder(chunk_text(x, z)), i32::from(changed)); } } + if add { + self.streaming.rank_forced(cx0, cz0, cx1, cz1); + } let (lo, hi) = (chunk_text(cx0, cz0), chunk_text(cx1, cz1)); let verb = if add { "added" } else { "removed" }; let (message, total) = tracker.message( diff --git a/crates/horizon-client/src/game/commands/text_commands.rs b/crates/horizon-client/src/game/commands/text_commands.rs index dead07d71..020157f83 100644 --- a/crates/horizon-client/src/game/commands/text_commands.rs +++ b/crates/horizon-client/src/game/commands/text_commands.rs @@ -14,10 +14,11 @@ impl Game<'_> { serde_json::from_str(json).map_err(|e| err("argument.component.invalid", &[&e]))?; // NbtContents.resolve: the path's values in the entity, block or // storage data, rich-styled (or plain, or interpreted), ", "-joined. + // ScoreContents.resolve: the holder's score in the objective. let nbt_values = std::cell::RefCell::new(Vec::new()); { let mut collect = |o: &serde_json::Map| { - if o.contains_key("nbt") { + if o.contains_key("nbt") || o.contains_key("score") { nbt_values.borrow_mut().push(o.clone()); } }; @@ -40,7 +41,11 @@ impl Game<'_> { } let mut resolved: Vec<(serde_json::Map, Text)> = Vec::new(); for o in nbt_values.into_inner() { - let t = self.resolve_nbt_component(&o); + let t = if o.contains_key("score") { + self.resolve_score_component(&o)? + } else { + self.resolve_nbt_component(&o) + }; resolved.push((o, t)); } let mut resolve = |raw: &str| -> Text { @@ -73,6 +78,54 @@ impl Game<'_> { }, )) } + /// The text of a `score` component (ScoreContents.resolve): the named + /// holder's score, `*` being the player the command runs for. + fn resolve_score_component( + &mut self, + o: &serde_json::Map, + ) -> R { + let score = o.get("score"); + let field = |k: &str| score.and_then(|s| s.get(k)).and_then(|v| v.as_str()); + let (name, objective) = ( + field("name").unwrap_or(""), + field("objective").unwrap_or(""), + ); + // findTargetName: a selector that matches one entity is that entity, + // one that matches none is just the name. + let mut reader = horizon_client::command::Reader::new(name); + let ty = horizon_client::command::args::ArgType::Entity { + single: false, + players: false, + }; + let mut holder = name.to_owned(); + if let Ok(Arg::Entity(sel)) = ty.parse(&mut reader, &self.ui.registries) + && !reader.can_read() + { + let found = self.select(&sel); + if found.len() > 1 { + return Err(err("argument.entity.toomany", &[])); + } + if let Some(t) = found.first().and_then(|t| self.holder_name(*t)) { + holder = t; + } + } + if holder == "*" { + holder = self.acting_player_name().to_owned(); + } + let board = &self.score.board; + let (Some(objective), Some(score)) = + (board.objective(objective), board.score(&holder, objective)) + else { + return Ok(Text::empty()); + }; + // numberFormatOrDefault(StyledFormat.NO_STYLE). + let format = (score.number_format.clone()) + .or_else(|| objective.number_format.clone()) + .unwrap_or(horizon_client::scoreboard::NumberFormat::Styled( + serde_json::json!({}), + )); + Ok(format.format(score.value)) + } /// The text of an `nbt` component. fn resolve_nbt_component(&mut self, o: &serde_json::Map) -> Text { use horizon_world::nbt::Tag; @@ -136,28 +189,40 @@ impl Game<'_> { } out } - fn player_targets(&mut self, ctx: &Context) -> R { - // Only the local player can receive messages and titles. + /// The players the command reaches: the window's own and the LAN guests. + fn player_targets(&mut self, ctx: &Context) -> R> { let targets = self.entities(ctx, "targets", true)?; - Ok(targets.iter().filter(|t| **t == Target::Player).count()) + Ok(targets + .into_iter() + .filter(|t| matches!(t, Target::Player | Target::Guest(_))) + .collect()) } pub(super) fn cmd_tellraw(&mut self, ctx: &Context) -> R { - let n = self.player_targets(ctx)?; + let players = self.player_targets(ctx)?; let message = self.component_arg(ctx, "message")?; - if n > 0 { - self.system_message(message); + // Each player's chat (a guest's through the connection). + for &t in &players { + self.for_player(t, |g| g.system_message(message.clone())); } - Ok(n as i32) + Ok(players.len() as i32) } pub(super) fn cmd_title(&mut self, ctx: &Context) -> R { - let n = self.player_targets(ctx)?; - let name = self.target_name(Target::Player); + let players = self.player_targets(ctx)?; + let n = players.len(); + let name = players + .first() + .map_or_else(Text::empty, |t| self.target_name(*t)); let single = n == 1; let key = if ctx.has("clear") { - self.titles_or_packet(Titles::clear, C::ClearTitles(play::Bool1 { value: false })); + self.titles_or_packet( + &players, + Titles::clear, + C::ClearTitles(play::Bool1 { value: false }), + ); "cleared" } else if ctx.has("reset") { self.titles_or_packet( + &players, |t| { t.clear(); t.reset_times(); @@ -172,6 +237,7 @@ impl Game<'_> { }; let (fade_in, stay, fade_out) = (get("fadeIn"), get("stay"), get("fadeOut")); self.titles_or_packet( + &players, |t| t.set_times(fade_in, stay, fade_out), C::SetTitlesAnimation(play::TitlesAnimation { fade_in, @@ -186,13 +252,17 @@ impl Game<'_> { text: component_nbt(&text.component()), }; if ctx.has("subtitle") { - self.titles_or_packet(|t| t.set_subtitle(text), C::SetSubtitleText(sent)); + self.titles_or_packet(&players, |t| t.set_subtitle(text), C::SetSubtitleText(sent)); "show.subtitle" } else if ctx.has("actionbar") { - self.titles_or_packet(|t| t.set_overlay(text, false), C::SetActionBarText(sent)); + self.titles_or_packet( + &players, + |t| t.set_overlay(text, false), + C::SetActionBarText(sent), + ); "show.actionbar" } else { - self.titles_or_packet(|t| t.set_title(text), C::SetTitleText(sent)); + self.titles_or_packet(&players, |t| t.set_title(text), C::SetTitleText(sent)); "show.title" } }; @@ -207,13 +277,27 @@ impl Game<'_> { self.feedback(message); Ok(n as i32) } - /// The player the title is for: the guest acting now is sent the packet - /// (TitleCommand's `connection.send`), the window's own player shows it. - fn titles_or_packet(&mut self, local: impl FnOnce(&mut Titles), packet: C) { - if self.lan_acting.is_some() { - self.guest_packets.push(packet); - } else { - local(&mut self.titles); + /// TitleCommand's `connection.send` for each player: a guest is sent the + /// packet, the window's own player shows it. + fn titles_or_packet(&mut self, players: &[Target], local: impl FnOnce(&mut Titles), packet: C) { + let mut local = Some(local); + for &t in players { + match t { + Target::Player if self.lan_acting.is_some() => { + self.guest_packets.push(packet.clone()); + } + Target::Player => { + if let Some(local) = local.take() { + local(&mut self.titles); + } + } + Target::Guest(conn) => { + if let Some(host) = self.lan.as_ref() { + host.hub.send_to(conn, &packet); + } + } + _ => {} + } } } } diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 1ce11755b..559d30db4 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -141,27 +141,37 @@ impl Game<'_> { Some(Arg::Entity(_)) => self.entities(ctx, "entity", false)?.first().copied(), _ => None, }; + let cause = match ctx.get("cause") { + Some(Arg::Entity(_)) => self.entities(ctx, "cause", false)?.first().copied(), + _ => None, + }; let from = match ctx.get("location") { Some(Arg::Coords(_)) => self.position_arg(ctx, "location"), _ => by.and_then(|t| self.target_position(t)), }; let hurt = match target { + // The causing mob is the one the hit is credited to and thorns + // answer; the source position gives the knockback its direction. Target::Player => { - if self.creative || self.spectator() { + // `DamageSource(type, cause, by)`: the death message names the + // causing entity, else the direct one. A mob is noted by + // `hurt_player_from`, a player here. + if let Some(t @ (Target::Player | Target::Guest(_))) = cause.or(by) { + let name = self.target_name(t); + self.note_direct_entity(&ty, name); + } + if self.spectator() { false - } else if let Some(player) = self.player.as_mut() { - match self.motion.health.damage.id(&ty) { - Some(id) => player - .hurt(&self.motion.health, self.world.health_rules, id, amount) - .unwrap_or(false), - None => false, - } } else { - false + let attacker = match cause.or(by) { + Some(Target::Mob(i)) => Some(Some(i)), + _ => Some(None), + }; + self.hurt_player_from(amount, from, &ty, attacker) } } Target::Mob(id) => { - let attacker = by.and_then(|t| match t { + let attacker = cause.or(by).and_then(|t| match t { Target::Player => Some(Who::Player), Target::Mob(i) => Some(Who::Mob(i)), _ => None, @@ -302,9 +312,18 @@ impl Game<'_> { float("minVolume", 0.0), ); let range = if volume > 1.0 { 16.0 * volume } else { 16.0 }; + // PlaySoundCommand: one seed for every player. + let seed = self.world.random.next_long(); + let here = self.dim.id(); let mut tracker = Tracker::default(); for t in targets { - if t != Target::Player { + if !matches!(t, Target::Player | Target::Guest(_)) { + continue; + } + // Only players in the source's level hear it. + if let Target::Guest(conn) = t + && self.command_guest(conn).is_none_or(|g| g.dimension != here) + { continue; } let Some(p) = self.target_position(t) else { @@ -328,8 +347,26 @@ impl Game<'_> { } else { (pos, volume) }; - self.audio.play_on(source, &sound, Some(at), v, pitch); - tracker.mark(&holder(Text::literal(self.acting_player_name()))); + // The connection is sent the sound; the window's own player + // plays it. + let guest = match t { + Target::Guest(conn) => Some(conn), + _ => self.lan_acting, + }; + match guest.and_then(|conn| Some((conn, self.lan.as_ref()?))) { + Some((conn, host)) => { + let packet = host + .hub + .sound_packet(&sound, at, v, pitch, source as i32, seed); + if t == Target::Player { + self.guest_packets.push(packet); + } else { + host.hub.send_to(conn, &packet); + } + } + None => self.audio.play_on(source, &sound, Some(at), v, pitch), + } + tracker.mark(&holder(self.target_name(t))); } let name = Text::literal(sound.clone()); let (message, total) = tracker.message( @@ -606,8 +643,10 @@ impl Game<'_> { let reached = reached.len() as i32; if !local { } else if count <= 0 { - // No count: one particle with the delta as velocity. - self.particles.create(&options, pos, delta); + // handleParticleEvent, count 0: one particle, the speed times + // the delta as velocity (both sent as floats, multiplied as floats). + self.particles + .create(&options, pos, delta.map(|d| f64::from(speed * d as f32))); } else { for _ in 0..count { let r = self.particles.random(); diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 191fa8359..9b5cd93e7 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -1083,6 +1083,9 @@ impl Game<'_> { "flashes": self.lightning_seen[1], "flash": self.flash}); // Primed TNT, falling blocks, projectiles, tridents and end crystals. status["projectiles"] = json!(self.projectiles_status()); + let mut fangs_vertices = Vec::new(); + self.fangs_geometry(glam::DVec3::ZERO, 0.5, &mut fangs_vertices); + status["fangs_vertices"] = json!(fangs_vertices.len()); status["maps"] = json!(self.maps_status()); // The particles made so far, by type. status["particles"] = json!(self.particles.made()); diff --git a/crates/horizon-client/src/game/creaking.rs b/crates/horizon-client/src/game/creaking.rs index c75325c2f..19b3442c2 100644 --- a/crates/horizon-client/src/game/creaking.rs +++ b/crates/horizon-client/src/game/creaking.rs @@ -218,8 +218,9 @@ impl Game<'_> { ); } /// `CreakingHeartBlock.playerWillDestroy`: the heart's creaking twitches to - /// death and a natural heart drops experience. - pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3]) { + /// death and a natural heart drops experience. `onExplosionHit` does the + /// same for the creaking (`by_player` false), without the experience. + pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3], by_player: bool) { let key = (pos[0], pos[1], pos[2]); if !matches!( self.world.block_entities.get(&key), @@ -242,7 +243,7 @@ impl Game<'_> { .state(state) .and_then(|s| s.properties.get("natural").cloned()) .is_some_and(|v| v == "true"); - if natural && !self.creative && !self.spectator() { + if by_player && natural && !self.creative && !self.spectator() { let xp = 20 + self.world.random.next_int_bound(5).unwrap_or(0) as u32; self.spawn_orbs( [ diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index e895cb7f7..2bc40a7af 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -18,6 +18,7 @@ use horizon_client::{ spawning::{self, BiomeFacts}, }, projectiles::{Hit, Projectile, ProjectileKind, ProjectileWorld}, + text::Text, }; use horizon_core::{ geometry::{Aabb, Vec3, traverse_blocks}, @@ -430,6 +431,12 @@ impl Game<'_> { ), } } + /// What the generator finalizes this level's structure mobs with. + pub(super) fn share_spawn_conditions(&self) { + if let Some(terrain) = self.end.locator() { + terrain.set_spawn_conditions(self.difficulty_id() as u8, self.world.day_time); + } + } /// `ServerLevel.getCurrentDifficultyAt`. pub(super) fn local_difficulty(&self, at: [f64; 3]) -> spawning::LocalDifficulty { use horizon_world::food::Difficulty; @@ -526,6 +533,8 @@ impl Game<'_> { _ => Vec::new(), }; let mut guest_events = Vec::new(); + // The mobs whose bodies go this tick: (id, feet, width, height). + let mut gone = Vec::new(); let level_random; { // The level random, lent to the mobs (brain behaviours draw from @@ -598,6 +607,11 @@ impl Game<'_> { let from = events.len(); let kept = m.tick(&w, &mut scratch, &mut events); horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes); + // LivingEntity.tickDeath: after twenty ticks the body is removed. + if !kept && !m.removed && !m.alive() && m.death_time >= 20 { + let (width, height) = (f64::from(m.width()), f64::from(m.height())); + gone.push((m.id, m.position, width, height)); + } if let Some(conn) = seen_guest { // ShulkerBullet.finalTarget is the guest's entity: the // bullet homes on it while the projectiles tick, where @@ -656,6 +670,12 @@ impl Game<'_> { } self.mobs.append(&mut mobs); self.died = died; + // ... and entity event 60 goes out as it is: the poof. + for (id, at, width, height) in gone { + let at = [at.x, at.y, at.z]; + self.lan_entity_event(id as i32, 60, at); + self.death_poof(at, width, height); + } self.sync_riders(); self.tick_skeleton_traps(); self.tick_apparition(); @@ -682,6 +702,22 @@ impl Game<'_> { self.handle_mob_events(queued)?; Ok(()) } + /// `LivingEntity.makePoofParticles` (entity event 60) about a mob's box. + pub(super) fn death_poof(&mut self, at: [f64; 3], width: f64, height: f64) { + let options = horizon_client::particles::ParticleOptions::simple( + horizon_client::particles::ParticleType::Poof, + ); + for _ in 0..20 { + let r = self.particles.level_random(); + let xa = r.next_gaussian() * 0.02; + let ya = r.next_gaussian() * 0.02; + let za = r.next_gaussian() * 0.02; + let x = at[0] + width * (2.0 * r.next_double() - 1.0) - xa * 10.0; + let y = at[1] + height * r.next_double() - ya * 10.0; + let z = at[2] + width * (2.0 * r.next_double() - 1.0) - za * 10.0; + self.particles.add(&options, [x, y, z], [xa, ya, za]); + } + } /// LivingEntity.die / dropAllDeathLoot. fn mob_died(&mut self, m: &Mob) { let killer = self.last_hurt_by_player.remove(&m.id); @@ -1078,6 +1114,11 @@ impl Game<'_> { self.next_entity += 1; p.id = self.next_entity; let (owner, at) = (p.owner, [p.position.x, p.position.y, p.position.z]); + // LlamaSpit.recreateFromPacket: the spit's burst on the client. + if p.kind == ProjectileKind::LlamaSpit { + let v = p.velocity; + self.particles.llama_spit_burst(at, [v.x, v.y, v.z]); + } self.creatures.projectiles.push(p); self.projectile_event("minecraft:projectile_shoot", owner, at); } @@ -1640,11 +1681,34 @@ impl Game<'_> { pub(super) fn mob_hits_player_kind(&mut self, amount: f32, from: [f64; 3], kind: &str) { self.mob_hits_player(amount, from, kind); } + /// Damage whose causing mob is known (`cause`, or none): not guessed + /// from the mob nearest to `from`. + pub(super) fn mob_hits_player_caused( + &mut self, + amount: f32, + from: [f64; 3], + kind: &str, + cause: Option, + ) { + self.hurt_player_from(amount, Some(from), kind, Some(cause)); + } pub(super) fn mob_hits_player( &mut self, amount: f32, from: [f64; 3], damage_type: &str, + ) -> bool { + self.hurt_player_from(amount, Some(from), damage_type, None) + } + /// `hurtServer` on the player. `from` is the source's position (none: no + /// direction), `known`: the causing mob when it is given (`/damage`), + /// else the melee attacker is the mob nearest to `from`. + pub(super) fn hurt_player_from( + &mut self, + amount: f32, + from: Option<[f64; 3]>, + damage_type: &str, + known: Option>, ) -> bool { // ServerPlayer.canHarmPlayer refused another player's projectile. if self.creative || self.combat.refuse_player_hit { @@ -1657,23 +1721,26 @@ impl Game<'_> { .damage_tags .get("minecraft:is_projectile") .is_some_and(|t| t.contains(damage_type)); - let blocking = self.player_blocking(Some(from), damage_type, false); + let blocking = self.player_blocking(from, damage_type, false); let raised = blocking.is_some(); // Melee: the attacker stands at `from` (another player's hit has no mob behind it). - let attacker = (!projectile && damage_type != "minecraft:player_attack") - .then(|| { - self.mobs - .iter() - .filter(|m| m.alive()) - .min_by(|a, b| { - let d = |m: &horizon_client::mobs::Mob| { - (m.position.x - from[0]).powi(2) + (m.position.z - from[2]).powi(2) - }; - d(a).total_cmp(&d(b)) - }) - .map(|m| m.id) - }) - .flatten(); + let attacker = match known { + Some(known) => known, + None => from + .filter(|_| !projectile && damage_type != "minecraft:player_attack") + .and_then(|from| { + self.mobs + .iter() + .filter(|m| m.alive()) + .min_by(|a, b| { + let d = |m: &horizon_client::mobs::Mob| { + (m.position.x - from[0]).powi(2) + (m.position.z - from[2]).powi(2) + }; + d(a).total_cmp(&d(b)) + }) + .map(|m| m.id) + }), + }; // The causing entity for the death message. let owner = self.combat.projectile_owner.take(); if let Some(a) = attacker.or(owner) { @@ -1701,7 +1768,10 @@ impl Game<'_> { // LivingEntity.hurtServer's dealDefaultKnockback: not inside the // hurt cooldown (a stronger hit there only adds its difference). if o.knockback { - let (xd, zd) = (from[0] - player.position.x, from[2] - player.position.z); + // No source position: a random direction. + let (xd, zd) = from.map_or((0.0, 0.0), |from| { + (from[0] - player.position.x, from[2] - player.position.z) + }); self.knock_back_player(f64::from(0.4_f32), xd, zd); if let Some(p) = self.player.as_mut() && let Some(r) = p.hurt_log.last_mut() @@ -2039,6 +2109,33 @@ impl Game<'_> { None => self.projectile_hit(p, hit), } } + /// What an arrow or a thrown trident hits an entity of type `victim` + /// for (`AbstractArrow.onHitEntity`, `ThrownTrident.onHitEntity`): a + /// trident's 8 through `EnchantmentHelper.modifyDamage` of the trident + /// (Impaling's `minecraft:damage` on `#sensitive_to_impaling`). + fn shot_damage(&mut self, shot: &mut Projectile, victim: Option<&str>) -> f32 { + if !matches!(shot.kind, ProjectileKind::Trident) { + return arrow_damage(shot, &mut self.world.random) + shot.bonus.damage; + } + let Some(trident) = shot.arrow.as_ref().map(|a| a.pickup_item.clone()) else { + return 8.0; + }; + let ctx = horizon_client::enchant::EffectContext { + this: victim, + attacker: (shot.owner == Some(Who::Player)).then_some("minecraft:player"), + direct_attacker: Some("minecraft:trident"), + damage_type: Some("minecraft:trident"), + items: Some(self.res.items()), + ..Default::default() + }; + self.res.stations().enchantments.modify_value( + Some(&trident), + "minecraft:damage", + &ctx, + &mut self.world.random, + 8.0, + ) + } /// What an arrow's tick asked for: its particles and sounds. fn arrow_event(&mut self, at: Vec3, event: horizon_client::arrows::ArrowEvent) { use horizon_client::arrows::{ArrowEvent, ArrowParticle, ArrowSound, BlockReaction}; @@ -2067,6 +2164,8 @@ impl Game<'_> { ArrowSound::Splash => "minecraft:entity.generic.splash", ArrowSound::HitGround => "minecraft:entity.arrow.hit", ArrowSound::Extinguish => "minecraft:entity.generic.extinguish_fire", + ArrowSound::TridentHitGround => "minecraft:item.trident.hit_ground", + ArrowSound::TridentHit => "minecraft:item.trident.hit", }; self.audio .play(name, Some([at.x, at.y, at.z]), volume, pitch); @@ -2216,11 +2315,11 @@ impl Game<'_> { && id >= super::dragon::SPECIAL { let by_player = p.owner == Some(Who::Player); - if let ProjectileKind::Arrow { .. } = p.kind { + if p.arrow.is_some() { // AbstractArrow.onHitEntity: spent if the part or crystal took // it, else turned back (a perched dragon sets it alight first). let mut arrow = p.clone(); - let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage; + let amount = self.shot_damage(&mut arrow, None); let outcome = match self.hit_special(id, amount, by_player, true) { super::dragon::Hurt::Landed { .. } => EntityHit::Hurt, super::dragon::Hurt::Refused => EntityHit::Refused, @@ -2241,17 +2340,15 @@ impl Game<'_> { self.hit_special(id, amount, by_player, false); return Ok(()); } - if let ( - ProjectileKind::Arrow { .. }, - Hit::Entity { + if p.arrow.is_some() + && let Hit::Entity { who: Who::Mob(id), .. - }, - ) = (&p.kind, hit) + } = hit && let Some(i) = self.carts.iter().position(|c| c.id == id) { // AbstractArrow.onHitEntity on a minecart. let mut arrow = p.clone(); - let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage; + let amount = self.shot_damage(&mut arrow, None); let burning = p.arrow.as_ref().is_some_and(|a| a.on_fire()); let creative = p.owner == Some(Who::Player) && self.creative; self.arrow_hits_cart(i, amount, p.velocity, burning, creative); @@ -2262,7 +2359,7 @@ impl Game<'_> { // Projectile.onHit: the landing is heard. self.projectile_event("minecraft:projectile_land", p.owner, atp); let source_kind = match p.kind { - ProjectileKind::Arrow { .. } => DamageKind::Arrow, + ProjectileKind::Arrow { .. } | ProjectileKind::Trident => DamageKind::Arrow, ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } => { DamageKind::Fireball } @@ -2274,6 +2371,40 @@ impl Game<'_> { from: Some([p.previous.x, p.previous.y, p.previous.z]), }; match (&p.kind, hit) { + // ThrownTrident.onHitEntity: 8 damage (Impaling on aquatic mobs), + // dealt whether or not the hurt lands, then it bounces off. + (ProjectileKind::Trident, Hit::Entity { who, .. }) => { + let mut trident = p.clone(); + let victim = match who { + Who::Mob(id) => self + .mobs + .iter() + .find(|m| m.id == id) + .map(|m| m.kind.id.clone()), + Who::Player => Some("minecraft:player".to_owned()), + }; + let amount = self.shot_damage(&mut trident, victim.as_deref()); + let hurt = match who { + Who::Player => self.mob_hits_player( + amount, + [p.previous.x, p.previous.y, p.previous.z], + "minecraft:trident", + ), + Who::Mob(id) => self + .mobs + .iter_mut() + .find(|m| m.id == id) + .is_some_and(|m| m.damage(amount, source)), + }; + let outcome = if hurt { + EntityHit::Hurt + } else { + EntityHit::Refused + }; + self.finish_arrow_hit(trident, outcome); + } + // AbstractArrow.onHitBlock plays its sound itself (ArrowEvent). + (ProjectileKind::Trident, Hit::Block { .. }) => {} (ProjectileKind::Arrow { effect, .. }, Hit::Entity { who, .. }) => { let mut arrow = p.clone(); let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage; @@ -2495,14 +2626,30 @@ impl Game<'_> { if d2 < 16.0 && !self.creative { let scale = 1.0 - d2.sqrt() / 4.0; let t = (f64::from(*ticks) * scale + 0.5) as i32; - if let Some(owner) = self.combat.projectile_owner { - self.note_attacker("minecraft:indirect_magic", owner); - } match *effect { - "minecraft:instant_damage" => self.hurt_player_by( - "minecraft:indirect_magic", - 6.0 * (1 << *amplifier) as f32 * scale as f32, - ), + "minecraft:instant_damage" => { + // indirectMagic(potion, owner), built where the + // hurt happens: the thrower, or the potion + // itself when it has none. A status effect + // deals no damage, so it records no source. + let owner = self + .combat + .projectile_owner + .filter(|id| self.mob_display_name(*id).is_some()); + match owner { + Some(owner) => { + self.note_attacker("minecraft:indirect_magic", owner) + } + None => self.note_direct_entity( + "minecraft:indirect_magic", + Text::translate("entity.minecraft.splash_potion", &[]), + ), + } + self.hurt_player_by( + "minecraft:indirect_magic", + 6.0 * (1 << *amplifier) as f32 * scale as f32, + ) + } e if t > 20 => self.give_player_effect(e, t, *amplifier), _ => {} } @@ -3411,6 +3558,30 @@ impl Game<'_> { } continue; } + // ThrownTridentRenderer. + if matches!(a.kind, ProjectileKind::Trident) { + let Some(model) = self.trident_model.as_ref() else { + continue; + }; + let Some(r) = atlas.sprites.get("entity/trident/trident").copied() else { + continue; + }; + let m = glam::Mat4::from_translation(c) + * glam::Mat4::from_rotation_y((a.yaw - 90.0).to_radians()) + * glam::Mat4::from_rotation_z((a.pitch + 90.0).to_radians()); + let poses = horizon_client::mobs::anim::Poses::new(model); + horizon_client::mobs::render::draw( + model, + m, + &poses, + [r.u0, r.v0, r.u1, r.v1], + 0xFFFF_FFFF, + packed, + 0, + out, + ); + continue; + } // WindChargeRenderer. if matches!( a.kind, diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index fa5365195..49b653ae1 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -654,6 +654,9 @@ impl Game<'_> { // DedicatedServer.initServer ends with saveEverything(false, true, true). self.save_game()?; self.log_saved_levels(); + if let Some(host) = self.lan.as_mut() { + host.hub.entity_range_percent = props.entity_broadcast_range_percentage; + } let mut state = ServerState { lists, console, diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index 61725c6ab..f902f1c05 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -982,7 +982,7 @@ impl Game<'_> { | "minecraft:lingering_potion" => { let mut shot = Projectile::new(ProjectileKind::Snowball, at, None); shot.shoot(&mut own, dir, power, uncertainty); - self.launch_thrown(one, at, shot.velocity); + self.launch_thrown(one, at, shot.velocity, None); } "minecraft:firework_rocket" => { let mut shot = Projectile::new(ProjectileKind::Snowball, at, None); diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index fff03ef1c..8f3fdb224 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -2157,11 +2157,14 @@ impl Game<'_> { } /// Damage from the dragon, which is its causing entity /// (`DamageSources.mobAttack(dragon)`, `indirectMagic(cloud, dragon)`): the - /// death message names it. + /// death message names it, or the cloud once the dragon is gone. fn dragon_hurts_player(&mut self, damage_type: &str, amount: f32) { if let Some(id) = self.dragon.as_ref().map(|d| d.id) { let name = Text::translate("entity.minecraft.ender_dragon", &[]); self.note_named_attacker(damage_type, id, name); + } else if damage_type == "minecraft:indirect_magic" { + let name = Text::translate("entity.minecraft.area_effect_cloud", &[]); + self.note_direct_entity(damage_type, name); } self.hurt_player_by(damage_type, amount); } @@ -2598,7 +2601,9 @@ impl Game<'_> { } pub(super) fn fight_ready(&mut self) -> bool { self.load_fight(); - self.fight.loaded + // spawnExitPortal runs from scanState and the dragon's death, both + // only with players in the fight. + self.fight.loaded && self.fight.players } pub(super) fn exit_portal(&self) -> Option<[i32; 3]> { self.fight.exit_portal diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 687884519..b2191aa9f 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -572,16 +572,16 @@ impl Game<'_> { let pitch = (1.0 + (client_float() - client_float()) * 0.2) * 0.7; self.audio .play("minecraft:entity.generic.explode", Some(center), 4.0, pitch); - let block_count = if interaction == BlockInteraction::Keep { - 0 - } else { - targets.len() - }; + // ServerLevel.explode sends toBlow.size() whatever the interaction, and + // `ServerExplosion.isSmall` also covers an explosion that keeps blocks. + let block_count = targets.len(); + let small = radius < 2.0 || interaction == BlockInteraction::Keep; let (world, facts) = (&self.world, self.res.facts()); - self.particles.explosion(center, radius, block_count, &|b| { - facts.is_air(world.block(b[0], b[1], b[2])) - }); - self.lan_explode(center, radius, block_count); + self.particles + .explosion(center, small, block_count, radius, &|b| { + facts.is_air(world.block(b[0], b[1], b[2])) + }); + self.lan_explode(center, small, radius, block_count); Ok(()) } /// `BlockBehaviour.onExplosionHit` (TNT: `wasExploded` primes a short fuse). @@ -598,6 +598,11 @@ impl Game<'_> { } let name = self.res.facts().get(state).name.clone(); let is_tnt = &*name == "minecraft:tnt"; + // CreakingHeartBlock.onExplosionHit: its creaking dies (no + // experience, as Horizon does not track a TNT's owner). + if &*name == "minecraft:creaking_heart" { + self.creaking_heart_broken(pos, false); + } // Block.onExplosionHit: the drops copy from the block entity, which // then spills its contents as the block turns to air. let key = (pos[0], pos[1], pos[2]); diff --git a/crates/horizon-client/src/game/falling_damage.rs b/crates/horizon-client/src/game/falling_damage.rs index 759b4f646..41c714561 100644 --- a/crates/horizon-client/src/game/falling_damage.rs +++ b/crates/horizon-client/src/game/falling_damage.rs @@ -64,6 +64,25 @@ impl Game<'_> { pos: BlockPos::new(pos[0], pos[1], pos[2]), data: 0, }); + } else if self + .res + .facts() + .get(block.state) + .name + .starts_with("minecraft:suspicious_") + { + // BrushableBlock.onBrokenAfterFall. + let at = BlockPos::new(pos[0], pos[1], pos[2]); + self.level_events.push(LevelEvent::LevelEvent { + id: 2001, + pos: at, + data: block.state.0 as i32, + }); + self.level_events.push(LevelEvent::GameEvent { + pos: at, + event: "minecraft:block_destroy", + state: None, + }); } return; } diff --git a/crates/horizon-client/src/game/fangs.rs b/crates/horizon-client/src/game/fangs.rs index aed692649..6c20ccf93 100644 --- a/crates/horizon-client/src/game/fangs.rs +++ b/crates/horizon-client/src/game/fangs.rs @@ -7,12 +7,13 @@ use std::sync::Arc; #[derive(Clone, Debug)] pub(super) struct Fangs { - pos: [f64; 3], - yaw: f32, + pub id: u32, + pub pos: [f64; 3], + pub yaw: f32, warmup: i32, - life: i32, + pub life: i32, owner: u32, - started: bool, + pub started: bool, } #[derive(Default)] pub(super) struct FangState { @@ -21,6 +22,11 @@ pub(super) struct FangState { } impl Game<'_> { pub(super) fn add_fangs(&mut self, at: [f64; 3], yaw: f32, delay: i32, owner: u32) { + self.next_entity += 1; + self.insert_fangs(self.next_entity, at, yaw, delay, owner); + } + + pub(super) fn insert_fangs(&mut self, id: u32, at: [f64; 3], yaw: f32, delay: i32, owner: u32) { if self.fangs.model.is_none() { self.fangs.model = horizon_client::mobs::load_model( &self.options.resources, @@ -29,6 +35,7 @@ impl Game<'_> { .map(Arc::new); } self.fangs.list.push(Fangs { + id, pos: at, yaw, warmup: delay, @@ -37,6 +44,30 @@ impl Game<'_> { started: false, }); } + /// `EvokerFangs.handleEntityEvent`: only event 4 starts a client attack. + pub(super) fn remote_fangs_event(&mut self, id: u32, event: i8) { + if event == 4 + && let Some(f) = self.fangs.list.iter_mut().find(|f| f.id == id) + { + f.started = true; + self.audio.play_unshared( + "minecraft:entity.evoker_fangs.attack", + Some(f.pos), + 1.0, + 1.0, + ); + } + } + + /// `EvokerFangs.tick`: clients only advance animation, never damage or discard. + pub(super) fn tick_remote_fangs(&mut self) { + for f in &mut self.fangs.list { + if f.started { + f.life -= 1; + } + } + } + /// `EvokerFangs.tick`. pub(super) fn tick_fangs(&mut self) { let mut list = std::mem::take(&mut self.fangs.list); @@ -50,7 +81,8 @@ impl Game<'_> { } if !f.started { f.started = true; - self.audio.play( + self.lan_entity_event(f.id as i32, 4, f.pos); + self.audio.play_unshared( "minecraft:entity.evoker_fangs.attack", Some(f.pos), 1.0, @@ -71,12 +103,23 @@ impl Game<'_> { let b = horizon_core::geometry::Aabb::new(lo, hi); // Every player in the box, the server's players too. let pos = f.pos; + // `EvokerFangs.dealDamageTo`: indirectMagic(fangs, owner) while the + // owner lives, plain magic (nobody to name) once it is gone. + let owner = self + .mobs + .iter() + .any(|m| m.id == f.owner && m.alive()) + .then_some(f.owner); let bite = move |g: &mut Self| { if let Some(p) = g.player_view() && p.alive && p.bounds.intersects(b) { - g.mob_hits_player_kind(6.0, pos, "minecraft:indirect_magic"); + let kind = match owner { + Some(_) => "minecraft:indirect_magic", + None => "minecraft:magic", + }; + g.mob_hits_player_caused(6.0, pos, kind, owner); } }; bite(self); diff --git a/crates/horizon-client/src/game/initial_spawn.rs b/crates/horizon-client/src/game/initial_spawn.rs index 7ddb9cb90..c1149b26a 100644 --- a/crates/horizon-client/src/game/initial_spawn.rs +++ b/crates/horizon-client/src/game/initial_spawn.rs @@ -20,7 +20,8 @@ use horizon_core::{ }; use horizon_world::{ block_collision::BlockCollisionRegistry, collision_context::CollisionContext, - heightmap::HeightmapType, worldgen::terrain::TerrainBlockStates, + heightmap::HeightmapType, level::flags::UPDATE_CLIENTS, registry::BlockStateId, + worldgen::terrain::TerrainBlockStates, }; /// The loaded world as the spawn searches query it. @@ -121,6 +122,96 @@ impl Game<'_> { } Ok(Some([ox * 16 + 8, height, oz * 16 + 8])) } + /// MinecraftServer.setInitialSpawn's bonus chest: BonusChestFeature.place + /// in the spawn chunk, a chest with the spawn bonus loot and a torch on + /// each side that can hold one, on the first free column of a shuffled + /// walk over the chunk. Skipped while the chunk is not loaded. + pub(super) fn place_bonus_chest(&mut self, origin: [i32; 3]) -> Result<()> { + use horizon_client::containers::BlockEntity; + let (cx, cz) = (origin[0] >> 4, origin[2] >> 4); + let registry = &self.pack.assets.registry; + let (Some(chest), Some(torch)) = ( + registry.default_state("minecraft:chest"), + registry.default_state("minecraft:torch"), + ) else { + return Ok(()); + }; + if !self.streaming.is_lit(cx, cz) { + return Ok(()); + } + // `level.getRandom()`. Util.toShuffledList of the chunk's x and z. + let random = &mut self.world.random; + let mut shuffled = |min: i32| -> [i32; 16] { + let mut values: [i32; 16] = std::array::from_fn(|i| min + i as i32); + for end in (2..=16usize).rev() { + let other = random.next_int_bound(end as i32).unwrap_or(0) as usize; + values.swap(end - 1, other); + } + values + }; + let (xs, zs) = (shuffled(cx * 16), shuffled(cz * 16)); + for x in xs { + for z in zs { + let y = self + .spawn_columns() + .height(HeightmapType::MotionBlockingNoLeaves, x, z); + if self.world.block(x, y, z) != self.world.air && !self.collision_empty([x, y, z]) { + continue; + } + self.set_block_clients([x, y, z], chest)?; + let seed = self.world.random.next_long(); + self.world + .block_entities + .insert((x, y, z), BlockEntity::Chest(Vec::new())); + self.load_block_entity_nbt( + [x, y, z], + &format!( + "{{LootTable:\"minecraft:chests/spawn_bonus_chest\",LootTableSeed:{seed}L}}" + ), + ); + for [dx, dz] in [[0, -1], [1, 0], [0, 1], [-1, 0]] { + let at = [x + dx, y, z + dz]; + let survives = self.with_level(|b, level, ticks| { + b.can_survive(level, ticks, BlockPos::new(at[0], at[1], at[2]), torch) + }); + if survives { + self.set_block_clients(at, torch)?; + } + } + return Ok(()); + } + } + Ok(()) + } + /// `Level.setBlock(pos, state, UPDATE_CLIENTS)`: no neighbour updates. + fn set_block_clients(&mut self, pos: [i32; 3], state: BlockStateId) -> Result<()> { + self.with_level(|b, level, ticks| { + b.set_block( + level, + ticks, + BlockPos::new(pos[0], pos[1], pos[2]), + state, + UPDATE_CLIENTS, + ); + }); + self.process_level_events() + } + /// The block at `pos` has no collision shape. + fn collision_empty(&self, pos: [i32; 3]) -> bool { + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }; + self.collision + .collision_shape_with_context( + &mut scene, + self.world.block(pos[0], pos[1], pos[2]), + BlockPos::new(pos[0], pos[1], pos[2]), + &CollisionContext::empty(false), + ) + .is_ok_and(|shape| shape.is_empty()) + } /// PlayerSpawnFinder.findSpawn around the world spawn: the feet of a /// player who has no position yet. None while a candidate's chunk loads. pub(super) fn find_player_spawn(&mut self, suggestion: [i32; 3]) -> Result> { diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index dd1c04e23..7d81c971d 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -52,6 +52,8 @@ struct Flags { /// server follows while it runs (IntegratedServer.tickServer). render_distance: AtomicI32, simulation_distance: AtomicI32, + /// `MinecraftServer.isCurrentlySaving`: the server is autosaving. + saving: AtomicBool, } /// Work the window hands its server thread (`MinecraftServer.execute`). @@ -69,6 +71,10 @@ impl Integrated { pub fn smoothed_tick_ms(&self) -> f32 { f32::from_bits(self.flags.smoothed_tick_ms.load(Ordering::Relaxed)) } + /// `MinecraftServer.isCurrentlySaving`. + pub fn is_saving(&self) -> bool { + self.flags.saving.load(Ordering::Relaxed) + } /// `IntegratedServer.tickServer` skips the world while the game is paused. pub fn set_paused(&self, paused: bool) { self.flags.paused.store(paused, Ordering::Relaxed); @@ -148,6 +154,12 @@ pub(super) struct Serving { /// is out of its place: applied after the tick. pending: Option, } +impl Serving { + /// The window reads this as `MinecraftServer.isCurrentlySaving`. + pub(super) fn set_saving(&self, saving: bool) { + self.flags.saving.store(saving, Ordering::Relaxed); + } +} enum Publish { Open(TcpListener, LanSettings), Close, diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index e39fa3a68..28ec3fe8a 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -11,7 +11,7 @@ use horizon_client::{ chunks::ChunkEncoder, data::SyncData, entity::{EntityState, States}, - hub::{HostEvent, HostState, Hub, HubConfig, TickCtx}, + hub::{BodyFlags, HostEvent, HostState, Hub, HubConfig, TickCtx}, playerdata, }, mobs::{Mob, Who, leash::Holder}, @@ -191,6 +191,17 @@ fn mob_meta( meta.push((9, serializer::FLOAT, Value::Float(health))); } defaults.push((9, serializer::FLOAT, Value::Float(1.0))); + // LivingEntity.DATA_EFFECT_PARTICLES and DATA_EFFECT_AMBIENCE_ID: the + // swirls of its effects (the ones a mob has are visible, not ambient). + meta.extend( + hub.effect_meta( + (m.extra.effects.iter()) + .filter(|e| !m.extra.hidden_effects.contains(&e.0)) + .map(|e| (e.0, false)), + ), + ); + defaults.push((10, serializer::PARTICLES, Value::Particles(Vec::new()))); + defaults.push((11, serializer::BOOLEAN, Value::Bool(false))); // Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2, aggressive 4 (what // draws a vindicator's axe, a skeleton's drawn bow, a piglin's raised // weapon). @@ -236,6 +247,27 @@ fn mob_meta( } defaults.push((16, serializer::BYTE, Value::Byte(0))); } + // SnowGolem.DATA_PUMPKIN_ID: 16 while the pumpkin is on (the default). + "minecraft:snow_golem" => { + if e.sheared { + meta.push((16, serializer::BYTE, Value::Byte(0))); + } + defaults.push((16, serializer::BYTE, Value::Byte(16))); + } + // MushroomCow.DATA_TYPE: 0 red, 1 brown. + "minecraft:mooshroom" => { + if e.variant == 1 { + meta.push((17, serializer::INT, Value::Int(1))); + } + defaults.push((17, serializer::INT, Value::Int(0))); + } + // Piglin.DATA_IS_DANCING (after the baby flag and the crossbow charge). + "minecraft:piglin" => { + if e.scratch[0] > 0 { + meta.push((19, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((19, serializer::BOOLEAN, Value::Bool(false))); + } // Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 when sheared. "minecraft:sheep" => { let value = (e.color & 15) | if e.sheared { 16 } else { 0 }; @@ -350,6 +382,14 @@ fn mob_meta( } defaults.push((17, serializer::BOOLEAN, Value::Bool(false))); } + // PolarBear.DATA_STANDING_ID (after AgeableMob's two): the bear + // rears up; the client animates it. + "minecraft:polar_bear" => { + if e.flag { + meta.push((18, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((18, serializer::BOOLEAN, Value::Bool(false))); + } // SpellcasterIllager.DATA_SPELL_CASTING_ID: the casting pose. "minecraft:evoker" | "minecraft:illusioner" => { if e.variant2 != 0 { @@ -845,6 +885,16 @@ impl Game<'_> { living_flags: living_flags(self.using) | if p.auto_spin_attack_ticks > 0 { 4 } else { 0 }, bed: self.sleeping, + body: BodyFlags { + gliding: p.fall_flying, + swimming: p.swimming, + crawling: p.pose == horizon_client::pose::Pose::Swimming && !p.swimming, + crouching: p.pose == horizon_client::pose::Pose::Crouching, + spin_attack: p.auto_spin_attack_ticks > 0, + on_fire: p.fire_ticks > 0, + invisible: self.potions.effects.get("invisibility").is_some(), + glowing: self.potions.effects.get("glowing").is_some(), + }, }) } @@ -962,6 +1012,16 @@ impl Game<'_> { host.hub.block_event(pos, b0, b1, state); } let entities = states.as_slice(); + // An entity that left the level since the last tick (a snowball + // that hit) is dropped by the tracker below: its event goes out + // first, as `Level.broadcastEntityEvent` precedes the discard. + let (gone, later): (Vec<_>, Vec<_>) = std::mem::take(&mut self.lan_entity_events) + .into_iter() + .partition(|(id, ..)| !entities.iter().any(|e| e.id == *id)); + self.lan_entity_events = later; + for (id, event, at) in gone { + host.hub.entity_event(id, event, at); + } 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(); @@ -1243,8 +1303,9 @@ impl Game<'_> { self.lan_entity_events.push((id, event, at)); } } - /// `ServerPlayer.crit`: this window's emitter, and an animation for the - /// attacker's client and observers once the hub is back in place. + /// `ServerPlayer.crit` (or `magicCrit` when `magic`): this window's + /// emitter, and an animation for the attacker's client and observers once + /// the hub is back in place. pub(super) fn critical_hit( &mut self, attacker: Option, @@ -1252,16 +1313,18 @@ impl Game<'_> { feet: [f64; 3], width: f64, height: f64, + magic: bool, ) { use horizon_client::particles::{ParticleOptions, ParticleType}; - self.particles.tracking_emitter( - ParticleOptions::simple(ParticleType::Crit), - feet, - width, - height, - ); + let particle = if magic { + ParticleType::EnchantedHit + } else { + ParticleType::Crit + }; + self.particles + .tracking_emitter(ParticleOptions::simple(particle), feet, width, height); if self.audio.capture.is_some() { - self.lan_critical_hits.push((attacker, id)); + self.lan_critical_hits.push((attacker, id, magic)); } } /// Send the tick's level events, sounds and mob animations. @@ -1339,13 +1402,13 @@ impl Game<'_> { seen.insert(m.id, (m.hurt_time, dead, swing)); } host.mob_state.insert(self.dim, seen); - for (attacker, target) in critical_hits { + for (attacker, target, magic) in critical_hits { let Some(attacker) = attacker.map_or(Some(host.host_entity), |conn| { host.hub.guest(conn).map(|g| g.entity_id) }) else { continue; }; - host.hub.critical_hit(attacker, target); + host.hub.critical_hit(attacker, target, magic); } } @@ -1428,6 +1491,13 @@ impl Game<'_> { .each_ref() .map(|s| s.as_ref().map(|s| s.item.clone())); m.extra.crouching = g.sneaking; + m.extra.sprinting = g.sprinting; + // LivingEntity.DATA_EFFECT_PARTICLES: the swirls of its visible effects. + let visible = || g.effects.list.iter().filter(|e| e.visible); + m.extra.effect_particles = visible() + .filter_map(|e| super::client_ambient::effect_particle(e.id, e.ambient)) + .collect(); + m.extra.effect_ambient = visible().all(|e| e.ambient); // Lying in its bed (LivingEntity.getBedOrientation). m.extra.ints[1] = g.bed.map_or(0, |b| self.bed_facing(b)); // LivingEntity.updateSwingTime: the arm swing lan_swings started. diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index dc1e74f0b..8c51a3f2a 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1216,6 +1216,12 @@ impl Game<'_> { { self.guest_carried_back(host, gi); } + S::SelectBundleItem(p) => { + if !spectator && let Ok(slot) = usize::try_from(p.slot) { + host.hub + .select_bundle_item(conn, slot, p.index, &mut self.world); + } + } S::ContainerClick(p) => { let rules = ItemRules(self.res.items()); let slots = host.hub.guests[gi] @@ -2319,7 +2325,35 @@ impl Game<'_> { for event in events { match event { MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, at), + // LivingEntity.checkFallDamage: the crumbs reach every player. + MotionEvent::Fall(horizon_client::landing::FallEvent::Particles { + state, + position, + count, + speed, + }) => self.landing_dust(Some(host), state, position, count, speed), MotionEvent::Fall(event) => self.landing_block_updates(&event), + // HoneyBlock.maybeDoSlideEffects: the sound reaches the + // others (Player.playSound excludes the player, whose client + // plays it), the entity event 53 everyone around. + MotionEvent::HoneySlide { + sound, particles, .. + } => { + let Some((id, at)) = host.hub.guest(conn).map(|g| (g.entity_id, g.position)) + else { + continue; + }; + if sound { + let name = "minecraft:block.honey_block.slide"; + let source = horizon_client::settings::sound_source(name) as i32; + self.audio.play_unshared(name, Some(at), 1.0, 1.0); + host.hub.sound(name, at, 1.0, 1.0, source, Some(conn)); + } + if particles { + self.honey_slide_particles(at); + host.hub.entity_event(id, 53, at); + } + } _ => {} } } diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 529666590..665710be2 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -304,6 +304,9 @@ impl Game<'_> { None => 0, }; let at = |p: horizon_core::geometry::Vec3| [p.x, p.y, p.z]; + for f in &self.fangs.list { + out.push(state(f.id, "minecraft:evoker_fangs", f.pos, f.yaw, false)); + } // LightningBolt: each client draws and flashes its own. for b in self.bolts.iter().filter(|b| b.id != 0) { out.push(state(b.id, "minecraft:lightning_bolt", b.at, 0.0, false)); @@ -354,6 +357,20 @@ impl Game<'_> { a.is_some_and(|a| a.in_ground) || p.stuck, )); } + // ThrownTrident.ID_LOYALTY (none for a mob's) and ID_FOIL, on + // AbstractArrow's flags. + K::Trident => { + let a = p.arrow.as_deref(); + e.meta.extend(arrow_meta( + false, + a.is_some_and(|a| a.no_physics), + 0, + a.is_some_and(|a| a.in_ground) || p.stuck, + )); + if a.is_some_and(|a| a.pickup_item.has_any_enchantments()) { + e.meta.push((12, serializer::BOOLEAN, Value::Bool(true))); + } + } // WitherSkull.DATA_DANGEROUS. K::WitherSkull { dangerous: true } => { e.meta.push((8, serializer::BOOLEAN, Value::Bool(true))); diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs index 599a3f637..648cef962 100644 --- a/crates/horizon-client/src/game/lan_particles.rs +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -1,7 +1,8 @@ //! Particles a server sends its players and its clients draw: //! `ClientboundLevelParticlesPacket` (`ServerLevel.sendParticles`, which //! `/particle` uses) and `ClientboundExplodePacket` (`ServerLevel.explode`). -use super::Game; +use super::{Game, lan::LanHost}; +use horizon_client::lan::hub::Hub; use horizon_client::particles::{ParticleOptions, ParticleType}; use horizon_core::{geometry::Vec3, random::RandomSource}; use horizon_protocol::{ @@ -81,6 +82,66 @@ impl Game<'_> { } } + /// `LivingEntity.checkFallDamage`'s `ServerLevel.sendParticles` of the + /// landing block's crumbs: drawn in this window, when it has one, and + /// sent to each player within 32 blocks. `host` is the hub of a guest's + /// turn, which is out of `self.lan` meanwhile. + pub(super) fn landing_dust( + &mut self, + host: Option<&LanHost>, + state: BlockStateId, + at: Vec3, + count: i32, + speed: f64, + ) { + let at = [at.x, at.y, at.z]; + if self.serving.is_none() && self.options.dedicated.is_none() { + let block = [ + at[0].floor() as i32, + (at[1] - 0.2).floor() as i32, + at[2].floor() as i32, + ]; + if let Some((sprite, tint)) = self.particle_sprite(state, block) { + self.particles.send_particles( + &ParticleOptions::block(ParticleType::Block, sprite, tint), + at, + [0.0; 3], + speed, + count as u32, + ); + } + } + let Some(hub) = host.or(self.lan.as_ref()).map(|h| &h.hub) else { + return; + }; + let Some(particle) = Self::hub_particle( + hub, + &ParticleOptions::simple(ParticleType::Block), + Some(state), + ) else { + return; + }; + let packet = C::LevelParticles(play::LevelParticles { + particle, + override_limiter: false, + always_show: false, + pos: at, + dist: [0.0; 3], + max_speed: [speed as f32; 3], + count, + randomization: 0, + }); + for g in hub.guests.iter().filter(|g| hub.here(g)) { + // ServerLevel compares the player's block centre, strictly within 32. + let distance: f64 = (0..3) + .map(|k| (g.position[k].floor() + 0.5 - at[k]).powi(2)) + .sum(); + if distance < 32.0 * 32.0 { + g.send(&packet); + } + } + } + /// `ParticleTypes.STREAM_CODEC`'s value for `options`: the type's /// network id and the data it carries (`state` for the block particles). /// None while not serving, or for a particle whose data isn't sent from @@ -89,13 +150,19 @@ impl Game<'_> { &self, options: &ParticleOptions, state: Option, + ) -> Option { + Self::hub_particle(&self.lan.as_ref()?.hub, options, state) + } + + /// `network_particle` for a hub that is out of `self.lan` meanwhile (a + /// guest's turn). + fn hub_particle( + hub: &Hub, + options: &ParticleOptions, + state: Option, ) -> Option { let name = format!("minecraft:{}", options.ty.name()); - let id = self - .lan - .as_ref()? - .hub - .registry_id("minecraft:particle_type", &name)?; + let id = hub.registry_id("minecraft:particle_type", &name)?; use ParticleType as T; let c = options.color; let data = match options.ty { @@ -254,8 +321,14 @@ impl Game<'_> { /// `ServerLevel.explode`'s packet to each player within 64 blocks. The /// sound and the push reach them on their own (the level's sounds, the /// motion a hurt player is sent), so the packet carries neither. - pub(super) fn lan_explode(&self, center: [f64; 3], radius: f32, block_count: usize) { - let emitter = if radius < 2.0 { + pub(super) fn lan_explode( + &self, + center: [f64; 3], + small: bool, + radius: f32, + block_count: usize, + ) { + let emitter = if small { "minecraft:explosion" } else { "minecraft:explosion_emitter" diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index 8e756b7be..65520221a 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -37,6 +37,8 @@ pub(super) struct Strike { amount: f32, scale: f32, crit: bool, + /// `Player.attack`'s `magicBoost > 0`: the enchantments added damage. + magic: bool, from: [f64; 3], sweep: Option<[f64; 3]>, /// `causeExtraKnockback`: its strength and direction (the attacker's @@ -109,7 +111,7 @@ impl Game<'_> { pub(super) fn pvp_strike(&mut self) -> Option { let p = self.player.as_ref()?; let from = [p.position.x, p.position.y, p.position.z]; - let (amount, scale, crit) = self.melee_damage("minecraft:player"); + let (amount, scale, crit, magic) = self.melee_damage("minecraft:player"); let sweep = self.sweep_attack_position(scale, crit); let (strength, knockback_attack) = self.extra_knockback("minecraft:player", scale); let (xd, zd) = self.extra_knockback_direction(); @@ -125,6 +127,7 @@ impl Game<'_> { amount, scale, crit, + magic, from, sweep, knockback: (strength, xd, zd), @@ -257,7 +260,7 @@ impl Game<'_> { } else { Default::default() }; - if hurt && s.crit { + if hurt && (s.crit || s.magic) { let target = match victim { Victim::Host => self.player.as_ref().map(|p| (host.host_entity, p)), Victim::Guest(conn) => host @@ -267,13 +270,17 @@ impl Game<'_> { }; if let Some((id, p)) = target { let d = p.dimensions; - self.critical_hit( - s.attacker, - id, + let (feet, width, height) = ( [p.position.x, p.position.y, p.position.z], f64::from(d.width), f64::from(d.height), ); + if s.crit { + self.critical_hit(s.attacker, id, feet, width, height, false); + } + if s.magic { + self.critical_hit(s.attacker, id, feet, width, height, true); + } } } // `Enchantment.doPostAttack`: thorns hurt the attacking player. diff --git a/crates/horizon-client/src/game/leads.rs b/crates/horizon-client/src/game/leads.rs index 8867157ee..ca70351c6 100644 --- a/crates/horizon-client/src/game/leads.rs +++ b/crates/horizon-client/src/game/leads.rs @@ -104,6 +104,9 @@ impl Game<'_> { }; let m = &mut self.mobs[i]; if let Some(h) = holder { + if h == Holder::Player { + m.extra.leash_player = Some(player_uuid); + } m.extra.leash = Some(h); m.extra.leash_pending = None; } else if m.age > 100 { @@ -201,7 +204,9 @@ impl Game<'_> { if self.mobs[index].extra.leash.is_some() { self.break_leash(id, true, false); } + let holder = self.acting_player_uuid(); self.mobs[index].extra.leash = Some(Holder::Player); + self.mobs[index].extra.leash_player = Some(holder); self.lead_sound("tied", at); // The lead is always used up. if let Some(stack) = self.held_mut().as_mut() { diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs index f12aedc5b..9fa53eb25 100644 --- a/crates/horizon-client/src/game/level_particles.rs +++ b/crates/horizon-client/src/game/level_particles.rs @@ -3,6 +3,7 @@ //! consumable's teleport (2017), electric sparks (3002), waxing (3003), wax //! off (3004) and scraping (3005). use super::Game; +use horizon_client::items::ItemStack; use horizon_client::particles::{self, ParticleOptions, ParticleType}; use horizon_core::{position::BlockPos, random::RandomSource}; use horizon_world::level::LevelEvent; @@ -134,6 +135,68 @@ impl Game<'_> { // Each guest plays it from the global packet. self.audio.play_unshared(sound, at, volume, 1.0); } + /// `LevelEventHandler.potionSplashParticles` (2002 with `Effect`, 2007 + /// with `InstantEffect`): eight splash potion crumbs, and a hundred + /// spell particles in the potion's colour `data`, flung out in a disc. + pub(super) fn potion_splash_particles(&mut self, pos: BlockPos, data: i32, instant: bool) { + let ty = if instant { + ParticleType::InstantEffect + } else { + ParticleType::Effect + }; + // Vec3.atBottomCenterOf. + let at = [ + f64::from(pos.x) + 0.5, + f64::from(pos.y), + f64::from(pos.z) + 0.5, + ]; + let crumb = self.item_particle(&ItemStack::new("minecraft:splash_potion", 1)); + let r = self.particles.level_random(); + let crumbs: Vec<[f64; 3]> = (0..8) + .map(|_| { + [ + r.next_gaussian() * 0.15, + r.next_double() * 0.2, + r.next_gaussian() * 0.15, + ] + }) + .collect(); + for v in crumbs { + self.particles.add(&crumb, at, v); + } + let channel = |shift: i32| ((data >> shift) & 0xFF) as f32 / 255.0; + let color = [channel(16), channel(8), channel(0)]; + for _ in 0..100 { + let r = self.particles.level_random(); + let dist = r.next_double() * 4.0; + let angle = r.next_double() * std::f64::consts::PI * 2.0; + let velocity = [ + angle.cos() * dist, + 0.01 + r.next_double() * 0.5, + angle.sin() * dist, + ]; + let brightness = 0.75 + r.next_float() * 0.25; + let options = ParticleOptions { + color: [ + color[0] * brightness, + color[1] * brightness, + color[2] * brightness, + 1.0, + ], + scale: dist as f32, + ..ParticleOptions::simple(ty) + }; + self.particles.add( + &options, + [ + at[0] + velocity[0] * 0.1, + at[1] + 0.3, + at[2] + velocity[2] * 0.1, + ], + velocity, + ); + } + } /// Queue and play level event `id` at `pos` (`Level.levelEvent`). pub(super) fn level_event_at(&mut self, id: i32, pos: [i32; 3], data: i32) { self.level_events.push(LevelEvent::LevelEvent { diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index 29bf6d511..5f0286d02 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -75,7 +75,7 @@ pub(super) struct Parked { lan_events: Vec<(i32, [i32; 3], i32, Option)>, lan_block_events: Vec<([i32; 3], i32, i32, u32)>, lan_entity_events: Vec<(i32, i8, [f64; 3])>, - lan_critical_hits: Vec<(Option, i32)>, + lan_critical_hits: Vec<(Option, i32, bool)>, /// Only the per-level parts of these are used (`swap_level`). anims: BlockEntityAnims, raiding: Raiding, @@ -192,6 +192,7 @@ impl Game<'_> { let mut locator = self.end.locator(); swap(&mut locator, &mut p.locator); self.end.set_locator(locator); + self.share_spawn_conditions(); swap(&mut self.save, &mut p.save); swap(&mut self.block_ticks, &mut p.block_ticks); swap(&mut self.tick_chunks, &mut p.tick_chunks); @@ -399,7 +400,8 @@ impl Game<'_> { } *next += self.clock.tick_duration(); if *next > now { - // A `/pregen` task keeps the workers fed until the next tick. + // A `/pregen` task or force-loaded chunks keep the workers fed + // until the next tick. self.pump_pregen(*next); let now = Instant::now(); if *next > now { diff --git a/crates/horizon-client/src/game/mob_blocks.rs b/crates/horizon-client/src/game/mob_blocks.rs index 083c96a66..a0ce5e9db 100644 --- a/crates/horizon-client/src/game/mob_blocks.rs +++ b/crates/horizon-client/src/game/mob_blocks.rs @@ -1,6 +1,7 @@ //! Blocks mobs carry: block items in a hand (`ItemInHandLayer`) and the //! block an enderman holds (`CarriedBlockLayer`), drawn as shaded cubes like -//! dropped block items. +//! dropped block items. Also the block models mobs wear (`SnowGolemHeadLayer`, +//! `MushroomCowMushroomLayer`). use super::Game; use horizon_client::{ items::ItemStack, @@ -218,6 +219,7 @@ impl Game<'_> { ) { self.captain_banner_geometry(mob, camera, alpha, light, out); self.held_item_geometry(mob, camera, alpha, light, true, out); + self.worn_block_geometry(mob, camera, alpha, light, out); if mob.species() == Species::Enderman && let Some(state) = mob.extra.carried && let Some((sprite, tint)) = self.block_face_sprite(state) @@ -244,6 +246,76 @@ impl Game<'_> { ); } } + /// `SnowGolemHeadLayer` and `MushroomCowMushroomLayer`: the carved pumpkin + /// on a snow golem's head, and the mushrooms on an adult mooshroom's back + /// and head, as baked block models. + fn worn_block_geometry( + &self, + mob: &Mob, + camera: glam::DVec3, + alpha: f64, + light: u32, + out: &mut Vec, + ) { + use glam::{Mat4, Vec3}; + let species = mob.species(); + let on_head = match species { + Species::SnowGolem => !mob.extra.sheared, + Species::Mooshroom => !mob.is_baby(), + _ => false, + }; + // The layers draw nothing on an invisible mob (the glow outline is not drawn). + if !on_head || horizon_client::mobs::trader::is_invisible(mob) { + return; + } + let registry = &self.pack.assets.registry; + let block = match species { + Species::SnowGolem => "minecraft:carved_pumpkin", + _ if mob.extra.variant == 1 => "minecraft:brown_mushroom", + _ => "minecraft:red_mushroom", + }; + let Some(state) = registry.default_state(block) else { + return; + }; + let alpha = alpha as f32; + let Some(head) = render::part_transform(mob, alpha, camera, self.res.mob_data(), "head") + else { + return; + }; + let unit = Mat4::from_translation(Vec3::splat(-0.5)); + let flip = Mat4::from_scale(Vec3::new(-1.0, -1.0, 1.0)); + let at = |x: f32, y: f32, z: f32| Mat4::from_translation(Vec3::new(x, y, z)); + let spin = |degrees: f32| Mat4::from_rotation_y(degrees.to_radians()); + let transforms = if species == Species::SnowGolem { + vec![ + head * at(0.0, -0.34375, 0.0) + * spin(180.0) + * Mat4::from_scale(Vec3::new(0.625, -0.625, -0.625)) + * unit, + ] + } else { + let base = render::base_transform(mob, alpha, camera); + vec![ + base * at(0.2, -0.35, 0.5) * spin(-48.0) * flip * unit, + base * at(0.2, -0.35, 0.5) + * spin(42.0) + * at(0.1, 0.0, -0.6) + * spin(-48.0) + * flip + * unit, + head * at(0.0, -0.7, -0.2) * spin(-78.0) * flip * unit, + ] + }; + // The hurt tint reaches these blocks as it does the body. + let overlay = horizon_client::overlay::living(0.0, mob.hurt_time > 0 || mob.death_time > 0); + for t in transforms { + let start = out.len(); + self.block_model_vertices(state, 0, t, light, true, out); + for vertex in &mut out[start..] { + vertex.layer = overlay; + } + } + } /// `ItemInHandLayer`: both hands through the item model pipeline; `lit` /// applies the level's diffuse lighting (off for GUI previews, which /// light the projected quads themselves). diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index d2e52d2a2..52dc46fe0 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -371,7 +371,10 @@ impl Game<'_> { } /// The chat's tree after the running mods changed. fn sync_mod_commands(&mut self) { - let mut names = self.mods.mods.commands().peekable(); + // In-frame, the window runs server mods too: their names, free text + // here (the server parses their arguments). + let server = self.mods.mods.server_commands().map(|c| c.name.as_str()); + let mut names = self.mods.mods.commands().chain(server).peekable(); self.mods.tree = names .peek() .is_some() diff --git a/crates/horizon-client/src/game/music.rs b/crates/horizon-client/src/game/music.rs index fa5e71f7b..97ca3763e 100644 --- a/crates/horizon-client/src/game/music.rs +++ b/crates/horizon-client/src/game/music.rs @@ -3,7 +3,7 @@ use super::Game; use horizon_client::{ blocks::Fluid, - music::{BackgroundMusic, Music, Situation}, + music::{BackgroundMusic, Music, MusicFrequency, Situation}, sound_engine::TickContext, }; @@ -11,6 +11,11 @@ impl Game<'_> { /// `Minecraft.tick` -> `MusicManager.tick`, once per client tick. pub(super) fn tick_music(&mut self) { let (music, volume) = self.situational_music(); + // Options.musicFrequency's listener: MusicManager.setMinutesBetweenSongs. + let frequency = MusicFrequency::parse(&self.settings.file.name("musicFrequency")); + if frequency != self.music.frequency { + self.music.set_frequency(frequency, music.as_ref()); + } // LevelLoadingScreen: no new track before the player is in the world. let loading = self.title.is_none() && self.player.is_none() && self.win.is_none(); self.music diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index b5e650e70..9e727d35d 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -357,7 +357,8 @@ impl Game<'_> { pub(super) fn load_mob(&mut self, tag: Tag, mount: Option) -> Option { self.next_entity += 1; let uuid = entity_nbt::uuid(&tag); - // Structure entities placed with finalizeEntities. + // Structure mobs that generation left to finish: saves from before + // they were finalized at placement, or a placement that could not. let mut tag = tag; let mut finalize = false; if let Tag::Compound(c) = &mut tag { @@ -449,7 +450,8 @@ impl Game<'_> { } } /// An entity of a type Horizon does not simulate, kept as its compound. - fn load_other(&mut self, tag: Tag, kind: &str) -> Option { + fn load_other(&mut self, mut tag: Tag, kind: &str) -> Option { + strip_finalize(&mut tag); let position = entity_nbt::position(&tag)?; let rotation = match tag.get("Rotation") { Some(Tag::List(l)) => { @@ -1014,3 +1016,9 @@ impl Game<'_> { self.save.save_entities(chunks) } } +/// Only a mob is finalized; another entity drops the request. +fn strip_finalize(tag: &mut Tag) { + if let Tag::Compound(c) = tag { + c.remove(&"horizon:finalize".into()); + } +} diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 2ccfd4116..4dd8cdb05 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -12,6 +12,7 @@ use horizon_client::{ hud_layout, hud_overlays, inventory_effects, items::ItemStack, mesher::Vertex, + text::Text, }; use horizon_core::{geometry::Vec3, random::RandomSource}; @@ -26,6 +27,9 @@ pub(super) struct ThrownPotion { position: Vec3, velocity: Vec3, age: u32, + /// `Projectile.getOwner`'s display name: the player who threw it (none + /// for a dispenser's). + owner: Option, } /// A mob's effect ids carry the `minecraft:` namespace. fn mob_effect_id(id: &str) -> Option<&'static str> { @@ -47,7 +51,13 @@ fn mob_effect_id(id: &str) -> Option<&'static str> { impl Game<'_> { /// A splash potion, lingering potion or experience bottle in flight (the /// player's throws and dispensers both end up here). - pub(super) fn launch_thrown(&mut self, stack: ItemStack, position: Vec3, velocity: Vec3) { + pub(super) fn launch_thrown( + &mut self, + stack: ItemStack, + position: Vec3, + velocity: Vec3, + owner: Option, + ) { self.potions.thrown.push(ThrownPotion { id: 0, stack, @@ -55,6 +65,7 @@ impl Game<'_> { position, velocity, age: 0, + owner, }); } } @@ -135,6 +146,7 @@ impl PotionState { position: at, velocity, age: 0, + owner: None, }); } /// ThrowableItemProjectile.DATA_ITEM_STACK: the potion it shows. @@ -237,6 +249,7 @@ impl Game<'_> { }, Vec3::new(eye[0], eye[1] - 0.1, eye[2]), v, + Some(self.player_display_text()), ); self.swing_arm(); self.consume_held(); @@ -548,15 +561,15 @@ impl Game<'_> { } } if let Some(p) = hit { - landed.push((t.stack.clone(), p)); + landed.push((t.stack.clone(), p, t.owner.clone())); return false; } t.position = next; t.age < 1200 && t.position.y > -128.0 }); self.potions.thrown = thrown; - for (stack, at) in landed { - self.splash(&stack, at); + for (stack, at, owner) in landed { + self.splash(&stack, at, owner); } } /// `ThrowableProjectile.tick`'s `applyGravity` and `applyInertia`, which @@ -664,6 +677,7 @@ impl Game<'_> { effects: &'static [(&'static str, i32, i32)], at: Vec3, scale: f64, + source: &Text, ) { if let Some(p) = self.player.as_ref() { let center = Vec3::new( @@ -679,6 +693,18 @@ impl Game<'_> { let instant = brewing::effect(id).is_some_and(|e| e.instant); if instant { if let Some(a) = horizon_client::effects::instant(id, *amp, intensity) { + // HealOrHarmMobEffect.applyInstantaneousEffect with + // a source: indirectMagic, not plain magic. + let a = match a { + EffectAction::Hurt("minecraft:magic", amount) => { + self.note_direct_entity( + "minecraft:indirect_magic", + source.clone(), + ); + EffectAction::Hurt("minecraft:indirect_magic", amount) + } + a => a, + }; self.apply_effect_action(a); } } else { @@ -694,68 +720,47 @@ impl Game<'_> { } } /// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash). - fn splash(&mut self, stack: &ItemStack, at: Vec3) { + fn splash(&mut self, stack: &ItemStack, at: Vec3, owner: Option) { + let block = [at.x, at.y, at.z].map(|v| v.floor() as i32); if &*stack.item == "minecraft:experience_bottle" { // ThrownExperienceBottle.onHit: the water-coloured splash (level - // event 2002) and 3 to 11 experience. - let pitch = self.world.random.next_float() * 0.1 + 0.9; - self.audio.play( - "minecraft:entity.splash_potion.break", - Some([at.x, at.y, at.z]), - 1.0, - pitch, - ); - for _ in 0..8 { - let v = [ - f64::from(self.world.random.next_float() - 0.5) * 0.3, - 0.2, - f64::from(self.world.random.next_float() - 0.5) * 0.3, - ]; - let p = horizon_client::particles::Particle::terrain( - &mut self.world.random, - [at.x, at.y, at.z], - v, - "item/splash_potion".into(), - 0x38_5DC6, - ); - self.particles.push(p); - } + // event 2002, its sound 1053) and 3 to 11 experience. + self.level_event_at(2002, block, 0xFF38_5DC6u32 as i32); + self.level_event_at(1053, block, 0); let r = &mut self.world.random; let value = 3 + r.next_int_bound(5).unwrap_or(0) + r.next_int_bound(5).unwrap_or(0); self.spawn_orbs([at.x, at.y, at.z], value as u32); return; } let lingering = &*stack.item == "minecraft:lingering_potion"; - let event = if lingering { - "minecraft:entity.lingering_potion.break" - } else { - "minecraft:entity.splash_potion.break" - }; - let pitch = self.world.random.next_float() * 0.1 + 0.9; - self.audio.play(event, Some([at.x, at.y, at.z]), 1.0, pitch); + // AbstractThrownPotion.onHit: level event 2007 and sound 1054 for a + // potion with instant effects, 2002 and 1053 otherwise. + let potion = stack.potion().and_then(brewing::potion); + let instant = potion.is_some_and(|d| { + d.effects + .iter() + .any(|(id, ..)| brewing::effect(id).is_some_and(|e| e.instant)) + }); let color = brewing::potion_color(stack.potion()); - for _ in 0..8 { - let v = [ - f64::from(self.world.random.next_float() - 0.5) * 0.3, - 0.2, - f64::from(self.world.random.next_float() - 0.5) * 0.3, - ]; - let p = horizon_client::particles::Particle::terrain( - &mut self.world.random, - [at.x, at.y, at.z], - v, - "item/splash_potion".into(), - color, - ); - self.particles.push(p); - } + self.level_event_at(if instant { 2007 } else { 2002 }, block, color as i32); + self.level_event_at(if instant { 1054 } else { 1053 }, block, 0); let scale = if lingering { 0.25 } else { 1.0 }; - let Some(def) = stack.potion().and_then(brewing::potion) else { + let Some(def) = potion else { return; }; // Every player in range (`ThrownSplashPotion.applySplash` over // `LivingEntity`s, the players among them). - self.for_each_player(|g| g.splash_on_player(def.effects, at, scale)); + // Instant damage is indirectMagic(potion or cloud, owner), which the + // death message names by the owner, else by the potion or cloud. + let source = owner.unwrap_or_else(|| { + let entity = if lingering { + "entity.minecraft.area_effect_cloud" + } else { + "entity.minecraft.splash_potion" + }; + Text::translate(entity, &[]) + }); + self.for_each_player(|g| g.splash_on_player(def.effects, at, scale, &source)); // Mobs take the instant effects (undead invert healing and harming). let undead = &self.res.stations().enchantments.entity_tags; let mut hits = Vec::new(); diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index 743f02f44..da7c79394 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -235,7 +235,7 @@ impl Game<'_> { } out } - fn difficulty_id(&self) -> i32 { + pub(super) fn difficulty_id(&self) -> i32 { use horizon_world::food::Difficulty; match self.world.health_rules.difficulty { Difficulty::Peaceful => 0, diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 945af4585..77e143f9a 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1560,7 +1560,7 @@ impl Game<'_> { } } /// Find a game slot in the menu's complete, contiguous slot mapping. - fn menu_slot_index(menu: &str, internal: usize) -> Option { + pub(super) fn menu_slot_index(menu: &str, internal: usize) -> Option { (0..) .map_while(|slot| Self::menu_slot(menu, slot)) .position(|slot| slot == internal) @@ -1741,7 +1741,17 @@ impl Game<'_> { f64::from(p.y) / 8.0, f64::from(p.z) / 8.0, ]; - self.audio.play(&name, Some(at), p.volume, p.pitch); + // ClientPacketListener.handleSoundEvent plays with packet.getSource(). + match usize::try_from(p.source) + .ok() + .filter(|s| *s < horizon_client::settings::SOUND_SOURCES.len()) + { + Some(source) => { + self.audio + .play_on(source, &name, Some(at), p.volume, p.pitch) + } + None => self.audio.play(&name, Some(at), p.volume, p.pitch), + } } } C::StopSound(p) => self @@ -1975,9 +1985,9 @@ impl Game<'_> { } } } - // Entity.DATA_SHARED_FLAGS_ID's crouching bit: another - // player's or a mannequin's crouch (their model and - // Entity.isDiscrete's name tag). + // Entity.DATA_SHARED_FLAGS_ID's crouching and sprinting bits: + // another player's or a mannequin's crouch (their model and + // Entity.isDiscrete's name tag), and the dust a runner raises. if (mannequin || self .remote @@ -1988,6 +1998,7 @@ impl Game<'_> { for (index, _, value) in &p.values { if let (0, Value::Byte(flags)) = (index, value) { m.extra.crouching = flags & 2 != 0; + m.extra.sprinting = flags & 8 != 0; } } } @@ -2111,6 +2122,7 @@ impl Game<'_> { if p.event == super::fireworks::FIREWORK_EXPLODE_EVENT { self.remote_firework_explosion(p.id); } + self.remote_fangs_event(p.id as u32, p.event); // LocalPlayer.setPermissions also refreshes an open World Options screen. if (24..=28).contains(&p.event) && self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) @@ -2135,9 +2147,33 @@ impl Game<'_> { { m.health = 0.0; } + // LivingEntity.handleEntityEvent 60: the poof as the dead body goes. + if p.event == 60 + && let Some(m) = self.mobs.iter().find(|m| m.id == p.id as u32) + { + let (at, w, h) = (m.position, f64::from(m.width()), f64::from(m.height())); + self.death_poof([at.x, at.y, at.z], w, h); + } if p.event == super::totem::TOTEM_EVENT { self.remote_totem(p.id); } + // Entity event 53: the honey slide particles of a player + // sliding down a honey block (HoneyBlock.showSlideParticles). + if p.event == 53 { + let at = if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) { + self.player + .as_ref() + .map(|q| [q.position.x, q.position.y, q.position.z]) + } else { + self.mobs + .iter() + .find(|m| m.id == p.id as u32) + .map(|m| [m.position.x, m.position.y, m.position.z]) + }; + if let Some(at) = at { + self.honey_slide_particles(at); + } + } } C::Animate(p) => self.remote_animate(p.id, p.action), // ClientPacketListener.handleSwingAnimation: the entity swings @@ -3141,6 +3177,8 @@ impl Game<'_> { // server says the entry ended. `onCooldownEnded` is the plain // ItemCooldowns' no-op on a client. self.cooldowns.tick(); + // Leaving a slot clears its bundle's selection here and on the server. + self.tick_bundle_hover(); // Options.broadcastOptions: a changed render distance or Chat option // is sent again. let view = client_view_distance(self.settings.render_distance); @@ -3331,6 +3369,13 @@ impl Game<'_> { horizon_client::motion::MotionEvent::InsidePortal { .. } => { self.client_inside_nether_portal(); } + // HoneyBlock.maybeDoSlideEffects on the client's own level: + // the slide sound, heard here (LocalPlayer.playSound); the + // particles come from the server's event 53. + horizon_client::motion::MotionEvent::HoneySlide { sound: true, .. } => { + self.audio + .play("minecraft:block.honey_block.slide", Some(feet), 1.0, 1.0); + } _ => {} } } @@ -3507,6 +3552,16 @@ impl Game<'_> { if m.species() == horizon_client::mobs::Species::Rabbit { horizon_client::mobs::rabbit::base_tick(m); } + if matches!( + m.species(), + horizon_client::mobs::Species::Horse + | horizon_client::mobs::Species::Donkey + | horizon_client::mobs::Species::Mule + | horizon_client::mobs::Species::SkeletonHorse + | horizon_client::mobs::Species::ZombieHorse + ) { + horizon_client::mobs::equine::tail_tick(m); + } if m.species() == horizon_client::mobs::Species::Creeper { horizon_client::mobs::hostile::creeper_client_tick(m); } @@ -3517,6 +3572,10 @@ impl Game<'_> { ) { horizon_client::mobs::guardian::client_tick(m); } + // PolarBear.tick: the stand animation follows the synched flag. + if m.species() == horizon_client::mobs::Species::PolarBear { + horizon_client::mobs::polar_bear::client_tick(m); + } if m.hurt_time > 0 { m.hurt_time -= 1; } @@ -4702,7 +4761,7 @@ impl Game<'_> { } /// The server's open menu: its window id and menu type (0, "inventory" /// when none is open). - fn remote_menu(&self) -> (i32, String) { + pub(super) fn remote_menu(&self) -> (i32, String) { match self.remote.as_ref().and_then(|r| r.menu.clone()) { Some((id, name)) => (id, name), None => (0, "inventory".to_owned()), @@ -4792,26 +4851,6 @@ impl Game<'_> { })); } } - /// A `ContainerClick` on game slot `internal` of the server's open menu - /// (`input` is the ContainerInput ordinal). False when the menu has no - /// such slot. - pub(super) fn remote_slot_click(&mut self, internal: usize, button: i8, input: i32) -> bool { - let (container, menu) = self.remote_menu(); - let slot = Self::menu_slot_index(&menu, internal); - let Some(slot) = slot else { return false }; - let carried = self.to_network(&self.carried).map(|s| Hashed::of(&s)); - let state = self.remote.as_ref().map_or(0, |r| r.state_id); - self.send(S::ContainerClick(play::ContainerClick { - container, - state, - slot: slot as i16, - button, - input, - changed: Vec::new(), - carried, - })); - true - } /// The server's open menu is the inventory or a chest-like container /// (chests, barrels, ender chests: `generic_9xN`; shulker boxes). pub(super) fn remote_storage_open(&self) -> bool { diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index c6702dfb6..65bbbfbbe 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -5,7 +5,8 @@ use super::Game; use horizon_client::mobs::render::{PROFESSIONS, VILLAGER_TYPES}; use horizon_client::mobs::{Mob, Species, Who, bat, tame}; -use horizon_protocol::entity_data::Value; +use horizon_client::particles::{ParticleOptions, ParticleType}; +use horizon_protocol::entity_data::{Particle, ParticleData, Value}; use horizon_protocol::registry::Builtin; /// The values `apply` takes from one SetEntityData packet, by vanilla's entry @@ -34,6 +35,10 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti // LivingEntity.DATA_HEALTH_ID: the boss bars and the death // animation follow it. (9, Value::Float(health)) => m.health = *health, + // LivingEntity.DATA_EFFECT_PARTICLES and DATA_EFFECT_AMBIENCE_ID: + // the swirls of its effects (`tickEffects` draws them). + (10, Value::Particles(list)) => m.extra.effect_particles = swirls(list, builtin), + (11, Value::Bool(ambient)) => m.extra.effect_ambient = *ambient, // Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2, aggressive 4. // Mob.isAggressive draws the illagers' and skeletons' attack // poses and the vindicator's axe. @@ -59,6 +64,8 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti Who::Mob(*target as u32) }); } + // PolarBear.DATA_STANDING_ID: the client animates the rearing. + (Species::PolarBear, 18, Value::Bool(standing)) => m.extra.flag = *standing, // Bat.DATA_ID_FLAGS: resting in bit 0. (Species::Bat, 16, Value::Byte(flags)) => bat::set_resting(m, flags & 1 != 0), // Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 sheared. @@ -66,6 +73,14 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti m.extra.color = (*wool & 15) as u8; m.extra.sheared = wool & 16 != 0; } + // SnowGolem.DATA_PUMPKIN_ID: 16 while the pumpkin is on. + (Species::SnowGolem, 16, Value::Byte(flags)) => m.extra.sheared = flags & 16 == 0, + // MushroomCow.DATA_TYPE: 0 red, 1 brown. + (Species::Mooshroom, 17, Value::Int(variant)) => { + m.extra.variant = (*variant == 1) as u8 + } + // Piglin.DATA_IS_DANCING: the dance pose. + (Species::Piglin, 19, Value::Bool(dancing)) => m.extra.scratch[0] = i32::from(*dancing), // TamableAnimal.DATA_FLAGS_ID: sitting 1, tame 4. (Species::Wolf | Species::Cat | Species::Parrot, 18, Value::Byte(flags)) => { m.extra.sitting = flags & 1 != 0; @@ -100,6 +115,30 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti } } +/// The options of a synched particle list: an entity effect carries its ARGB +/// colour, the omens none. +fn swirls(list: &[Particle], builtin: &Builtin) -> Vec { + let channel = |argb: i32, shift: u32| ((argb >> shift) & 255) as f32 / 255.0; + list.iter() + .filter_map(|p| { + let name = builtin.get("minecraft:particle_type")?.name(p.id)?; + let ty = ParticleType::from_name(name)?; + Some(match p.data { + Some(ParticleData::Color(argb)) => ParticleOptions::colored( + ty, + [ + channel(argb, 16), + channel(argb, 8), + channel(argb, 0), + channel(argb, 24), + ], + ), + _ => ParticleOptions::simple(ty), + }) + }) + .collect() +} + /// VillagerData as the network sends it: the type and the profession by /// their built-in registry ids, then the level. fn villager_data(m: &mut Mob, data: &[i32], builtin: &Builtin) { diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index 897999c6b..55c233ca0 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -95,6 +95,7 @@ impl Game<'_> { let (yaw, pitch) = rotation; self.remove_remote_projectile(id); match kind { + "minecraft:evoker_fangs" => self.insert_fangs(id, position, yaw, 0, 0), "minecraft:tnt" => self.tnts.push(super::tnt::PrimedTnt { id, position: at, @@ -161,6 +162,10 @@ impl Game<'_> { let Some(k) = projectile_kind(kind) else { return false; }; + if k == ProjectileKind::LlamaSpit { + self.particles + .llama_spit_burst(position, [velocity.x, velocity.y, velocity.z]); + } let mut p = Projectile::new(k, at, None); p.id = id; p.velocity = velocity; @@ -296,6 +301,7 @@ impl Game<'_> { /// One tick of interpolation, as `tick_remote_objects`. pub(super) fn tick_remote_projectiles(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) { + self.tick_remote_fangs(); // PrimedTnt.tick runs on a client too: it falls, bounces and burns its // fuse down (the swell and flash follow it) between the server's // updates (every 10 ticks), and a client discards it when the fuse @@ -458,6 +464,7 @@ impl Game<'_> { } pub(super) fn remove_remote_projectile(&mut self, id: u32) { + self.fangs.list.retain(|f| f.id != id); self.tnts.retain(|t| t.id != id); self.falling.retain(|f| f.id != id); self.creatures.projectiles.retain(|p| p.id != id); @@ -473,6 +480,7 @@ impl Game<'_> { /// Every one a server sent (a new connection, level or dimension). pub(super) fn clear_remote_projectiles(&mut self) { + self.fangs.list.clear(); self.tnts.clear(); self.falling.clear(); self.creatures.projectiles.clear(); @@ -493,6 +501,12 @@ impl Game<'_> { use serde_json::json; let at = |p: Vec3| [p.x, p.y, p.z]; let mut out = Vec::new(); + for f in &self.fangs.list { + out.push( + json!({"id": f.id, "kind": "minecraft:evoker_fangs", "position": f.pos, + "yaw": f.yaw, "started": f.started, "life": f.life}), + ); + } for t in &self.tnts { out.push(json!({"id": t.id, "kind": "minecraft:tnt", "position": at(t.position), "fuse": t.fuse})); } diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index e013c8d29..3f5862f49 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -7,6 +7,7 @@ use horizon_client::{ biome::Biomes, blocks::{BlockFacts, Fluid}, chunk::{HEIGHT, MIN_Y}, + containers::BlockEntity, particles::{ParticleLevel, ParticleOptions, ParticleType}, world::World, }; @@ -344,6 +345,10 @@ impl Game<'_> { &mut self.particles, &ctx, r.block_entities(), + &|pos| match self.world.block_entities.get(&(pos[0], pos[1], pos[2])) { + Some(BlockEntity::Campfire(c)) => c.items.each_ref().map(Option::is_some), + _ => [false; 4], + }, ); } let level = ParticleLevel { diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 81c03e288..72b3ab000 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -132,8 +132,16 @@ impl Game<'_> { match t { Target::Player => Some(self.acting_player_name().to_owned()), Target::Guest(conn) => self.command_guest(conn).map(|g| g.name.clone()), - Target::Mob(id) | Target::Item(id) => Some(uuid_text(self.uuid_for(id))), - _ => None, + Target::Mob(id) + | Target::Item(id) + | Target::Stand(id) + | Target::Frame(id) + | Target::Painting(id) + | Target::Boat(id) + | Target::Cart(id) + | Target::Other(id) => Some(uuid_text(self.uuid_for(id))), + // Orbs and projectiles are addressed by index and have no UUID here. + Target::Orb(_) | Target::Projectile(_) => None, } } fn holder_for(&mut self, t: Target) -> Option { diff --git a/crates/horizon-client/src/game/server_mods.rs b/crates/horizon-client/src/game/server_mods.rs index f5ee5cdc2..a5a4b0f3f 100644 --- a/crates/horizon-client/src/game/server_mods.rs +++ b/crates/horizon-client/src/game/server_mods.rs @@ -59,9 +59,12 @@ mod run { lan::data::component_nbt, text::{self, Text}, }; - use horizon_mods::{BlockPos, GameMode, Output, ServerPlayer, WorldView}; + use horizon_mods::{ + ArgumentKind, BlockPos, GameMode, Output, ServerCommand, ServerPlayer, WorldView, + }; use horizon_protocol::packets::play::{self, Clientbound as C}; use horizon_world::registry::{BlockRegistry, BlockStateId}; + use serde_json::{Value, json}; /// Blocks queued for levels that don't tick (another dimension, in-frame) /// are kept up to this many; the oldest go first. @@ -98,6 +101,60 @@ mod run { } } + /// Server mods' commands as a root of the commands report + /// (`lan::commands`): a literal per command, then its arguments in a + /// chain, each node runnable where only optional arguments follow. + fn command_tree<'a>(commands: impl Iterator) -> Value { + let mut root = serde_json::Map::new(); + for c in commands { + let mut next: Option<(String, Value)> = None; + for (i, a) in c.arguments.iter().enumerate().rev() { + let executable = c.arguments.get(i + 1).is_none_or(|b| b.optional); + let (parser, properties) = match a.kind { + ArgumentKind::Word => ("brigadier:string", json!({"type": "word"})), + ArgumentKind::Text => ("brigadier:string", json!({"type": "greedy"})), + ArgumentKind::Integer((min, max)) => { + let mut p = serde_json::Map::new(); + if let Some(min) = min { + p.insert("min".into(), min.into()); + } + if let Some(max) = max { + p.insert("max".into(), max.into()); + } + ("brigadier:integer", Value::Object(p)) + } + ArgumentKind::Number => ("brigadier:double", Value::Null), + ArgumentKind::Boolean => ("brigadier:bool", Value::Null), + ArgumentKind::Player => ( + "minecraft:entity", + json!({"amount": "single", "type": "players"}), + ), + ArgumentKind::BlockPos => ("minecraft:block_pos", Value::Null), + }; + let mut node = json!({ + "type": "argument", + "parser": parser, + "properties": properties, + "executable": executable, + }); + if let Some((name, child)) = next.take() { + node["children"] = json!({ name: child }); + } + next = Some((a.name.clone(), node)); + } + let executable = c.arguments.first().is_none_or(|a| a.optional); + let mut literal = json!({"type": "literal", "executable": executable}); + if let Some((name, child)) = next { + literal["children"] = json!({ name: child }); + } + root.insert(c.name.clone(), literal); + } + if root.is_empty() { + return Value::Null; + } + json!({"type": "root", "children": root}) + } + /// `minecraft:oak_log[axis=y]`. fn state_string(registry: &BlockRegistry, state: BlockStateId) -> String { let Some(s) = registry.state(state) else { @@ -191,6 +248,7 @@ mod run { // A server has no frames to check its dev mods in. self.reload_dev_mods(); } + self.send_server_mod_commands(); if !self.mods.server { return; } @@ -257,6 +315,20 @@ mod run { self.apply_mod_block_writes(); } + /// Players' command trees list the running server mods' commands + /// after vanilla's, whenever they change (or a hub opens). + fn send_server_mod_commands(&mut self) { + let key = self.mods.mods.generation(); + let Some(host) = self.lan.as_mut() else { + return; + }; + if host.hub.mod_commands_key() == Some(key) { + return; + } + let tree = command_tree(self.mods.mods.server_commands()); + host.hub.set_mod_commands(key, tree); + } + /// Lends the levels' chunks to capability `world` for the calls up to /// [`Game::return_world`], when a running server mod has it. fn lend_world(&mut self) { diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index c5ddcf9a1..361879d2e 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -277,6 +277,10 @@ fn argb(c: i32) -> u32 { ) } +/// A text style's `0xRRGGBB` colour from a HUD colour (`rgba`). +fn rgb_of(rgba: u32) -> u32 { + (rgba & 0xFF) << 16 | (rgba >> 8 & 0xFF) << 8 | (rgba >> 16 & 0xFF) +} impl Game<'_> { /// `Component.translatable`: the selected language (which `lang` layers /// over `en_us`), the caller's English text last. @@ -1690,20 +1694,34 @@ impl Game<'_> { &self, stack: &ItemStack, ) -> Vec<(horizon_client::text::Text, u32)> { - let e: &Enchantments = &self.res.stations().enchantments; - let props = e.props(&stack.item); + self.stack_tooltip_lines(stack, false) + } + /// `ItemStack.getRarity`'s colour for the name line and a `[name]` link. + fn rarity_color(&self, stack: &ItemStack) -> u32 { + let props = self.res.stations().enchantments.props(&stack.item); let rarity = horizon_client::item_tooltip::rarity( stack, props.map_or("common", |p| p.rarity.as_str()), ); - let color = match rarity { + match rarity { "uncommon" => rgba(255, 255, 85, 255), "rare" => rgba(85, 255, 255, 255), "epic" => rgba(255, 85, 255, 255), _ => u32::MAX, - }; - let name = if let Some(n) = stack.custom_name() { + } + } + /// `ItemStack.getHoverName`: the custom name, a written book's title, the + /// item name component, else the item's or potion's name. + fn stack_hover_name(&self, stack: &ItemStack) -> String { + if let Some(n) = stack.custom_name() { n.to_owned() + } else if let Some(title) = stack + .data() + .and_then(|d| d.written.as_ref()) + .map(|w| w.title.as_str()) + .filter(|t| !t.trim().is_empty()) + { + title.to_owned() } else if let Some(n) = stack.item_name() { n } else if stack.data().is_some_and(|d| d.ominous_banner) { @@ -1719,16 +1737,47 @@ impl Game<'_> { .unwrap_or_else(|| self.pack.names.display_item(&stack.item)) } else { self.pack.names.display_item(&stack.item) - }; + } + } + /// `ItemStack.getTooltipLines`. A `nested` stack is a crossbow's + /// projectile: `ChargedProjectiles.addProjectileTooltip` takes its details + /// without the name, the player and the advanced flag. + fn stack_tooltip_lines( + &self, + stack: &ItemStack, + nested: bool, + ) -> Vec<(horizon_client::text::Text, u32)> { + let e: &Enchantments = &self.res.stations().enchantments; + let color = self.rarity_color(stack); + let advanced = !nested && self.options_advanced_tooltips(); let display = horizon_client::item_tooltip::TooltipDisplay::for_stack(stack); let mut lines = Vec::new(); - if display.name_visible(self.screen == Screen::Creative) { - lines.push((horizon_client::text::Text::legacy(&name), color)); + if !nested && display.name_visible(self.screen == Screen::Creative) { + // `getStyledHoverName`: a custom name is italic. + let name = self.stack_hover_name(stack); + let name = if stack.custom_name().is_some() { + horizon_client::text::Text::literal(name).italic() + } else { + horizon_client::text::Text::legacy(&name) + }; + lines.push((name, color)); } let translate = |k: &str| self.pack.names.display_get(k); let push = |lines: &mut Vec<(horizon_client::text::Text, u32)>, s: String, c: u32| { lines.push((horizon_client::text::Text::legacy(&s), c)); }; + let gray = rgba(170, 170, 170, 255); + let item_info = self.res.items().get(&stack.item); + // InstrumentComponent.addToTooltip. + if let Some(text) = + horizon_client::item_tooltip::instrument_line(stack, &display, &translate) + { + push(&mut lines, text, gray); + } + // Bees.addToTooltip. + if let Some(text) = horizon_client::item_tooltip::bees_line(stack, &display, &translate) { + push(&mut lines, text, gray); + } // ItemContainerContents.addToTooltip. let hover_name = |s: &ItemStack| { s.custom_name() @@ -1743,6 +1792,70 @@ impl Game<'_> { push(&mut lines, text, u32::MAX); } } + // BannerPatternLayers.addToTooltip: up to six layer names. + if display.shows("minecraft:banner_patterns") { + for layer in horizon_client::banner::tooltip_layers(stack).iter().take(6) { + let key = self.res.stations().banners.layer_key(layer); + push( + &mut lines, + self.translate(&key, &key), + rgba(170, 170, 170, 255), + ); + } + } + // WrittenBookContent.addToTooltip. + for text in horizon_client::item_tooltip::written_book_lines(stack, &display, &translate) { + push(&mut lines, text, gray); + } + // ChargedProjectiles.addToTooltip: each run of equal projectiles, then + // the projectile's own details indented under it. + if display.shows("minecraft:charged_projectiles") { + let charged = stack.data().map_or(&[][..], |d| &d.charged[..]); + for run in charged.chunk_by(|a, b| a.same_item_same_components(b)) { + let projectile = &run[0]; + let name = self.stack_hover_name(projectile); + let line = if run.len() == 1 { + // `getDisplayName`: `[name]` in the rarity colour. + let mut shown = horizon_client::text::Text::literal(format!("[{name}]")) + .with_color(rgb_of(self.rarity_color(projectile))); + if projectile.custom_name().is_some() { + shown = shown.italic(); + } + horizon_client::text::format_translation( + &self.translate( + "item.minecraft.crossbow.projectile.single", + "Projectile: %s", + ), + &[shown], + ) + } else { + horizon_client::text::format_translation( + &self.translate( + "item.minecraft.crossbow.projectile.multiple", + "Projectile: %s x %s", + ), + &[ + horizon_client::text::Text::literal(run.len().to_string()), + horizon_client::text::Text::literal(name), + ], + ) + }; + lines.push((line, u32::MAX)); + for (text, c) in self.stack_tooltip_lines(projectile, true) { + // `literal(" ").append(line).withStyle(GRAY)`: the line's + // own colours win over the gray. + let rgb = if c == u32::MAX { + horizon_client::text::GRAY + } else { + rgb_of(c) + }; + let indented = horizon_client::text::Text::literal(" ") + .append(text) + .with_color(rgb); + lines.push((indented, u32::MAX)); + } + } + } // Fireworks / FireworkExplosion.addToTooltip. for text in horizon_client::item_tooltip::firework_lines(stack, &translate) { push(&mut lines, text, rgba(170, 170, 170, 255)); @@ -1765,6 +1878,17 @@ impl Game<'_> { }; push(&mut lines, text, c); } + // The attribute modifiers of the effects (`When Applied:`). + for (text, c) in horizon_client::item_tooltip::potion_modifier_lines(stack, &translate) + { + push(&mut lines, text, c); + } + } + // JukeboxPlayable.addToTooltip. + if let Some(text) = + horizon_client::item_tooltip::jukebox_line(stack, item_info, &display, &translate) + { + push(&mut lines, text, gray); } if display.shows("minecraft:trim") && let Some((material, pattern)) = stack.data().and_then(|d| d.trim.clone()) @@ -1812,16 +1936,12 @@ impl Game<'_> { ); } } - // BannerPatternLayers.addToTooltip: up to six layer names. - if display.shows("minecraft:banner_patterns") { - for layer in horizon_client::banner::tooltip_layers(stack).iter().take(6) { - let key = self.res.stations().banners.layer_key(layer); - push( - &mut lines, - self.translate(&key, &key), - rgba(170, 170, 170, 255), - ); - } + // DyedItemColor.addToTooltip. + if let Some((text, italic)) = + horizon_client::item_tooltip::dyed_line(stack, &display, advanced, &translate) + { + let text = horizon_client::text::Text::legacy(&text); + lines.push((if italic { text.italic() } else { text }, gray)); } // ItemLore.addToTooltip: after the enchantments, before the attributes // (ItemStack.addDetailsToTooltip). @@ -1830,6 +1950,50 @@ impl Game<'_> { lines.push((text, u32::MAX)); } } + if display.shows("minecraft:attribute_modifiers") { + // The item's own modifiers, then its enchantments' for each slot + // group (`ItemStack.forEachModifier`). + let mut modifiers = item_info.map(|i| i.modifiers.clone()).unwrap_or_default(); + modifiers.extend(e.modifier_rows(stack)); + let base = |name: &str, default| { + self.player + .as_ref() + .and_then(|player| { + let key = player.attributes.key(name)?; + let handle = player.attributes.lookup(Some(&key))?; + player + .attributes + .instance(&handle) + .ok() + .map(|value| value.base_value()) + }) + .unwrap_or(default) + }; + let player_base = (!nested).then(|| { + [ + base("minecraft:attack_damage", 1.0), + base( + "minecraft:attack_speed", + horizon_client::attack_strength::BASE_ATTACK_SPEED, + ), + ] + }); + for (text, c) in + horizon_client::item_tooltip::attribute_lines(&modifiers, player_base, &translate) + { + push(&mut lines, text, c); + } + } + // ItemStack.UNBREAKABLE_TOOLTIP. + if let Some(text) = + horizon_client::item_tooltip::unbreakable_line(stack, &display, &translate) + { + push(&mut lines, text, rgba(85, 85, 255, 255)); + } + // BlockItemStateProperties.addToTooltip. + if let Some(text) = horizon_client::item_tooltip::honey_line(stack, &display, &translate) { + push(&mut lines, text, gray); + } // Spawner.appendHoverText: what a spawner or trial spawner item spawns. if display.shows("minecraft:block_entity_data") && matches!( @@ -1853,43 +2017,11 @@ impl Game<'_> { } } } - if display.shows("minecraft:attribute_modifiers") - && let Some(info) = self.res.items().get(&stack.item) - { - let base = |name: &str, default| { - self.player - .as_ref() - .and_then(|player| { - let key = player.attributes.key(name)?; - let handle = player.attributes.lookup(Some(&key))?; - player - .attributes - .instance(&handle) - .ok() - .map(|value| value.base_value()) - }) - .unwrap_or(default) - }; - let player_base = [ - base("minecraft:attack_damage", 1.0), - base( - "minecraft:attack_speed", - horizon_client::attack_strength::BASE_ATTACK_SPEED, - ), - ]; - for (text, c) in horizon_client::item_tooltip::attribute_lines( - &info.modifiers, - Some(player_base), - &translate, - ) { - push(&mut lines, text, c); - } - } if display.shows("minecraft:damage") - && let Some(info) = self.res.items().get(&stack.item) + && let Some(info) = item_info && info.max_damage > 0 && stack.damage > 0 - && self.options_advanced_tooltips() + && advanced { push( &mut lines, @@ -1901,8 +2033,23 @@ impl Game<'_> { u32::MAX, ); } + // ItemStack.addDetailsToTooltipTail: with advanced tooltips the item id + // and how many components the stack has. + if advanced { + let dark_gray = rgba(85, 85, 85, 255); + push(&mut lines, stack.item.to_string(), dark_gray); + let count = horizon_client::item_tooltip::component_count(stack, item_info); + if count > 0 { + let text = self.translate("item.components", "%s component(s)"); + push( + &mut lines, + text.replacen("%s", &count.to_string(), 1), + dark_gray, + ); + } + } // ItemStack.OP_NBT_WARNING, for a player with game master permission. - if self.ui.registries.permission >= 2 && block_entity_item::op_warning(stack) { + if !nested && self.ui.registries.permission >= 2 && block_entity_item::op_warning(stack) { for (key, fallback) in [ ("item.op_warning.line1", "Warning:"), ( @@ -2105,12 +2252,18 @@ impl Game<'_> { batch: &mut HudBatch, layout: &horizon_client::bundle::TooltipLayout, ) { - for (at, stack) in &layout.slots { + for (i, (at, stack)) in layout.slots.iter().enumerate() { + let selected = layout.selected == Some(i); + let sprite = |name: &str| format!("gui/sprites/container/bundle/{name}"); // Each draw takes the atlas on its own: the item's needs `&mut self`. horizon_client::ui::nine_slice( batch, &self.gui.atlas, - "gui/sprites/container/bundle/slot_background", + &sprite(if selected { + "slot_highlight_back" + } else { + "slot_background" + }), at[0], at[1], 24.0, @@ -2120,6 +2273,18 @@ impl Game<'_> { let stack = stack.clone(); let [x, y] = *at; self.draw_item(batch, &stack, x + 4.0, y + 4.0); + if selected { + horizon_client::ui::nine_slice( + batch, + &self.gui.atlas, + &sprite("slot_highlight_front"), + x, + y, + 24.0, + 24.0, + u32::MAX, + ); + } } let atlas = &self.gui.atlas; if let Some((at, hidden)) = layout.overflow { diff --git a/crates/horizon-client/src/game/titles.rs b/crates/horizon-client/src/game/titles.rs index cbae1f6b4..9bb000314 100644 --- a/crates/horizon-client/src/game/titles.rs +++ b/crates/horizon-client/src/game/titles.rs @@ -21,6 +21,22 @@ impl Game<'_> { draws.extend(self.titles.title(w, h, partial, font, background)); hud_layout::paint(batch, &self.gui.atlas, &draws); } + /// `Hud.extractSavingIndicator`, under the screens: the option, then the + /// fading "Saving world" text. + pub(super) fn draw_saving_indicator(&self, batch: &mut HudBatch) { + if !self.settings.autosave_indicator { + return; + } + let draws = self.saving_indicator.draw( + batch.width as i32, + batch.height as i32, + self.clock.fraction() as f32, + &self.gui.atlas.font, + Text::literal(self.translate("menu.savingLevel", "Saving world")), + self.settings.text_background(0.0), + ); + hud_layout::paint(batch, &self.gui.atlas, &draws); + } /// The selected stack as `Hud.tick` compares it for the name highlight. fn held_name(&self) -> Option { let stack = self.inventory.get(self.selected)?.as_ref()?; @@ -44,6 +60,12 @@ impl Game<'_> { /// The title, action bar and selected-item parts of `Hud.tick`. pub(super) fn tick_hud(&mut self) { self.titles.tick(); + // `MinecraftServer.isCurrentlySaving` of single player's server. + let saving = self + .integrated + .as_ref() + .map_or(self.autosaving, |server| server.is_saving()); + self.saving_indicator.tick(saving); let held = self.held_name(); self.tool_highlight .tick(held, f64::from(self.settings.notification_display_time)); diff --git a/crates/horizon-client/src/game/tweaks.rs b/crates/horizon-client/src/game/tweaks.rs index cec83e248..648073874 100644 --- a/crates/horizon-client/src/game/tweaks.rs +++ b/crates/horizon-client/src/game/tweaks.rs @@ -70,8 +70,7 @@ impl Game<'_> { /// One ordinary click on a game slot. False when nothing took it. pub(super) fn tweak_click(&mut self, slot: usize, button: i32, input: Input) -> bool { if self.remote.is_some() { - let ordinal = super::remote::input_ordinal(input); - return self.remote_slot_click(slot, button as i8, ordinal); + return self.remote_menu_ops(&[(Some(slot), button, input)]); } if !self.menu_click(Some(slot), button, input) { return false; diff --git a/crates/horizon-client/src/graphics_style.rs b/crates/horizon-client/src/graphics_style.rs index e02a0e1d9..62979903b 100644 --- a/crates/horizon-client/src/graphics_style.rs +++ b/crates/horizon-client/src/graphics_style.rs @@ -118,8 +118,9 @@ impl Style { (x, y, w): (f32, f32, f32), label: &Text, hover: bool, + active: bool, ) { - ui::button(batch, atlas, x, y, w, 20.0, label, true, hover); + ui::button(batch, atlas, x, y, w, 20.0, label, active, hover); } pub fn slider( &self, diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index 3c7a40e02..d55e44d99 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -468,6 +468,10 @@ fn max_workers() -> u32 { } impl Item { + /// False for a setting whose system is not in Horizon yet (`Opt::available`). + fn available(self) -> bool { + !matches!(self, Item::Vanilla(o) if !o.available()) + } /// On/off settings and their value. pub fn switch(self, s: &Settings) -> Option { let g = &s.horizon; @@ -510,6 +514,9 @@ impl Item { } } pub fn set_slider(self, s: &mut Settings, v: f32) { + if !self.available() { + return; + } match self { Item::Vanilla(o) => o.set_slider(s, v), Item::Horizon(h) => h.set_slider(s, v), @@ -517,6 +524,9 @@ impl Item { self.touched(s); } pub fn cycle(self, s: &mut Settings, back: bool, framebuffer: [i32; 2]) { + if !self.available() { + return; + } match self { Item::Vanilla(o) => o.cycle(s, back, framebuffer), Item::Horizon(h) => h.cycle(s, back), @@ -689,6 +699,7 @@ impl GraphicsUi { }) .collect(); let mut index = 0; + let mut tooltip = None; for wd in &widgets { let hover = ui::hovered(cursor, wd.x, wd.y, wd.w, 20.0) && (!wd.list || (cursor.1 >= top && cursor.1 < bottom)); @@ -700,6 +711,13 @@ impl GraphicsUi { continue; } let label = item.label(s); + let live = item.available(); + if hover && !live { + tooltip = Some(atlas.font.split( + &Text::literal("This feature is not yet available in Horizon."), + 170.0, + )); + } match item.slider(s) { Some(value) => STYLE.slider( batch, @@ -709,7 +727,14 @@ impl GraphicsUi { value, hover || self.dragging == Some(item), ), - None => STYLE.button(batch, atlas, (wd.x, wd.y, wd.w), &label, hover), + None => STYLE.button( + batch, + atlas, + (wd.x, wd.y, wd.w), + &label, + hover && live, + live, + ), } STYLE.description( batch, @@ -732,6 +757,7 @@ impl GraphicsUi { (wd.x, wd.y, wd.w), &Text::literal(label), hover, + true, ); } } @@ -751,6 +777,9 @@ impl GraphicsUi { Level::Advanced => "Graphics: Advanced", }; STYLE.title(batch, atlas, &Text::literal(title)); + if let Some(lines) = tooltip { + ui::tooltip(batch, atlas, &lines, cursor); + } } /// A press (or a drag with `drag`) at `(x, y)`. pub fn click( @@ -788,6 +817,8 @@ impl GraphicsUi { } return match wd.target { Target::Button(action) => vec![Action::ButtonClick, action], + // A disabled control does nothing: no sound, no preset change. + Target::Item(item) if !item.available() => Vec::new(), Target::Item(item) => { if item.slider(s).is_some() { self.dragging = Some(item); diff --git a/crates/horizon-client/src/hud_overlays.rs b/crates/horizon-client/src/hud_overlays.rs index ebd860e08..c6b098f75 100644 --- a/crates/horizon-client/src/hud_overlays.rs +++ b/crates/horizon-client/src/hud_overlays.rs @@ -191,6 +191,53 @@ pub fn effects(w: i32, demo: bool, effects: &[EffectIcon]) -> Vec { out } +/// The saving indicator: `Hud.tickAutosaveIndicator` fades a value towards 1 +/// while the server is saving and `extractSavingIndicator` draws the text. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct SavingIndicator { + last: f32, + value: f32, +} +impl SavingIndicator { + /// `Hud.tickAutosaveIndicator`: `Mth.lerp(0.2F, value, saving ? 1 : 0)`. + pub fn tick(&mut self, saving: bool) { + self.last = self.value; + self.value += (if saving { 1.0 } else { 0.0 } - self.value) * 0.2; + } + /// `Hud.extractSavingIndicator` without the option check: the text in the + /// bottom right corner. + pub fn draw( + &self, + w: i32, + h: i32, + partial: f32, + font: &Font, + label: Text, + background: u32, + ) -> Vec { + let mut out = Vec::new(); + if self.value <= 0.0 && self.last <= 0.0 { + return out; + } + let fade = (self.last + (self.value - self.last) * partial).clamp(0.0, 1.0); + let alpha = (255.0 * fade).floor() as u32; + if alpha > 0 { + let label_width = width(font, &label); + let color = crate::hud_layout::argb(alpha, 255, 255, 255); + text_with_backdrop( + &mut out, + label, + w - label_width - 5, + h - 9 - 5, + label_width, + color, + background, + ); + } + out + } +} + /// Titles and the action bar: `Hud.title`, `subtitle`, `titleTime`, the /// fade times and `overlayMessageString` / `overlayMessageTime`. #[derive(Clone, Debug, PartialEq)] diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index ac624e85b..253bc6cc5 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -52,6 +52,8 @@ pub struct StackData { pub pot_decorations: Option; 4]>>, /// `minecraft:bundle_contents`. pub bundle_contents: Vec, + /// `BundleContents.selectedItem`: runtime only, never saved or sent. + pub bundle_selected: BundleSelected, /// `minecraft:suspicious_stew_effects`: (effect id, duration). pub stew_effects: Vec<(Arc, i32)>, /// `minecraft:map_post_processing`: 0 lock, 1 scale. @@ -60,6 +62,20 @@ pub struct StackData { /// max stack size...), kept as their saved values in key order. pub other: Vec<(String, Tag)>, } +/// A bundle's selected item index (-1: none). Like vanilla's +/// `BundleContents.equals` it is left out when stacks are compared. +#[derive(Clone, Copy, Debug)] +pub struct BundleSelected(pub i32); +impl Default for BundleSelected { + fn default() -> Self { + Self(-1) + } +} +impl PartialEq for BundleSelected { + fn eq(&self, _: &Self) -> bool { + true + } +} /// The components `components_tag` writes from modelled fields. const MODELLED: &[&str] = &[ "minecraft:banner_patterns", @@ -791,6 +807,7 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option Value { /// The resolver's view of a client stack: its item, count and component patch. pub fn stack_view(stack: &crate::items::ItemStack) -> StackView { let mut view = StackView::new(&stack.item, stack.count as i32); + view.bundle_selected = stack.data().map_or(-1, |d| d.bundle_selected.0); if let Some(Tag::Compound(c)) = crate::item_data::components_tag(stack.damage, stack.data()) { for (k, v) in &c { let key = k.to_string_lossy(); diff --git a/crates/horizon-client/src/item_tooltip.rs b/crates/horizon-client/src/item_tooltip.rs index 88f01439e..63a19b114 100644 --- a/crates/horizon-client/src/item_tooltip.rs +++ b/crates/horizon-client/src/item_tooltip.rs @@ -108,6 +108,32 @@ fn modifier_line( ) } +/// `Attribute.getStyle`: the colour of a line for an attribute whose value +/// rises or falls. Gravity, scale and the waypoint ranges are neutral, burning +/// time and fall damage are negative, every other attribute is positive. +fn attribute_color(attribute: &str, rises: bool) -> u32 { + let (blue, red) = (rgba(85, 85, 255, 255), rgba(255, 85, 85, 255)); + match attribute { + "burning_time" | "fall_damage_multiplier" => { + if rises { + red + } else { + blue + } + } + "gravity" | "scale" | "waypoint_transmit_range" | "waypoint_receive_range" => { + rgba(170, 170, 170, 255) + } + _ => { + if rises { + blue + } else { + red + } + } + } +} + /// `ItemStack.addAttributeTooltips`: slot groups, colors and optional player /// attack damage/speed bases. Recipe search has no player context. pub fn attribute_lines( @@ -150,10 +176,8 @@ pub fn attribute_lines( ) { let (line, color) = if base.is_some() { (format!(" {line}"), rgba(0, 170, 0, 255)) - } else if *amount > 0.0 { - (line, rgba(85, 85, 255, 255)) } else { - (line, rgba(255, 85, 85, 255)) + (line, attribute_color(path, *amount > 0.0)) }; lines.push((line, color)); } @@ -231,6 +255,235 @@ pub fn rarity<'a>(stack: &ItemStack, default: &'a str) -> &'a str { } } +fn is_beehive(path: &str) -> bool { + matches!(path, "beehive" | "bee_nest") +} + +/// `InstrumentComponent.addToTooltip`: the instrument's description. A goat +/// horn without the component has the item's default, the ponder horn. +pub fn instrument_line( + stack: &ItemStack, + display: &TooltipDisplay, + translate: &dyn Fn(&str) -> Option, +) -> Option { + if !display.shows("minecraft:instrument") { + return None; + } + let id = match stack.data().and_then(|d| d.other("minecraft:instrument")) { + Some(Tag::String(id)) => id.to_string_lossy(), + // An inline instrument carries its own description. + Some(inline) => { + return inline + .get("description") + .map(|d| crate::entity_nbt::name_text(d).plain()); + } + None if &*stack.item == "minecraft:goat_horn" => "minecraft:ponder_goat_horn".to_owned(), + None => return None, + }; + let key = format!("instrument.{}", id.replacen(':', ".", 1)); + Some(translate(&key).unwrap_or(key)) +} + +/// `Bees.addToTooltip`: how many bees a hive item holds (a hive item without +/// the component has the item's default, none). +pub fn bees_line( + stack: &ItemStack, + display: &TooltipDisplay, + translate: &dyn Fn(&str) -> Option, +) -> Option { + if !display.shows("minecraft:bees") { + return None; + } + let bees = match stack.data().and_then(|d| d.other("minecraft:bees")) { + Some(Tag::List(bees)) => bees.len(), + Some(_) => return None, + None if is_beehive(stack.item.trim_start_matches("minecraft:")) => 0, + None => return None, + }; + let text = + translate("container.beehive.bees").unwrap_or_else(|| "container.beehive.bees".into()); + Some( + text.replacen("%s", &bees.to_string(), 1) + .replacen("%s", "3", 1), + ) +} + +/// `BlockItemStateProperties.addToTooltip`: a hive item's honey level (a hive +/// item without the component has the item's default, 0). +pub fn honey_line( + stack: &ItemStack, + display: &TooltipDisplay, + translate: &dyn Fn(&str) -> Option, +) -> Option { + if !display.shows("minecraft:block_state") { + return None; + } + let level = match stack.data().and_then(|d| d.other("minecraft:block_state")) { + Some(Tag::Compound(state)) => { + match state.get(&horizon_world::nbt::JavaString::from("honey_level")) { + Some(Tag::String(level)) => level.to_string_lossy().parse::().ok()?, + _ => return None, + } + } + Some(_) => return None, + None if is_beehive(stack.item.trim_start_matches("minecraft:")) => 0, + None => return None, + }; + let text = + translate("container.beehive.honey").unwrap_or_else(|| "container.beehive.honey".into()); + Some( + text.replacen("%s", &level.to_string(), 1) + .replacen("%s", "5", 1), + ) +} + +/// `WrittenBookContent.addToTooltip`: "by " and the generation. +pub fn written_book_lines( + stack: &ItemStack, + display: &TooltipDisplay, + translate: &dyn Fn(&str) -> Option, +) -> Vec { + let text = |key: &str| translate(key).unwrap_or_else(|| key.to_owned()); + let Some(book) = stack + .data() + .and_then(|d| d.written.as_ref()) + .filter(|_| display.shows("minecraft:written_book_content")) + else { + return Vec::new(); + }; + let mut lines = Vec::new(); + if !book.author.trim().is_empty() { + lines.push( + crate::text::format_translation( + &text("book.byAuthor"), + &[crate::text::Text::literal(&book.author)], + ) + .plain(), + ); + } + lines.push(text(&format!("book.generation.{}", book.generation))); + lines +} + +/// `JukeboxPlayable.addToTooltip`: the song's description. +pub fn jukebox_line( + stack: &ItemStack, + info: Option<&ItemInfo>, + display: &TooltipDisplay, + translate: &dyn Fn(&str) -> Option, +) -> Option { + if !display.shows("minecraft:jukebox_playable") { + return None; + } + let song = match stack + .data() + .and_then(|d| d.other("minecraft:jukebox_playable")) + { + Some(Tag::String(song)) => song.to_string_lossy(), + // An inline song carries its own description. + Some(inline) => { + return inline + .get("description") + .map(|d| crate::entity_nbt::name_text(d).plain()); + } + None => info?.jukebox_song.clone()?, + }; + let key = format!("jukebox_song.{}", song.replacen(':', ".", 1)); + Some(translate(&key).unwrap_or(key)) +} + +/// `DyedItemColor.addToTooltip`: "Dyed" (italic, the flag), or with advanced +/// tooltips the colour's hex code. +pub fn dyed_line( + stack: &ItemStack, + display: &TooltipDisplay, + advanced: bool, + translate: &dyn Fn(&str) -> Option, +) -> Option<(String, bool)> { + let rgb = stack.data()?.dyed_color?; + if !display.shows("minecraft:dyed_color") { + return None; + } + let text = |key: &str| translate(key).unwrap_or_else(|| key.to_owned()); + Some(if advanced { + let hex = format!("#{:06X}", rgb & 0xFF_FFFF); + (text("item.color").replacen("%s", &hex, 1), false) + } else { + (text("item.dyed"), true) + }) +} + +/// `ItemStack.UNBREAKABLE_TOOLTIP`. +pub fn unbreakable_line( + stack: &ItemStack, + display: &TooltipDisplay, + translate: &dyn Fn(&str) -> Option, +) -> Option { + (stack.data()?.other("minecraft:unbreakable").is_some() + && display.shows("minecraft:unbreakable")) + .then(|| translate("item.unbreakable").unwrap_or_else(|| "item.unbreakable".into())) +} + +/// `PotionContents.addPotionTooltip`'s attribute block: an empty line, "When +/// Applied:" and the modifiers of the potion's effects (blue for a gain, red +/// for a loss); nothing for a potion whose effects add none. +pub fn potion_modifier_lines( + stack: &ItemStack, + translate: &dyn Fn(&str) -> Option, +) -> Vec<(String, u32)> { + if !is_potion_item(&stack.item) { + return Vec::new(); + } + let applied: Vec<(String, u32)> = stack + .potion() + .and_then(crate::brewing::potion) + .into_iter() + .flat_map(|p| p.effects.iter()) + .filter_map(|(effect, _, amplifier)| { + let (attribute, amount, operation) = effect_modifier(effect)?; + let amount = amount * (*amplifier + 1) as f64; + let line = modifier_line(translate, attribute, amount, operation, false)?; + let color = if amount > 0.0 { + rgba(85, 85, 255, 255) + } else { + rgba(255, 85, 85, 255) + }; + Some((line, color)) + }) + .collect(); + if applied.is_empty() { + return applied; + } + let mut lines = vec![ + (String::new(), u32::MAX), + ( + translate("potion.whenDrank").unwrap_or_else(|| "potion.whenDrank".into()), + rgba(170, 0, 170, 255), + ), + ]; + lines.extend(applied); + lines +} + +/// `ItemStack.components.size()`: the item's default components with the +/// stack's own changes applied. +pub fn component_count(stack: &ItemStack, info: Option<&ItemInfo>) -> usize { + let mut keys: std::collections::HashSet = info + .map(|i| i.components.iter().cloned().collect()) + .unwrap_or_default(); + if let Some(Tag::Compound(patch)) = crate::item_data::components_tag(stack.damage, stack.data()) + { + for key in patch.keys() { + let key = key.to_string_lossy(); + match key.strip_prefix('!') { + Some(removed) => keys.remove(removed), + None => keys.insert(key), + }; + } + } + keys.len() +} + /// The lines of `stack` below its name that its components give, in /// `ItemStack.addDetailsToTooltip` order. pub fn detail_lines( @@ -265,19 +518,9 @@ pub fn detail_lines( )) )); } - // BeehiveBlock: the block state components of the item. - if path == "beehive" { - lines.push( - text("container.beehive.bees") - .replacen("%s", "0", 1) - .replacen("%s", "3", 1), - ); - lines.push( - text("container.beehive.honey") - .replacen("%s", "0", 1) - .replacen("%s", "5", 1), - ); - } + let display = TooltipDisplay::for_stack(stack); + lines.extend(bees_line(stack, &display, translate)); + lines.extend(honey_line(stack, &display, translate)); let data = stack.data(); // PotDecorations.addToTooltip. if let Some(sherds) = data @@ -303,32 +546,13 @@ pub fn detail_lines( .into_iter() .map(|l| l.0), ); - let applied: Vec = stack - .potion() - .and_then(crate::brewing::potion) - .into_iter() - .flat_map(|p| p.effects.iter()) - .filter_map(|(effect, _, amplifier)| { - let (attribute, amount, operation) = effect_modifier(effect)?; - modifier_line( - translate, - attribute, - amount * (*amplifier + 1) as f64, - operation, - false, - ) - }) - .collect(); - if !applied.is_empty() { - lines.push(String::new()); - lines.push(text("potion.whenDrank")); - lines.extend(applied); - } - } - // JukeboxPlayable.addToTooltip: the song's description. - if path.starts_with("music_disc_") { - lines.push(text(&format!("item.minecraft.{path}.desc"))); + lines.extend( + potion_modifier_lines(stack, translate) + .into_iter() + .map(|l| l.0), + ); } + lines.extend(jukebox_line(stack, info, &display, translate)); // Trim.addToTooltip. if let Some((material, pattern)) = data.and_then(|d| d.trim.as_ref()) { let short = |s: &str| s.trim_start_matches("minecraft:").to_owned(); @@ -342,10 +566,7 @@ pub fn detail_lines( text(&format!("trim_material.minecraft.{}", short(material))) )); } - // DyedItemColor.addToTooltip (without advanced tooltips). - if data.is_some_and(|d| d.dyed_color.is_some()) { - lines.push(text("item.dyed")); - } + lines.extend(dyed_line(stack, &display, false, translate).map(|l| l.0)); if let Some(info) = info { lines.extend( attribute_lines(&info.modifiers, None, translate) diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 905843d23..10f1c72ad 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -131,6 +131,8 @@ pub struct ItemInfo { pub block_transformer: Option, /// Has a default `bundle_contents` (the bundles, `BundleItem`). pub bundle: bool, + /// The ids of the item's default components (its prototype's keys). + pub components: Vec, } /// `Item.Properties.craftRemainder` (not a data component, so not in the /// default-component report): what an item leaves in the grid when crafted with. @@ -650,6 +652,10 @@ impl Items { cushion_color: c["minecraft:cushion/color"].as_str().map(str::to_owned), block_transformer: c["minecraft:block_transformer"].as_str().map(str::to_owned), bundle: c.get("minecraft:bundle_contents").is_some(), + components: c + .as_object() + .map(|c| c.keys().cloned().collect()) + .unwrap_or_default(), crafting_remainder: CRAFT_REMAINDERS .iter() .find(|(item, _)| *item == name) diff --git a/crates/horizon-client/src/keybinds.rs b/crates/horizon-client/src/keybinds.rs index 7575fb953..2047b9117 100644 --- a/crates/horizon-client/src/keybinds.rs +++ b/crates/horizon-client/src/keybinds.rs @@ -2,7 +2,6 @@ //! defaults, `key_:key.keyboard.x` persistence, display names, and the //! translation of rebound physical keys back to the default keys the game //! logic listens for. -use crate::text::Text; use std::collections::BTreeMap; use winit::{event::MouseButton, keyboard::KeyCode}; @@ -225,40 +224,7 @@ pub fn mouse_button(name: &str) -> Option { _ => return None, }) } -/// InputConstants.Key.getDisplayName: one-character keys as the upper-case -/// character, others by translation. -pub fn display_name(key: &str) -> Text { - if let Some(rest) = key.strip_prefix("key.keyboard.") - && rest.chars().count() == 1 - { - let c = rest.to_uppercase(); - return Text::literal(c); - } - let symbol = match key { - "key.keyboard.minus" => Some("-"), - "key.keyboard.equal" => Some("="), - "key.keyboard.left.bracket" => Some("["), - "key.keyboard.right.bracket" => Some("]"), - "key.keyboard.backslash" => Some("\\"), - "key.keyboard.semicolon" => Some(";"), - "key.keyboard.apostrophe" => Some("'"), - "key.keyboard.grave.accent" => Some("`"), - "key.keyboard.comma" => Some(","), - "key.keyboard.period" => Some("."), - "key.keyboard.slash" => Some("/"), - _ => None, - }; - if let Some(s) = symbol { - return Text::literal(s); - } - if let Some(n) = key.strip_prefix("key.mouse.") - && n.parse::().is_ok() - && !crate::lang::has(key) - { - return Text::translate("key.mouse", &[Text::literal(n)]); - } - Text::translate(key, &[]) -} +pub use horizon_client_core::key_display::display_name; /// Current bindings by mapping name. #[derive(Clone, Debug, PartialEq, Eq)] diff --git a/crates/horizon-client/src/lan/chunks.rs b/crates/horizon-client/src/lan/chunks.rs index 122d37bcd..9ca20b894 100644 --- a/crates/horizon-client/src/lan/chunks.rs +++ b/crates/horizon-client/src/lan/chunks.rs @@ -66,6 +66,7 @@ pub fn block_entity_type(name: &str) -> Option<&'static str> { "sculk_catalyst" => "minecraft:sculk_catalyst", "sculk_shrieker" => "minecraft:sculk_shrieker", "crafter" => "minecraft:crafter", + "potent_sulfur" => "minecraft:potent_sulfur", "chiseled_bookshelf" => "minecraft:chiseled_bookshelf", "trial_spawner" => "minecraft:trial_spawner", "vault" => "minecraft:vault", diff --git a/crates/horizon-client/src/lan/commands.rs b/crates/horizon-client/src/lan/commands.rs index 71b7fa68d..c3e462348 100644 --- a/crates/horizon-client/src/lan/commands.rs +++ b/crates/horizon-client/src/lan/commands.rs @@ -86,6 +86,18 @@ impl CommandTree { /// The ClientboundCommandsPacket for a player with `level` permissions. pub fn packet(&self, level: u8, dedicated: bool, builtin: &Builtin) -> Commands { + self.packet_with(level, dedicated, builtin, &Value::Null) + } + + /// [`CommandTree::packet`] with more commands after vanilla's: `extra` + /// is a root in the report's format (server mods' commands). + pub fn packet_with( + &self, + level: u8, + dedicated: bool, + builtin: &Builtin, + extra: &Value, + ) -> Commands { let mut nodes = vec![Node { name: String::new(), kind: 0, @@ -99,16 +111,18 @@ impl CommandTree { let suggestions: HashMap<&str, &'static str> = SUGGESTIONS.iter().copied().collect(); let mut paths: HashMap, usize> = HashMap::new(); paths.insert(Vec::new(), 0); - fill( - &self.root, - 0, - &mut Vec::new(), - level, - dedicated, - &suggestions, - &mut nodes, - &mut paths, - ); + for root in [&self.root, extra] { + fill( + root, + 0, + &mut Vec::new(), + level, + dedicated, + &suggestions, + &mut nodes, + &mut paths, + ); + } // enumerateNodes: breadth first from the root, each node's children // (in registration order) then its redirect target. let mut ids = vec![None; nodes.len()]; @@ -365,4 +379,33 @@ mod tests { ); assert!(op.nodes[3].restricted); } + + #[test] + fn server_mods_commands_follow_vanillas() { + let report: Value = serde_json::from_str( + r#"{"type":"root","children":{"me":{"type":"literal","children":{"action":{"type":"argument","parser":"minecraft:message","executable":true}}}}}"#, + ) + .unwrap(); + let mods: Value = serde_json::from_str( + r#"{"type":"root","children":{"beacon":{"type":"literal","executable":true,"children":{ + "height":{"type":"argument","parser":"brigadier:integer","properties":{"min":1,"max":64},"executable":true}}}}}"#, + ) + .unwrap(); + let tree = CommandTree { root: report }; + let packet = tree.packet_with(0, true, &Builtin::default(), &mods); + let names: Vec<_> = packet.nodes.iter().map(|n| n.name.as_str()).collect(); + assert_eq!(names, ["", "me", "beacon", "action", "height"]); + let beacon = &packet.nodes[2]; + assert!(beacon.executable && !beacon.restricted); + assert_eq!(beacon.children, [4]); + let height = packet.nodes[4].parser.as_ref().unwrap(); + assert_eq!(height.1, vec![3, 0, 0, 0, 1, 0, 0, 0, 64]); + // No mods: vanilla's tree as it is. + assert_eq!( + tree.packet_with(0, true, &Builtin::default(), &Value::Null) + .nodes + .len(), + 3 + ); + } } diff --git a/crates/horizon-client/src/lan/containers.rs b/crates/horizon-client/src/lan/containers.rs index 002f95cbb..59f01552e 100644 --- a/crates/horizon-client/src/lan/containers.rs +++ b/crates/horizon-client/src/lan/containers.rs @@ -36,6 +36,30 @@ impl Hub { /// ClientboundSoundPacket for a sound event name (an inline event when /// the registry does not know it). + pub fn sound_packet( + &self, + name: &str, + at: [f64; 3], + volume: f32, + pitch: f32, + source: i32, + seed: i64, + ) -> C { + let sound = match self.sync.id("minecraft:sound_event", name) { + Some(id) => (id, None), + None => (-1, Some((name.to_owned(), None))), + }; + C::Sound(play::Sound { + sound, + source, + x: (at[0] * 8.0) as i32, + y: (at[1] * 8.0) as i32, + z: (at[2] * 8.0) as i32, + volume, + pitch, + seed, + }) + } pub fn sound( &self, name: &str, @@ -45,20 +69,7 @@ impl Hub { source: i32, except: Option, ) { - let sound = match self.sync.id("minecraft:sound_event", name) { - Some(id) => (id, None), - None => (-1, Some((name.to_owned(), None))), - }; - let packet = C::Sound(play::Sound { - sound, - source, - x: (at[0] * 8.0) as i32, - y: (at[1] * 8.0) as i32, - z: (at[2] * 8.0) as i32, - volume, - pitch, - seed: self.ticks as i64, - }); + let packet = self.sound_packet(name, at, volume, pitch, source, self.ticks as i64); self.broadcast_near(at, f64::from(volume.max(1.0)) * 16.0, &packet, except); } @@ -120,12 +131,13 @@ impl Hub { ); } - /// `ServerPlayer.crit`: send the victim's animation to the players tracking - /// the attacker and the attacker themselves (`sendToTrackingPlayersAndSelf`). - pub fn critical_hit(&self, attacker: i32, target: i32) { + /// `ServerPlayer.crit` (`magicCrit` when `magic`): send the victim's + /// animation to the players tracking the attacker and the attacker + /// themselves (`sendToTrackingPlayersAndSelf`). + pub fn critical_hit(&self, attacker: i32, target: i32, magic: bool) { let body = C::Animate(play::Animate { id: target, - action: 1, + action: if magic { 2 } else { 1 }, }) .encode(); for g in self.guests.iter().filter(|g| { @@ -421,6 +433,42 @@ impl Hub { drops } + /// `AbstractContainerMenu.setSelectedBundleItemIndex` on the guest's open + /// menu: a container's own slots, or the inventory's. A bundle's selection + /// lives on the server's stack until the click that takes from it. + pub fn select_bundle_item(&mut self, conn: u32, slot: usize, index: i32, world: &mut World) { + let Some(g) = self.guests.iter_mut().find(|g| g.conn == conn) else { + return; + }; + let open = g.menu.as_ref().map(|m| (m.size, m.slots)); + let mut items = match open { + Some((size, source)) if slot < size => source.read(world, g), + _ => None, + }; + let stack = match open { + Some((size, _)) if slot < size => items + .as_mut() + .and_then(|items| items.get_mut(slot)) + .and_then(Option::as_mut), + Some((size, _)) => g + .inventory + .get_mut(player_slot(slot - size)) + .and_then(Option::as_mut), + None => match slot { + 9..=35 => g.inventory.get_mut(slot).and_then(Option::as_mut), + 36..=44 => g.inventory.get_mut(slot - 36).and_then(Option::as_mut), + 45 => g.offhand.as_mut(), + _ => None, + }, + }; + if let Some(stack) = stack { + crate::bundle::toggle_selected(stack, index); + } + if let (Some((_, source)), Some(items)) = (open, items) { + source.write(world, g, items); + } + } + /// A click on the inventory menu (window 0) the game applied itself /// (the crafting grid): the client is corrected like after any click. pub fn inventory_clicked( diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index ae3089006..920052b5a 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -611,8 +611,9 @@ pub struct Viewer<'a> { } /// One entity as this tick's range checks read it: where it is -/// horizontally, its id, its type's tracking range in chunks and the chunk -/// it is in (an index into the tick's chunks). +/// horizontally, its id, its tracking range in blocks (scaled by +/// `entity-broadcast-range-percentage`) and the chunk it is in (an index +/// into the tick's chunks). #[derive(Clone, Copy)] struct Probe { x: f64, @@ -627,7 +628,7 @@ struct Probe { /// each of the tick's chunks whether the client has it (0: not looked up /// yet, 1: no, 2: yes), so each chunk is looked up once per client. fn sees(v: &Viewer, p: &Probe, chunks: &[(i32, i32)], held: &mut [u8]) -> bool { - let range = f64::from(p.range.min(v.view_distance) * 16); + let range = f64::from(p.range.min(v.view_distance * 16)); let (dx, dz) = (v.position[0] - p.x, v.position[2] - p.z); dx * dx + dz * dz <= range * range && { let held = &mut held[p.chunk as usize]; @@ -641,6 +642,9 @@ fn sees(v: &Viewer, p: &Probe, chunks: &[(i32, i32)], held: &mut [u8]) -> bool { /// One level's tracked entities (ChunkMap.entityMap). #[derive(Default)] pub struct Entities { + /// `entity-broadcast-range-percentage` (None: 100), which scales every + /// type's tracking range (MinecraftServer.getScaledTrackingDistance). + pub range_percent: Option, states: crate::fast_hash::FxHashMap, /// The level tick, stamped on every entity still in the level. tick: u32, @@ -732,7 +736,9 @@ impl Entities { x: e.position[0], z: e.position[2], id: e.id, - range: s.range, + range: self + .range_percent + .map_or(s.range * 16, |p| p * (s.range * 16) / 100), chunk, }); } diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index b1a8cbc62..f9b6e8ce7 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -21,7 +21,7 @@ use crate::{ use horizon_core::geometry::{Aabb, ShapeOp, Vec3, VoxelShape}; use horizon_protocol::ids::play::clientbound as ids; use horizon_protocol::{ - entity_data::{Value, serializer}, + entity_data::{Particle, ParticleData, Value, serializer}, packets::play::{self, Clientbound as C, Serverbound as S}, text::{literal, translatable}, }; @@ -87,6 +87,29 @@ pub struct HostState { pub living_flags: i8, /// The bed the host sleeps in (`LivingEntity.SLEEPING_POS`). pub bed: Option<[i32; 3]>, + pub body: BodyFlags, +} + +/// What the other players see of a player's body besides sneaking and +/// sprinting: the pose and the rest of `Entity.DATA_SHARED_FLAGS_ID`. +#[derive(Clone, Copy, Debug, Default)] +pub struct BodyFlags { + /// `Entity.isFallFlying`: gliding with elytra. + pub gliding: bool, + /// `Entity.isSwimming` (the swimming flag). + pub swimming: bool, + /// The swimming pose of a player crawling under a block. + pub crawling: bool, + /// The crouching pose, held without sneaking under a low ceiling. + pub crouching: bool, + /// `LivingEntity.isAutoSpinAttack`: Riptide's spin. + pub spin_attack: bool, + /// `Entity.isOnFire`. + pub on_fire: bool, + /// `Entity.isInvisible`: the invisibility effect. + pub invisible: bool, + /// The glowing effect. + pub glowing: bool, } /// Everything the hub needs from the game for one tick. @@ -168,6 +191,8 @@ pub struct Hub { level_sync: std::collections::HashMap, /// Operators and their permission levels (dedicated servers). pub ops: std::collections::HashMap, + /// `entity-broadcast-range-percentage` (dedicated servers). + pub entity_range_percent: i32, chat_type: i32, dimension_type: i32, clock_ids: Vec, @@ -177,6 +202,9 @@ pub struct Hub { entities: std::collections::HashMap, /// What one tick of entity tracking sends each guest, kept between ticks. entity_out: Vec>>, + /// Server mods' commands, a root in the commands report's format, sent + /// after vanilla's; the key the game last set them for. + mod_commands: (serde_json::Value, Option), } fn string(s: &str) -> Tag { @@ -332,6 +360,7 @@ impl Hub { ticking: (20.0, false), stepping: 0, ops: Default::default(), + entity_range_percent: 100, weather: (false, 0.0, 0.0), level_sync: Default::default(), chat_type, @@ -341,6 +370,7 @@ impl Hub { entity_types: Default::default(), entities: Default::default(), entity_out: Vec::new(), + mod_commands: (serde_json::Value::Null, None), teams: Vec::new(), } } @@ -849,13 +879,36 @@ impl Hub { } } + /// The key [`Hub::set_mod_commands`] last had: the game compares it + /// with its server mods' each tick. + pub fn mod_commands_key(&self) -> Option { + self.mod_commands.1 + } + /// Server mods' commands changed: every player gets their tree again. + pub fn set_mod_commands(&mut self, key: u64, commands: serde_json::Value) { + let resend = self.mod_commands.0 != commands; + self.mod_commands = (commands, Some(key)); + if resend { + for i in 0..self.guests.len() { + if self.guests[i].placed { + self.send_commands(i); + } + } + } + } + /// Commands.sendCommands: the command tree for this player. fn send_commands(&self, i: usize) { let g = &self.guests[i]; let packet = match &self.sync.commands { Some(tree) => { let dedicated = self.config.dedicated && !self.config.integrated; - tree.packet(g.permission, dedicated, &self.sync.builtin) + tree.packet_with( + g.permission, + dedicated, + &self.sync.builtin, + &self.mod_commands.0, + ) } None => play::Commands { nodes: vec![play::CommandNode { @@ -1500,6 +1553,49 @@ impl Hub { // ---- entities ------------------------------------------------------ + /// `LivingEntity.updateSynchronizedMobEffectParticles`: DATA_EFFECT_PARTICLES + /// (10) and DATA_EFFECT_AMBIENCE_ID (11) for the visible `effects`, as + /// (effect, ambient). The entries are left out when there is nothing to + /// show, which is their default. + pub fn effect_meta<'a>( + &self, + effects: impl IntoIterator, + ) -> Vec<(u8, i32, Value)> { + let mut particles = Vec::new(); + let mut all_ambient = true; + for (effect, ambient) in effects { + let effect = effect.trim_start_matches("minecraft:"); + // MobEffect.particleFactory: the omens have their own particles, + // the others an entity effect in their colour (faint if ambient). + let (name, data) = match effect { + "trial_omen" | "raid_omen" => (effect, None), + _ => { + let Some(def) = crate::brewing::effect(effect) else { + continue; + }; + let alpha = if ambient { 38 } else { 255 }; + let argb = (alpha << 24) | def.color as i32; + ("entity_effect", Some(ParticleData::Color(argb))) + } + }; + let Some(id) = + self.registry_id("minecraft:particle_type", &format!("minecraft:{name}")) + else { + continue; + }; + particles.push(Particle { id, data }); + all_ambient &= ambient; + } + if particles.is_empty() { + return Vec::new(); + } + let mut meta = vec![(10, serializer::PARTICLES, Value::Particles(particles))]; + if all_ambient { + meta.push((11, serializer::BOOLEAN, Value::Bool(true))); + } + meta + } + fn player_state( &self, id: i32, @@ -1507,21 +1603,29 @@ impl Hub { position: [f64; 3], rot: (f32, f32, f32), on_ground: bool, - flags: (bool, bool, bool, bool), + flags: (bool, bool, bool), + body: BodyFlags, living_flags: i8, bed: Option<[i32; 3]>, skin: u8, health: f32, equipment: Vec<(u8, Option)>, attributes: Vec, + effects: &[EffectInstance], ) -> EntityState { - let (sneaking, sprinting, gliding, sleeping) = flags; - let shared = shared_flags(sneaking, sprinting, gliding); + let (sneaking, sprinting, sleeping) = flags; + let shared = shared_flags(sneaking, sprinting, &body); + // Player.getDesiredPose (and updatePlayerPose's crawl): sleeping, + // swimming, gliding, Riptide's spin, crouching. let pose = if sleeping { 2 - } else if gliding { + } else if body.swimming || body.crawling { + 3 + } else if body.gliding { 1 - } else if sneaking { + } else if body.spin_attack { + 4 + } else if sneaking || body.crouching { 5 } else { 0 @@ -1547,6 +1651,14 @@ impl Hub { if skin != 0 { meta.push((16, serializer::BYTE, Value::Byte(skin as i8))); } + meta.extend( + self.effect_meta( + effects + .iter() + .filter(|e| e.visible) + .map(|e| (e.id, e.ambient)), + ), + ); EntityState { id, uuid, @@ -1559,7 +1671,11 @@ impl Hub { velocity: [0.0; 3], data: 0, meta, - defaults: Vec::new(), + // The effect swirls go back to none. + defaults: vec![ + (10, serializer::PARTICLES, Value::Particles(Vec::new())), + (11, serializer::BOOLEAN, Value::Bool(false)), + ], equipment, attributes, precise: false, @@ -1607,13 +1723,15 @@ impl Hub { h.position, (h.yaw, h.pitch, h.head_yaw), h.on_ground, - (h.sneaking, h.sprinting, false, h.bed.is_some()), + (h.sneaking, h.sprinting, h.bed.is_some()), + h.body, h.living_flags, h.bed, 0x7F, h.health, equipment, h.attributes.clone(), + &[], )); } let placed: Vec = (0..self.guests.len()) @@ -1639,7 +1757,8 @@ impl Hub { g.position, (g.yaw, g.pitch, g.head_yaw), g.on_ground, - (g.sneaking, g.sprinting, g.fall_flying, g.sleeping), + (g.sneaking, g.sprinting, g.sleeping), + guest_body(g), g.living_flags, g.bed, g.info.model_customisation, @@ -1649,6 +1768,7 @@ impl Hub { .as_ref() .map(|m| super::attributes::syncable(&m.attributes)) .unwrap_or_default(), + &g.effects.list, ) }) .collect(); @@ -1678,6 +1798,7 @@ impl Hub { out, }) .collect(); + level.range_percent = Some(self.entity_range_percent); let (types, sync) = (&mut self.entity_types, &self.sync); level.tick(&entities, &self.riding, &mut viewers, |kind| { entity_type(types, sync, kind) @@ -1798,7 +1919,7 @@ impl Hub { // too, so the sprint a hit stops (Player.causeExtraKnockback) stops // on its client. let g = &mut self.guests[i]; - let shared = shared_flags(g.sneaking, g.sprinting, g.fall_flying); + let shared = shared_flags(g.sneaking, g.sprinting, &guest_body(g)); if shared != g.sent_shared { g.sent_shared = shared; g.send(&C::SetEntityData(play::SetEntityData { @@ -2043,6 +2164,20 @@ impl Hub { S::Chat(c) => self.handle_chat(i, c, events), S::ChatAck(p) => self.chat_ack(i, p.offset, events), S::ChatSessionUpdate(p) => self.chat_session_update(i, p, events), + // handlePlayerAction (a dig starting, stopping or finishing) is the + // game's, run after this pass. A move queued behind it is checked + // against the block the player just broke and falls through, so it + // would be sent back; it waits for the next tick, when the block is + // gone, as vanilla handles the two packets in order. + S::PlayerAction(p) if p.action <= 3 => { + events.push(HostEvent::Packet(conn, Box::new(S::PlayerAction(p)))); + if matches!( + self.guests[i].inbox.front(), + Some(S::MovePlayerPos(_) | S::MovePlayerPosRot(_)) + ) { + break; + } + } other => events.push(HostEvent::Packet(conn, Box::new(other))), } } @@ -2578,16 +2713,44 @@ fn ticking_state(rate: f32, frozen: bool) -> C { raw(ids::TICKING_STATE, w.data) } -/// Entity.DATA_SHARED_FLAGS_ID of a player: crouching, sprinting, gliding. -fn shared_flags(sneaking: bool, sprinting: bool, gliding: bool) -> i8 { +/// What the others see of a guest's body, from its server-side state. +fn guest_body(g: &Guest) -> BodyFlags { + let m = g.motion.as_deref(); + BodyFlags { + gliding: g.fall_flying, + swimming: m.is_some_and(|m| m.swimming), + crawling: m.is_some_and(|m| m.pose == crate::pose::Pose::Swimming && !m.swimming), + crouching: m.is_some_and(|m| m.pose == crate::pose::Pose::Crouching), + spin_attack: m.is_some_and(|m| m.auto_spin_attack_ticks > 0), + on_fire: m.is_some_and(|m| m.fire_ticks > 0), + invisible: g.effects.get("invisibility").is_some(), + glowing: g.effects.get("glowing").is_some(), + } +} + +/// Entity.DATA_SHARED_FLAGS_ID of a player: on fire 0x01, crouching 0x02, +/// sprinting 0x08, swimming 0x10, invisible 0x20, glowing 0x40, gliding 0x80. +fn shared_flags(sneaking: bool, sprinting: bool, body: &BodyFlags) -> i8 { let mut shared = 0i8; + if body.on_fire { + shared |= 0x01; + } if sneaking { shared |= 0x02; } if sprinting { shared |= 0x08; } - if gliding { + if body.swimming { + shared |= 0x10; + } + if body.invisible { + shared |= 0x20; + } + if body.glowing { + shared |= 0x40; + } + if body.gliding { shared |= -128; } shared diff --git a/crates/horizon-client/src/lan/menu.rs b/crates/horizon-client/src/lan/menu.rs index 859bafa23..641e45b1b 100644 --- a/crates/horizon-client/src/lan/menu.rs +++ b/crates/horizon-client/src/lan/menu.rs @@ -5,7 +5,7 @@ //! menu are returned for the game to drop. use super::guest::Guest; use crate::{ - bundle::{Contents, can_be_in_bundle}, + bundle::{Contents, can_be_in_bundle, toggle_selected}, items::{ItemStack, Items}, world::World, }; @@ -514,7 +514,10 @@ fn bundle_click(view: &mut View, i: usize, right: bool, rules: &dyn Rules) -> bo } } (carried, _) => { + // toggleSelectedItem(-1), then the click goes on. view.guest.carried = carried; + toggle_selected(&mut bundle, -1); + view.set(i, Some(bundle)); return false; } } diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index ebfbdea58..fa5ef1c4d 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -19,13 +19,11 @@ pub mod biome; pub mod block_entities; pub mod block_entity_anim; pub mod block_entity_item; -pub mod block_entity_nbt; pub mod block_entity_render; pub mod block_transform; pub mod blocks; pub mod border_render; pub mod boss_overlay; -pub mod bossbar; pub mod breaking; pub mod brewing; pub mod bundle; @@ -38,10 +36,8 @@ pub mod clipboard; pub mod clock; pub mod clouds; pub mod collisions; -pub mod command; pub mod command_block; pub mod command_storage; -pub mod component; pub mod confirm_screen; pub mod container_screen; pub mod containers; @@ -71,7 +67,6 @@ pub mod extras; pub mod extras_hud; pub mod falling_block; pub mod fast_hash; -pub mod fastutil_order; pub mod fire_render; pub mod first_person; pub mod flatgen; @@ -80,7 +75,6 @@ pub mod font; pub mod friends_screen; pub mod game_mode_switcher; pub mod gamepad; -pub mod gamerules; pub mod gfx; pub mod gizmos; pub mod gossip; @@ -109,7 +103,6 @@ pub mod keybinds; pub mod keymapping; pub mod lan; pub mod landing; -pub mod lang; pub mod level_loading; pub mod light; pub mod locator_bar; @@ -131,7 +124,6 @@ pub mod mouse; pub mod moved_extras; pub mod multiplayer; pub mod music; -pub mod nbt_path; pub mod net; pub mod nether_portal; pub mod offline_name; @@ -160,7 +152,6 @@ pub mod recipe_book; pub mod recipe_book_screen; pub mod reconnect; pub mod save; -pub mod scoreboard; pub mod scoreboard_cmd; pub mod screen_draw; pub mod screen_effects; @@ -173,7 +164,6 @@ pub mod shader_pack_list; pub mod shadows; pub mod signs; pub mod skins; -pub mod snbt; pub mod sound_engine; pub mod sound_events; pub mod spans; @@ -186,7 +176,6 @@ pub mod structure_blocks; pub mod tab_list; pub mod telemetry; pub mod testgen; -pub mod text; pub mod text_display; pub mod tick_chunk_membership; pub mod ticket_levels; @@ -206,4 +195,15 @@ pub mod world; pub mod world_spawn; pub mod worldborder; pub mod zip; -pub type Result = std::result::Result>; +pub use horizon_client_core::Result; +pub use horizon_client_core::block_entity_nbt; +pub use horizon_client_core::bossbar; +pub use horizon_client_core::component; +pub use horizon_client_core::fastutil_order; +pub use horizon_client_core::gamerules; +pub use horizon_client_core::lang; +pub use horizon_client_core::nbt_path; +pub use horizon_client_core::scoreboard; +pub use horizon_client_core::snbt; +pub use horizon_client_core::text; +pub use horizon_command as command; diff --git a/crates/horizon-client/src/menu/bundle.rs b/crates/horizon-client/src/menu/bundle.rs index fba4a488e..78a52655a 100644 --- a/crates/horizon-client/src/menu/bundle.rs +++ b/crates/horizon-client/src/menu/bundle.rs @@ -1,7 +1,7 @@ //! `BundleItem`'s click overrides in a PICKUP click //! (`tryItemClickBehaviourOverride`). use super::{Env, Menu, tidy}; -use crate::bundle::{Contents, INSERT, INSERT_FAIL, REMOVE_ONE, can_be_in_bundle}; +use crate::bundle::{Contents, INSERT, INSERT_FAIL, REMOVE_ONE, can_be_in_bundle, toggle_selected}; impl Menu { /// The carried stack's `overrideStackedOnOther`, then the clicked @@ -88,8 +88,11 @@ impl Menu { } } (carried, _) => { - // toggleSelectedItem(-1): Horizon keeps no selected item. + // toggleSelectedItem(-1), then the click goes on. self.carried = carried; + toggle_selected(&mut bundle, -1); + let slot = self.slots[s]; + self.containers[slot.container][slot.index] = Some(bundle); return false; } } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 0d7fb4b54..2325c3f5b 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -50,6 +50,7 @@ pub mod nether; pub mod path; pub mod phantom; pub mod piglin; +pub mod polar_bear; pub mod rabbit; pub mod raider; pub mod ravager; @@ -645,6 +646,8 @@ pub struct Attrs { pub struct Extra { /// Players: crouching and riding (HumanoidModel's poses). pub crouching: bool, + /// Players: sprinting (`Entity.DATA_SHARED_FLAGS_ID`), for the dust they raise. + pub sprinting: bool, pub passenger: bool, /// AgeableMob.age: negative while a baby (a tadpole counts up to 24000). pub age: i32, @@ -726,6 +729,12 @@ pub struct Extra { pub vector: [f64; 3], /// Active status effects: (effect id, ticks left, amplifier). pub effects: Vec<(&'static str, i32, i32)>, + /// The effects above given with `hideParticles`: no swirls for them. + pub hidden_effects: Vec<&'static str>, + /// `LivingEntity.DATA_EFFECT_PARTICLES` and `DATA_EFFECT_AMBIENCE_ID` as a + /// server gave them: the swirls around it, and whether they are all faint. + pub effect_particles: Vec, + pub effect_ambient: bool, /// An invisible illusioner's mirror images. pub illusions: Option, /// A villager's claimed bed head and meeting bell. @@ -737,6 +746,8 @@ pub struct Extra { /// the spin the rope's torque gives it. pub leash: Option, pub leash_pending: Option, + /// The UUID of the player behind `Holder::Player` (host or guest). + pub leash_player: Option<[i32; 4]>, pub leash_spin: f64, /// More species scratch values. pub scratch: [i32; 4], @@ -1959,8 +1970,15 @@ impl Mob { } pub fn add_effect(&mut self, effect: &'static str, ticks: i32, amplifier: i32) { if let Some(e) = self.extra.effects.iter_mut().find(|e| e.0 == effect) { - e.1 = e.1.max(ticks); - e.2 = e.2.max(amplifier); + // MobEffectInstance.update: a stronger effect replaces the old one + // with its own duration, an equal one keeps the longer duration, + // and a weaker one never changes the active effect. + if amplifier > e.2 { + e.1 = ticks; + e.2 = amplifier; + } else if amplifier == e.2 { + e.1 = e.1.max(ticks); + } } else { self.extra.effects.push((effect, ticks, amplifier)); } diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 3406c09d7..26b94eeac 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -106,6 +106,7 @@ pub enum Family { Strider, Bat, Bee, + PolarBear, } pub fn family(s: Species) -> Family { use Species as S; @@ -167,6 +168,7 @@ pub fn family(s: Species) -> Family { S::Strider => Family::Strider, S::Bat => Family::Bat, S::Bee => Family::Bee, + S::PolarBear => Family::PolarBear, _ => Family::Generic, } } @@ -227,6 +229,7 @@ pub fn register(m: &mut Mob) { Family::Strider => super::strider::register(m), Family::Bat => super::bat::register(m), Family::Bee => super::bee::register(m), + Family::PolarBear => super::polar_bear::register(m), } // FloatGoal's constructor lets the navigation float, as do the // constructors of these brain-driven and flying mobs. A floater rises @@ -416,6 +419,7 @@ pub fn tick( super::axolotl::tick_animation(m); m.anim.end_tick(m.ai.swinging); tick_swing(m); + flower_contact_effects(m, w); if m.species() == Species::CopperGolem { // CopperGolem.tick: updateWeathering after the living tick. super::copper_golem::update_weathering(m, w, level_random, events); @@ -674,7 +678,7 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & } // AbstractHorse.aiStep: the tail swishes now and then (moveTail). if super::equine::is_equine(m.species()) { - let _ = m.random.next_int_bound(200); + super::equine::tail_tick(m); } // Monster.aiStep: updateNoActionTime (Raider: always +2). if is_monster(m.species()) @@ -701,6 +705,9 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & // serverAiStep has no goals, so it only falls and is pushed. let immobile = (m.species() == Species::Ravager && super::ravager::immobile(m)) || m.species() == Species::Mannequin; + if m.species() == Species::Piglin && m.alive() { + super::piglin::celebrate(m, w); + } if m.alive() && !immobile { server_ai_step(m, w, level_random, events); } else { @@ -1025,6 +1032,7 @@ fn species_ai_step( Species::Wither => super::wither::ai_step(m, w, events), Species::Allay => super::allay::ai_step(m), Species::Bee => super::bee::ai_step(m, w), + Species::PolarBear => super::polar_bear::ai_step(m, w), Species::Breeze => super::breeze::ai_step(m), Species::Sniffer => super::sniffer::ai_step(m, events), Species::HappyGhast => super::happy_ghast::ai_step(m, w), @@ -1517,6 +1525,56 @@ pub fn custom_travel(m: &mut Mob, w: &MobWorld, input: Vec3, events: &mut Vec = Vec::new(); + for at in [m.previous, m.position] { + let cells = |lo: f64, hi: f64| lo.floor() as i32..=hi.floor() as i32; + for x in cells(at.x - half, at.x + half) { + for y in cells(at.y + 1.0e-5, at.y + height) { + for z in cells(at.z - half, at.z + half) { + let p = [x, y, z]; + if visited.contains(&p) { + continue; + } + match w.block_name(x, y, z) { + "minecraft:wither_rose" => { + // isInvulnerableTo(wither): the invulnerable time + // after a hit; WitherBoss and WitherSkeleton + // refuse the effect (`canBeAffected`). + if m.invulnerable <= 0 + && !m.invulnerable_flag + && !matches!(m.species(), Species::Wither | Species::WitherSkeleton) + { + m.add_effect("minecraft:wither", 40, 0); + } + } + "minecraft:open_eyeblossom" + if m.species() == Species::Bee + && super::bee::attracts_bees(w, p) + && !m.has_effect("minecraft:poison") => + { + m.add_effect("minecraft:poison", 25, 0); + } + _ => continue, + } + visited.push(p); + } + } + } + } +} + /// MobEffect ticking for the effects mobs receive (poison, wither, regeneration). fn tick_effects(m: &mut Mob) { let mut effects = std::mem::take(&mut m.extra.effects); @@ -1541,6 +1599,9 @@ fn tick_effects(m: &mut Mob) { *ticks -= 1; } effects.retain(|e| e.1 > 0); + m.extra + .hidden_effects + .retain(|h| effects.iter().any(|e| e.0 == *h)); m.extra.effects = effects; } diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index b81f224ae..a4c27960e 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -197,7 +197,8 @@ pub fn state(m: &Mob, alpha: f32) -> State { let walking = m.alive() && !m.extra.passenger; State { pos: if walking { - m.limb_position - m.limb_speed * (1.0 - alpha) + // WalkAnimationState.position(partial): babies' legs move 3 times as far. + (m.limb_position - m.limb_speed * (1.0 - alpha)) * if m.is_baby() { 3.0 } else { 1.0 } } else { 0.0 }, @@ -248,18 +249,24 @@ pub enum ArmPose { pub fn humanoid_pub(p: &mut Poses, s: &State, _m: &Mob) { humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty)); } -/// `AnimationUtils.swingWeaponDown` with the right arm as the main arm. -pub(super) fn swing_weapon_down(p: &mut Poses, swing: f32, age: f32) { +/// `AnimationUtils.swingWeaponDown`: the main arm swings down, the other +/// one hangs and bobs. +pub(super) fn swing_weapon_down(p: &mut Poses, swing: f32, age: f32, left_main: bool) { let attack2 = (swing * PI).msin(); let attack = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin(); + let (main, off) = if left_main { + ("left_arm", "right_arm") + } else { + ("right_arm", "left_arm") + }; p.zrot("right_arm", 0.0); p.zrot("left_arm", 0.0); p.yrot("right_arm", PI / 20.0); p.yrot("left_arm", -PI / 20.0); - p.xrot("right_arm", -1.884_955_8 + (age * 0.09).mcos() * 0.15); - p.xrot("left_arm", -0.0 + (age * 0.19).mcos() * 0.5); - p.get("right_arm")[3] += attack2 * 2.2 - attack * 0.4; - p.get("left_arm")[3] += attack2 * 1.2 - attack * 0.4; + p.xrot(main, -1.884_955_8 + (age * 0.09).mcos() * 0.15); + p.xrot(off, -0.0 + (age * 0.19).mcos() * 0.5); + p.get(main)[3] += attack2 * 2.2 - attack * 0.4; + p.get(off)[3] += attack2 * 1.2 - attack * 0.4; bob(p, "right_arm", age, 1.0); bob(p, "left_arm", age, -1.0); } @@ -286,6 +293,8 @@ pub struct Hum { pub using_item: bool, /// The arm the current swing moves (`Some(true)` for the right one). pub swing_right_arm: Option, + /// `mainArm` is the left one (`Mob.isLeftHanded`): a mob's swing uses it. + pub left_main: bool, } impl Hum { pub fn new(right: ArmPose, left: ArmPose) -> Self { @@ -303,6 +312,7 @@ impl Hum { swim: 0.0, using_item: false, swing_right_arm: None, + left_main: false, } } } @@ -315,7 +325,7 @@ impl ArmPose { } } /// `AnimationUtils.animateCrossbowHold`. -fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) { +pub(super) fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) { let (hold, shoot) = if in_right { ("right_arm", "left_arm") } else { @@ -327,7 +337,7 @@ fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) { p.xrot(shoot, -1.5 + hx); } /// `AnimationUtils.animateCrossbowCharge`. -fn crossbow_charge(p: &mut Poses, max: f32, ticks: f32, in_right: bool) { +pub(super) fn crossbow_charge(p: &mut Poses, max: f32, ticks: f32, in_right: bool) { let (hold, pull) = if in_right { ("right_arm", "left_arm") } else { @@ -418,13 +428,17 @@ pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) { pose_arm(p, h.right, true, h); } } - // setupAttackAnimation (WHACK swing with the right arm). + // setupAttackAnimation (WHACK swing with the arm of the swinging hand). let hx = p.get("head")[3]; let swing = s.swing; + let swing_left = h.swing_right_arm.map_or(h.left_main, |right| !right); if swing > 0.0 && h.weapon_swing { - swing_weapon_down(p, swing, s.age); + swing_weapon_down(p, swing, s.age, h.left_main); } else if swing > 0.0 { - let body_y = (swing.sqrt() * PI * 2.0).msin() * 0.2; + let mut body_y = (swing.sqrt() * PI * 2.0).msin() * 0.2; + if swing_left { + body_y = -body_y; + } p.yrot("body", body_y); let age_scale = if s.baby { 0.5 } else { 1.0 }; { @@ -444,7 +458,7 @@ pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) { let eased = 1.0 - (1.0 - swing).powi(4); let aa = (eased * PI).msin(); let bb = (swing * PI).msin() * -(hx - 0.7) * 0.75; - let r = p.get("right_arm"); + let r = p.get(if swing_left { "left_arm" } else { "right_arm" }); r[3] -= aa * 1.2 + bb; r[4] += body_y * 2.0; r[5] += (swing * PI).msin() * -0.4; @@ -652,6 +666,7 @@ pub fn setup( } else { Hum::new(main, ArmPose::Empty) }; + h.left_main = m.main_arm_left(); h.zombie = Some(m.ai.aggressive); h.holding = m.extra.main_hand.is_some(); h.crouching = m.extra.crouching; @@ -715,6 +730,7 @@ pub fn setup( h.swim = m.extra.swim.amount(s.partial); h.using_item = m.extra.using_item > 0; h.swing_right_arm = m.extra.swing_right_arm; + h.left_main = m.main_arm_left(); humanoid(p, s, &h); if m.ai.aggressive && !bow { // SkeletonModel melee pose. diff --git a/crates/horizon-client/src/mobs/body_anim.rs b/crates/horizon-client/src/mobs/body_anim.rs index bbb44c5ab..0e88fafb2 100644 --- a/crates/horizon-client/src/mobs/body_anim.rs +++ b/crates/horizon-client/src/mobs/body_anim.rs @@ -959,7 +959,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool { let st = &m.anim.states; match m.species() { Species::Goat => goat(p, s, &Goat::from_mob(m)), - Species::PolarBear => polar_bear(p, s, 0.0), + Species::PolarBear => polar_bear(p, s, super::polar_bear::standing_scale(m, s.partial)), Species::Panda => panda(p, s, &Panda::default()), Species::Llama | Species::TraderLlama => { llama(p, s, m.extra.chested && !s.baby); diff --git a/crates/horizon-client/src/mobs/equine.rs b/crates/horizon-client/src/mobs/equine.rs index 5bb5faf53..1155388fd 100644 --- a/crates/horizon-client/src/mobs/equine.rs +++ b/crates/horizon-client/src/mobs/equine.rs @@ -28,6 +28,8 @@ pub const MARKINGS: [&str; 5] = ["", "white", "whitefield", "whitedots", "blackd pub const EAT: usize = 0; pub const STAND: usize = 1; pub const MOUTH: usize = 2; +/// `AbstractHorse.tailCounter`: client-side, it only drives the model. +pub const TAIL: usize = 3; /// What a rider asks of its mount this tick. #[derive(Clone, Copy, Debug, Default)] @@ -418,6 +420,20 @@ pub fn ridden_step(m: &mut Mob) { } } } +/// `AbstractHorse.aiStep`'s `moveTail` (one in 200 ticks) and the counter's +/// step in `tick` (it runs to 8, then stops). A client runs it on its own +/// random, as vanilla's client-side `aiStep` does. +pub fn tail_tick(m: &mut Mob) { + if m.random.next_int_bound(200).unwrap_or(1) == 0 { + m.anim.v[TAIL] = 1.0; + } + if m.anim.v[TAIL] > 0.0 { + m.anim.v[TAIL] += 1.0; + if m.anim.v[TAIL] > 8.0 { + m.anim.v[TAIL] = 0.0; + } + } +} /// `AbstractHorse.aiStep` and `tick`: healing, grazing, the rear and the /// eating/standing/mouth animations. pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { @@ -603,7 +619,15 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { t[1] += speed * age; t[2] += speed * 2.0 * age; } - p.yrot("tail", 0.0); + // animateTail: the tail swings while the counter runs. + p.yrot( + "tail", + if m.anim.v[TAIL] > 0.0 { + (s.age * 0.7).mcos() + } else { + 0.0 + }, + ); if baby && donkey { // BabyDonkeyModel overrides the state's pitch with -30 degrees and // sets the head parts again. diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 541398bc5..d0b784166 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -1017,6 +1017,8 @@ pub struct MeleeAttack { pub speed: f64, pub follow_unseen: bool, pub zombie: bool, + /// `PolarBear.PolarBearMeleeAttackGoal`: rears up before each strike. + pub polar_bear: bool, path_target: [f64; 3], recalc: i32, pub until_attack: i32, @@ -1031,6 +1033,7 @@ impl MeleeAttack { speed, follow_unseen, zombie: false, + polar_bear: false, path_target: [0.0; 3], recalc: 0, until_attack: 0, @@ -1043,6 +1046,10 @@ impl MeleeAttack { self.zombie = true; self } + pub fn polar_bear(mut self) -> Self { + self.polar_bear = true; + self + } pub fn interval(mut self, ticks: i32) -> Self { self.interval = ticks; self @@ -1098,6 +1105,9 @@ impl Goal for MeleeAttack { } m.ai.aggressive = false; m.nav_stop(); + if self.polar_bear { + super::polar_bear::set_standing(m, false); + } } fn every_tick(&self) -> bool { true @@ -1131,7 +1141,17 @@ impl Goal for MeleeAttack { self.recalc = adjusted(true, self.recalc); } self.until_attack = (self.until_attack - 1).max(0); - if self.until_attack <= 0 && m.within_melee_range(&t) && m.sees(cx.w, who) { + if self.polar_bear { + let cooldown = adjusted(true, self.interval); + super::polar_bear::check_and_perform_attack( + &mut self.until_attack, + cooldown, + m, + who, + &t, + cx, + ); + } else if self.until_attack <= 0 && m.within_melee_range(&t) && m.sees(cx.w, who) { self.until_attack = adjusted(true, self.interval); m.swing(); super::ai::do_hurt_target(m, who, cx); @@ -1422,6 +1442,9 @@ pub struct HurtByTarget { /// `Bee.BeeHurtByOtherGoal`: kept only while angry, and alerting others /// only when the attacker is in sight. pub bee: bool, + /// `PolarBear.PolarBearHurtByTargetGoal`: a hurt cub only calls the + /// adult bears and drops the target itself. + pub polar_bear: bool, timestamp: i32, st: TargetState, } @@ -1432,6 +1455,7 @@ impl HurtByTarget { alert_except: vec![], ignore: vec![], bee: false, + polar_bear: false, timestamp: 0, st: TargetState { unseen_memory: 300, @@ -1451,6 +1475,10 @@ impl HurtByTarget { self.bee = true; self } + pub fn polar_bear(mut self) -> Self { + self.polar_bear = true; + self + } } impl Default for HurtByTarget { fn default() -> Self { @@ -1462,6 +1490,8 @@ impl Goal for HurtByTarget { fn name(&self) -> &'static str { if self.bee { "BeeHurtByOtherGoal" + } else if self.polar_bear { + "PolarBearHurtByTargetGoal" } else { "HurtByTarget" } @@ -1500,7 +1530,9 @@ impl Goal for HurtByTarget { self.timestamp = m.ai.last_hurt_by_time; self.st.unseen_memory = 300; self.st.unseen = 0; - if self.alert + // PolarBearHurtByTargetGoal.start: a cub alerts the adults itself. + let cub = self.polar_bear && m.is_baby(); + if (self.alert || cub) && let Some(by) = m.ai.target { let range = m.attrs.follow_range; @@ -1520,6 +1552,8 @@ impl Goal for HurtByTarget { && (s.position.z - pos.z).abs() <= range + 1.0 }) .filter(|s| !self.alert_except.contains(&s.species)) + // PolarBearHurtByTargetGoal.alertOther: adults only. + .filter(|s| !(self.polar_bear && s.baby)) .filter(|s| Who::Mob(s.id) != by) .map(|s| s.id) .collect(); @@ -1534,6 +1568,9 @@ impl Goal for HurtByTarget { }); } } + if cub { + m.ai.target = None; + } } fn stop(&mut self, m: &mut Mob, _: &mut Cx) { m.ai.target = None; diff --git a/crates/horizon-client/src/mobs/illager.rs b/crates/horizon-client/src/mobs/illager.rs index be178a7b9..00581d6d3 100644 --- a/crates/horizon-client/src/mobs/illager.rs +++ b/crates/horizon-client/src/mobs/illager.rs @@ -681,7 +681,12 @@ pub fn anim_pose(m: &Mob, s: &State, p: &mut Poses, pose: ArmPose) { p.xrot("right_arm", x + a * 1.2 - b * 0.4); p.xrot("left_arm", x + a * 1.2 - b * 0.4); } else { - // swingWeaponDown (right-handed). + // swingWeaponDown: the main arm swings down. + let (main, off) = if m.main_arm_left() { + ("left_arm", "right_arm") + } else { + ("right_arm", "left_arm") + }; let swing = s.swing; let a2 = (swing * PI).msin(); let a = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin(); @@ -690,11 +695,11 @@ pub fn anim_pose(m: &Mob, s: &State, p: &mut Poses, pose: ArmPose) { p.yrot("right_arm", PI / 20.0); p.yrot("left_arm", -PI / 20.0); p.xrot( - "right_arm", + main, -1.884_955_8 + (s.age * 0.09).mcos() * 0.15 + (a2 * 2.2 - a * 0.4), ); p.xrot( - "left_arm", + off, -0.0 + (s.age * 0.19).mcos() * 0.5 + (a2 * 1.2 - a * 0.4), ); } diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 394821ace..e9cd42798 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -908,7 +908,7 @@ impl Mob { (distance * 4.0).min(1.0) }; self.limb_speed += (target - self.limb_speed) * 0.4; - self.limb_position += self.limb_speed * if self.is_baby() { 3.0 } else { 1.0 }; + self.limb_position += self.limb_speed; } else { self.limb_speed = 0.0; } diff --git a/crates/horizon-client/src/mobs/piglin.rs b/crates/horizon-client/src/mobs/piglin.rs index de9ba42dd..b62262bb0 100644 --- a/crates/horizon-client/src/mobs/piglin.rs +++ b/crates/horizon-client/src/mobs/piglin.rs @@ -10,7 +10,7 @@ use super::{ }, }; use horizon_core::geometry::{Vec3, trig::Mth}; -use horizon_core::random::RandomSource; +use horizon_core::random::{LegacyRandom, RandomSource}; use std::f32::consts::PI; /// `PiglinAi.ADMIRE_DURATION`. @@ -20,6 +20,9 @@ pub const ADMIRE: i32 = 119; pub const ATE_RECENTLY: i32 = 200; /// `AbstractPiglin.CONVERSION_TIME` (and the hoglin's). const CONVERSION: i32 = 300; +/// `PiglinAi.CELEBRATION_TIME`: how long the `CELEBRATE_LOCATION` and +/// `DANCING` memories last. +const CELEBRATION: i32 = 300; fn hostile_to_player(m: &Mob, w: &MobWorld) -> bool { if m.is_baby() { @@ -50,6 +53,7 @@ pub fn register_piglin(m: &mut Mob) { g.add(3, MeleeAttack::new(1.0, true)); g.add(4, PiglinAvoidRepellent); g.add(4, GoToWantedItem); + g.add(4, Celebrate); g.add(5, Stroll::avoiding_water(0.6)); g.add(6, LookAtPlayer::new(8.0)); g.add(7, RandomLookAround::default()); @@ -243,6 +247,45 @@ impl Goal for Admire { m.nav_stop(); } } +/// The celebrate activity: `GoToTargetLocation` on the spot a killed target +/// fell (within 2 blocks, or 4 and slower while dancing). +#[derive(Clone, Debug)] +struct Celebrate; +impl Celebrate { + fn walk(m: &mut Mob, cx: &mut Cx) { + let Some(at) = m.extra.home else { return }; + let (close, speed) = if m.extra.scratch[0] > 0 { + (4.0, 0.6) + } else { + (2.0, 1.0) + }; + let center = Vec3::new( + f64::from(at[0]) + 0.5, + f64::from(at[1]), + f64::from(at[2]) + 0.5, + ); + if m.distance_sqr(center) >= close * close { + m.nav_move_to(cx.w, [center.x, center.y, center.z], speed); + } + } +} +impl Goal for Celebrate { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + m.extra.scratch[1] > 0 && m.extra.home.is_some() && m.extra.using_item == 0 + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + Self::walk(m, cx); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if m.ai.nav.is_done() { + Self::walk(m, cx); + } + } +} /// `GoToWantedItem`: walk to the gold the game spotted. #[derive(Clone, Debug)] struct GoToWantedItem; @@ -294,6 +337,54 @@ fn hoglin_repellent(m: &mut Mob, w: &MobWorld) { m.ai.target = None; } } +/// `StartCelebratingIfTargetDead` for a piglin (`scratch[0]` dancing, +/// `scratch[1]` ticks of celebration left, `scratch[2]` the hit seen, `home` +/// the `CELEBRATE_LOCATION`): a killed target starts a celebration at its +/// spot, and a hoglin's death makes the piglin dance one time in ten. +/// `PiglinAi.wasHurtBy` ends both. Runs before the target goals drop the +/// dead target. +pub fn celebrate(m: &mut Mob, w: &MobWorld) { + if m.extra.scratch[1] > 0 { + m.extra.scratch[1] -= 1; + if m.extra.scratch[1] == 0 { + m.extra.scratch[0] = 0; + m.extra.home = None; + } + } + if let Some(by) = m.ai.last_hurt_by + && m.ai.last_hurt_by_time != m.extra.scratch[2] + { + m.extra.scratch[2] = m.ai.last_hurt_by_time; + // PiglinAi.wasHurtBy: another piglin's hit ends nothing. + let piglin = + matches!(by, Who::Mob(id) if w.seen(id).is_some_and(|s| s.species == Species::Piglin)); + if !piglin { + m.extra.scratch[0] = 0; + m.extra.scratch[1] = 0; + m.extra.home = None; + } + } + if m.extra.scratch[1] > 0 { + return; + } + let Some(target) = m.ai.target else { return }; + let Some(t) = w.target_info(target).filter(|t| !t.alive) else { + return; + }; + let hoglin = + matches!(target, Who::Mob(id) if w.seen(id).is_some_and(|s| s.species == Species::Hoglin)); + // PiglinAi.wantsToDance: a fresh random seeded with the game time, not + // the piglin's own. + if hoglin && LegacyRandom::new(w.game_time).next_float() < 0.1 { + m.extra.scratch[0] = 1; + } + m.extra.scratch[1] = CELEBRATION; + m.extra.home = Some([ + t.position.x.floor() as i32, + t.position.y.floor() as i32, + t.position.z.floor() as i32, + ]); +} /// Per-tick piglin and hoglin state: admiring, anger, zombification and the /// hoglin attack animation. Returns a conversion when it happens. pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { @@ -420,7 +511,10 @@ pub fn ears(p: &mut Poses, s: &State) { /// Piglins' and brutes' ears flap (`AbstractPiglinModel`), arms follow the /// arm pose (`PiglinModel`). pub fn piglin_anim(m: &Mob, s: &State, p: &mut Poses) { - let pose = if m.extra.using_item > 0 { + // Piglin.getArmPose: dancing comes first. + let pose = if m.extra.scratch[0] > 0 { + PiglinPose::Dancing + } else if m.extra.using_item > 0 { PiglinPose::AdmiringItem } else if m.extra.flag { PiglinPose::CrossbowCharge @@ -431,7 +525,14 @@ pub fn piglin_anim(m: &Mob, s: &State, p: &mut Poses) { } else { PiglinPose::Default }; - piglin_pose(p, s, pose, 25.0, m.extra.using_item as f32); + piglin_pose( + p, + s, + pose, + 25.0, + m.extra.using_item as f32, + m.main_arm_left(), + ); } /// `PiglinArmPose`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -443,11 +544,19 @@ pub enum PiglinPose { CrossbowCharge, AdmiringItem, } -/// `PiglinModel.setupAnim` for a piglin facing right-handed. -pub fn piglin_pose(p: &mut Poses, s: &State, pose: PiglinPose, max_charge: f32, ticks: f32) { - use super::anim::{ArmPose, Hum, humanoid}; +/// `PiglinModel.setupAnim`; `left` when the piglin's main arm is the left one. +pub fn piglin_pose( + p: &mut Poses, + s: &State, + pose: PiglinPose, + max_charge: f32, + ticks: f32, + left: bool, +) { + use super::anim::{ArmPose, Hum, crossbow_charge, crossbow_hold, humanoid}; let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty); h.weapon_swing = pose == PiglinPose::MeleeWeapon; + h.left_main = left; h.charge = (max_charge, ticks); humanoid(p, s, &h); ears(p, s); @@ -474,27 +583,22 @@ pub fn piglin_pose(p: &mut Poses, s: &State, pose: PiglinPose, max_charge: f32, p.get("left_arm")[1] += (dance * 40.0).msin() * 0.5 + 0.5; p.get("body")[1] += (dance * 40.0).msin() * 0.35; } - PiglinPose::MeleeWeapon if s.swing == 0.0 => p.xrot("right_arm", -1.8), - PiglinPose::CrossbowHold => { - p.yrot("right_arm", -0.3 + hy); - p.yrot("left_arm", 0.6 + hy); - p.xrot("right_arm", -PI / 2.0 + hx + 0.1); - p.xrot("left_arm", -1.5 + hx); - } - PiglinPose::CrossbowCharge => { - p.yrot("right_arm", -0.8); - p.xrot("right_arm", -0.970_796_35); - p.xrot("left_arm", -0.970_796_35); - let alpha = ticks.clamp(0.0, max_charge) / max_charge; - p.yrot("left_arm", 0.4 + alpha * (0.85 - 0.4)); - let x = -0.970_796_35 + alpha * (-PI / 2.0 - -0.970_796_35); - p.xrot("left_arm", x); + // holdWeaponHigh + PiglinPose::MeleeWeapon if s.swing == 0.0 => { + p.xrot(if left { "left_arm" } else { "right_arm" }, -1.8) } + PiglinPose::CrossbowHold => crossbow_hold(p, hx, hy, !left), + PiglinPose::CrossbowCharge => crossbow_charge(p, max_charge, ticks, !left), PiglinPose::AdmiringItem => { p.xrot("head", 0.5); p.yrot("head", 0.0); - p.yrot("left_arm", 0.5); - p.xrot("left_arm", -0.9); + if left { + p.yrot("right_arm", -0.5); + p.xrot("right_arm", -0.9); + } else { + p.yrot("left_arm", 0.5); + p.xrot("left_arm", -0.9); + } } _ => {} } diff --git a/crates/horizon-client/src/mobs/polar_bear.rs b/crates/horizon-client/src/mobs/polar_bear.rs new file mode 100644 index 000000000..bfd464a93 --- /dev/null +++ b/crates/horizon-client/src/mobs/polar_bear.rs @@ -0,0 +1,191 @@ +//! Polar bears (`PolarBear`): a neutral animal that defends its cubs, +//! fights back when hurt, and rears up before each swing. A cub flees what +//! hurts it and calls the adults. +//! +//! `extra.flag` is `DATA_STANDING_ID`, `extra.counter` the warning sound's +//! delay, `extra.anger` the `NeutralMob` anger left and `extra.flag2` whether +//! the player is who it is angry at. `anim.v[STAND]` is +//! `clientSideStandAnimation`. +use horizon_core::{geometry::Vec3, random::RandomSource}; + +use super::{ + DamageKind, Mob, MobWorld, Species, Who, + goals::{ + Cx, Float, FollowParent, Goal, HurtByTarget, LookAtPlayer, MOVE, MeleeAttack, + NearestTarget, Panic, RandomLookAround, Stroll, goal_clone, + }, + world::TargetInfo, +}; + +/// `anim.v` slot of `clientSideStandAnimation`. +pub const STAND: usize = 0; +/// `STAND_ANIMATION_TICKS`. +const STAND_TICKS: f32 = 6.0; + +pub fn register(m: &mut Mob) { + let g = &mut m.ai.goals; + g.add(0, Float); + g.add(1, MeleeAttack::new(1.25, true).polar_bear()); + g.add(1, PolarBearPanic(Panic::new(2.0))); + g.add(4, FollowParent::new(1.25)); + g.add(5, Stroll::new(1.0)); + g.add(6, LookAtPlayer::new(6.0)); + g.add(7, RandomLookAround::default()); + let t = &mut m.ai.targets; + t.add(1, HurtByTarget::new().polar_bear()); + // PolarBearAttackPlayersGoal: players near a cub, within half the + // follow range, never for a cub itself. + t.add( + 2, + NearestTarget::player(true) + .interval(20) + .follow_scale(0.5) + .reach() + .gate(|m, _| !m.is_baby()) + .when(cub_nearby) + .named("PolarBearAttackPlayersGoal"), + ); + t.add( + 3, + NearestTarget::player(true).when(|m, _| m.extra.anger > 0 && m.extra.flag2), + ); + t.add( + 4, + NearestTarget::species(&[Species::Fox], true) + .interval(10) + .reach() + .when(|m, _| !m.is_baby()), + ); +} + +/// `PolarBearAttackPlayersGoal.canUse`: a polar bear cub within 8 blocks +/// (4 up and down). +fn cub_nearby(m: &Mob, w: &MobWorld) -> bool { + let area = m.bounds().inflate(Vec3::new(8.0, 4.0, 8.0)); + w.others_near(area) + .any(|s| s.species == Species::PolarBear && s.baby && s.bounds.intersects(area)) +} + +/// `PanicGoal` with a function of the bear's age for the damage tag: a cub +/// panics at `PANIC_CAUSES`, an adult only at `PANIC_ENVIRONMENTAL_CAUSES`. +#[derive(Clone, Debug)] +struct PolarBearPanic(Panic); +impl Goal for PolarBearPanic { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + (m.is_baby() || environmental_panic(m)) && self.0.can_use(m, cx) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.0.can_continue(m, cx) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.start(m, cx) + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.stop(m, cx) + } +} +/// `DamageTypeTags.PANIC_ENVIRONMENTAL_CAUSES` (fire, lava, cactus), or +/// burning. +fn environmental_panic(m: &Mob) -> bool { + m.fire_ticks > 0 && !m.kind.flags.fire_immune + || m.last_damage.is_some_and(|(d, t)| { + matches!( + d.kind, + DamageKind::OnFire | DamageKind::InFire | DamageKind::Lava | DamageKind::Cactus + ) && i64::from(m.age) - t <= 40 + }) +} + +/// `PolarBear.setStanding`. +pub fn set_standing(m: &mut Mob, standing: bool) { + m.extra.flag = standing; +} + +/// `PolarBear.playWarningSound`. +fn play_warning_sound(m: &mut Mob, cx: &mut Cx) { + if m.extra.counter <= 0 { + m.voice("entity.polar_bear.warning", cx.events); + m.extra.counter = 40; + } +} + +/// `PolarBearMeleeAttackGoal.checkAndPerformAttack`: strike when ready and +/// in reach, rear up and growl in the last 10 ticks while close. +pub fn check_and_perform_attack( + until_attack: &mut i32, + cooldown: i32, + m: &mut Mob, + who: Who, + t: &TargetInfo, + cx: &mut Cx, +) { + if *until_attack <= 0 && m.within_melee_range(t) && m.sees(cx.w, who) { + *until_attack = cooldown; + super::ai::do_hurt_target(m, who, cx); + set_standing(m, false); + return; + } + let reach = t.bounds.size().x as f32 + 3.0; + if m.distance_sqr(t.position) < f64::from(reach * reach) { + if *until_attack <= 0 { + set_standing(m, false); + *until_attack = cooldown; + } + if *until_attack <= 10 { + set_standing(m, true); + play_warning_sound(m, cx); + } + } else { + *until_attack = cooldown; + set_standing(m, false); + } +} + +/// `PolarBear.tick`'s client half: `clientSideStandAnimation` follows the +/// synched standing flag by one tick a tick. A client of a server runs it +/// too. +pub fn client_tick(m: &mut Mob) { + let v = m.anim.v[STAND]; + m.anim.vo[STAND] = v; + let step = if m.extra.flag { 1.0 } else { -1.0 }; + m.anim.v[STAND] = (v + step).clamp(0.0, STAND_TICKS); +} +/// `PolarBear.getStandingAnimationScale`. +pub fn standing_scale(m: &Mob, partial: f32) -> f32 { + m.anim.lerp(STAND, partial) / STAND_TICKS +} + +/// `PolarBear.tick`: the stand animation, the warning sound's delay and +/// `NeutralMob.updatePersistentAnger`. +pub fn ai_step(m: &mut Mob, w: &MobWorld) { + client_tick(m); + if m.extra.counter > 0 { + m.extra.counter -= 1; + } + if m.ai.target.is_some() { + // Anger follows the target and starts over every tick it is held: + // 20 to 39 seconds (`PERSISTENT_ANGER_TIME`). + m.extra.flag2 = m.ai.target == Some(Who::Player); + m.extra.anger = 400 + m.random.next_int_bound(381).unwrap_or(0); + } else if m.extra.anger > 0 { + m.extra.anger -= 1; + if m.extra.anger == 0 { + stop_being_angry(m); + } + } + // A player in creative or spectator mode is forgiven at once. + if m.extra.flag2 && w.player.as_ref().is_some_and(|p| p.creative || p.spectator) { + stop_being_angry(m); + } +} +/// `NeutralMob.stopBeingAngry`. +fn stop_being_angry(m: &mut Mob) { + m.ai.last_hurt_by = None; + m.ai.target = None; + m.extra.anger = 0; + m.extra.flag2 = false; +} diff --git a/crates/horizon-client/src/mobs/undead.rs b/crates/horizon-client/src/mobs/undead.rs index 52efea3c4..3707f4bbe 100644 --- a/crates/horizon-client/src/mobs/undead.rs +++ b/crates/horizon-client/src/mobs/undead.rs @@ -232,8 +232,10 @@ pub fn drowned_travel( m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9); true } -/// The trident throw of `Drowned.performRangedAttack`, until thrown tridents -/// exist: an arrow-like shot with the trident's damage. +/// The trident throw of `Drowned.performRangedAttack`: a `ThrownTrident` of +/// the held trident (a plain one when it holds none), owned by the drowned, +/// which cannot be picked up and does not return (`AbstractArrow` constructor: +/// only a player's projectile is `Pickup.ALLOWED`). fn drowned_throw(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { let Some(t) = cx.w.target_info(who) else { return; @@ -243,15 +245,18 @@ fn drowned_throw(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { let yd = t.position.y + (t.bounds.max_position().y - t.bounds.min_position().y) / 3.0 - start.y; let zd = t.position.z - m.position.z; let dist = (xd * xd + zd * zd).sqrt(); - let mut p = Projectile::new( - ProjectileKind::Arrow { - base_damage: 8.0, - critical: false, - effect: None, - }, - start, - Some(Who::Mob(m.id)), - ); + let mut trident = crate::items::ItemStack::new("minecraft:trident", 1); + if m.extra.main_hand.as_deref() == Some("minecraft:trident") + && let Some(g) = super::gear::gear(m) + { + for (e, l) in &g.slots[super::gear::MAIN] { + trident.enchant(e, *l); + } + } + let mut p = Projectile::new(ProjectileKind::Trident, start, Some(Who::Mob(m.id))); + if let Some(a) = p.arrow.as_mut() { + a.set_item(&trident); + } p.shoot( &mut crate::projectiles::own_random(m), [xd, yd + dist * f64::from(0.2_f32), zd], diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index dfdc3f168..be8dc5837 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -226,6 +226,14 @@ pub enum MotionEvent { bubble: bool, position: Vec3, }, + /// `HoneyBlock.maybeDoSlideEffects` for a player sliding down the side of + /// the honey block at `pos`: its slide sound, and the server's entity + /// event 53 (the five block particles at the player). + HoneySlide { + pos: BlockPos, + sound: bool, + particles: bool, + }, /// Entity event 67 (`LivingEntity.makeDrownParticles`): eight bubbles /// around a drowning player. Drown, @@ -1449,6 +1457,9 @@ impl MotionWorld<'_, '_, '_> { "minecraft:sweet_berry_bush" if damage_only => { self.sweet_berry_bush_damage(state)?; } + // HoneyBlock.entityInside: a server's player slides too, so + // its fall distance resets (its client moves it). + "minecraft:honey_block" => self.honey_block_inside(p)?, // PowderSnowBlock.entityInside's FREEZE. "minecraft:powder_snow" if damage_only => entered.push((step, p)), _ => {} @@ -1479,6 +1490,50 @@ impl MotionWorld<'_, '_, '_> { } Ok(iterations + 1) } + /// `HoneyBlock.entityInside`: a falling player touching a side of the block + /// slides down it (`isSlidingDown`, `doSlideMovement`, `maybeDoSlideEffects`). + fn honey_block_inside(&mut self, pos: BlockPos) -> Result<()> { + let old_delta_y = |dy: f64| dy / f64::from(0.98_f32) + 0.08; + let new_delta_y = |dy: f64| (dy - 0.08) * f64::from(0.98_f32); + let position = self.player.position; + let velocity = self.player.velocity; + if self.player.ground.on_ground + || position.y > f64::from(pos.y) + 0.9375 - 1.0e-7 + || old_delta_y(velocity.y) >= -0.08 + { + return Ok(()); + } + let dx = (f64::from(pos.x) + 0.5 - position.x).abs(); + let dz = (f64::from(pos.z) + 0.5 - position.z).abs(); + let overlap = 0.4375 + f64::from(self.player.dimensions.width / 2.0); + if !(dx + 1.0e-7 > overlap || dz + 1.0e-7 > overlap) { + return Ok(()); + } + // doSlideMovement + let old = old_delta_y(velocity.y); + if old < -0.13 { + let factor = -0.05 / old; + self.player.velocity = + Vec3::new(velocity.x * factor, new_delta_y(-0.05), velocity.z * factor); + } else { + self.player.velocity = Vec3::new(velocity.x, new_delta_y(-0.05), velocity.z); + } + self.player.fall_distance = 0.0; + // maybeDoSlideEffects: the sound, then the server's event 53. + let random = &mut self.scene.random; + let sound = random.next_int_bound(5).map_err(|e| format!("{e:?}"))? == 0; + // Only the server broadcasts event 53 (`!level.isClientSide()`). + let particles = !self.player.client_side + && random.next_int_bound(5).map_err(|e| format!("{e:?}"))? == 0; + if sound || particles { + self.player.events.push(MotionEvent::HoneySlide { + pos, + sound, + particles, + }); + } + Ok(()) + } /// `Player.makeStuckInBlock`: the next move is scaled by `multiplier` /// (and the fall forgotten) unless flying; the impulse context resets /// either way. diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 61fda9878..a40d11258 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -67,6 +67,7 @@ pub enum Opt { ReducedDebugInfo, HighContrast, ShowSubtitles, + MusicFrequency, NotificationDisplayTime, Narrator, TextBackground, @@ -172,6 +173,10 @@ impl Opt { | Opt::MonochromeLogo | Opt::RotateWithMinecarts | Opt::HighContrastBlockOutlines + // Saved, but nothing in rendering reads them yet. + | Opt::ChunkFade + | Opt::ImprovedTransparency + | Opt::ChunkBuilder ) } fn file_key(self) -> Option<&'static str> { @@ -192,6 +197,7 @@ impl Opt { Opt::NarratorHotkey => "narratorHotkey", Opt::RotateWithMinecarts => "rotateWithMinecart", Opt::HighContrastBlockOutlines => "highContrastBlockOutline", + Opt::MusicFrequency => "musicFrequency", _ => return None, }) } @@ -248,6 +254,7 @@ impl Opt { Opt::ReducedDebugInfo => "options.reducedDebugInfo", Opt::HighContrast => "options.accessibility.high_contrast", Opt::ShowSubtitles => "options.showSubtitles", + Opt::MusicFrequency => "options.music_frequency", Opt::NotificationDisplayTime => "options.notifications.display_time", Opt::Narrator => "options.narrator", Opt::TextBackground => "options.accessibility.text_background", @@ -578,6 +585,11 @@ impl Opt { Opt::ReducedDebugInfo => on_off(s.reduced_debug_info), Opt::HighContrast => on_off(s.high_contrast), Opt::ShowSubtitles => on_off(s.show_subtitles), + Opt::MusicFrequency => tr([ + "options.music_frequency.default", + "options.music_frequency.frequent", + "options.music_frequency.constant", + ][s.file.int("musicFrequency").clamp(0, 2) as usize]), Opt::ForceUnicode => on_off(s.force_unicode), Opt::JapaneseGlyphs => on_off(s.japanese_glyphs), Opt::PadEnabled => on_off(s.controller.enabled), @@ -747,6 +759,11 @@ impl Opt { Opt::ReducedDebugInfo => s.reduced_debug_info = !s.reduced_debug_info, Opt::HighContrast => s.high_contrast = !s.high_contrast, Opt::ShowSubtitles => s.show_subtitles = !s.show_subtitles, + Opt::MusicFrequency => { + let n = next(s.file.int("musicFrequency").clamp(0, 2) as u8, 3); + s.file + .set("musicFrequency", crate::options_file::V::Int(i32::from(n))); + } Opt::ForceUnicode => s.force_unicode = !s.force_unicode, Opt::JapaneseGlyphs => s.japanese_glyphs = !s.japanese_glyphs, Opt::PadEnabled => s.controller.enabled = !s.controller.enabled, @@ -1412,6 +1429,9 @@ impl OptionsUi { let others: Vec = (1..SOUND_SOURCES.len()).map(Opt::Volume).collect(); rows.extend(pairs(&others)); rows.extend(pairs(&[Opt::ShowSubtitles])); + // SoundOptionsScreen: Music Frequency starts the next row (with + // Music Toast, not in Horizon yet). + rows.extend(pairs(&[Opt::MusicFrequency])); rows } Page::Controls => { @@ -2533,6 +2553,21 @@ impl OptionsUi { if opt == Opt::Preset { apply_preset(s); } + if opt == Opt::HighContrast { + // Options.highContrast: the built-in pack follows the option. + let on = s.resource_packs.iter().any(|id| id == "high_contrast"); + if on != s.high_contrast { + s.resource_packs.retain(|id| id != "high_contrast"); + if s.high_contrast { + s.resource_packs.push("high_contrast".into()); + } + // PackSelectionScreen reads the repository each time it + // opens: the next one starts from this selection. + self.pack_selection = s.resource_packs.clone(); + self.pack_screen = None; + events.push(Event::Packs(s.resource_packs.clone())); + } + } events.push(Event::Changed); } Act::Extra(item) => { @@ -2701,6 +2736,7 @@ impl OptionsUi { { let ids = p.commit(); s.resource_packs = ids.clone(); + self.pack_selection = ids.clone(); events.push(Event::Packs(ids)); } } diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index fa9dc9c6e..5efc83621 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -23,212 +23,7 @@ use std::{ path::Path, }; -macro_rules! particle_types { - ($($variant:ident = $name:literal),* $(,)?) => { - /// Vanilla particle types with a client implementation here. - #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] - pub enum ParticleType { $($variant),* } - impl ParticleType { - pub const ALL: &'static [ParticleType] = &[$(ParticleType::$variant),*]; - /// Registry path (`minecraft:`), also the sprite-set file name. - pub fn name(self) -> &'static str { - match self { $(ParticleType::$variant => $name),* } - } - pub fn from_name(name: &str) -> Option { - let name = name.strip_prefix("minecraft:").unwrap_or(name); - match name { $($name => Some(ParticleType::$variant),)* _ => None } - } - } - }; -} -particle_types! { - Block = "block", - BlockCrumble = "block_crumble", - Trail = "trail", - DustPillar = "dust_pillar", - FallingDust = "falling_dust", - Smoke = "smoke", - LargeSmoke = "large_smoke", - WhiteSmoke = "white_smoke", - Flame = "flame", - SoulFireFlame = "soul_fire_flame", - CopperFireFlame = "copper_fire_flame", - SmallFlame = "small_flame", - Lava = "lava", - DrippingWater = "dripping_water", - FallingWater = "falling_water", - DrippingLava = "dripping_lava", - FallingLava = "falling_lava", - LandingLava = "landing_lava", - DrippingHoney = "dripping_honey", - FallingHoney = "falling_honey", - LandingHoney = "landing_honey", - FallingNectar = "falling_nectar", - FallingSporeBlossom = "falling_spore_blossom", - SporeBlossomAir = "spore_blossom_air", - DrippingObsidianTear = "dripping_obsidian_tear", - FallingObsidianTear = "falling_obsidian_tear", - LandingObsidianTear = "landing_obsidian_tear", - DrippingDripstoneWater = "dripping_dripstone_water", - FallingDripstoneWater = "falling_dripstone_water", - DrippingDripstoneLava = "dripping_dripstone_lava", - FallingDripstoneLava = "falling_dripstone_lava", - Splash = "splash", - Rain = "rain", - Bubble = "bubble", - SulfurBubbles = "sulfur_bubbles", - BubblePop = "bubble_pop", - BubbleColumnUp = "bubble_column_up", - CurrentDown = "current_down", - Underwater = "underwater", - Portal = "portal", - ReversePortal = "reverse_portal", - Enchant = "enchant", - Nautilus = "nautilus", - VaultConnection = "vault_connection", - Crit = "crit", - EnchantedHit = "enchanted_hit", - DamageIndicator = "damage_indicator", - Heart = "heart", - AngryVillager = "angry_villager", - HappyVillager = "happy_villager", - Composter = "composter", - Mycelium = "mycelium", - Dolphin = "dolphin", - EggCrack = "egg_crack", - Poof = "poof", - Explosion = "explosion", - ExplosionEmitter = "explosion_emitter", - CampfireCosySmoke = "campfire_cosy_smoke", - CampfireSignalSmoke = "campfire_signal_smoke", - Note = "note", - Dust = "dust", - TotemOfUndying = "totem_of_undying", - Firework = "firework", - EndRod = "end_rod", - Ash = "ash", - WhiteAsh = "white_ash", - CrimsonSpore = "crimson_spore", - WarpedSpore = "warped_spore", - CherryLeaves = "cherry_leaves", - PaleOakLeaves = "pale_oak_leaves", - TintedLeaves = "tinted_leaves", - Effect = "effect", - InstantEffect = "instant_effect", - EntityEffect = "entity_effect", - Witch = "witch", - Infested = "infested", - Cloud = "cloud", - Sneeze = "sneeze", - Snowflake = "snowflake", - Soul = "soul", - SculkSoul = "sculk_soul", - DragonBreath = "dragon_breath", - Gust = "gust", - SmallGust = "small_gust", - GustEmitterLarge = "gust_emitter_large", - GustEmitterSmall = "gust_emitter_small", - DustColorTransition = "dust_color_transition", - SculkCharge = "sculk_charge", - SculkChargePop = "sculk_charge_pop", - Shriek = "shriek", - SonicBoom = "sonic_boom", - Vibration = "vibration", - SweepAttack = "sweep_attack", - Glow = "glow", - WaxOn = "wax_on", - WaxOff = "wax_off", - ElectricSpark = "electric_spark", - Scrape = "scrape", - SquidInk = "squid_ink", - GlowSquidInk = "glow_squid_ink", - Item = "item", - ItemSlime = "item_slime", - ItemSnowball = "item_snowball", - ItemCobweb = "item_cobweb", - SulfurCubeGoo = "sulfur_cube_goo", - Flash = "flash", - Firefly = "firefly", - TrialSpawnerDetection = "trial_spawner_detection", - TrialSpawnerDetectionOminous = "trial_spawner_detection_ominous", - TrialOmen = "trial_omen", - RaidOmen = "raid_omen", - OminousSpawning = "ominous_spawning", - Spit = "spit", - Fishing = "fishing", - DustPlume = "dust_plume", - RedPoplarLeaves = "red_poplar_leaves", - OrangePoplarLeaves = "orange_poplar_leaves", - YellowPoplarLeaves = "yellow_poplar_leaves", - PauseMobGrowth = "pause_mob_growth", - ResetMobGrowth = "reset_mob_growth", - BlockMarker = "block_marker", -} -impl ParticleType { - /// `ParticleType.getOverrideLimiter` (`ParticleTypes.register(name, true)`): - /// spawned regardless of distance. - pub fn override_limiter(self) -> bool { - matches!( - self, - Self::BlockMarker - | Self::DamageIndicator - | Self::ExplosionEmitter - | Self::Explosion - | Self::Gust - | Self::GustEmitterLarge - | Self::GustEmitterSmall - | Self::SonicBoom - | Self::SculkCharge - | Self::SculkChargePop - | Self::Vibration - | Self::Poof - | Self::Spit - | Self::SquidInk - | Self::SweepAttack - | Self::CampfireCosySmoke - | Self::CampfireSignalSmoke - | Self::GlowSquidInk - | Self::Glow - | Self::WaxOn - | Self::WaxOff - | Self::ElectricSpark - | Self::Scrape - | Self::TrialSpawnerDetection - | Self::TrialSpawnerDetectionOminous - | Self::VaultConnection - | Self::OminousSpawning - ) - } - /// `SingleQuadParticle.Layer.translucent`: types whose vanilla particle class - /// hardcodes the translucent layer, drawn after translucent terrain. - /// `TerrainParticle`, `BreakingItemParticle` and `BlockMarker` resolve their - /// layer from the sprite instead (`Layer.bySprite`); see the `translucent` - /// sprite set on the engine. - pub fn translucent_layer(self) -> bool { - match self { - // CampfireSmokeParticle. - Self::CampfireCosySmoke | Self::CampfireSignalSmoke - // PlayerCloudParticle. - | Self::Cloud | Self::Sneeze - // SpellParticle. - | Self::Effect | Self::InstantEffect | Self::EntityEffect - | Self::Witch | Self::Infested | Self::TrialOmen | Self::RaidOmen - // EmissiveRisingParticle. - | Self::Soul | Self::SculkSoul - // SculkChargeParticle, SculkChargePopParticle, ShriekParticle, - // VibrationSignalParticle, FireflyParticle, OverlayParticle. - | Self::SculkCharge | Self::SculkChargePop | Self::Shriek - | Self::Vibration | Self::Firefly | Self::Flash - // SimpleAnimatedParticle and its subclasses: EndRodParticle, - // SparkParticle (firework), SquidInkParticle, TotemParticle. - | Self::EndRod | Self::Firework | Self::SquidInk | Self::GlowSquidInk - | Self::TotemOfUndying - // FlyTowardsPositionParticle: its LifetimeAlpha(0, 0.6, 0.25, 1) is not opaque. - | Self::VaultConnection => true, - _ => false, - } - } -} +pub use horizon_client_core::particle_type::ParticleType; /// `ParticleOptions` with the parameters of the option classes used here. #[derive(Clone, Debug)] @@ -1381,16 +1176,17 @@ impl ParticleEngine { } } /// `ClientPacketListener.handleExplosion` + `ClientExplosionTracker`: the - /// explosion particle (emitter for radius >= 2) and up to 512 poof/smoke - /// particles thrown from air inside the radius. + /// explosion particle (the emitter unless `ServerExplosion.isSmall`) and up + /// to 512 poof/smoke particles thrown from air inside the radius. pub fn explosion( &mut self, center: [f64; 3], - radius: f32, + small: bool, block_count: usize, + radius: f32, is_air: &dyn Fn([i32; 3]) -> bool, ) { - let ty = if radius < 2.0 { + let ty = if small { ParticleType::Explosion } else { ParticleType::ExplosionEmitter @@ -1398,6 +1194,18 @@ impl ParticleEngine { self.add(&ParticleOptions::simple(ty), center, [1.0, 0.0, 0.0]); self.explosion_blocks(center, radius, block_count, is_air); } + /// `LlamaSpit.recreateFromPacket`: seven spit particles thrown ahead of a + /// new spit, each faster than the last along x and z. + pub fn llama_spit_burst(&mut self, at: [f64; 3], movement: [f64; 3]) { + for i in 0..7 { + let k = 0.4 + 0.1 * f64::from(i); + self.add( + &ParticleOptions::simple(ParticleType::Spit), + at, + [movement[0] * k, movement[1], movement[2] * k], + ); + } + } /// `ClientExplosionTracker` with `Level.DEFAULT_EXPLOSION_BLOCK_PARTICLES`. pub fn explosion_blocks( &mut self, diff --git a/crates/horizon-client/src/projectiles.rs b/crates/horizon-client/src/projectiles.rs index 8a709067d..aae9b296b 100644 --- a/crates/horizon-client/src/projectiles.rs +++ b/crates/horizon-client/src/projectiles.rs @@ -28,6 +28,10 @@ pub enum ProjectileKind { critical: bool, effect: Option<(&'static str, i32)>, }, + /// `ThrownTrident` of a mob (a drowned's): flies and sticks with + /// `AbstractArrow`'s tick; the trident itself is the arrow state's + /// `pickup_item`. + Trident, Snowball, Egg, EnderPearl, @@ -66,6 +70,7 @@ impl ProjectileKind { pub fn id(&self) -> &'static str { match self { Self::Arrow { .. } => "minecraft:arrow", + Self::Trident => "minecraft:trident", Self::Snowball => "minecraft:snowball", Self::Egg => "minecraft:egg", Self::EnderPearl => "minecraft:ender_pearl", @@ -152,7 +157,7 @@ fn axis_of(d: u8) -> u8 { } impl Projectile { pub fn new(kind: ProjectileKind, position: Vec3, owner: Option) -> Self { - let kind_is_arrow = matches!(kind, ProjectileKind::Arrow { .. }); + let kind_is_arrow = matches!(kind, ProjectileKind::Arrow { .. } | ProjectileKind::Trident); Self { id: 0, kind, @@ -253,7 +258,7 @@ impl Projectile { } fn gravity(&self) -> f64 { match self.kind { - ProjectileKind::Arrow { .. } => 0.05, + ProjectileKind::Arrow { .. } | ProjectileKind::Trident => 0.05, ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } | ProjectileKind::WitherSkull { .. } => 0.0, @@ -604,8 +609,8 @@ impl Projectile { | ProjectileKind::WitherSkull { .. } => { self.apply_hurting_inertia(water); } - // Arrows tick with `arrows::tick`. - ProjectileKind::Arrow { .. } => {} + // Arrows and tridents tick with `arrows::tick`. + ProjectileKind::Arrow { .. } | ProjectileKind::Trident => {} ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge => {} // LlamaSpit.tick: gone in water; drag and gravity follow the move. ProjectileKind::LlamaSpit => { @@ -746,7 +751,8 @@ impl Projectile { ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge => return None, ProjectileKind::WitherSkull { dangerous: false } => "entity/wither/wither", ProjectileKind::WitherSkull { dangerous: true } => "entity/wither/wither_invulnerable", - ProjectileKind::Arrow { .. } => return None, + // Drawn as their models by the game. + ProjectileKind::Arrow { .. } | ProjectileKind::Trident => return None, }) } /// Render scale of the item billboard (fireball renderers). diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 5431adcd6..dc08d90b0 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -2435,28 +2435,7 @@ fn write_saved_data(world: &Path, name: &str, data: Tag) -> Result<()> { Tag::compound([("data", data), ("DataVersion", Tag::Int(DATA_VERSION))]), ) } -pub fn uuid_text(u: [i32; 4]) -> String { - let hex: String = u.iter().map(|v| format!("{:08x}", *v as u32)).collect(); - format!( - "{}-{}-{}-{}-{}", - &hex[0..8], - &hex[8..12], - &hex[12..16], - &hex[16..20], - &hex[20..32] - ) -} -pub fn uuid_from_text(s: &str) -> Option<[i32; 4]> { - let hex: String = s.chars().filter(|c| *c != '-').collect(); - if hex.len() != 32 { - return None; - } - let mut out = [0i32; 4]; - for (i, v) in out.iter_mut().enumerate() { - *v = u32::from_str_radix(&hex[i * 8..i * 8 + 8], 16).ok()? as i32; - } - Some(out) -} +pub use horizon_client_core::uuid::{uuid_from_text, uuid_text}; /// A random (version 4) UUID as vanilla's four-int form. pub fn random_uuid() -> [i32; 4] { let t = std::time::SystemTime::now() @@ -5125,6 +5104,30 @@ mod tests { }; assert_eq!(back.recipes_used.get("minecraft:cooked_porkchop"), Some(&3)); } + /// The world's save (Level.write) writes the rules as they are now, and a + /// world opened again reads them back (#74). + #[test] + fn level_save_keeps_changed_rules() { + use crate::gamerules::{GameRules, Value}; + let dir = + std::env::temp_dir().join(format!("horizon-gamerules-level-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut level = super::Level::default(); + level.write(&dir).unwrap(); + // Rules changed while playing, then saved and loaded again. + let mut rules = GameRules::load(&dir); + assert_eq!(rules, GameRules::default()); + assert!(rules.set("advance_time", Value::Bool(false))); + assert!(rules.set("advance_weather", Value::Bool(false))); + assert!(rules.set("random_tick_speed", Value::Int(0))); + level.game_rules = rules.by_name(); + level.write(&dir).unwrap(); + assert_eq!(GameRules::load(&dir), rules); + let read = super::Level::read(&dir).unwrap(); + assert_eq!(read.game_rules, rules.by_name()); + assert_eq!(read.game_rule("advance_time"), 0); + let _ = std::fs::remove_dir_all(dir); + } /// A save written before the key was namespaced holds an id twice, once bare: vanilla /// refuses such a furnace, so a load merges them under the full id. diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 74c428923..2308794d3 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -5,11 +5,7 @@ use crate::keybinds::KeyBinds; use crate::options_file::{OptionsFile, V}; use std::{fs, path::Path}; -/// SoundSource names in vanilla order. -pub const SOUND_SOURCES: [&str; 11] = [ - "master", "music", "record", "weather", "block", "hostile", "neutral", "player", "ambient", - "voice", "ui", -]; +pub use horizon_client_core::sound_source::SOUND_SOURCES; /// Per-source volumes for the mixer (soundCategory_* except master). static SOURCE_VOLUMES: std::sync::RwLock<[f32; 11]> = std::sync::RwLock::new([1.0; 11]); diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 0c9ae0c5b..c0a96f504 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -1417,6 +1417,14 @@ impl Streaming { pub fn band(&self) -> Option { self.band } + /// Rank the chunks `/forceload add` over chunks `(x0, z0)..=(x1, z1)` + /// decorates in vanilla's order (`forced_order`), after every chunk + /// ranked before. + pub fn rank_forced(&mut self, x0: i32, z0: i32, x1: i32, z1: i32) { + for (x, z) in horizon_world::worldgen::decoration_order::forced_order(x0, z0, x1, z1) { + self.decoration_order.rank_or_append(x, z); + } + } /// Generate, light and keep the chunks of `band` (none: stop), and let /// go of what earlier bands held as it falls out of range. The chunks a /// band reaches are ranked for decoration row by row, as they first come diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index 01c60ed71..0a4c9a88e 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -196,23 +196,27 @@ fn text(nbt: &Compound, key: &str) -> Option { /// The client block entity for one of a chunk's generated block entities, /// before a container's loot is unpacked: `StructureTemplate.placeInWorld` -/// hands the template's block entity NBT to the level's block entity. +/// hands the template's block entity NBT to `loadWithComponents`, which is +/// what a chunk load does with a saved one. fn generated_block_entity(block: &str, nbt: &Compound) -> Option { - let mut entity = BlockEntity::for_block(block)?; - match &mut entity { - // MonsterRoomFeature and the structures' setEntityId. - BlockEntity::Spawner(s) => { - **s = crate::mobs::spawner::Spawner::load(&Tag::Compound(nbt.clone())); - } - BlockEntity::TrialSpawner(s) => { - **s = crate::mobs::trial_spawner::TrialSpawner::load(&Tag::Compound(nbt.clone())); - } - BlockEntity::Vault(v) => **v = crate::vault::Vault::load(&Tag::Compound(nbt.clone())), - // BannerBlockEntity.loadAdditional: the End cities' black triangles. - BlockEntity::Banner(b) => *b = crate::save::decode_banner(&Tag::Compound(nbt.clone())), - _ => {} + let fallback = BlockEntity::for_block(block)?; + let mut tag = nbt.clone(); + // RandomizableContainer.tryLoadLootTable: with a table the items are not read. + if text(&tag, "LootTable").is_some() { + tag.remove(&JavaString::from("Items")); } - Some(entity) + // Programmatic block entities (and a template that saved none) carry no id. + if !tag.contains_key(&JavaString::from("id")) { + tag.insert("id".into(), Tag::String(fallback.id().into())); + } + for axis in ["x", "y", "z"] { + tag.insert(axis.into(), Tag::Int(0)); + } + // A saved kind the client cannot decode keeps the block's own entity. + Some( + crate::save::decode_block_entity(&Tag::Compound(tag)) + .map_or(fallback, |(_, entity)| entity), + ) } /// Client block entities for the generated block entities of a chunk, and the diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index 79d316969..dc729bd8c 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -24,7 +24,9 @@ use horizon_world::{ }; use std::{path::Path, sync::Arc}; mod lod; +mod structure_mobs; use lod::VanillaLodSampler; +use structure_mobs::StructureMobFinalizer; pub struct VanillaTerrain { generator: OverworldGenerator, @@ -32,6 +34,7 @@ pub struct VanillaTerrain { biome_map: Vec, /// Loot tables for generated containers. loot: Option>, + structure_mobs: Arc, /// A worker for structure queries from the game thread. query: std::sync::Mutex>, /// Block state id -> block index, the game's block tick type: worldgen @@ -39,6 +42,8 @@ pub struct VanillaTerrain { tick_blocks: Vec, /// Block index -> default state id: `tick_blocks` the other way. tick_states: Vec, + /// Block state id -> the block entity type of its block, if it has one. + block_entity_types: Vec>, seed: i64, dimension: String, /// When the last proto chunk was generated, in milliseconds since @@ -51,6 +56,51 @@ enum VanillaProto { Ready(Box), Failed(i32, i32), } +/// WorldGenRegion.setBlock gives every block with a block entity a new +/// one: the blocks nothing placed data for (a sculk patch's sensors) get +/// vanilla's defaults. +fn add_default_block_entities(kinds: &[Option<&str>], out: &mut Chunk, raw: &mut Vec) { + let kind = |v: u32| kinds.get(v as usize).copied().flatten(); + let mut states = [0u32; 4096]; + for (si, section) in out.sections.iter().enumerate() { + if !section.blocks.maybe_has(|v| kind(v).is_some()) { + continue; + } + section.unpack(&mut states); + for (i, &v) in states.iter().enumerate() { + let Some(id) = kind(v) else { + continue; + }; + let i = i as i32; + let pos = [ + out.x * 16 + (i & 15), + MIN_Y + si as i32 * 16 + (i >> 8), + out.z * 16 + ((i >> 4) & 15), + ]; + let at = |t: &Tag| { + ["x", "y", "z"] + .iter() + .zip(pos) + .all(|(k, p)| t.get(k) == Some(&Tag::Int(p))) + }; + if raw.iter().any(at) || out.block_entities.iter().any(|(p, _)| *p == pos.into()) { + continue; + } + let tag = Tag::compound([ + ("id", Tag::String(id.into())), + ("x", Tag::Int(pos[0])), + ("y", Tag::Int(pos[1])), + ("z", Tag::Int(pos[2])), + ]); + let tag = crate::block_entity_nbt::canonical(&tag).unwrap_or(tag); + match crate::save::decode_block_entity(&tag) { + Some(modelled) => out.block_entities.push(modelled), + None => raw.push(tag), + } + } + } +} + impl VanillaTerrain { fn client_surface(&self, surface: SurfaceSample) -> crate::lod::Surface { crate::lod::Surface { @@ -119,6 +169,7 @@ impl VanillaTerrain { } let mut tick_blocks = Vec::with_capacity(registry.len()); let mut tick_states = Vec::new(); + let mut block_entity_types = Vec::with_capacity(registry.len()); let mut last: Option<&str> = None; let mut index = 0u32; for id in 0..registry.len() { @@ -133,20 +184,31 @@ impl VanillaTerrain { } last = Some(name); tick_blocks.push(index); + block_entity_types.push(crate::lan::chunks::block_entity_type(name)); } Ok(Self { generator, biome_map, loot, + structure_mobs: Arc::new(StructureMobFinalizer::new( + dir.parent().unwrap_or(dir).to_owned(), + dimension, + )), query: std::sync::Mutex::new(None), tick_blocks, tick_states, + block_entity_types, seed, dimension: dimension.to_owned(), last_proto: std::sync::atomic::AtomicU64::new(0), created: std::time::Instant::now(), }) } + /// The difficulty (0 peaceful to 3 hard) and overworld clock structure + /// mobs are finalized with. + pub fn set_spawn_conditions(&self, difficulty: u8, day_time: i64) { + self.structure_mobs.set_conditions(difficulty, day_time); + } /// A proto chunk's blocks, biomes, scheduled ticks and post-processing /// marks as a column. fn column(&self, chunk: &ProtoChunk) -> Chunk { @@ -362,7 +424,9 @@ pub fn shared_data( impl ChunkGenerator for VanillaTerrain { type Worker = GeneratorWorker; fn worker(&self) -> GeneratorWorker { - self.generator.worker() + let mut worker = self.generator.worker(); + worker.set_structure_mobs(self.structure_mobs.clone()); + worker } fn lod_sampler(self: Arc) -> Box { Box::new(VanillaLodSampler::new(self)) @@ -561,7 +625,7 @@ impl ChunkGenerator for VanillaTerrain { // The block entities Horizon does not model (decorated pots with their // sherds and loot table, brushable blocks) stay as placed, like a // loaded chunk's. - let unmodelled: Vec = chunk + let mut unmodelled: Vec = chunk .block_entities .iter() .filter(|(pos, _)| { @@ -581,6 +645,7 @@ impl ChunkGenerator for VanillaTerrain { Some(Tag::Compound(nbt)) }) .collect(); + add_default_block_entities(&self.block_entity_types, &mut out, &mut unmodelled); if !unmodelled.is_empty() || !rolled_loot.is_empty() { let mut extras = out .saved @@ -604,3 +669,35 @@ impl ChunkGenerator for VanillaTerrain { out } } + +#[cfg(test)] +mod default_block_entity_tests { + use super::*; + + #[test] + fn generated_blocks_get_their_block_entities() { + let mut out = Chunk::empty(-2, 3); + out.set(4, -40, 9, 7); + out.set(5, -40, 9, 6); + let mut kinds = vec![None; 8]; + kinds[6] = Some("minecraft:potent_sulfur"); + kinds[7] = Some("minecraft:sculk_sensor"); + let mut raw = vec![]; + add_default_block_entities(&kinds, &mut out, &mut raw); + assert!(matches!( + out.block_entities[..], + [((-28, -40, 57), crate::containers::BlockEntity::Sculk(_))] + )); + assert_eq!(raw.len(), 1); + assert_eq!( + raw[0].get("id"), + Some(&Tag::String("minecraft:potent_sulfur".into())) + ); + add_default_block_entities(&kinds, &mut out, &mut raw); + assert_eq!( + (out.block_entities.len(), raw.len()), + (1, 1), + "a placed block entity is kept, not doubled" + ); + } +} diff --git a/crates/horizon-client/src/vanillagen/structure_mobs.rs b/crates/horizon-client/src/vanillagen/structure_mobs.rs new file mode 100644 index 000000000..dec5aa92b --- /dev/null +++ b/crates/horizon-client/src/vanillagen/structure_mobs.rs @@ -0,0 +1,446 @@ +//! `Mob.finalizeSpawn(level, level.getCurrentDifficultyAt(pos), STRUCTURE, null)` +//! of the mobs structures place (StructureTemplate.placeEntities with +//! finalizeEntities, ocean ruin drowned, mansion illagers, witch huts, +//! monuments), run as decoration places them, with the WorldGenRegion's random. +use crate::{ + enchant::Enchantments, + entity_nbt, + items::Items, + mobs::{ + Mob, MobType, MobTypes, + finalize::{self, Ctx, FinalizeLevel, Reason, SpawnData, SpawnRegistries}, + spawning::{LocalDifficulty, MOON_BRIGHTNESS}, + }, +}; +use chrono::Datelike; +use horizon_core::{ + geometry::{Aabb, Vec3}, + random::{LegacyRandom, RandomSource, XoroshiroRandom}, +}; +use horizon_world::{ + nbt::{Compound, Tag}, + worldgen::{generator::StructureMobs, structure::legacy::PieceRandom}, +}; +use std::{ + collections::{HashMap, HashSet}, + path::PathBuf, + sync::{ + Arc, OnceLock, + atomic::{AtomicI64, AtomicU8, Ordering}, + }, +}; + +struct Data { + types: HashMap>, + biome_tags: HashMap>, + registries: SpawnRegistries, + enchantments: Enchantments, + items: Items, + camel_husk: (f32, f32), +} +fn load(root: &std::path::Path) -> Option { + let types = MobTypes::load(root).ok()?.types; + let camel = types.get("minecraft:camel_husk")?; + let camel_husk = (camel.width as f32, camel.height as f32); + Some(Data { + types: types.into_iter().map(|(k, t)| (k, Arc::new(t))).collect(), + biome_tags: crate::items::load_tags(root, "worldgen/biome").unwrap_or_default(), + registries: SpawnRegistries::load(root), + enchantments: Enchantments::load(root), + items: Items::tags_only(root).ok()?, + camel_husk, + }) +} + +pub struct StructureMobFinalizer { + root: PathBuf, + dimension: String, + data: OnceLock>, + /// The level's difficulty (0 peaceful to 3 hard) and overworld clock. + difficulty: AtomicU8, + day_time: AtomicI64, +} +impl StructureMobFinalizer { + pub fn new(root: PathBuf, dimension: &str) -> Self { + Self { + root, + dimension: dimension.to_owned(), + data: OnceLock::new(), + difficulty: AtomicU8::new(2), + day_time: AtomicI64::new(0), + } + } + pub fn set_conditions(&self, difficulty: u8, day_time: i64) { + self.difficulty.store(difficulty, Ordering::Relaxed); + self.day_time.store(day_time, Ordering::Relaxed); + } +} + +struct Level<'a> { + data: &'a Data, + biome: &'a str, + structures: &'a [String], + difficulty: u8, + day_time: i64, + next_id: u32, +} +impl FinalizeLevel for Level<'_> { + fn biome(&self, _: [i32; 3]) -> String { + self.biome.to_owned() + } + fn biome_tag(&self, tag: &str, _: [i32; 3]) -> bool { + self.data + .biome_tags + .get(tag) + .is_some_and(|b| b.contains(self.biome)) + } + fn structures_with_piece_at(&self, _: [i32; 3]) -> Vec { + self.structures.to_vec() + } + fn moon_phase(&self, _: [i32; 3]) -> usize { + self.day_time.div_euclid(24000).rem_euclid(8) as usize + } + fn spawning_monsters(&self) -> bool { + self.difficulty != 0 + } + // No block collision: only a husk's camel asks, and no structure places husks. + fn no_collision(&self, _: Aabb) -> bool { + true + } + // WorldGenRegion holds no entities. + fn free_chicken(&self, _: Aabb) -> Option { + None + } + fn ride_chicken(&mut self, _: u32, _: u32) {} + fn game_time(&self) -> i64 { + self.day_time + } + fn halloween(&self) -> bool { + let today = chrono::Local::now(); + (today.month(), today.day()) == (10, 31) + } + fn create(&mut self, kind: &str, _: Reason) -> Option { + if self.difficulty == 0 && !finalize::allowed_in_peaceful(kind) { + return None; + } + let t = self.data.types.get(kind)?.clone(); + self.next_id += 1; + Some(Mob::new(self.next_id, t, Vec3::ZERO, 0.0)) + } +} + +fn run( + level: &mut Level<'_>, + random: &mut R, + difficulty: LocalDifficulty, + data: &SpawnData<'_>, + m: &mut Mob, +) -> Vec { + let mut cx = Ctx { + level, + random, + difficulty, + data, + created: Vec::new(), + }; + cx.finalize(m, Reason::Structure, None); + cx.created +} + +/// The saved compound of mob `i` with the mobs riding it under `Passengers`. +fn tree(mobs: &[(Mob, Option)], i: usize, dimension: &str) -> Compound { + let (m, raw) = &mobs[i]; + let Tag::Compound(mut c) = entity_nbt::mob_to_nbt(m, [0; 4], raw.as_ref()) else { + return Compound::new(); + }; + c.remove(&"UUID".into()); + entity_nbt::put_brain(&mut c, m, dimension); + let riders: Vec = (0..mobs.len()) + .filter(|&j| mobs[j].0.extra.mount == Some(m.id)) + .map(|j| Tag::Compound(tree(mobs, j, dimension))) + .collect(); + if !riders.is_empty() { + c.insert("Passengers".into(), Tag::List(riders)); + } + c +} + +impl StructureMobs for StructureMobFinalizer { + fn finalize( + &self, + nbt: &mut Compound, + biome: &str, + structures: &[String], + random: &mut dyn PieceRandom, + ) -> bool { + let Some(data) = self.data.get_or_init(|| { + let data = load(&self.root); + if data.is_none() { + log::error!("Horizon: no mob data, structure mobs are finalized when loaded"); + } + data + }) else { + return false; + }; + let mut raw = Tag::Compound(nbt.clone()); + if let Tag::Compound(c) = &mut raw { + c.remove(&"horizon:finalize".into()); + } + let Some(mut m) = entity_nbt::mob_from_nbt(&raw, &data.types, 1) else { + // Not a mob: vanilla finalizes only Mob instances. + return true; + }; + let base = self.difficulty.load(Ordering::Relaxed); + let day_time = self.day_time.load(Ordering::Relaxed); + let mut level = Level { + data, + biome, + structures, + difficulty: base, + day_time, + next_id: 1, + }; + let moon = MOON_BRIGHTNESS[level.moon_phase([0; 3])]; + // WorldGenRegion.getCurrentDifficultyAt: no inhabited time. + let difficulty = LocalDifficulty::new(base, day_time, 0, moon); + let spawn = SpawnData { + registries: &data.registries, + enchantments: &data.enchantments, + items: &data.items, + camel_husk_size: data.camel_husk, + }; + let any = random.as_any(); + let created = if let Some(r) = any.downcast_mut::() { + run(&mut level, r, difficulty, &spawn, &mut m) + } else if let Some(r) = any.downcast_mut::() { + run(&mut level, r, difficulty, &spawn, &mut m) + } else { + log::error!("Horizon: unknown region random, structure mobs are finalized when loaded"); + return false; + }; + let mut mobs = vec![(m, Some(raw))]; + mobs.extend(created.into_iter().map(|c| (c, None))); + let root = mobs + .iter() + .position(|(m, _)| m.extra.mount.is_none()) + .unwrap_or(0); + *nbt = tree(&mobs, root, &self.dimension); + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The bastion's crossbow piglin keeps its crossbow (STRUCTURE skips + /// createSpawnWeapon) and saves what Piglin.addAdditionalSaveData writes. + #[test] + fn bastion_crossbow_piglin_finalizes_as_structure() { + let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES").map(PathBuf::from) else { + return; + }; + let file = root.join("worldgen/structure/minecraft/bastion/mobs/crossbow_piglin.nbt"); + let mut bytes = Vec::new(); + std::io::Read::read_to_end( + &mut flate2::read::GzDecoder::new(std::fs::File::open(file).unwrap()), + &mut bytes, + ) + .unwrap(); + let limits = horizon_world::nbt::Limits::templates(); + let template = horizon_world::nbt::read_named(&bytes, limits) + .unwrap() + .0 + .tag; + let Some(Tag::List(entities)) = template.get("entities") else { + panic!("no entities"); + }; + let Some(Tag::Compound(mut nbt)) = entities[0].get("nbt").cloned() else { + panic!("no nbt"); + }; + nbt.remove(&"UUID".into()); + let hook = StructureMobFinalizer::new(root, "minecraft:the_nether"); + let mut random = LegacyRandom::new(12345); + hook.finalize(&mut nbt, "minecraft:nether_wastes", &[], &mut random); + let keys: Vec = { + let mut k: Vec = nbt.keys().map(|k| k.to_string_lossy()).collect(); + k.sort(); + k + }; + assert_eq!( + keys, + [ + "AbsorptionAmount", + "Air", + "Brain", + "CanPickUpLoot", + "CannotHunt", + "DeathTime", + "FallFlying", + "Fire", + "Health", + "HurtTime", + "Inventory", + "Invulnerable", + "IsBaby", + "IsImmuneToZombification", + "LeftHanded", + "Motion", + "OnGround", + "PersistenceRequired", + "PortalCooldown", + "Pos", + "Rotation", + "TimeInOverworld", + "attributes", + "current_impulse_context_reset_grace_time", + "equipment", + "fall_distance", + "id", + ] + ); + let tag = Tag::Compound(nbt); + let held = tag.get("equipment").and_then(|e| e.get("mainhand")); + assert!( + matches!(held.and_then(|h| h.get("id")), Some(Tag::String(s)) if s.to_string_lossy() == "minecraft:crossbow") + ); + let hunted = tag + .get("Brain") + .and_then(|b| b.get("memories")) + .and_then(|m| m.get("minecraft:hunted_recently")); + assert!(matches!( + hunted.and_then(|h| h.get("ttl")), + Some(Tag::Long(600..=2400)) + )); + let Some(Tag::List(attributes)) = tag.get("attributes") else { + panic!("no attributes"); + }; + assert!(attributes.iter().any(|a| { + matches!(a.get("id"), Some(Tag::String(s)) if s.to_string_lossy() == "minecraft:follow_range") + && matches!(a.get("modifiers"), Some(Tag::List(m)) if m.len() == 1) + })); + } + + fn id(t: Option<&Tag>) -> String { + match t.and_then(|t| t.get("id")) { + Some(Tag::String(s)) => s.to_string_lossy().trim_start_matches("minecraft:").into(), + _ => "-".into(), + } + } + /// What a vanilla world saves of a structure mob that finalizeSpawn decides. + fn describe(mob: &Tag) -> String { + let eq = mob.get("equipment"); + let gear: Vec = ["mainhand", "head", "chest", "legs", "feet"] + .iter() + .map(|slot| id(eq.and_then(|e| e.get(slot)))) + .collect(); + let ttl = match mob + .get("Brain") + .and_then(|b| b.get("memories")) + .and_then(|m| m.get("minecraft:hunted_recently")) + .and_then(|h| h.get("ttl")) + { + Some(Tag::Long(t)) => t.to_string(), + _ => "-".into(), + }; + let bonus = crate::entity_nbt::spawn_bonus(mob).unwrap_or(f64::NAN); + let flag = |k: &str| matches!(mob.get(k), Some(Tag::Byte(1))); + let riders = match mob.get("Passengers") { + Some(Tag::List(p)) => format!( + " [{}]", + p.iter().map(describe).collect::>().join("; ") + ), + _ => String::new(), + }; + format!( + "{} {} ttl={ttl} bonus={bonus:.6} left={} baby={}{riders}", + id(Some(mob)), + gear.join(","), + flag("LeftHanded"), + flag("IsBaby") || matches!(mob.get("Age"), Some(Tag::Int(a)) if *a < 0), + ) + } + /// The described entities of chunk (x, z) after decorating the 3x3 around it. + fn chunk_mobs( + root: &std::path::Path, + seed: i64, + dimension: &str, + x: i32, + z: i32, + ) -> Vec { + use crate::streaming::{ChunkGenerator, Proto}; + let assets = crate::assets::Assets::load(root).unwrap(); + let biomes = crate::biome::Biomes::load(root).unwrap(); + let terrain = super::super::VanillaTerrain::for_dimension( + &root.join("worldgen"), + assets.registry, + &biomes, + seed, + dimension, + ) + .unwrap(); + let mut worker = terrain.worker(); + let mut region: [Proto; 9] = std::array::from_fn(|i| { + terrain.proto(&mut worker, x + i as i32 % 3 - 1, z + i as i32 / 3 - 1) + }); + terrain.decorate(&mut worker, &mut region); + let center = std::mem::replace(&mut region[4], Box::new(())); + let mut got: Vec = terrain + .finish(center) + .entities + .iter() + .map(describe) + .collect(); + got.sort(); + got + } + /// Seed 12345's bastion at chunk (-21, 8): the mobs of chunk (-23, 8) as two + /// vanilla 26.3 runs saved them (weapons and armour, hunting memory, follow + /// range bonus, handedness), from the region random of that chunk. The + /// memories are as placed: vanilla saved them 13 brain ticks later. + #[test] + fn bastion_chunk_mobs_match_vanilla() { + let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES").map(PathBuf::from) else { + return; + }; + let got = chunk_mobs(&root, 12345, "minecraft:the_nether", -23, 8); + let mut expected = [ + "piglin golden_sword,-,golden_chestplate,-,- ttl=1760 bonus=0.013784", + "piglin crossbow,-,-,-,- ttl=806 bonus=-0.011458", + "piglin golden_sword,-,-,-,- ttl=1315 bonus=-0.084585", + "piglin golden_sword,-,-,-,- ttl=1489 bonus=-0.038292", + "piglin_brute golden_axe,-,-,-,- ttl=- bonus=-0.020574", + "piglin crossbow,-,-,-,- ttl=1620 bonus=-0.079135", + "hoglin -,-,-,-,- ttl=- bonus=-0.012052", + "piglin golden_sword,-,-,-,- ttl=783 bonus=-0.077071", + "piglin crossbow,-,-,golden_leggings,- ttl=1431 bonus=0.007058", + ] + .map(|e| format!("{e} left=false baby=false")); + expected.sort(); + assert_eq!(got, expected); + } + + /// Seed 12345's ocean ruin at (53, 39, 424): Drowned.finalizeSpawn mounts the + /// trident drowned on a zombie nautilus, as vanilla saved chunk (3, 26). + #[test] + fn ocean_ruin_drowned_match_vanilla() { + let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES").map(PathBuf::from) else { + return; + }; + let got = chunk_mobs(&root, 12345, "minecraft:overworld", 3, 26); + let d = |gear: &str, bonus: &str| { + format!("drowned {gear},-,-,-,- ttl=- bonus={bonus} left=false baby=false") + }; + let mut expected = vec![ + d("-", "0.001996"), + format!( + "zombie_nautilus -,-,-,-,- ttl=- bonus=-0.044983 left=false baby=false [{}]", + d("trident", "-0.045604") + ), + d("fishing_rod", "-0.059079"), + d("-", "0.021658"), + ]; + expected.sort(); + assert_eq!(got, expected); + } +} diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index 34e8265a1..c4ed2884b 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -186,6 +186,7 @@ impl Server { attributes: Vec::new(), bed: None, living_flags: 0, + body: Default::default(), }; let mut ctx = TickCtx { world: &mut self.world, diff --git a/crates/horizon-command/Cargo.toml b/crates/horizon-command/Cargo.toml new file mode 100644 index 000000000..10191ed6f --- /dev/null +++ b/crates/horizon-command/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "horizon-command" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version = "1.90" +description = "Commands (Brigadier): the vanilla command tree, argument types, selectors, parsing, suggestions and the network form of the tree" + +[dependencies] +horizon-client-core = { path = "../horizon-client-core" } +horizon-protocol = { path = "../horizon-protocol" } +horizon-world = { path = "../horizon-world" } + +[lints] +workspace = true diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-command/src/args.rs similarity index 87% rename from crates/horizon-client/src/command/args.rs rename to crates/horizon-command/src/args.rs index ccced67a7..9d24d672f 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-command/src/args.rs @@ -1,192 +1,8 @@ //! Argument types (Brigadier's and Minecraft's `ArgumentType`s): parsing with //! the vanilla error messages and completion suggestions. use super::{CmdResult, CommandError, Context, Reader, SuggestionsBuilder}; -use std::collections::BTreeMap; -/// Registry contents and source state used to validate and complete arguments. -#[derive(Clone, Debug, Default)] -pub struct Registries { - /// Permission level of the command source. - pub permission: u8, - pub items: Vec, - pub item_tags: Vec, - /// Block id -> (property, allowed values). - pub blocks: BTreeMap)>>, - pub block_tags: Vec, - /// Entity types that `summon` can create. - pub summonable: Vec, - /// Every entity type (selector `type=`). - pub entity_types: Vec, - pub effects: Vec, - pub enchantments: Vec, - pub structures: Vec, - pub biomes: Vec, - pub dimensions: Vec, - pub clocks: Vec, - pub timelines: Vec, - pub time_markers: Vec, - pub advancements: Vec, - /// Game rule name -> integer-valued. - pub game_rules: Vec<(String, bool)>, - pub players: Vec, - /// Scoreboard objective names, team names and tracked score holders. - pub objectives: Vec, - pub teams: Vec, - pub tracked: Vec, - /// Loaded datapack functions (`ns:path`) and function tags (`ns:path`). - pub functions: Vec, - /// `/data ... storage` ids. - pub storages: Vec, - /// Boss bar ids and datapack predicate ids. - pub bossbars: Vec, - pub predicates: Vec, - pub item_modifiers: Vec, - pub schedules: Vec, - pub stopwatches: Vec, - pub recipes: Vec, - pub sounds: Vec, - pub damage_types: Vec, - pub attributes: Vec, - pub loot_tables: Vec, - pub templates: Vec, - pub random_sequences: Vec, - pub datapacks_enabled: Vec, - pub datapacks_disabled: Vec, - pub function_tags: Vec, - /// The block the source is looking at (relevant coordinates). - pub target_block: Option<[i32; 3]>, - /// Every registry's element and tag ids (`minecraft:item` -> ...), as - /// the server's registry access and reloadable registries hold them. - pub by_registry: BTreeMap, - /// Blocks whose default state has a block entity. - pub block_entities: std::collections::BTreeSet, - /// Block tag -> member blocks. - pub block_tag_members: BTreeMap>, - /// Data component types with a codec (not transient). - pub persistent_components: Vec, - /// Recipes `/recipe` can give (not special). - pub learnable_recipes: Vec, - /// Advancement id -> criterion names. - pub advancement_criteria: BTreeMap>, - /// World clock -> time markers shown in commands. - pub clock_time_markers: BTreeMap>, - /// Trigger objectives the source may use (`/trigger` suggestions). - pub trigger_objectives: Vec, - /// Objectives with the `trigger` criterion -> holder -> whether its score is locked. - pub trigger_scores: BTreeMap>, -} -/// The ids and tag ids of one registry. -#[derive(Clone, Debug, Default)] -pub struct RegistryIds { - pub ids: Vec, - pub tags: Vec, -} -const EMPTY: &[String] = &[]; -impl Registries { - /// Fill what the game did not build itself from vanilla's exported - /// registries (`command-registries.json`, written by - /// `VanillaCommandParseOracle registries`): built-in registries such as - /// mob effects, data component types and dialogs, block entities and tag - /// members. Registries that data packs reload stay with the game. - pub fn fill_from_export(&mut self, r: &serde_json::Value) { - fn strings(v: &serde_json::Value) -> Vec { - v.as_array() - .map(|a| { - a.iter() - .filter_map(|x| x.as_str().map(str::to_owned)) - .collect() - }) - .unwrap_or_default() - } - let fill = |field: &mut Vec, key: &str| { - if field.is_empty() { - *field = strings(&r[key]); - } - }; - fill(&mut self.effects, "effects"); - fill(&mut self.enchantments, "enchantments"); - fill(&mut self.attributes, "attributes"); - fill(&mut self.damage_types, "damage_types"); - fill(&mut self.templates, "templates"); - fill(&mut self.persistent_components, "persistent_components"); - fill(&mut self.learnable_recipes, "learnable_recipes"); - const RELOADED: [&str; 5] = [ - "minecraft:advancement", - "minecraft:recipe", - "minecraft:loot_table", - "minecraft:predicate", - "minecraft:item_modifier", - ]; - for (name, entry) in r["by_registry"].as_object().into_iter().flatten() { - if RELOADED.contains(&name.as_str()) || self.by_registry.contains_key(name) { - continue; - } - self.by_registry.insert( - name.clone(), - RegistryIds { - ids: strings(&entry["ids"]), - tags: strings(&entry["tags"]), - }, - ); - } - if self.block_entities.is_empty() { - self.block_entities = strings(&r["block_entities"]).into_iter().collect(); - } - if self.block_tag_members.is_empty() { - for (tag, members) in r["block_tag_members"].as_object().into_iter().flatten() { - self.block_tag_members.insert(tag.clone(), strings(members)); - } - } - if self.clock_time_markers.is_empty() { - for (clock, markers) in r["clock_time_markers"].as_object().into_iter().flatten() { - self.clock_time_markers - .insert(clock.clone(), strings(markers)); - } - } - if self.advancement_criteria.is_empty() { - for (id, criteria) in r["advancement_criteria"].as_object().into_iter().flatten() { - self.advancement_criteria - .insert(id.clone(), strings(criteria)); - } - } - } - /// The element ids of a registry (sorted). - pub fn ids(&self, registry: &str) -> &[String] { - if let Some(r) = self.by_registry.get(registry) { - return &r.ids; - } - match registry { - "minecraft:item" => &self.items, - "minecraft:entity_type" => &self.entity_types, - "minecraft:mob_effect" => &self.effects, - "minecraft:enchantment" => &self.enchantments, - "minecraft:worldgen/structure" => &self.structures, - "minecraft:worldgen/biome" => &self.biomes, - "minecraft:world_clock" => &self.clocks, - "minecraft:timeline" => &self.timelines, - "minecraft:attribute" => &self.attributes, - "minecraft:damage_type" => &self.damage_types, - "minecraft:sound_event" => &self.sounds, - "minecraft:predicate" => &self.predicates, - "minecraft:item_modifier" => &self.item_modifiers, - "minecraft:loot_table" => &self.loot_tables, - "minecraft:recipe" => &self.recipes, - "minecraft:advancement" => &self.advancements, - _ => EMPTY, - } - } - /// The tag ids of a registry (sorted). - pub fn tags(&self, registry: &str) -> &[String] { - if let Some(r) = self.by_registry.get(registry) { - return &r.tags; - } - match registry { - "minecraft:item" => &self.item_tags, - "minecraft:block" => &self.block_tags, - _ => EMPTY, - } - } -} +pub use horizon_client_core::registries::{Registries, RegistryIds}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Resource { @@ -637,22 +453,7 @@ pub fn read_identifier(reader: &mut Reader) -> CmdResult { } } } -/// Identifier.parse: `ns:path` or `path`, validated. -pub fn parse_identifier(raw: &str) -> Option { - let (ns, path) = match raw.split_once(':') { - Some(("", path)) => ("minecraft", path), - Some((ns, path)) => (ns, path), - None => ("minecraft", raw), - }; - let ns_ok = ns != ".." - && ns - .chars() - .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-')); - let path_ok = path.chars().all(|c| { - c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/') - }); - (ns_ok && path_ok).then(|| format!("{ns}:{path}")) -} +pub use horizon_client_core::identifier::parse_identifier; pub fn normalize(id: &str) -> String { match id.split_once(':') { Some(("", path)) => format!("minecraft:{path}"), @@ -1220,7 +1021,10 @@ impl ArgType { reader.cursor = start; return Err(CommandError::tr_at( "argument.float.low", - &[&crate::snbt::java_float(*min), &crate::snbt::java_float(v)], + &[ + &horizon_client_core::snbt::java_float(*min), + &horizon_client_core::snbt::java_float(v), + ], reader, )); } @@ -1228,7 +1032,10 @@ impl ArgType { reader.cursor = start; return Err(CommandError::tr_at( "argument.float.big", - &[&crate::snbt::java_float(*max), &crate::snbt::java_float(v)], + &[ + &horizon_client_core::snbt::java_float(*max), + &horizon_client_core::snbt::java_float(v), + ], reader, )); } @@ -1241,8 +1048,8 @@ impl ArgType { return Err(CommandError::tr_at( "argument.double.low", &[ - &crate::snbt::java_double(*min), - &crate::snbt::java_double(v), + &horizon_client_core::snbt::java_double(*min), + &horizon_client_core::snbt::java_double(v), ], reader, )); @@ -1252,8 +1059,8 @@ impl ArgType { return Err(CommandError::tr_at( "argument.double.big", &[ - &crate::snbt::java_double(*max), - &crate::snbt::java_double(v), + &horizon_client_core::snbt::java_double(*max), + &horizon_client_core::snbt::java_double(v), ], reader, )); @@ -1597,7 +1404,7 @@ impl ArgType { return Err(CommandError::tr_at(key, &[&m], reader)); } let text = &reader.string[start..reader.cursor]; - match crate::component::parse_snbt(text) { + match horizon_client_core::component::parse_snbt(text) { Ok((v, _)) => Arg::Str(v.to_string()), Err(_) => Arg::Str(text.to_owned()), } @@ -1645,7 +1452,7 @@ impl ArgType { } let id = &reader.string[start..reader.cursor]; // ObjectiveCriteria.byName: statistics resolve to their canonical name. - match crate::scoreboard::criteria_by_name(id, reg) { + match horizon_client_core::scoreboard::criteria_by_name(id, reg) { Ok(Some(canonical)) => Arg::Str(canonical), Ok(None) => { reader.cursor = start; @@ -1667,7 +1474,7 @@ impl ArgType { } ArgType::ScoreboardSlot => { let name = reader.read_unquoted_string(); - if !crate::scoreboard::display_slot_valid(name) { + if !horizon_client_core::scoreboard::display_slot_valid(name) { return Err(CommandError::tr_at( "argument.scoreboardDisplaySlot.invalid", &[&name], @@ -1695,7 +1502,7 @@ impl ArgType { } ArgType::TeamColor => { let name = reader.read_unquoted_string(); - if crate::scoreboard::team_color_rgb(name).is_none() { + if horizon_client_core::scoreboard::team_color_rgb(name).is_none() { return Err(CommandError::tr_at( "argument.color.invalid", &[&name], @@ -1743,7 +1550,7 @@ impl ArgType { let id = read_identifier(reader)?; let known = reg.ids("minecraft:particle_type"); let exists = if known.is_empty() { - crate::particles::ParticleType::from_name(&id).is_some() + horizon_client_core::particle_type::ParticleType::from_name(&id).is_some() } else { known.contains(&id) }; @@ -1931,15 +1738,16 @@ impl ArgType { } ArgType::Team => builder.suggest_matching(reg.teams.iter().map(String::as_str)), ArgType::Criteria => { - let mut ids: Vec = crate::scoreboard::CUSTOM_CRITERIA + let mut ids: Vec = horizon_client_core::scoreboard::CUSTOM_CRITERIA .iter() .map(|s| (*s).to_owned()) .collect(); - for c in crate::scoreboard::team_colors() { + for c in horizon_client_core::scoreboard::team_colors() { ids.push(format!("teamkill.{c}")); ids.push(format!("killedByTeam.{c}")); } - let stat = |ty: &str, key: &str| crate::scoreboard::stat_criteria(ty, key); + let stat = + |ty: &str, key: &str| horizon_client_core::scoreboard::stat_criteria(ty, key); ids.extend(reg.blocks.keys().map(|b| stat("mined", b))); for ty in ["crafted", "used", "broken", "picked_up", "dropped"] { ids.extend(reg.items.iter().map(|i| stat(ty, i))); @@ -1948,14 +1756,14 @@ impl ArgType { ids.extend(reg.entity_types.iter().map(|e| stat(ty, e))); } ids.extend( - crate::scoreboard::CUSTOM_STATS + horizon_client_core::scoreboard::CUSTOM_STATS .iter() .map(|c| stat("custom", &format!("minecraft:{c}"))), ); builder.suggest_matching(ids.iter().map(String::as_str)); } ArgType::ScoreboardSlot => { - let slots = crate::scoreboard::display_slots(); + let slots = horizon_client_core::scoreboard::display_slots(); builder.suggest_matching(slots.iter().map(String::as_str)); } ArgType::Operation => builder.suggest_matching(OPERATIONS), @@ -1963,7 +1771,7 @@ impl ArgType { ArgType::Particle => { let known = reg.ids("minecraft:particle_type"); if known.is_empty() { - let names: Vec = crate::particles::ParticleType::ALL + let names: Vec = horizon_client_core::particle_type::ParticleType::ALL .iter() .map(|t| format!("minecraft:{}", t.name())) .collect(); @@ -1999,7 +1807,9 @@ impl ArgType { suggest_resources(builder, reg.ids("minecraft:slot_source"), ""); } ArgType::ResourceOrId(registry) => suggest_resources(builder, reg.ids(registry), ""), - ArgType::TeamColor => builder.suggest_matching(crate::scoreboard::team_colors()), + ArgType::TeamColor => { + builder.suggest_matching(horizon_client_core::scoreboard::team_colors()) + } ArgType::Anchor => builder.suggest_matching(["eyes", "feet"]), ArgType::Component | ArgType::Style | ArgType::NbtTag => super::snbt::suggest(builder), ArgType::Swizzle | ArgType::Message | ArgType::Nbt => {} diff --git a/crates/horizon-client/src/command/block.rs b/crates/horizon-command/src/block.rs similarity index 100% rename from crates/horizon-client/src/command/block.rs rename to crates/horizon-command/src/block.rs diff --git a/crates/horizon-client/src/command/codec.rs b/crates/horizon-command/src/codec.rs similarity index 99% rename from crates/horizon-client/src/command/codec.rs rename to crates/horizon-command/src/codec.rs index 7c4d26682..40f5c1ce0 100644 --- a/crates/horizon-client/src/command/codec.rs +++ b/crates/horizon-command/src/codec.rs @@ -6,7 +6,7 @@ use super::{CmdResult, CommandError, Reader}; use horizon_world::nbt::{Compound, JavaString, Tag}; pub fn snbt(t: &Tag) -> String { - crate::snbt::to_snbt(t) + horizon_client_core::snbt::to_snbt(t) } pub fn not_map(t: &Tag) -> String { format!("Not a map: {}", snbt(t)) diff --git a/crates/horizon-client/src/command/component.rs b/crates/horizon-command/src/component.rs similarity index 98% rename from crates/horizon-client/src/command/component.rs rename to crates/horizon-command/src/component.rs index 15a8fa6a0..2933afeca 100644 --- a/crates/horizon-client/src/command/component.rs +++ b/crates/horizon-command/src/component.rs @@ -164,7 +164,7 @@ fn color(t: &Tag) -> R { _ => partial(format!("Invalid color value: {s}")), }; } - if crate::text::named_color(&s).is_some() { + if horizon_client_core::text::named_color(&s).is_some() { Ok(()) } else { partial(format!("Invalid color name: {s}")) @@ -278,7 +278,7 @@ fn content(kind: &str, map: &Compound) -> bool { "nbt" => { let path_ok = get(map, "nbt") .and_then(string_of) - .is_some_and(|p| crate::nbt_path::NbtPath::parse(&p).is_ok()); + .is_some_and(|p| horizon_client_core::nbt_path::NbtPath::parse(&p).is_ok()); let source = if let Some(e) = get(map, "entity") { selector_string(e) } else if let Some(b) = get(map, "block") { diff --git a/crates/horizon-client/src/command/item.rs b/crates/horizon-command/src/item.rs similarity index 99% rename from crates/horizon-client/src/command/item.rs rename to crates/horizon-command/src/item.rs index f2abc91ef..da9c4b8b0 100644 --- a/crates/horizon-client/src/command/item.rs +++ b/crates/horizon-command/src/item.rs @@ -72,9 +72,9 @@ pub fn decode_component(id: &str, t: &Tag) -> Result<(), String> { } else { format!("minecraft:{id}") }; - let known = crate::block_entity_nbt::TYPES + let known = horizon_client_core::block_entity_nbt::TYPES .iter() - .chain(&crate::block_entity_nbt::NEWEST) + .chain(&horizon_client_core::block_entity_nbt::NEWEST) .any(|k| *k == id); if known { Ok(()) diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-command/src/lib.rs similarity index 99% rename from crates/horizon-client/src/command/mod.rs rename to crates/horizon-command/src/lib.rs index a61c8c08d..838c8de87 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-command/src/lib.rs @@ -3,6 +3,7 @@ //! relevant child and keeps the best result, completion suggestions, smart //! usage text and the vanilla error messages. Argument types live in //! [`args`]; the vanilla command tree in [`vanilla`]. +#![forbid(unsafe_code)] pub mod args; pub mod block; pub mod codec; @@ -21,8 +22,8 @@ pub mod tree_world; pub mod vanilla; mod vanilla_order; -use crate::text::Text; pub use args::{Arg, ArgType, Registries}; +use horizon_client_core::text::Text; /// The command id of a mod's command (`Dispatcher::with_mod_commands`). pub const MOD_COMMAND: &str = "mod"; @@ -623,8 +624,10 @@ impl Suggests { for id in ®.summonable { if args::resource_matches(&contents, id) { let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id)); - let name = - crate::lang::get(&format!("entity.{ns}.{}", path.replace('/', "."))); + let name = horizon_client_core::lang::get(&format!( + "entity.{ns}.{}", + path.replace('/', ".") + )); builder.suggest_tooltip(id.clone(), name); } } diff --git a/crates/horizon-client/src/command/network.rs b/crates/horizon-command/src/network.rs similarity index 100% rename from crates/horizon-client/src/command/network.rs rename to crates/horizon-command/src/network.rs diff --git a/crates/horizon-client/src/command/packrat.rs b/crates/horizon-command/src/packrat.rs similarity index 99% rename from crates/horizon-client/src/command/packrat.rs rename to crates/horizon-command/src/packrat.rs index 42f42d9f4..ebe9df09d 100644 --- a/crates/horizon-client/src/command/packrat.rs +++ b/crates/horizon-command/src/packrat.rs @@ -402,7 +402,7 @@ impl<'g, V: Value> State<'g, V> { Reason::Error(e) => e.clone(), }; } - CommandError::new(crate::text::Text::literal("Failed to parse")) + CommandError::new(horizon_client_core::text::Text::literal("Failed to parse")) } /// CachedParseState.parse: a named rule, memoised per position. pub fn parse(&mut self, rule: RuleId) -> Option { diff --git a/crates/horizon-client/src/command/selector.rs b/crates/horizon-command/src/selector.rs similarity index 99% rename from crates/horizon-client/src/command/selector.rs rename to crates/horizon-command/src/selector.rs index eb4e637a4..777124f60 100644 --- a/crates/horizon-client/src/command/selector.rs +++ b/crates/horizon-command/src/selector.rs @@ -687,7 +687,7 @@ impl<'r, 'a> SelectorParser<'r, 'a> { fn fill_selectors(builder: &mut SuggestionsBuilder) { for (s, tip) in SELECTOR_KINDS { - builder.suggest_tooltip(s, crate::lang::get(tip)); + builder.suggest_tooltip(s, horizon_client_core::lang::get(tip)); } } @@ -785,7 +785,9 @@ impl<'r, 'a> SelectorParser<'r, 'a> { if self.can_use(o) && o.starts_with(&lower) { b.suggest_tooltip( format!("{o}="), - crate::lang::get(&format!("argument.entity.options.{o}.description")), + horizon_client_core::lang::get(&format!( + "argument.entity.options.{o}.description" + )), ); } } diff --git a/crates/horizon-client/src/command/snbt.rs b/crates/horizon-command/src/snbt.rs similarity index 100% rename from crates/horizon-client/src/command/snbt.rs rename to crates/horizon-command/src/snbt.rs diff --git a/crates/horizon-client/src/command/tests.rs b/crates/horizon-command/src/tests.rs similarity index 100% rename from crates/horizon-client/src/command/tests.rs rename to crates/horizon-command/src/tests.rs diff --git a/crates/horizon-client/src/command/tree_data.rs b/crates/horizon-command/src/tree_data.rs similarity index 100% rename from crates/horizon-client/src/command/tree_data.rs rename to crates/horizon-command/src/tree_data.rs diff --git a/crates/horizon-client/src/command/tree_execute.rs b/crates/horizon-command/src/tree_execute.rs similarity index 100% rename from crates/horizon-client/src/command/tree_execute.rs rename to crates/horizon-command/src/tree_execute.rs diff --git a/crates/horizon-client/src/command/tree_extra.rs b/crates/horizon-command/src/tree_extra.rs similarity index 100% rename from crates/horizon-client/src/command/tree_extra.rs rename to crates/horizon-command/src/tree_extra.rs diff --git a/crates/horizon-client/src/command/tree_misc.rs b/crates/horizon-command/src/tree_misc.rs similarity index 99% rename from crates/horizon-client/src/command/tree_misc.rs rename to crates/horizon-command/src/tree_misc.rs index a66fd5f37..1bcd880bb 100644 --- a/crates/horizon-client/src/command/tree_misc.rs +++ b/crates/horizon-command/src/tree_misc.rs @@ -230,12 +230,12 @@ fn bossbar(d: &mut Dispatcher, root: usize) { let name = d.argument(name_l, "name", ArgType::Component); d.executes(name, "bossbar.set.name"); let color = d.literal(id, "color"); - for c in crate::bossbar::COLORS { + for c in horizon_client_core::bossbar::COLORS { let l = d.literal(color, c); d.executes(l, "bossbar.set.color"); } let style = d.literal(id, "style"); - for s in crate::bossbar::STYLES { + for s in horizon_client_core::bossbar::STYLES { let l = d.literal(style, s); d.executes(l, "bossbar.set.style"); } diff --git a/crates/horizon-client/src/command/tree_scoreboard.rs b/crates/horizon-command/src/tree_scoreboard.rs similarity index 100% rename from crates/horizon-client/src/command/tree_scoreboard.rs rename to crates/horizon-command/src/tree_scoreboard.rs diff --git a/crates/horizon-client/src/command/tree_world.rs b/crates/horizon-command/src/tree_world.rs similarity index 99% rename from crates/horizon-client/src/command/tree_world.rs rename to crates/horizon-command/src/tree_world.rs index 0bd2edd3b..86ebba0ca 100644 --- a/crates/horizon-client/src/command/tree_world.rs +++ b/crates/horizon-command/src/tree_world.rs @@ -7,7 +7,7 @@ use super::{ args::{ArgType, integer}, vanilla::{ENTITIES, ENTITY, GAMEMASTERS, PLAYERS}, }; -use crate::settings::SOUND_SOURCES; +use horizon_client_core::sound_source::SOUND_SOURCES; fn float(min: f32) -> ArgType { ArgType::Float { min, max: f32::MAX } diff --git a/crates/horizon-client/src/command/vanilla.rs b/crates/horizon-command/src/vanilla.rs similarity index 99% rename from crates/horizon-client/src/command/vanilla.rs rename to crates/horizon-command/src/vanilla.rs index 2ce892077..37ec1c3de 100644 --- a/crates/horizon-client/src/command/vanilla.rs +++ b/crates/horizon-command/src/vanilla.rs @@ -5,7 +5,7 @@ use super::{ Dispatcher, args::{ArgType, Resource, integer}, }; -use crate::gamerules::{RULES, Value}; +use horizon_client_core::gamerules::{RULES, Value}; /// Permission levels (Commands.LEVEL_*). pub const ALL: u8 = 0; diff --git a/crates/horizon-client/src/command/vanilla_order.rs b/crates/horizon-command/src/vanilla_order.rs similarity index 100% rename from crates/horizon-client/src/command/vanilla_order.rs rename to crates/horizon-command/src/vanilla_order.rs diff --git a/crates/horizon-mod-sdk/examples/beacons/horizon-mod.toml b/crates/horizon-mod-sdk/examples/beacons/horizon-mod.toml index 0c2004b5f..5b58273c6 100644 --- a/crates/horizon-mod-sdk/examples/beacons/horizon-mod.toml +++ b/crates/horizon-mod-sdk/examples/beacons/horizon-mod.toml @@ -1,7 +1,7 @@ id = "beacons" name = "Beacons" version = "0.1.0" -description = "/beacon lights a pillar of glowstone beside you; /ground says what you are standing on, and in which biome." +description = "/beacon [height] lights a pillar of glowstone beside you; /ground [pos] says what you are standing on (or what is at pos), and in which biome." authors = ["Horizon"] api = "0.3" side = "server" diff --git a/crates/horizon-mod-sdk/examples/beacons/src/lib.rs b/crates/horizon-mod-sdk/examples/beacons/src/lib.rs index 509431775..4a4de5cc1 100644 --- a/crates/horizon-mod-sdk/examples/beacons/src/lib.rs +++ b/crates/horizon-mod-sdk/examples/beacons/src/lib.rs @@ -1,9 +1,12 @@ //! Example Horizon server mod (`docs/mods.md`, "Server mods") with -//! capability `world`: `/beacon` lights a pillar of glowstone two blocks east -//! of the player, `/ground` reads the block under their feet and the biome. -use horizon_mod_sdk::server::{BlockChange, Player, Registration, ServerMod, players, world}; +//! capability `world` and typed commands: `/beacon [height]` lights a +//! pillar of glowstone two blocks east of the player, `/ground [pos]` reads +//! the block under their feet (or at `pos`) and its biome. +use horizon_mod_sdk::server::{ + Args, Argument, BlockChange, Player, Registration, ServerMod, players, world, +}; -/// How tall `/beacon` builds. +/// How tall `/beacon` builds when no height is given. const HEIGHT: i32 = 4; struct Beacons; @@ -17,10 +20,10 @@ fn feet(player: &Player) -> (i32, i32, i32) { ) } -/// The pillar beside `player`: `HEIGHT` blocks of glowstone, from their feet up. -fn pillar(player: &Player) -> Vec { +/// The pillar beside `player`: `height` blocks of glowstone, from their feet up. +fn pillar(player: &Player, height: i32) -> Vec { let (x, y, z) = feet(player); - (0..HEIGHT) + (0..height) .map(|dy| BlockChange { x: x + 2, y: y + dy, @@ -34,7 +37,12 @@ impl ServerMod for Beacons { fn init() -> Result<(Self, Registration), String> { Ok(( Beacons, - Registration::new().command("beacon").command("ground"), + Registration::new() + .command_with( + "beacon", + [Argument::integer("height", Some(1), Some(64)).optional()], + ) + .command_with("ground", [Argument::block_pos("pos").optional()]), )) } @@ -42,11 +50,12 @@ impl ServerMod for Beacons { &mut self, player: &Player, name: &str, - _args: &str, + args: &Args, ) -> Result, String> { let (x, y, z) = feet(player); if name == "beacon" { - world::set_blocks(&player.dimension, &pillar(player))?; + let height = args.integer("height").unwrap_or(HEIGHT); + world::set_blocks(&player.dimension, &pillar(player, height))?; players::broadcast(&format!( "{} lit a beacon at {} {y} {z}", player.name, @@ -54,10 +63,17 @@ impl ServerMod for Beacons { )); return Ok(None); } - let below = world::get_block(&player.dimension, x, y - 1, z) - .ok_or("The ground under you isn't loaded")?; - let biome = world::get_biome(&player.dimension, x, y, z).unwrap_or_default(); - Ok(Some(format!("You are standing on {below} in {biome}"))) + let (bx, by, bz) = match args.block_pos("pos") { + Some(p) => (p.x, p.y, p.z), + None => (x, y - 1, z), + }; + let block = + world::get_block(&player.dimension, bx, by, bz).ok_or("That block isn't loaded")?; + let biome = world::get_biome(&player.dimension, bx, by, bz).unwrap_or_default(); + if args.block_pos("pos").is_some() { + return Ok(Some(format!("{bx} {by} {bz} is {block} in {biome}"))); + } + Ok(Some(format!("You are standing on {block} in {biome}"))) } } @@ -79,7 +95,7 @@ mod tests { game_mode: horizon_mod_sdk::server::GameMode::Survival, health: 20.0, }; - let blocks = pillar(&p); + let blocks = pillar(&p, HEIGHT); assert_eq!(blocks.len(), HEIGHT as usize); assert_eq!((blocks[0].x, blocks[0].y, blocks[0].z), (1, 64, 3)); assert_eq!(blocks[3].y, 67); diff --git a/crates/horizon-mod-sdk/examples/beacons/tests/beacons.toml b/crates/horizon-mod-sdk/examples/beacons/tests/beacons.toml index e75caeb75..bab4839f3 100644 --- a/crates/horizon-mod-sdk/examples/beacons/tests/beacons.toml +++ b/crates/horizon-mod-sdk/examples/beacons/tests/beacons.toml @@ -1,4 +1,4 @@ -# /ground reads the block under the player and the biome; /beacon sets four blocks of glowstone two to the east. +# /ground [pos] reads the block under the player (or at pos) and the biome; /beacon [height] sets glowstone two to the east. [[step]] join = "Alex" @@ -20,3 +20,20 @@ expect.blocks = [ player = { x = 10.5, z = 10.5 } command = "ground" expect.feedback = "You are standing on minecraft:air in minecraft:plains" + +# Typed arguments: a height, a position relative to the player. +[[step]] +player = { x = 5.5, y = 64.0, z = 5.5 } +command = "beacon 2" +expect.blocks = [ + { x = 7, y = 65, z = 5, state = "minecraft:glowstone" }, + { x = 7, y = 66, z = 5, state = "minecraft:air" }, +] + +[[step]] +command = "beacon 65" +expect.error = "Integer must not be more than 64, found 65" + +[[step]] +command = "ground ~2 ~1 ~" +expect.feedback = "7 65 5 is minecraft:glowstone in minecraft:plains" diff --git a/crates/horizon-mod-sdk/examples/welcome/src/lib.rs b/crates/horizon-mod-sdk/examples/welcome/src/lib.rs index c45712c88..e5a5ef13e 100644 --- a/crates/horizon-mod-sdk/examples/welcome/src/lib.rs +++ b/crates/horizon-mod-sdk/examples/welcome/src/lib.rs @@ -1,9 +1,10 @@ //! Example Horizon server mod (`docs/mods.md`, "Server mods"): greets each //! player who joins, announces a newcomer to everyone (the players it has //! seen are kept in `storage`), `/online` lists who is on and where, and -//! `/mined` counts the blocks the player broke since the server started. +//! `/mined [player]` counts the blocks a player broke since the server +//! started (typed arguments: the chat box completes the player's name). use horizon_mod_sdk::{ - server::{BlockPos, Player, Registration, ServerMod, players}, + server::{Args, Argument, BlockPos, Player, Registration, ServerMod, players}, storage, }; use std::collections::HashMap; @@ -25,8 +26,8 @@ impl ServerMod for Welcome { }) .unwrap_or_default(); let hooks = Registration::new() - .command("online") - .command("mined") + .command_with("online", []) + .command_with("mined", [Argument::player("player").optional()]) .on_joins() .on_blocks(); Ok(( @@ -55,7 +56,7 @@ impl ServerMod for Welcome { &mut self, player: &Player, name: &str, - _args: &str, + args: &Args, ) -> Result, String> { Ok(Some(match name { "online" => players::online() @@ -69,10 +70,16 @@ impl ServerMod for Welcome { }) .collect::>() .join(", "), - _ => { - let n = self.mined.get(&player.id).copied().unwrap_or(0); - format!("You broke {n} block(s)") - } + _ => match args.player("player") { + Some(other) if other.id != player.id => { + let n = self.mined.get(&other.id).copied().unwrap_or(0); + format!("{} broke {n} block(s)", other.name) + } + _ => { + let n = self.mined.get(&player.id).copied().unwrap_or(0); + format!("You broke {n} block(s)") + } + }, })) } diff --git a/crates/horizon-mod-sdk/examples/welcome/tests/commands.toml b/crates/horizon-mod-sdk/examples/welcome/tests/commands.toml index 5f0018346..a55bd421d 100644 --- a/crates/horizon-mod-sdk/examples/welcome/tests/commands.toml +++ b/crates/horizon-mod-sdk/examples/welcome/tests/commands.toml @@ -1,4 +1,4 @@ -# /online lists the players and their dimension; /mined counts the acting player's blocks. +# /online lists the players and their dimension; /mined [player] counts a player's blocks. [[step]] join = "Alex" @@ -29,3 +29,18 @@ expect.feedback = "You broke 2 block(s)" as = "Steve" command = "mined" expect.feedback = "You broke 0 block(s)" + +[[step]] +as = "Steve" +command = "mined alex" +expect.feedback = "Alex broke 2 block(s)" + +# The server parses the arguments before the mod: vanilla's errors. +[[step]] +as = "Steve" +command = "mined Herobrine" +expect.error = "No player was found" + +[[step]] +command = "online now" +expect.error = "Incorrect argument for command" diff --git a/crates/horizon-mod-sdk/src/lib.rs b/crates/horizon-mod-sdk/src/lib.rs index e15b96e72..1e7120091 100644 --- a/crates/horizon-mod-sdk/src/lib.rs +++ b/crates/horizon-mod-sdk/src/lib.rs @@ -194,7 +194,10 @@ pub mod server { }, }); - pub use exports::horizon::mods::server_events::{BlockPos, Guest as __Guest, Registration}; + pub use exports::horizon::mods::server_events::{ + Argument, ArgumentKind, ArgumentValue, BlockPos, Guest as __Guest, Registration, + ServerCommand, + }; pub use horizon::mods::players::{self, GameMode, Player}; pub use horizon::mods::world::{self, BlockChange}; @@ -211,13 +214,14 @@ pub mod server { fn player_left(&mut self, _player: &Player) {} /// A chat message a player sent, when [`Registration::chat`] is set. fn chat(&mut self, _player: &Player, _text: &str) {} - /// `/name args` typed by `player`. `Ok(Some(text))` is their - /// feedback, `Err(text)` their error in red. + /// `/name args` typed by `player`, parsed as the command's + /// arguments say ([`Registration::command_with`]). `Ok(Some(text))` + /// is their feedback, `Err(text)` their error in red. fn command( &mut self, _player: &Player, _name: &str, - _args: &str, + _args: &Args, ) -> Result, String> { Err("This command does nothing".into()) } @@ -237,9 +241,23 @@ pub mod server { blocks: false, } } - /// Adds `/name`. - pub fn command(mut self, name: &str) -> Self { - self.commands.push(name.into()); + /// Adds `/name`, taking free text ([`Args::text`]): one optional + /// `text` argument named `args`. + pub fn command(self, name: &str) -> Self { + self.command_with(name, [Argument::text("args").optional()]) + } + /// Adds `/name` with typed arguments (none: nothing after the name): + /// players' chat boxes complete and check them, and the server + /// parses them into [`Args`]. + pub fn command_with( + mut self, + name: &str, + arguments: impl IntoIterator, + ) -> Self { + self.commands.push(ServerCommand { + name: name.into(), + arguments: arguments.into_iter().collect(), + }); self } pub fn on_tick(mut self) -> Self { @@ -264,6 +282,105 @@ pub mod server { Self::new() } } + + impl Argument { + fn of(name: &str, kind: ArgumentKind) -> Self { + Self { + name: name.into(), + kind, + optional: false, + } + } + /// One word: letters, digits and `_ - . +`. + pub fn word(name: &str) -> Self { + Self::of(name, ArgumentKind::Word) + } + /// The rest of the line: only last. + pub fn text(name: &str) -> Self { + Self::of(name, ArgumentKind::Text) + } + /// A whole number, at least `min` and at most `max` when given. + pub fn integer(name: &str, min: Option, max: Option) -> Self { + Self::of(name, ArgumentKind::Integer((min, max))) + } + pub fn number(name: &str) -> Self { + Self::of(name, ArgumentKind::Number) + } + pub fn boolean(name: &str) -> Self { + Self::of(name, ArgumentKind::Boolean) + } + /// One online player: a name, `@s` or `@p`. + pub fn player(name: &str) -> Self { + Self::of(name, ArgumentKind::Player) + } + /// `x y z`, each one also `~` or `~n`. + pub fn block_pos(name: &str) -> Self { + Self::of(name, ArgumentKind::BlockPos) + } + /// May be left out; optional arguments come after the required ones. + pub fn optional(mut self) -> Self { + self.optional = true; + self + } + } + + /// A command's arguments: the line as typed, and the values the server + /// parsed from it, by argument name. + #[derive(Clone, Debug, Default)] + pub struct Args { + text: String, + values: Vec<(String, ArgumentValue)>, + } + impl Args { + pub fn new(text: String, values: Vec<(String, ArgumentValue)>) -> Self { + Self { text, values } + } + /// The line after the command's name, as typed. + pub fn text(&self) -> &str { + &self.text + } + /// The value of argument `name`; `None` when it was left out. + pub fn get(&self, name: &str) -> Option<&ArgumentValue> { + self.values.iter().find(|(n, _)| n == name).map(|(_, v)| v) + } + pub fn integer(&self, name: &str) -> Option { + match self.get(name)? { + ArgumentValue::Integer(n) => Some(*n), + _ => None, + } + } + pub fn number(&self, name: &str) -> Option { + match self.get(name)? { + ArgumentValue::Number(n) => Some(*n), + _ => None, + } + } + /// A `word` or `text` argument. + pub fn string(&self, name: &str) -> Option<&str> { + match self.get(name)? { + ArgumentValue::Word(s) | ArgumentValue::Text(s) => Some(s), + _ => None, + } + } + pub fn boolean(&self, name: &str) -> Option { + match self.get(name)? { + ArgumentValue::Boolean(b) => Some(*b), + _ => None, + } + } + pub fn player(&self, name: &str) -> Option<&Player> { + match self.get(name)? { + ArgumentValue::Player(p) => Some(p), + _ => None, + } + } + pub fn block_pos(&self, name: &str) -> Option { + match self.get(name)? { + ArgumentValue::BlockPos(p) => Some(*p), + _ => None, + } + } + } } /// Exports a [`ServerMod`](server::ServerMod) as the component's @@ -273,7 +390,7 @@ macro_rules! export_server_mod { ($t:ty) => { const _: () = { use ::std::cell::RefCell; - use $crate::server::{BlockPos, Player, Registration, ServerMod}; + use $crate::server::{Args, ArgumentValue, BlockPos, Player, Registration, ServerMod}; ::std::thread_local! { static STATE: RefCell> = const { RefCell::new(None) }; } @@ -307,8 +424,10 @@ macro_rules! export_server_mod { player: Player, name: String, args: String, + values: Vec<(String, ArgumentValue)>, ) -> Result, String> { let mut out = Err("The mod is not running".to_string()); + let args = Args::new(args, values); with(|m| out = m.command(&player, &name, &args)); out } diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index 274444a69..e75bb3cac 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -680,10 +680,61 @@ interface %world { interface server-events { use players.{player}; + record block-pos { + x: s32, + y: s32, + z: s32, + } + /// What an argument of a command takes. The server sends each command + /// and its arguments to players' games, whose chat box completes and + /// colours them as vanilla's; the server parses them before the mod's + /// `command` hook gets their values. + variant argument-kind { + /// One word: letters, digits and `_ - . +`. + word, + /// The rest of the line, spaces included: only last. + text, + /// A whole number, within the bounds given. + integer(tuple, option>), + /// A number with or without decimals. + number, + /// `true` or `false`. + boolean, + /// One online player: a name, or `@s` or `@p` (whoever typed it, + /// as vanilla picks for a player). + player, + /// A block position: three whole numbers, each one also `~` or + /// `~n`, relative to whoever typed it. + block-pos, + } + record argument { + /// Shown in the chat box's hint (``) and the key of its value. + name: string, + kind: argument-kind, + /// Optional arguments come after every required one. + optional: bool, + } + record server-command { + /// Without the slash. A name vanilla already uses is refused + /// (vanilla's command runs). + name: string, + /// In order; none: the command takes nothing after its name. Free + /// text is one optional `text` argument. + arguments: list, + } + /// An argument's value, parsed as its kind says. + variant argument-value { + word(string), + text(string), + integer(s32), + number(f64), + boolean(bool), + player(player), + block-pos(block-pos), + } record registration { - /// Commands players may type, without the slash. A name vanilla - /// already uses is refused (vanilla's command runs). - commands: list, + /// Commands players may type. + commands: list, /// Call `tick` every server tick (20 per second). tick: bool, /// Call `player-joined` and `player-left`. @@ -693,11 +744,6 @@ interface server-events { /// Call `block-broken` and `block-placed`. blocks: bool, } - record block-pos { - x: s32, - y: s32, - z: s32, - } /// Once, after loading. An error keeps the mod off and is logged. init: func() -> result; /// Each server tick, with the server's tick counter. @@ -709,8 +755,10 @@ interface server-events { /// A chat message a player sent, as plain text. chat: func(player: player, text: string); /// `/name args` typed by `player`: ok(some(text)) is their feedback, - /// err(text) their error in red. - command: func(player: player, name: string, args: string) -> result, string>; + /// err(text) their error in red. `values` holds each argument given, by + /// name, in order (an optional one left out isn't there); a line that + /// doesn't parse never reaches the mod: the player gets vanilla's error. + command: func(player: player, name: string, args: string, values: list>) -> result, string>; /// A player broke the block at `pos` in their dimension: `state` is what /// was there, as `minecraft:oak_log[axis=y]`. block-broken: func(player: player, pos: block-pos, state: string); diff --git a/crates/horizon-mods/src/commands.rs b/crates/horizon-mods/src/commands.rs new file mode 100644 index 000000000..4421b47ba --- /dev/null +++ b/crates/horizon-mods/src/commands.rs @@ -0,0 +1,301 @@ +//! Server mods' typed commands: an argument line parsed as the command's +//! arguments say, the way vanilla's Brigadier parsers read them, with +//! vanilla's error messages. The game sends the same arguments to players' +//! command trees, so their chat box checks them before the server does. +use crate::runtime::{Argument, ArgumentKind, ArgumentValue, BlockPos, ServerPlayer}; + +/// The values of `args`, typed by `player`, for `arguments` (in order; +/// optional ones left out aren't there), or the error the player reads. +pub fn parse( + arguments: &[Argument], + args: &str, + player: &ServerPlayer, + online: &[ServerPlayer], +) -> Result, String> { + let mut values = Vec::new(); + let mut rest = args; + for (i, argument) in arguments.iter().enumerate() { + if i > 0 && !rest.is_empty() { + rest = rest.strip_prefix(' ').ok_or( + "Expected whitespace to end one argument, but found trailing data".to_string(), + )?; + } + if rest.is_empty() { + if argument.optional { + break; + } + return Err("Unknown or incomplete command, see below for error".into()); + } + let (value, after) = one(&argument.kind, rest, player, online)?; + values.push((argument.name.clone(), value)); + rest = after; + } + if !rest.is_empty() { + return Err("Incorrect argument for command".into()); + } + Ok(values) +} + +/// StringReader.isAllowedInUnquotedString. +fn unquoted(c: char) -> bool { + c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '+') +} + +/// The unquoted string at the start of `s`, and what follows it. +fn word(s: &str) -> (&str, &str) { + let end = s.find(|c: char| !unquoted(c)).unwrap_or(s.len()); + s.split_at(end) +} + +/// One argument from the start of `s`, and what follows it. +fn one<'a>( + kind: &ArgumentKind, + s: &'a str, + player: &ServerPlayer, + online: &[ServerPlayer], +) -> Result<(ArgumentValue, &'a str), String> { + Ok(match kind { + ArgumentKind::Word => { + let (w, rest) = word(s); + if w.is_empty() { + return Err("Expected string".into()); + } + (ArgumentValue::Word(w.into()), rest) + } + ArgumentKind::Text => (ArgumentValue::Text(s.into()), ""), + ArgumentKind::Integer((min, max)) => { + let (n, rest) = integer(s)?; + if let Some(min) = min.filter(|m| n < *m) { + return Err(format!("Integer must not be less than {min}, found {n}")); + } + if let Some(max) = max.filter(|m| n > *m) { + return Err(format!("Integer must not be more than {max}, found {n}")); + } + (ArgumentValue::Integer(n), rest) + } + ArgumentKind::Number => { + let (n, rest) = double(s)?; + (ArgumentValue::Number(n), rest) + } + ArgumentKind::Boolean => { + let (w, rest) = word(s); + let b = match w { + "true" => true, + "false" => false, + "" => return Err("Expected bool".into()), + _ => { + return Err(format!( + "Invalid boolean, expected 'true' or 'false' but found '{w}'" + )); + } + }; + (ArgumentValue::Boolean(b), rest) + } + ArgumentKind::Player => { + if let Some(selector) = s.strip_prefix('@') { + let (kind, rest) = word(selector); + return match kind { + // A player's @p is themselves (the nearest to where they are). + "s" | "p" => Ok((ArgumentValue::Player(player.clone()), rest)), + "a" | "e" | "r" | "n" => { + Err("Only one player is allowed, but the provided selector allows more than one".into()) + } + _ => Err(format!("Unknown selector type '@{kind}'")), + }; + } + let (name, rest) = word(s); + if name.is_empty() { + return Err("Invalid name or UUID".into()); + } + let found = online + .iter() + .find(|p| p.name.eq_ignore_ascii_case(name)) + .ok_or("No player was found")?; + (ArgumentValue::Player(found.clone()), rest) + } + ArgumentKind::BlockPos => { + let (x, rest) = coordinate(s, player.x)?; + let rest = rest + .strip_prefix(' ') + .ok_or("Incomplete (expected 3 coordinates)")?; + let (y, rest) = coordinate(rest, player.y)?; + let rest = rest + .strip_prefix(' ') + .ok_or("Incomplete (expected 3 coordinates)")?; + let (z, rest) = coordinate(rest, player.z)?; + (ArgumentValue::BlockPos(BlockPos { x, y, z }), rest) + } + }) +} + +/// StringReader.readInt. +fn integer(s: &str) -> Result<(i32, &str), String> { + let end = s + .find(|c: char| !(c.is_ascii_digit() || c == '-' || c == '.')) + .unwrap_or(s.len()); + let (n, rest) = s.split_at(end); + if n.is_empty() { + return Err("Expected integer".into()); + } + let n = n.parse().map_err(|_| format!("Invalid integer '{n}'"))?; + Ok((n, rest)) +} + +/// StringReader.readDouble. +fn double(s: &str) -> Result<(f64, &str), String> { + let end = s + .find(|c: char| !(c.is_ascii_digit() || c == '-' || c == '.')) + .unwrap_or(s.len()); + let (n, rest) = s.split_at(end); + if n.is_empty() { + return Err("Expected double".into()); + } + let n = n.parse().map_err(|_| format!("Invalid double '{n}'"))?; + Ok((n, rest)) +} + +/// WorldCoordinate.parseInt, then BlockPos.containing: `~` and `~n` from +/// `base`, a whole number as it is. +fn coordinate(s: &str, base: f64) -> Result<(i32, &str), String> { + if s.starts_with('^') { + return Err( + "Cannot mix world & local coordinates (everything must either use ^ or not)".into(), + ); + } + if let Some(offset) = s.strip_prefix('~') { + if offset.is_empty() || offset.starts_with(' ') { + return Ok((base.floor() as i32, offset)); + } + let (n, rest) = double(offset)?; + return Ok(((base + n).floor() as i32, rest)); + } + integer(s) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::runtime::GameMode; + + fn player(name: &str) -> ServerPlayer { + ServerPlayer { + id: format!("id-{name}"), + name: name.into(), + x: 10.7, + y: 64.0, + z: -3.2, + dimension: "minecraft:overworld".into(), + game_mode: GameMode::Survival, + health: 20.0, + } + } + fn arg(name: &str, kind: ArgumentKind, optional: bool) -> Argument { + Argument { + name: name.into(), + kind, + optional, + } + } + + #[test] + fn values_in_order_and_optional_ones_left_out() { + let alex = player("Alex"); + let online = [alex.clone(), player("Steve")]; + let args = [ + arg("who", ArgumentKind::Player, false), + arg("height", ArgumentKind::Integer((Some(1), Some(64))), true), + arg("note", ArgumentKind::Text, true), + ]; + let v = parse(&args, "steve 5 hello there", &alex, &online).unwrap(); + assert_eq!(v[0].0, "who"); + assert!(matches!(&v[0].1, ArgumentValue::Player(p) if p.name == "Steve")); + assert_eq!(v[1], ("height".into(), ArgumentValue::Integer(5))); + assert_eq!( + v[2], + ("note".into(), ArgumentValue::Text("hello there".into())) + ); + let v = parse(&args, "@s", &alex, &online).unwrap(); + assert_eq!(v.len(), 1); + assert!(matches!(&v[0].1, ArgumentValue::Player(p) if p.name == "Alex")); + } + + #[test] + fn vanilla_errors() { + let alex = player("Alex"); + let online = [alex.clone()]; + let height = [arg( + "height", + ArgumentKind::Integer((Some(1), Some(64))), + false, + )]; + let err = |a: &[Argument], s| parse(a, s, &alex, &online).unwrap_err(); + assert_eq!( + err(&height, "0"), + "Integer must not be less than 1, found 0" + ); + assert_eq!( + err(&height, "65"), + "Integer must not be more than 64, found 65" + ); + assert_eq!(err(&height, "x"), "Expected integer"); + assert_eq!(err(&height, "1.5"), "Invalid integer '1.5'"); + assert_eq!( + err(&height, ""), + "Unknown or incomplete command, see below for error" + ); + assert_eq!(err(&height, "3 4"), "Incorrect argument for command"); + let who = [arg("who", ArgumentKind::Player, false)]; + assert_eq!(err(&who, "Herobrine"), "No player was found"); + assert_eq!(err(&who, "@q"), "Unknown selector type '@q'"); + let flag = [arg("on", ArgumentKind::Boolean, false)]; + assert_eq!( + err(&flag, "yes"), + "Invalid boolean, expected 'true' or 'false' but found 'yes'" + ); + let pos = [arg("at", ArgumentKind::BlockPos, false)]; + assert_eq!(err(&pos, "1 2"), "Incomplete (expected 3 coordinates)"); + } + + #[test] + fn block_positions_relative_to_the_player() { + let alex = player("Alex"); + let pos = [arg("at", ArgumentKind::BlockPos, false)]; + let v = parse(&pos, "~ ~1 ~-0.5", &alex, &[]).unwrap(); + assert_eq!( + v[0].1, + ArgumentValue::BlockPos(BlockPos { + x: 10, + y: 65, + z: -4 + }) + ); + let v = parse(&pos, "-5 70 ~", &alex, &[]).unwrap(); + assert_eq!( + v[0].1, + ArgumentValue::BlockPos(BlockPos { + x: -5, + y: 70, + z: -4 + }) + ); + } + + #[test] + fn free_text_is_an_optional_text_argument() { + let alex = player("Alex"); + let free = [arg("args", ArgumentKind::Text, true)]; + assert_eq!(parse(&free, "", &alex, &[]), Ok(Vec::new())); + assert_eq!( + parse(&free, "anything at all", &alex, &[]), + Ok(vec![( + "args".into(), + ArgumentValue::Text("anything at all".into()) + )]) + ); + assert_eq!( + parse(&[], "more", &alex, &[]), + Err("Incorrect argument for command".into()) + ); + assert_eq!(parse(&[], "", &alex, &[]), Ok(Vec::new())); + } +} diff --git a/crates/horizon-mods/src/lib.rs b/crates/horizon-mods/src/lib.rs index 20f475165..983df73d4 100644 --- a/crates/horizon-mods/src/lib.rs +++ b/crates/horizon-mods/src/lib.rs @@ -6,6 +6,8 @@ //! Nothing here runs unless a mod is installed and turned on: an empty //! [`Mods`] makes no engine and every hook returns at once. pub mod api_level; +#[cfg(feature = "runtime")] +pub mod commands; pub mod content; #[cfg(feature = "index")] pub mod index; diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index a0ad0b87c..a75dd5a43 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -52,7 +52,9 @@ use bindings::{ horizon::mods::{chat, command, game, hud, log as mod_log, storage}, }; pub use server_bindings::{ - exports::horizon::mods::server_events::BlockPos, + exports::horizon::mods::server_events::{ + Argument, ArgumentKind, ArgumentValue, BlockPos, ServerCommand, + }, horizon::mods::players::{GameMode, Player as ServerPlayer}, horizon::mods::world::BlockChange, }; @@ -336,10 +338,10 @@ impl Hooks { Hooks::Client(..) => None, } } - fn commands(&self) -> &[String] { + fn commands(&self) -> Vec<&str> { match self { - Hooks::Client(_, r) => &r.commands, - Hooks::Server(_, r) => &r.commands, + Hooks::Client(_, r) => r.commands.iter().map(String::as_str).collect(), + Hooks::Server(_, r) => r.commands.iter().map(|c| c.name.as_str()).collect(), } } } @@ -434,9 +436,16 @@ pub struct Mods { snapshot: Arc, out: Vec, world: WorldSlot, + /// Moves on whenever a mod starts or stops: the game resends the server + /// mods' commands to players when it changes. + generation: u64, } impl Mods { + /// Changes whenever the running mods (so their commands) change. + pub fn generation(&self) -> u64 { + self.generation + } /// Whether a running mod may use capability `world`: only then is a /// view worth lending. pub fn wants_world(&self) -> bool { @@ -571,7 +580,8 @@ impl Mods { .iter() .filter_map(|e| e.run.as_ref()) .filter(|r| r.hooks.server().is_some() == server) - .flat_map(|r| r.hooks.commands().iter().cloned()) + .flat_map(|r| r.hooks.commands()) + .map(str::to_owned) .collect(); let snapshot = self.snapshot.clone(); let world = self.world.clone(); @@ -640,17 +650,30 @@ impl Mods { .map_err(|e| reason(&e))??; (Hooks::Client(exports, r), ui) }; - let commands = match &mut hooks { - Hooks::Client(_, r) => &mut r.commands, - Hooks::Server(_, r) => &mut r.commands, - }; - commands.retain(|c| { - let free = !reserved(c) && !taken.contains(c); + let free = |c: &str| { + let free = !reserved(c) && !taken.iter().any(|t| t == c); if !free { log::warn!("Horizon: mod {} cannot take /{c}: already a command", m.id); } free - }); + }; + match &mut hooks { + Hooks::Client(_, r) => r.commands.retain(|c| free(c)), + Hooks::Server(_, r) => { + r.commands.retain(|c| free(&c.name)); + for c in &mut r.commands { + if let Err(e) = check_arguments(&c.arguments) { + log::warn!( + "Horizon: mod {}'s /{}: {e}; it takes free text", + m.id, + c.name + ); + c.arguments.clear(); + } + } + } + } + self.generation += 1; self.out.append(&mut store.data_mut().out); Ok(Some(Running { store, @@ -768,6 +791,7 @@ impl Mods { }); entry.status = Status::Failed(reason); entry.run = None; + self.generation += 1; None } } @@ -792,7 +816,7 @@ impl Mods { fn command_owner(&self, server: bool, name: &str) -> Option { self.entries.iter().position(|e| { e.run.as_ref().is_some_and(|r| { - r.hooks.server().is_some() == server && r.hooks.commands().iter().any(|c| c == name) + r.hooks.server().is_some() == server && r.hooks.commands().contains(&name) }) }) } @@ -825,7 +849,7 @@ impl Mods { .iter() .filter_map(|e| e.run.as_ref()) .filter(move |r| r.hooks.server().is_some() == server) - .flat_map(|r| r.hooks.commands().iter().map(String::as_str)) + .flat_map(|r| r.hooks.commands()) } /// A server tick. @@ -868,9 +892,13 @@ impl Mods { |m, s| m.call_block_placed(s, player, pos, state), ); } - /// The commands running server mods own, for the server's command tree. - pub fn server_commands(&self) -> impl Iterator { - self.owned_commands(true) + /// The commands running server mods own and their arguments, for the + /// server's command tree. + pub fn server_commands(&self) -> impl Iterator { + self.entries + .iter() + .filter_map(|e| e.run.as_ref()?.hooks.server()) + .flat_map(|r| r.commands.iter()) } /// Runs `line` (without its slash), typed by `player`, if a server mod /// owns its command; its feedback is an [`Output::Reply`]. False when @@ -880,18 +908,35 @@ impl Mods { let Some(i) = self.command_owner(true, name) else { return false; }; - let result = self.call(i, FUEL_EVENT, |run| match &run.hooks { - Hooks::Server(m, _) => { - m.horizon_mods_server_events() - .call_command(&mut run.store, player, name, args) - } - Hooks::Client(..) => Ok(Ok(None)), - }); let reply = |text, error| Output::Reply { player: player.id.clone(), text, error, }; + let arguments = self.entries[i] + .run + .as_ref() + .and_then(|r| r.hooks.server()) + .and_then(|r| r.commands.iter().find(|c| c.name == name)) + .map(|c| c.arguments.as_slice()) + .unwrap_or_default(); + let values = match crate::commands::parse(arguments, args, player, &self.snapshot.players) { + Ok(values) => values, + Err(e) => { + self.out.push(reply(e, true)); + return true; + } + }; + let result = self.call(i, FUEL_EVENT, |run| match &run.hooks { + Hooks::Server(m, _) => m.horizon_mods_server_events().call_command( + &mut run.store, + player, + name, + args, + &values, + ), + Hooks::Client(..) => Ok(Ok(None)), + }); match result { Some(Ok(Some(text))) => self.out.push(reply(text, false)), Some(Err(text)) => self.out.push(reply(text, true)), @@ -1217,6 +1262,7 @@ impl Mods { continue; } any = true; + self.generation += 1; self.entries[i].modified = now; self.entries[i].run = None; let path = self.entries[i].path.clone(); @@ -1242,6 +1288,34 @@ impl Mods { } } +/// A command's arguments are well formed: names given and distinct, +/// optional ones last, free text only last. +fn check_arguments(arguments: &[Argument]) -> Result<(), String> { + for (i, a) in arguments.iter().enumerate() { + if a.name.is_empty() + || !a + .name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_') + { + return Err(format!("argument name '{}' isn't [A-Za-z0-9_]+", a.name)); + } + if arguments[..i].iter().any(|b| b.name == a.name) { + return Err(format!("two arguments are named {}", a.name)); + } + if i > 0 && arguments[i - 1].optional && !a.optional { + return Err(format!("{} is required after an optional argument", a.name)); + } + if a.kind == ArgumentKind::Text && i + 1 < arguments.len() { + return Err(format!( + "{} takes the rest of the line, so it must be last", + a.name + )); + } + } + Ok(()) +} + fn modified(path: &Path) -> Option { let meta = std::fs::metadata(path).ok()?; if meta.is_dir() { diff --git a/crates/horizon-mods/src/testing.rs b/crates/horizon-mods/src/testing.rs index ff26bfffa..0fe821074 100644 --- a/crates/horizon-mods/src/testing.rs +++ b/crates/horizon-mods/src/testing.rs @@ -253,7 +253,7 @@ impl TestGame { } /// The commands the mod registered. pub fn commands(&self) -> Vec { - let server = self.mods.server_commands(); + let server = self.mods.server_commands().map(|c| c.name.as_str()); self.mods .commands() .chain(server) diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index 216bc8765..5ca3faf77 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -900,7 +900,7 @@ fn a_server_mod_without_a_world_reads_nothing() { assert!( out.iter() .any(|o| matches!(o, Output::Reply { text, error: true, .. } - if text == "The ground under you isn't loaded")), + if text == "That block isn't loaded")), "{out:?}" ); } @@ -999,10 +999,12 @@ fn a_server_mod_runs_only_where_the_world_does() { let mut mods = Mods::load_for(Runs::Server, paths, |_| true, |c| c == "give"); assert!(mods.runs_server()); - assert_eq!( - mods.server_commands().collect::>(), - ["online", "mined"] - ); + let commands: Vec<_> = mods.server_commands().map(|c| c.name.as_str()).collect(); + assert_eq!(commands, ["online", "mined"]); + // `/mined [player]`: its argument travels with it, for the command tree. + let mined = mods.server_commands().nth(1).unwrap(); + assert_eq!(mined.arguments[0].kind, horizon_mods::ArgumentKind::Player); + assert!(mined.arguments[0].optional); assert_eq!(mods.commands().count(), 0, "not the window's chat commands"); let alex = alex(); mods.set_snapshot(Snapshot { diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 26bc09a84..7ab82720d 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -2249,6 +2249,11 @@ packet!( /// Input flags: forward 1, backward 2, left 4, right 8, jump 16, shift 32, sprint 64. PlayerInput { flags: u8 => UByte } ); +packet!( + /// ServerboundSelectBundleItemPacket: the menu slot of a bundle and the + /// index of its selected item (-1: none). + SelectBundleItem { slot: i32 => VarInt, index: i32 => VarInt } +); packet!(SetCarriedItem { slot: i16 => Short }); packet!(SetCreativeModeSlot { slot: i16 => Short, item: Option => Slot }); packet!(UseItem { hand: i32 => VarInt, sequence: i32 => VarInt, yaw: f32 => Float, pitch: f32 => Float }); @@ -2317,6 +2322,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { ContainerSlotStateChanged(ContainerSlotStateChanged) = CONTAINER_SLOT_STATE_CHANGED, Punch(Empty) = PUNCH, ResourcePack(ResourcePackResponse) = RESOURCE_PACK, + SelectBundleItem(SelectBundleItem) = BUNDLE_ITEM_SELECTED, SelectTrade(SelectTrade) = SELECT_TRADE, SetBeacon(SetBeacon) = SET_BEACON, SetCarriedItem(SetCarriedItem) = SET_CARRIED_ITEM, diff --git a/crates/horizon-world/src/level/redstone.rs b/crates/horizon-world/src/level/redstone.rs index b07f8c6a2..42ba42634 100644 --- a/crates/horizon-world/src/level/redstone.rs +++ b/crates/horizon-world/src/level/redstone.rs @@ -1174,7 +1174,8 @@ impl Sim<'_, L> { self.game_event(pos, "minecraft:note_block_play"); } } - /// `NoteBlock.triggerEvent`: the note's sound. + /// `NoteBlock.triggerEvent`: the note's particle (tunable instruments) + /// and sound. pub(crate) fn note_trigger_event(&mut self, pos: BlockPos, state: BlockStateId) { let b = self.b; let instrument = b.table.text(state, b.props.instrument).to_owned(); @@ -1186,6 +1187,12 @@ impl Sim<'_, L> { let pitch = if mob_head { 1.0 } else { + // `isTunable`: the client adds the NOTE particle above the block. + self.emit(LevelEvent::BlockEvent { + pos, + state, + kind: "note_particle", + }); horizon_core::jmath::pow(2.0, f64::from(note - 12) / 12.0) as f32 }; let sound = match instrument.as_str() { diff --git a/crates/horizon-world/src/worldgen/decoration_order.rs b/crates/horizon-world/src/worldgen/decoration_order.rs index 6b0fb2252..0e53e7d09 100644 --- a/crates/horizon-world/src/worldgen/decoration_order.rs +++ b/crates/horizon-world/src/worldgen/decoration_order.rs @@ -29,7 +29,7 @@ //! overlap), so a chunk may be decorated as soon as no lower-ranked chunk //! within two of it is still waiting: [`DecorationOrder::blocked`]. Chunks //! further apart still decorate in parallel. -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; #[derive(Default)] pub struct DecorationOrder { @@ -121,7 +121,6 @@ fn ticket_hash(x: i32, z: i32) -> u64 { /// The chunks decorated around a player at `center`, in vanilla's order. pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { use std::cmp::Reverse; - use std::collections::{BinaryHeap, VecDeque}; let mut tickets: Vec<(i32, i32)> = (-radius..=radius) .flat_map(|dx| (-radius..=radius).map(move |dz| (center.0 + dx, center.1 + dz))) .collect(); @@ -132,16 +131,31 @@ pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { Reverse(ticket_hash(x, z) & (TICKET_SET_CAPACITY - 1)), ) }); - let mut tickets: VecDeque<_> = tickets.into(); // Every chunk this touches lies within `half` of the centre: tickets // reach `LIGHT_LEVEL - TICKET_LEVEL` further, and FULL tasks decorate - // one more ring. Dense grids over that square replace hash maps. + // one more ring. + let half = radius.max(0) + LIGHT_LEVEL - TICKET_LEVEL + 1; + ticket_order( + tickets.into(), + TICKETS_IN_FLIGHT, + (center.0 - half, center.1 - half), + (2 * half + 1) as usize, + ) +} + +/// The decoration order of `tickets` (level 31) added in turn, at most +/// `in_flight` at a time. Dense grids of `side` chunks from `origin` hold +/// every chunk this touches, in place of hash maps. +fn ticket_order( + mut tickets: VecDeque<(i32, i32)>, + in_flight: usize, + origin: (i32, i32), + side: usize, +) -> Vec<(i32, i32)> { + use std::cmp::Reverse; + use std::collections::BinaryHeap; let reach = LIGHT_LEVEL - TICKET_LEVEL; - let half = radius.max(0) + reach + 1; - let side = (2 * half + 1) as usize; - let cell = |(x, z): (i32, i32)| { - ((x - center.0 + half) as usize) * side + (z - center.1 + half) as usize - }; + let cell = |(x, z): (i32, i32)| ((x - origin.0) as usize) * side + (z - origin.1) as usize; let mut active: Vec<(i32, i32)> = Vec::new(); // Queued task per chunk (level, sequence), `NONE` when there is none; // stale heap entries are skipped. @@ -177,10 +191,9 @@ pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { } } }; - for _ in 0..TICKETS_IN_FLIGHT { - if let Some(t) = tickets.pop_front() { - add(t, &mut active, &mut queued, &mut heap, &full); - } + while active.len() < in_flight { + let Some(t) = tickets.pop_front() else { break }; + add(t, &mut active, &mut queued, &mut heap, &full); } while let Some(Reverse((l, s, chunk))) = heap.pop() { let i = cell(chunk); @@ -202,7 +215,7 @@ pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { full[i] = true; } active.retain(|t| !(-2..=2).all(|dx| (-2..=2).all(|dz| full[cell((t.0 + dx, t.1 + dz))]))); - while active.len() < TICKETS_IN_FLIGHT { + while active.len() < in_flight { let Some(t) = tickets.pop_front() else { break }; add(t, &mut active, &mut queued, &mut heap, &full); } @@ -210,10 +223,36 @@ pub fn vanilla_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { order } +/// The chunks `/forceload add` over chunks `(x0, z0)..=(x1, z1)` decorates, +/// in vanilla's order: ForceLoadCommand adds a FORCED ticket (level 31) per +/// chunk, x-outer, z-inner, all at once. +pub fn forced_order(x0: i32, z0: i32, x1: i32, z1: i32) -> Vec<(i32, i32)> { + let tickets = (x0..=x1) + .flat_map(|x| (z0..=z1).map(move |z| (x, z))) + .collect(); + let pad = LIGHT_LEVEL - TICKET_LEVEL + 1; + let side = ((x1 - x0).max(z1 - z0) + 2 * pad + 1) as usize; + ticket_order(tickets, usize::MAX, (x0 - pad, z0 - pad), side) +} + #[cfg(test)] mod tests { use super::*; + /// Seed 8675309's geodes in chunks (-26, -1) and (14, -20) run into the + /// trial chambers of (-26, 0) and (14, -19); vanilla decorates the lower + /// z first, wherever the batch lies, so the chambers are drawn over them. + #[test] + fn forced_chunks_decorate_x_outer_z_inner() { + let rank = |order: &[(i32, i32)], c| order.iter().position(|&o| o == c).unwrap(); + let west = forced_order(-32, -16, -17, -1); + assert!(rank(&west, (-26, -1)) < rank(&west, (-26, 0))); + let east = forced_order(0, -32, 15, -17); + assert!(rank(&east, (14, -20)) < rank(&east, (14, -19))); + assert_eq!(west[0], (-33, -17)); + assert_eq!(west.len(), 22 * 22); + } + /// The hash map version this module had before its dense grids. fn hashed_order(center: (i32, i32), radius: i32) -> Vec<(i32, i32)> { use std::cmp::Reverse; diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 7a38608be..f3bf7cab7 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -23,6 +23,7 @@ use super::{ climate::{ClimateSampler, decode_parameter, quantize}, decode_noise, density::DensityRegistry, + generator_structures::Starts, material_condition::{ MaterialConditionRegistry, MaterialConditions, MaterialDensitySources, MaterialRule, MaterialRuleError, MaterialRuleLibrary, MaterialSurfaceQueries, @@ -567,6 +568,9 @@ pub struct ProtoChunk { pub block_entities: Vec<([i32; 3], crate::nbt::Compound)>, /// Structure starts referencing this chunk (STRUCTURE_REFERENCES). pub(super) structure_starts: Vec>, + /// The starts made in this chunk (STRUCTURE_STARTS), also those none of + /// whose pieces reach it (a giant ruined portal next door). + own_starts: Starts, /// Entities placed by structures (`ProtoChunk.addEntity`), as NBT with /// absolute `Pos`. pub entities: Vec, @@ -620,12 +624,7 @@ impl ProtoChunk { } /// The structure starts this chunk holds itself (`structures.starts`). pub fn own_starts(&self) -> Vec> { - let pos = self.position(); - self.structure_starts - .iter() - .filter(|s| s.chunk == pos) - .cloned() - .collect() + self.own_starts.to_vec() } /// Also restores a saved proto chunk that was decorated before it was saved. pub fn set_decorated(&mut self) { @@ -1114,16 +1113,19 @@ where ) .map_err(stage("noise"))?; chunk.set_generation_stage(PreLightChunkStage::Biomes); - let references = match &self.structures { - Some(structures) => structures.references( - &mut StructureQueries { + let (references, own_starts) = match &self.structures { + Some(structures) => { + let mut queries = StructureQueries { pipeline: self, worker, valid: BTreeSet::new(), - }, - pos, - ), - None => Vec::new(), + }; + ( + structures.references(&mut queries, pos), + structures.starts_at(&mut queries, pos), + ) + } + None => (Vec::new(), Starts::default()), }; if let Some(beard) = self .structures @@ -1259,6 +1261,7 @@ where decorated: false, block_entities: Vec::new(), structure_starts: references, + own_starts, entities: Vec::new(), }) } @@ -1648,6 +1651,22 @@ pub(super) struct WorkerState { heights: HashMap<(i32, i32, u8), i32>, /// Decorate with structure pieces only (for structure parity checks). pub(super) structures_only: bool, + pub(super) structure_mobs: Option>, +} +/// `Mob.finalizeSpawn(level, difficulty, STRUCTURE, null)` of the entities a +/// structure places with finalizeEntities, run by the game, which owns mobs. +pub trait StructureMobs: Send + Sync { + /// Finalizes the entity in `nbt` if it is a mob, drawing from the + /// region's random. `biome` is the biome at its block, `structures` the + /// structures with a piece there. False when it could not: the entity + /// keeps its `horizon:finalize` for the game to finish on load. + fn finalize( + &self, + nbt: &mut crate::nbt::Compound, + biome: &str, + structures: &[String], + random: &mut dyn super::structure::legacy::PieceRandom, + ) -> bool; } trait SeededPipeline: Send + Sync { @@ -2464,6 +2483,7 @@ impl OverworldGenerator { carver_biomes: HashMap::new(), timings: StageTimings::default(), structures_only: false, + structure_mobs: None, heights: HashMap::new(), }, } @@ -2590,6 +2610,9 @@ impl GeneratorWorker { pub fn set_structures_only(&mut self, only: bool) { self.state.structures_only = only; } + pub fn set_structure_mobs(&mut self, mobs: Arc) { + self.state.structure_mobs = Some(mobs); + } } #[cfg(test)] @@ -2975,6 +2998,26 @@ mod tests { } } + /// Seed 8675309's giant ruined portal starts in chunk (-26, 23) and lies + /// wholly in (-26, 24): its own chunk still holds the start, as vanilla's + /// getAllStarts does, though no piece reaches it. + #[test] + fn a_chunk_holds_its_starts_whose_pieces_lie_elsewhere() { + let Some(data) = prepared_data() else { + return; + }; + let generator = OverworldGenerator::new(data, 8675309).expect("generator"); + let mut worker = generator.worker(); + let proto = worker + .generate_proto(ChunkPos::new(-26, 23)) + .expect("proto"); + let own: Vec<_> = proto.own_starts().iter().map(|s| s.name.clone()).collect(); + assert!( + own.iter().any(|n| n == "minecraft:ruined_portal_mountain"), + "{own:?}" + ); + } + /// Chunks no ring search can end near are decided without the rings, /// which stay unsearched, and get the starts they get with them. #[test] diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs index fc1cd8bcf..0f3ea6810 100644 --- a/crates/horizon-world/src/worldgen/generator_decoration.rs +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -310,6 +310,7 @@ impl Decoration { Err(e) => return Err(resource(e.to_string())), }; let structures_only = worker.structures_only; + let references = region[4].structure_starts.clone(); let mut block_entities = Vec::new(); for chunk in region.iter_mut() { block_entities.append(&mut chunk.block_entities); @@ -318,6 +319,9 @@ impl Decoration { block_entities, entities: Vec::new(), level_random, + structure_mobs: worker.structure_mobs.clone(), + starts: references.clone(), + biome_names: data.biome_names(), blocks: data .feature_resources .as_ref() @@ -334,7 +338,6 @@ impl Decoration { }; let mut stats = DecorateStats::default(); let blocks = self.blocks; - let references = region[4].structure_starts.clone(); // ChunkGenerator.getWritableArea: the chunk's minimum Y + 1 to its maximum Y. let chunk_box = BoundingBox::new( [center.x * 16, min_y + 1, center.z * 16], @@ -419,15 +422,11 @@ impl Decoration { } // WorldGenRegion.addFreshEntity: into the chunk holding the position. for nbt in std::mem::take(&mut world.entities) { - let Some(crate::nbt::Tag::List(p)) = nbt.get(&"Pos".into()) else { + let Some(at) = block_of(&nbt) else { continue; }; - let coord = |i: usize| match p.get(i) { - Some(crate::nbt::Tag::Double(b)) => f64::from_bits(*b).floor() as i32, - _ => 0, - }; - let index = ((coord(2) >> 4).wrapping_sub(center.z) + 1) * 3 - + (coord(0) >> 4).wrapping_sub(center.x) + let index = ((at[2] >> 4).wrapping_sub(center.z) + 1) * 3 + + (at[0] >> 4).wrapping_sub(center.x) + 1; if let Some(chunk) = usize::try_from(index).ok().and_then(|i| region.get_mut(i)) { chunk.entities.push(nbt); @@ -454,6 +453,9 @@ struct World<'a> { block_entities: Vec<([i32; 3], crate::nbt::Compound)>, entities: Vec, level_random: &'a mut dyn super::structure::legacy::PieceRandom, + structure_mobs: Option>, + starts: Vec>, + biome_names: &'a [Arc], blocks: Option<&'a BlockBehavior>, region: TerrainRegion<'static, GenBlockStates>, biomes: BiomeRegion, @@ -847,10 +849,57 @@ impl PlacementContext for World<'_> { (0..ny).all(|y| (0..nz).all(|z| shape.is_full(x as i32, y as i32, z as i32))) })) } - fn add_entity(&mut self, nbt: crate::nbt::Compound) -> Result<(), PlacementQueryError> { + fn add_entity(&mut self, mut nbt: crate::nbt::Compound) -> Result<(), PlacementQueryError> { + if let Some(mobs) = self.structure_mobs.clone() + && nbt.contains_key(&"horizon:finalize".into()) + { + let at = block_of(&nbt).unwrap_or([0; 3]); + let biome = self + .biome_identity(at) + .ok() + .and_then(|b| self.biome_names.get(b.0 as usize)) + .map_or("", |n| &**n) + .to_owned(); + let structures: Vec = self + .starts + .iter() + .filter(|s| s.pieces.iter().any(|p| p.bounding_box().is_inside(at))) + .map(|s| s.name.clone()) + .collect(); + if mobs.finalize(&mut nbt, &biome, &structures, self.level_random) { + nbt.remove(&"horizon:finalize".into()); + } + } self.entities.push(nbt); Ok(()) } + /// SpikeFeature.placeSpike: the crystal is a fresh entity of the region, + /// saved with the chunk. + fn spawn_end_crystal( + &mut self, + position: [f64; 3], + yaw: f32, + beam_target: Option<[i32; 3]>, + invulnerable: bool, + ) -> Result<(), PlacementQueryError> { + use crate::nbt::Tag; + let mut nbt = crate::nbt::Compound::new(); + nbt.insert("id".into(), Tag::String("minecraft:end_crystal".into())); + nbt.insert( + "Pos".into(), + Tag::List(position.iter().map(|v| Tag::Double(v.to_bits())).collect()), + ); + nbt.insert( + "Rotation".into(), + Tag::List(vec![Tag::Float(yaw.to_bits()), Tag::Float(0)]), + ); + nbt.insert("Invulnerable".into(), Tag::Byte(i8::from(invulnerable))); + nbt.insert("ShowBottom".into(), Tag::Byte(1)); + if let Some(b) = beam_target { + nbt.insert("beam_target".into(), Tag::IntArray(b.to_vec())); + } + self.add_entity(nbt) + } fn set_block_entity( &mut self, position: [i32; 3], @@ -1167,3 +1216,14 @@ impl PlacementContext for World<'_> { Ok(Some(false)) } } + +/// The block an entity's `Pos` is in. +fn block_of(nbt: &crate::nbt::Compound) -> Option<[i32; 3]> { + let Some(crate::nbt::Tag::List(p)) = nbt.get(&"Pos".into()) else { + return None; + }; + Some(std::array::from_fn(|i| match p.get(i) { + Some(crate::nbt::Tag::Double(b)) => f64::from_bits(*b).floor() as i32, + _ => 0, + })) +} diff --git a/crates/horizon-world/src/worldgen/structure/legacy.rs b/crates/horizon-world/src/worldgen/structure/legacy.rs index 785b5fb2e..19d121718 100644 --- a/crates/horizon-world/src/worldgen/structure/legacy.rs +++ b/crates/horizon-world/src/worldgen/structure/legacy.rs @@ -31,14 +31,19 @@ pub type Markers = Vec<(String, [i32; 3])>; pub trait PieceRandom: ProcessorRandom { fn boolean(&mut self) -> bool; fn double(&mut self) -> f64; + /// The concrete random, for callers that need all of `RandomSource`. + fn as_any(&mut self) -> &mut dyn std::any::Any; } -impl PieceRandom for R { +impl PieceRandom for R { fn boolean(&mut self) -> bool { self.next_boolean() } fn double(&mut self) -> f64 { self.next_double() } + fn as_any(&mut self) -> &mut dyn std::any::Any { + self + } } /// Object-safe world access for piece post-processing. diff --git a/crates/horizon-world/src/worldgen/structure/start.rs b/crates/horizon-world/src/worldgen/structure/start.rs index 810332c61..f84a953a1 100644 --- a/crates/horizon-world/src/worldgen/structure/start.rs +++ b/crates/horizon-world/src/worldgen/structure/start.rs @@ -275,16 +275,15 @@ fn terrain(name: Option<&str>) -> TerrainAdjustment { _ => TerrainAdjustment::None, } } -fn pair(value: Option<&Value>, a: &str, b: &str, default: i32) -> [i32; 2] { +/// A jigsaw field given as one number or as an object of two. In the object a +/// missing `a` is 0 and a missing `b` is `missing_b` (`JigsawStructure.MaxDistance` +/// and `DimensionPadding` default their second value, not copy the first). +fn pair(value: Option<&Value>, a: &str, b: &str, default: i32, missing_b: i32) -> [i32; 2] { match value { Some(Value::Number(n)) => [n.as_i64().unwrap_or(0) as i32; 2], Some(Value::Object(o)) => { - let get = |k: &str| o.get(k).and_then(Value::as_i64).unwrap_or(0) as i32; - let first = get(a); - [ - first, - o.get(b).and_then(Value::as_i64).map_or(first, |v| v as i32), - ] + let get = |k: &str| o.get(k).and_then(Value::as_i64).map(|v| v as i32); + [get(a).unwrap_or(0), get(b).unwrap_or(missing_b)] } _ => [default; 2], } @@ -326,9 +325,11 @@ impl StructureRegistry { "horizontal", "vertical", 80, + // DimensionType.Y_SIZE. + 4064, ), aliases: v["pool_aliases"].as_array().cloned().unwrap_or_default(), - padding: pair(v.get("dimension_padding"), "bottom", "top", 0), + padding: pair(v.get("dimension_padding"), "bottom", "top", 0, 0), waterlogging: v["liquid_settings"].as_str() != Some("ignore_waterlogging"), checks: super::start_checks::StartChecks::decode(v.get("horizon:start_checks")), piece_limited: v diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index 9563c2019..3956b6457 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -689,16 +689,6 @@ What the server calls in a server mod (manifest `api = "0.3"`, experimental). On `type player = player` -### record `registration` - -| Field | Type | | -| --- | --- | --- | -| `commands` | `list` | Commands players may type, without the slash. A name vanilla already uses is refused (vanilla's command runs). | -| `tick` | `bool` | Call `tick` every server tick (20 per second). | -| `joins` | `bool` | Call `player-joined` and `player-left`. | -| `chat` | `bool` | Call `chat` for each chat message a player sends. | -| `blocks` | `bool` | Call `block-broken` and `block-placed`. | - ### record `block-pos` | Field | Type | | @@ -707,6 +697,59 @@ What the server calls in a server mod (manifest `api = "0.3"`, experimental). On | `y` | `s32` | | | `z` | `s32` | | +### variant `argument-kind` + +What an argument of a command takes. The server sends each command and its arguments to players' games, whose chat box completes and colours them as vanilla's; the server parses them before the mod's `command` hook gets their values. + +| Case | Payload | | +| --- | --- | --- | +| `word` | | One word: letters, digits and `_ - . +`. | +| `text` | | The rest of the line, spaces included: only last. | +| `integer` | `tuple, option>` | A whole number, within the bounds given. | +| `number` | | A number with or without decimals. | +| `boolean` | | `true` or `false`. | +| `player` | | One online player: a name, or `@s` or `@p` (whoever typed it, as vanilla picks for a player). | +| `block-pos` | | A block position: three whole numbers, each one also `~` or `~n`, relative to whoever typed it. | + +### record `argument` + +| Field | Type | | +| --- | --- | --- | +| `name` | `string` | Shown in the chat box's hint (``) and the key of its value. | +| `kind` | `argument-kind` | | +| `optional` | `bool` | Optional arguments come after every required one. | + +### record `server-command` + +| Field | Type | | +| --- | --- | --- | +| `name` | `string` | Without the slash. A name vanilla already uses is refused (vanilla's command runs). | +| `arguments` | `list` | In order; none: the command takes nothing after its name. Free text is one optional `text` argument. | + +### variant `argument-value` + +An argument's value, parsed as its kind says. + +| Case | Payload | | +| --- | --- | --- | +| `word` | `string` | | +| `text` | `string` | | +| `integer` | `s32` | | +| `number` | `f64` | | +| `boolean` | `bool` | | +| `player` | `player` | | +| `block-pos` | `block-pos` | | + +### record `registration` + +| Field | Type | | +| --- | --- | --- | +| `commands` | `list` | Commands players may type. | +| `tick` | `bool` | Call `tick` every server tick (20 per second). | +| `joins` | `bool` | Call `player-joined` and `player-left`. | +| `chat` | `bool` | Call `chat` for each chat message a player sends. | +| `blocks` | `bool` | Call `block-broken` and `block-placed`. | + | Function | Signature | What it does | | --- | --- | --- | | `init` | `func() -> result` | Once, after loading. An error keeps the mod off and is logged. | @@ -714,6 +757,6 @@ What the server calls in a server mod (manifest `api = "0.3"`, experimental). On | `player-joined` | `func(player: player)` | A player joined the server; they are in `players.online` already. | | `player-left` | `func(player: player)` | A player left the server; they are no longer in `players.online`. | | `chat` | `func(player: player, text: string)` | A chat message a player sent, as plain text. | -| `command` | `func(player: player, name: string, args: string) -> result, string>` | `/name args` typed by `player`: ok(some(text)) is their feedback, err(text) their error in red. | +| `command` | `func(player: player, name: string, args: string, values: list>) -> result, string>` | `/name args` typed by `player`: ok(some(text)) is their feedback, err(text) their error in red. `values` holds each argument given, by name, in order (an optional one left out isn't there); a line that doesn't parse never reaches the mod: the player gets vanilla's error. | | `block-broken` | `func(player: player, pos: block-pos, state: string)` | A player broke the block at `pos` in their dimension: `state` is what was there, as `minecraft:oak_log[axis=y]`. | | `block-placed` | `func(player: player, pos: block-pos, state: string)` | A player placed `state` at `pos` in their dimension. | diff --git a/docs/api/mods.md b/docs/api/mods.md index 536bfd7e7..55f890cc1 100644 --- a/docs/api/mods.md +++ b/docs/api/mods.md @@ -18,7 +18,7 @@ the player before the mod is turned on, and checked against the component's real | Hooks a mod exports | 5: `init`, `tick`, `frame`, `command`, `chat`; a server mod 8: `init`, `tick`, `player-joined`, `player-left`, `chat`, `command`, `block-broken`, `block-placed` | | Capabilities | 6: `game-read`, `chat`, `hud`, `storage`, `registries`, `players` | | Manifest `api` lines served | 3: `0.1` (code), `0.2` (content), `0.3` (server mods, experimental) | -| SDK | the `Mod` trait (5 methods), `Registration` (4 builders), `export_mod!`, log helpers; `server::ServerMod` (8 methods), `server::Registration` (5 builders), `export_server_mod!` | +| SDK | the `Mod` trait (5 methods), `Registration` (4 builders), `export_mod!`, log helpers; `server::ServerMod` (8 methods), `server::Registration` (6 builders), `server::Argument`, `server::Args`, `export_server_mod!` | | `cargo horizon-mod` | `new` (templates `code` and `content`), `build`, `run`, `test`, `check` | | Example mods | `coords-hud` (code), `ruby-content` (content), `welcome` (server) | @@ -88,9 +88,9 @@ release. What real mods need next, in the order modpacks and servers need it: - **More for server mods** (`api = "0.3"`, [Server mods](../mods.md#server-mods-api-03-experimental)): they run - on the server thread, a LAN host and the dedicated server today, with joins, chat, commands, players' block - breaking and placing, and `world` (read blocks and biomes, set blocks as `/setblock` does); next entity events, game rules, - server commands with typed arguments sent to clients' command trees. + on the server thread, a LAN host and the dedicated server today, with joins, chat, typed commands in players' + command trees, players' block breaking and placing, and `world` (read blocks and biomes, set blocks as `/setblock` + does); next entity events, game rules, entity, item and block-state arguments. - **World and blocks**: blocks, block states and biomes are there for server mods (`world`); next block entities, and `world` for client mods (raycasts, single player and LAN hosts). - **Items and inventories**: the player's inventory, held item and open container; item stacks with components. @@ -106,6 +106,9 @@ What real mods need next, in the order modpacks and servers need it: ## Changelog +- API 0.3: typed server commands: `registration.commands` lists each command's arguments (`argument-kind`: word, + text, integer, number, boolean, player, block-pos), sent in players' command trees and parsed by the server; + `command` gets their values. SDK `Registration::command_with`, `Argument`, `Args`. - API 0.3: capability `world` (`get-block`, `get-biome`, `set-blocks`); example `beacons`; test scripts' `blocks` and `expect.blocks`. - Server mods run in the game: single player (server thread and in-frame), LAN hosts, the dedicated server. diff --git a/docs/api/stability.md b/docs/api/stability.md index baaccdbef..9911b79e9 100644 --- a/docs/api/stability.md +++ b/docs/api/stability.md @@ -108,7 +108,7 @@ Deprecations and breaking changes are in bold. The release notes of the game rel | Mod API: `render` (HUD shapes, camera shake and zoom; drawn by the game, no mod shaders) | experimental | manifest `experimental = ["render"]` | | Mod API: `input` (claimed items' use, the mod's keys, the mouse wheel) | experimental | manifest `experimental = ["input"]` | | Content mods (`registries`: data-driven blocks and items) | preview | manifest `api = "0.2"` | -| Server mods: world `horizon-server-mod`, `players`, `server-events` | experimental | manifest `api = "0.3"` | +| Server mods: world `horizon-server-mod`, `players`, `server-events`, `world`, typed `server-command`s | experimental | manifest `api = "0.3"` | | Script mods (Lua run by an interpreter mod, [mods.md](mods.md#ways-in)) | not started | | | `cargo horizon-mod` (`new`, `build`, `run`), `horizon-mod-sdk` | preview | 0.1.0 | | Shader API | not started | | diff --git a/docs/architecture.md b/docs/architecture.md index 0350bd1ea..3aec2338b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -5,8 +5,9 @@ counted only for the game loop because nearly every gameplay change touches it). organised and how to build and test are in [AGENTS.md](../AGENTS.md). Paths: `L/` = `crates/horizon-client/src/`, `G/` = `crates/horizon-client/src/game/`, `W/` = -`crates/horizon-world/src/`. Checks: a bare name is a harness (`python3 tools/parity.py `, script -`tools/test__parity.py`); `lan_e2e ` is `python3 tools/lan_e2e.py --check `. +`crates/horizon-world/src/`, `K/` = `crates/horizon-client-core/src/`, `C/` = `crates/horizon-command/src/`. +Checks: a bare name is a harness (`python3 tools/parity.py `, script `tools/test__parity.py`); +`lan_e2e ` is `python3 tools/lan_e2e.py --check `. For the full set of harnesses a file can affect, ask the runner: `printf '%s\n' > /tmp/p.txt && python3 tools/parity.py --changed-files /tmp/p.txt --list`. @@ -17,7 +18,7 @@ file selects ~103. |---|---|---|---| | 1 | Game loop, tick order, frame pacing (554) | `L/game.rs` (`fn tick`, `fn tick_world`, `fn render`, `about_to_wait`), `L/clock.rs`, `L/window.rs`, `L/spans.rs` | game_loop, frame_limiter, interaction_input, tick | | 2 | Mobs in the game loop, spawning (166) | `G/creatures.rs`, `G/natural_spawning.rs`, `L/mobs/spawning.rs`, `L/mobs/spawn_rules.rs`, `L/mobs/spawn_selection.rs`, `L/mobs/finalize.rs`, `G/spawner.rs`, `G/trial_spawner.rs` | natural_spawn, spawn_rules, finalize_spawn, spawner, trial_spawner, mob_ai | -| 3 | World save and load (163) | `L/save.rs`, `G/saving.rs`, `G/persist.rs` (entities), `L/entity_nbt.rs`, `L/block_entity_nbt.rs`, `W/region.rs`, `W/nbt.rs` | save_roundtrip, world_reopen, world, datafix | +| 3 | World save and load (163) | `L/save.rs`, `G/saving.rs`, `G/persist.rs` (entities), `L/entity_nbt.rs`, `K/block_entity_nbt.rs`, `W/region.rs`, `W/nbt.rs` | save_roundtrip, world_reopen, world, datafix | | 4 | World generation (153) | `W/worldgen.rs`, `W/worldgen/` (`generator*.rs`, `feature_graph.rs`, `structure/`, `placement/`), `L/vanillagen.rs` | chunk_generation, worldgen, server_world_gen, world_spawn, feature_graph, feature_placement, decoration and the other worldgen harnesses | | 5 | Multiplayer client, packets in (145) | `G/remote.rs` (`fn handle_packet`, `fn tick_remote`), `G/remote_*.rs`, `L/net.rs` | dedicated_server, server_entities, lan_e2e (all) | | 6 | Agent control, horizon-ctl (145) | `L/control.rs`, `L/bin/horizon-ctl/`, `G/control.rs`, `G/agent.rs`, `G/events.rs`, `G/ui_control.rs` | `python3 tools/agent_control_e2e.py`; `cargo test -p horizon-client --bin horizon-ctl` | @@ -32,7 +33,7 @@ file selects ~103. | 15 | Items and item use (96) | `L/items.rs`, `L/item_data.rs`, `G/hand.rs`, `G/consume.rs`, `G/potions.rs`, `L/effects.rs`; game.rs `fn use_hand`, `fn use_item` | use_item_on, item_use, item_use_lifecycle, consumable, consume_effect, status_effect | | 16 | Options and settings screens (93) | `L/options_ui.rs`, `G/options.rs`, `L/settings.rs`, `L/options_file.rs`, `L/graphics_ui.rs`, `L/graphics.rs` | options, toggle_keys | | 17 | HUD, chat, tab list (93) | `L/hud.rs`, `L/hud_layout.rs`, `L/hud_overlays.rs`, `L/chat.rs`, `G/chat.rs`, `L/tab_list.rs`, `L/locator_bar.rs`, `G/locator_bar.rs` | hud, tab_list, locator_bar, chat_screen, secure_chat | -| 18 | Command execution (88) | `G/commands.rs`, `G/commands/*.rs`, `L/scoreboard_cmd.rs`, `L/data_cmd.rs`, `G/functions.rs` | command_exec (corpus `tools/command_exec_corpus.py`), scoreboard, server_ops_feedback, lan_e2e commands | +| 18 | Command execution (88) | `G/commands.rs`, `G/commands/*.rs`, `L/scoreboard_cmd.rs`, `L/data_cmd.rs`, `K/scoreboard.rs`, `G/functions.rs` | command_exec (corpus `tools/command_exec_corpus.py`), scoreboard, server_ops_feedback, lan_e2e commands | | 19 | Chunk streaming, light, tickets (85) | `L/streaming.rs`, `L/world.rs`, `L/chunk.rs`, `L/chunk_map.rs`, `L/light.rs`, `L/ticket_levels.rs`, `L/tick_chunk_membership.rs`, `G/world_loading.rs` | light, chunk_status, random_tick_sections; `cargo test -p horizon-client --test streaming_meshes` | | 20 | Mob models and animation (78) | `L/mobs/render.rs`, `L/mobs/anim.rs`, `L/mobs/body_anim.rs`, `L/mobs/keyframes.rs`, `L/entity.wgsl` | entity_model | | 21 | Block behaviour, server side (78) | `W/level/` (`mod.rs`, `tick.rs`, `hooks.rs`, `data.rs`, `redstone.rs`, `place.rs`), `G/block_entity_ticks.rs`, `G/moving_pistons.rs` | block_update, redstone, random_tick, simple_block, piston_movement, block_entity_tickers | @@ -46,12 +47,12 @@ file selects ~103. | 29 | Title, worlds, startup (49) | `L/title.rs` + `L/title/`, `G/startup_menu.rs`, `L/title_edition.rs` | world_options; `cargo test -p horizon-client --lib title` | | 30 | Dedicated server, horizon-server (48) | `G/dedicated.rs`, `G/dedicated/status.rs`, `crates/horizon-server/`, `crates/horizon-server-files/` | dedicated_server, server_files, user_cache, online_mode, server_ops_feedback | | 31 | Particles and client effects (46) | `L/particles.rs`, `G/render_tick.rs`, `G/level_particles.rs`, `L/animate_tick.rs` | particle_providers, block_particles, entity_particles, emitter_particles, marker_particles | -| 32 | Bosses and the End (45) | `G/dragon.rs`, `G/wither.rs`, `G/end.rs` | server_dragon, end_podium, end_gateway | +| 32 | Bosses and the End (45) | `G/dragon.rs`, `G/wither.rs`, `G/end.rs` | server_dragon, forced_end, end_podium, end_gateway | | 33 | Protocol and packets (44) | `crates/horizon-protocol/src/` (`packets/play.rs`, `entity_data.rs`, `connection.rs`) | dedicated_server, online_mode, secure_chat; `cargo test -p horizon-protocol` | | 34 | Multiplayer and LAN screens, friends (44) | `L/multiplayer.rs`, `G/lan_screen.rs`, `G/friends.rs`, `L/friends_screen.rs`, `crates/horizon-friends/`, `crates/horizon-relay/` | lan, world_options; `python3 tools/test_friends.py` | | 35 | Dispensers (43) | `G/dispenser.rs`, `G/dispense_fixture.rs` (the harness side) | dispenser | | 36 | Audio and music (38) | `L/audio.rs`, `L/sound_engine.rs`, `L/sound_events.rs`, `L/music.rs`, `G/music.rs`, `L/ambience.rs`, `G/subtitle_hud.rs` | sound_engine, sound_event, music, situational_music, ambient_sound, subtitle | | 37 | Integrated server and levels (34) | `G/integrated.rs`, `G/levels.rs`, `G/server_travel.rs` | server_dimension_players, `lan_e2e` (server-thread by default; portals, levels, distance, lava) | -| 38 | Command parsing (34) | `L/command/` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`) | command_parse (corpus `tools/command_parse_corpus.py`) | +| 38 | Command parsing (34) | `C/` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`); `cargo test -p horizon-command` | command_parse (corpus `tools/command_parse_corpus.py`) | | 39 | Benchmarks and telemetry (34) | `L/benchmark.rs`, `tools/perf_bench.py`, `L/telemetry.rs`, `crates/horizon-telemetry*/`, `crates/horizon-bench/` | `python3 -m unittest tests.test_perf_bench`; [benchmark.md](benchmark.md) | | 40 | Explosions and TNT (31) | `G/explosion.rs`, `G/tnt.rs` | lan_e2e blast; no dedicated harness yet | diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index 1e9fb7722..a5c7b17fb 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -50,9 +50,11 @@ Start the client. horizon-launcher play +- `--instance`: The instance to play (its name or id; default: the selected one) - `--world`: Open or create this world (a folder under saves) at once - `--creative`: Creative mode for a new world - `--join`: Join a friend's world with its invite code +- `--server`: Join this server at once: an address, or a server of the list by name or position - `--arg`: An extra argument for the game, passed through as-is (repeatable), for example --server-thread MCP: `play`, then the `game_*` tools. @@ -151,6 +153,26 @@ Show or set the extra arguments the game starts with (for example --server-threa MCP: `game_args`. +## `horizon-launcher share-log` + +Upload an instance's latest.log to mclo.gs (a paste service for Minecraft logs) and print its link, for a bug report: only when the player asks. The home folder, the user name and the account names are taken out first; the link expires after 90 days unread. + + horizon-launcher share-log + +- `--instance`: The instance (default: the selected one) + +MCP: `share_log`, only when the player asks. + +## `horizon-launcher unshare-log` + +Delete a log shared with share-log: the ":" it printed. + + horizon-launcher unshare-log + +- `SHARED` + +MCP: `unshare_log`, needs `confirm: true`. + ## `horizon-launcher logs` Print the end of the game's log (logs/latest.log in the game folder), or its newest crash report. @@ -257,6 +279,292 @@ Upload a benchmark report (docs/benchmark-report.md); it is printed first. MCP: `data_benchmark`, only when the player asks. +## `horizon-launcher instance list` + +The instances, each with its game folder (* = the one Play starts). + + horizon-launcher instance list + +MCP: `instance_list`. + +## `horizon-launcher instance create` + +Make an instance: empty but for your options and name, or a copy of another one's worlds, options and packs. + + horizon-launcher instance create + +- `NAME` +- `--copy`: The instance to copy (its name or id) + +MCP: `instance_create`. + +## `horizon-launcher instance rename` + +Rename an instance (its folder stays). + + horizon-launcher instance rename + +- `INSTANCE` +- `NAME` + +MCP: `instance_rename`. + +## `horizon-launcher instance icon` + +Set an instance's icon: a block or item name from your prepared files (grass_block), a colour (#3fa7d6), or none. + + horizon-launcher instance icon + +- `INSTANCE` +- `ICON` + +MCP: `instance_icon`. + +## `horizon-launcher instance group` + +Put an instance in a sidebar group, or take it out with no group. + + horizon-launcher instance group [GROUP] + +- `INSTANCE` +- `GROUP` + +MCP: `instance_group`. + +## `horizon-launcher instance select` + +Make Play start this instance. + + horizon-launcher instance select + +- `INSTANCE` + +MCP: `instance_select`. + +## `horizon-launcher instance version` + +Keep an instance on one installed Horizon version, or "latest" to follow updates again. + + horizon-launcher instance version + +- `INSTANCE` + +MCP: `instance_version`. + +## `horizon-launcher instance export` + +Export an instance (or a port) to share: its settings, packs, Horizon mods and the worlds named, as a .mrpack (resource packs from Modrinth listed by download) or a zip. Never logs, screenshots or account data; worlds go without their per-player files. + + horizon-launcher instance export [INSTANCE] + +- `INSTANCE`: The instance (default: the selected one) +- `--format` (mrpack, zip) +- `--world`: A world to put in it (its name or folder); repeat for more +- `--out`: Where to write it (default: ".mrpack" in the current folder) + +MCP: `instance_export`. + +## `horizon-launcher instance import` + +Import what a file is, as dropping it on the window does: a shared instance (a .mrpack without mod loaders, such as `instance export` writes, or a game folder zip) becomes a new instance; a Java modpack goes to the Modpacks import; a resource or shader pack into the instance (default: the selected one). + + horizon-launcher instance import + +- `FILE` +- `--instance`: The instance a pack goes into + +MCP: `instance_import`. + +## `horizon-launcher worlds list` + +The worlds: name, mode, version, last played and size (the default). + + horizon-launcher worlds list + +- `--instance`: The instance (default: the selected one) + +MCP: `worlds_list`. + +## `horizon-launcher worlds backup` + +Zip a world into the instance's backups/ folder, as the game's Make Backup does. + + horizon-launcher worlds backup + +- `WORLD`: Its folder or name +- `--instance` + +MCP: `worlds_backup`. + +## `horizon-launcher worlds copy` + +Copy a world beside it, as " (1)". + + horizon-launcher worlds copy + +- `WORLD` +- `--instance` + +MCP: `worlds_copy`. + +## `horizon-launcher worlds delete` + +Move a world to the system's trash. + + horizon-launcher worlds delete + +- `WORLD` +- `--instance` + +MCP: `worlds_delete`, needs `confirm: true`. + +## `horizon-launcher worlds datapack-list` + +A world's data packs, and which are on. + + horizon-launcher worlds datapack-list + +- `WORLD` +- `--instance` + +MCP: `worlds_datapack_list`. + +## `horizon-launcher worlds datapack-add` + +Copy a data pack zip into a world (the game turns it on when the world opens). + + horizon-launcher worlds datapack-add + +- `WORLD` +- `FILE` +- `--instance` + +MCP: `worlds_datapack_add`. + +## `horizon-launcher worlds datapack-remove` + +Move a world's data pack to the system's trash. + + horizon-launcher worlds datapack-remove + +- `WORLD` +- `PACK`: Its file name, with or without .zip +- `--instance` + +MCP: `worlds_datapack_remove`, needs `confirm: true`. + +## `horizon-launcher packs list` + +The resource and shader packs, and which are on (the default). + + horizon-launcher packs list + +- `--kind` (resource, shader): Only this kind +- `--instance`: The instance (default: the selected one) + +MCP: `packs_list`. + +## `horizon-launcher packs add` + +Copy a pack file in: a resource pack .zip, a shader pack .zip or a .hshader. + + horizon-launcher packs add + +- `FILE` +- `--instance` + +MCP: `packs_add`. + +## `horizon-launcher packs on` + +Turn a pack on (a resource pack goes on top; a shader pack replaces the one that was on). + + horizon-launcher packs on + +- `PACK`: Its file name or title +- `--kind` (resource, shader) +- `--instance` + +MCP: `packs_on`. + +## `horizon-launcher packs off` + +Turn a pack off. + + horizon-launcher packs off + +- `PACK` +- `--kind` (resource, shader) +- `--instance` + +MCP: `packs_off`. + +## `horizon-launcher packs remove` + +Turn a pack off and move it to the system's trash. + + horizon-launcher packs remove + +- `PACK` +- `--kind` (resource, shader) +- `--instance` + +MCP: `packs_remove`, needs `confirm: true`. + +## `horizon-launcher screenshots list` + +The screenshots, the newest first, with their files (the default). + + horizon-launcher screenshots list + +- `--instance`: The instance (default: the selected one) + +MCP: `screenshots_list`. + +## `horizon-launcher screenshots delete` + +Move a screenshot to the system's trash. + + horizon-launcher screenshots delete + +- `SCREENSHOT`: Its file name, with or without .png +- `--instance` + +MCP: `screenshots_delete`, needs `confirm: true`. + +## `horizon-launcher multiplayer list` + +The servers of the game's Multiplayer screen (the default). + + horizon-launcher multiplayer list + +- `--instance`: The instance (default: the selected one) + +MCP: `multiplayer_list`. + +## `horizon-launcher multiplayer add` + +Add a server to the list. + + horizon-launcher multiplayer add
+ +- `ADDRESS`: Its address, as in the game's Add Server (host or host:port) +- `--name`: Its name in the list (default: Minecraft Server) +- `--instance` + +MCP: `multiplayer_add`. + +## `horizon-launcher multiplayer remove` + +Remove a server from the list: its position from 1, name or address. + + horizon-launcher multiplayer remove + +- `SERVER` +- `--instance` + +MCP: `multiplayer_remove`, needs `confirm: true`. + ## `horizon-launcher modpack list` The imported packs and their coverage (the default). @@ -308,10 +616,12 @@ MCP: `modpack_remove`, needs `confirm: true`. ## `horizon-launcher mods list` -What the browser installed (the default). +What the browser installed in an instance (the default). horizon-launcher mods list +- `--instance`: The instance (default: the selected one) + MCP: `mods_list`. ## `horizon-launcher mods search` @@ -321,7 +631,7 @@ Search for packs Horizon loads. horizon-launcher mods search [TEXT]... - `TEXT` -- `--kind` (mod, resource, modpack, shader) +- `--kind` (mod, resource, modpack, shader, datapack) - `--everything`: Also what was made for other versions or runs only partly, each marked - `--source` (modrinth, curseforge, horizon) @@ -341,11 +651,13 @@ MCP: `mods_check`. ## `horizon-launcher mods install` -Install a pack and what it needs, by its id or slug (checksums checked); a Java mod is ported into horizon-mods and turned on; a modpack is imported. +Install a pack and what it needs into an instance, by its id or slug (checksums checked); a Java mod is ported into horizon-mods and turned on; a modpack is imported as an instance of its own; a data pack goes into the world `--world` names. horizon-launcher mods install - `PROJECT` +- `--world`: Install the project's data pack into this world of the instance (its name or folder) +- `--instance`: The instance (default: the selected one) - `--everything`: Allow a version made for another Minecraft version - `--source` (modrinth, curseforge, horizon) @@ -359,6 +671,7 @@ Update what the browser installed (or one pack). - `PROJECT` - `--check`: Only say what is newer +- `--instance`: The instance (default: the selected one) MCP: `mods_update`. @@ -369,6 +682,7 @@ Remove a pack the browser installed. horizon-launcher mods remove - `PROJECT` +- `--instance`: The instance (default: the selected one) MCP: `mods_remove`, needs `confirm: true`. @@ -379,6 +693,7 @@ Turn on a mod the browser installed (horizon-mods.txt, as the game's Options > M horizon-launcher mods enable - `PROJECT` +- `--instance`: The instance (default: the selected one) MCP: `mods_enable`. @@ -389,6 +704,7 @@ Turn off a mod the browser installed; it stays installed. horizon-launcher mods disable - `PROJECT` +- `--instance`: The instance (default: the selected one) MCP: `mods_disable`. diff --git a/docs/mod-browser.md b/docs/mod-browser.md index dfdd1617d..8db26c26a 100644 --- a/docs/mod-browser.md +++ b/docs/mod-browser.md @@ -1,6 +1,6 @@ # The launcher's mod browser -Search Modrinth (CurseForge support is coming soon) for Java mods, modpacks and resource packs, and Horizon's +Search Modrinth (CurseForge support is coming soon) for Java mods, modpacks, resource packs and data packs, and Horizon's registry for Horizon's own mods, modpacks, resource packs and shader packs; see how well each one runs before installing it, and install it with its checksum checked. This is item 16 of the roadmap and issue #577. The code is in `launcher/src/browser.rs` and `launcher/src/browser/`. @@ -17,6 +17,12 @@ yet (Modrinth has no `horizon` loader). | Resource packs | `resourcepacks/` beside `options.txt` | **Works** when made for 26.3 ([resource-packs.md](resource-packs.md) lists what Horizon reads). Older packs are **Partly**: they load with vanilla's compatibility warning | | Modpacks (`.mrpack`, CurseForge zip) | the Modpacks page's import | **Partly**: Horizon runs the mods it can port, from the player's own downloads ([modpacks.md](modpacks.md)) | | Shader packs (`.hshader`, Horizon's registry only) | `shaderpacks/` beside `options.txt` | **Works** when made for 26.3: checked by the game's own check before install ([shaders.md](shaders.md)). The `shaders/`-format packs on Modrinth and CurseForge are not offered | +| Data packs (Modrinth) | `datapacks/` of the world picked on the **Data packs** tab (`mods install --world `); not in the Installed list: each world's list on Home has them | **Partly**: Horizon runs a data pack's functions, function tags, predicates and item modifiers, not yet its recipes, loot tables, advancements, other tags or worldgen. The install reads the zip and says what of it runs; a pack with none of those (worldgen only, such as Tectonic) is refused | + +Mods, resource packs and shader packs go into the game folder of the instance selected in the sidebar, and the +Installed list, updates and Remove are that instance's: picking another instance reads its list. The page says which +instance it installs into when there is more than one. The CLI's `mods list|install|update|remove|enable|disable` take +`--instance ` (default: the selected one). A modpack becomes an instance of its own. By default a search shows only what runs: Java mods made for 26.3, resource packs made for 26.3, and every modpack. **Show everything** lists the rest of the kind too, each marked with how well it runs; what doesn't run is never offered for install. @@ -82,7 +88,8 @@ downloads, source and licence, how well it runs (and why), **Page** (the project **Install** (**Import** for a modpack). The Modpacks tab lists the imported packs first, with their coverage report, **Port** and **Play** ([modpacks.md](modpacks.md)). Installed packs are listed above the results with their version, source, file and the checksum they were checked against, with **Update to …** when a newer version runs and **Remove** -(asked twice). +(asked twice). **Update all (N)** above the list updates every pack a newer version was found for, of every kind, +one after the other; one that fails is named and doesn't stop the others. ### Project pages, filters and icons @@ -130,6 +137,7 @@ same name the player put there is never overwritten. pack still has to be turned on in the game's Resource Packs screen, as in vanilla, and a shader pack picked in the game's Shader Packs page. - **Update** installs the newer version and removes the old file. +- **Update all** does the same for each pack with a newer version (`horizon-launcher mods update` with no pack name). - **Remove** deletes the file and its entry. Packs installed as dependencies stay. - **A modpack** is downloaded (checked the same way) into `ports/downloads/`, imported, and ported straight away for the selected version when it is prepared (`modpacks::import_and_port`): the jars of the mods Horizon can carry diff --git a/docs/mods.md b/docs/mods.md index 9765827a1..d2f76ac5a 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -488,7 +488,7 @@ its component targets the WIT world `horizon-server-mod` instead of | `tick(tick)` | each server tick | | `player-joined(player)`, `player-left(player)` | `registration.joins` | | `chat(player, text)` | `registration.chat`: each chat message a player sends | -| `command(player, name, args)` | `/name args` typed by a player, for a command it registered; `ok(some)` is that player's feedback, `err` their red error | +| `command(player, name, args, values)` | `/name args` typed by a player, for a command it registered, with its arguments' values (below); `ok(some)` is that player's feedback, `err` their red error | | `block-broken(player, pos, state)`, `block-placed(player, pos, state)` | `registration.blocks`, with the state as `minecraft:oak_log[axis=y]` | Capabilities that act on a local player (`game-read`, `chat`, `hud`) are for @@ -497,6 +497,31 @@ horizon_mod_sdk::server::ServerMod` and `export_server_mod!`; the example is [`welcome`](../crates/horizon-mod-sdk/examples/welcome/src/lib.rs), and with `world`, [`beacons`](../crates/horizon-mod-sdk/examples/beacons/src/lib.rs). +**Typed commands.** Each command in `registration.commands` lists its +arguments, in order: a name and a kind, required or optional (optional ones +last). The server adds them to the command tree every player receives, after +vanilla's commands, so a player's chat box completes and colours them as it +does vanilla's (player names, coordinates, bounds); when a player sends one, +the server parses the line the way vanilla's parsers do and gives the mod the +values, by argument name, or answers with vanilla's error (`Integer must not +be more than 64, found 65`, `No player was found`) without calling the mod. + +| Kind | Takes | Value | Chat box parser | +|---|---|---|---| +| `word` | one word: letters, digits, `_ - . +` | `word(string)` | `brigadier:string` (word) | +| `text` | the rest of the line, only last | `text(string)` | `brigadier:string` (greedy) | +| `integer(min, max)` | a whole number within the bounds given | `integer(s32)` | `brigadier:integer` | +| `number` | a number | `number(f64)` | `brigadier:double` | +| `boolean` | `true` or `false` | `boolean(bool)` | `brigadier:bool` | +| `player` | an online player's name, `@s` or `@p` (whoever typed it) | `player(player)` | `minecraft:entity` (one player) | +| `block-pos` | `x y z`, each a whole number, `~` or `~n` (from whoever typed it) | `block-pos(block-pos)` | `minecraft:block_pos` | + +A command with no arguments takes nothing after its name. In Rust, +`Registration::command_with("beacon", [Argument::integer("height", Some(1), +Some(64)).optional()])`, read with `args.integer("height")`; `command(name)` +alone takes free text, an optional `text` argument named `args` +(`args.text()` is the line as typed either way). + **Capability `world`.** Reads are of the server's loaded chunks as they are during the call: the game lends a server mod's call the levels' chunk maps (moved, not copied, and only while a running mod has `world`), so a read @@ -537,10 +562,11 @@ chat for the in-frame player and a system message for a connection; on, each of these points costs one branch (measured in the PR that added them). -**Not yet.** Clients aren't sent server mods' commands with vanilla's -command tree, so a player's chat box doesn't complete or colour them; typing -them works. Block events are a player's own breaking and placing, not -explosions, pistons or other mods. +**Not yet.** Block events are a player's own breaking and placing, not +explosions, pistons or other mods. Command arguments don't take entities, +items or block states yet, and `^` coordinates; in-frame single player's chat +box lists server mods' commands by name only (the server still parses their +arguments). ## Publish your mod diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index 50b67c571..73ac5c47c 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -40,13 +40,13 @@ The game logs into `HORIZON_HOME` and falls back to the player's own game folder ### Other machines -Harnesses can also run on the Mac mini, the desktop and playhorizon (`tools/parity_hosts.json` describes them; `desktop` and `playhorizon` use their CI runner's environment and vanilla data, and the desktop refuses work, or stops it, while someone uses it: docs/release-flow.md, "The desktop's runner"; its `default` list is empty, so pass `--hosts macmini,playhorizon` or set `PARITY_HOSTS`, after copying `shared-local/` to `~/code/horizon-parity/shared-local` on each host). The runner mirrors the worktree there with rsync (not `.git`, `.local`, `target` or ignored files) into `~/code/horizon-parity/remote/`, whose `.local` links to the vanilla data in `~/code/horizon-parity/shared-local`, and starts `tools/parity.py --worker` over ssh. The worker builds the probes (about 80 s the first time) and runs what it is sent under the same tracer, admitting harnesses against its own free memory. One queue, longest first, feeds every machine, remote ones first: the Mac takes up to 14 harnesses, the desktop 8, playhorizon 6. Each pass comes back with the content hash of every file it depended on, so it is keyed on exactly what ran, and logs come back to `.local/parity-runner/logs/`; state, sharing and `gate.py` work as before. If a host can't be reached, or drops out, its harnesses run here. +Harnesses can also run on the Mac mini, the desktop and playhorizon (`tools/parity_hosts.json` describes them; `desktop` and `playhorizon` use their CI runner's environment and vanilla data, and the desktop refuses work, or stops it, while someone uses it: docs/release-flow.md, "The desktop's runner"; its `default` list is empty, so pass `--hosts macmini,playhorizon` or set `PARITY_HOSTS`, after copying `shared-local/` to `~/code/horizon-parity/shared-local` on each host). The runner mirrors the worktree there with rsync (not `.git`, `.local`, `target` or ignored files) into `~/code/horizon-parity/remote/`, whose `.local` links to the vanilla data in `~/code/horizon-parity/shared-local`, and starts `tools/parity.py --worker` over ssh. The worker builds the probes (about 80 s the first time) and runs what it is sent under the same tracer, admitting harnesses against its own free memory. One queue, longest first, feeds every machine, remote ones first: the Mac takes up to 14 harnesses, the desktop 8, playhorizon 3 (on CPUs 0-3: its CI runner has 4-7). Each pass comes back with the content hash of every file it depended on, so it is keyed on exactly what ran, and logs come back to `.local/parity-runner/logs/`; state, sharing and `gate.py` work as before. If a host can't be reached, or drops out, its harnesses run here. Harnesses a host can't run are listed in the file: `local_only` (`save_roundtrip` runs the game on a virtual screen) and each host's `exclude`. The Mac excludes nothing: vanilla's `Math.sin`, `pow`, `log` and the like don't round the same on an Apple silicon Mac as on Linux (HotSpot uses fdlibm there, Intel's stubs on x86-64), and Rust's float functions round like neither (they call the platform libm), so code that mirrors a vanilla `Math` call uses `horizon_core::jmath`, which computes what HotSpot computes on the host architecture. The ThinkPad no longer runs harnesses (2026-10-26): playhorizon is the Linux host that is always on. ### Any command on playhorizon: `tools/remote.sh` -For Linux work that doesn't need a whole parity run (a crate's tests, a few harnesses, a server build), `tools/remote.sh ` runs the command on playhorizon at the worktree's commit and streams its output back; its exit status is the command's. Commit and push first: the host fetches the commit from GitHub, and nothing else leaves this machine (no files, no credentials, no environment). Each worktree keeps one checkout there, `~/remote-work/` with its own `target/`, so the next run only rebuilds what changed, and one run per name goes at a time. The command runs niced in the host's CI slice, pinned to CPUs 4-7 (`--cpus`; 0-3 stay free for benchmarks), with scratch game and launcher homes and the vanilla data linked as CI links it; a command naming `parity`, `lan_e2e` or `horizon-prepare` also gets `.local/horizon-client`, prepared as CI prepares it. Whatever the command leaves running (a game, a daemon) is stopped when it ends, and stopping `remote.sh` (or losing the connection) stops the command on the host. Logs stay in `~/remote-work/.logs/`; `--list` shows the checkouts, `--gc [DAYS]` removes old ones. +For Linux work that doesn't need a whole parity run (a crate's tests, a few harnesses, a server build), `tools/remote.sh ` runs the command on playhorizon at the worktree's commit and streams its output back; its exit status is the command's. Commit and push first: the host fetches the commit from GitHub, and nothing else leaves this machine (no files, no credentials, no environment). Each worktree keeps one checkout there, `~/remote-work/` with its own `target/`, so the next run only rebuilds what changed, and one run per name goes at a time. The command runs niced in the host's CI slice, pinned to CPUs 0-3 (`--cpus`): the CI runner has 4-7, so these runs never slow a pull request's parity job. A benchmark asks for its CPUs with `--cpus 0-3 --exclusive` (and says so in its pull request): it starts only when no other run uses them, and later runs wait for it to end. The command gets scratch game and launcher homes and the vanilla data linked as CI links it; a command naming `parity`, `lan_e2e` or `horizon-prepare` also gets `.local/horizon-client`, prepared as CI prepares it. Whatever the command leaves running (a game, a daemon) is stopped when it ends, and stopping `remote.sh` (or losing the connection) stops the command on the host. Logs stay in `~/remote-work/.logs/`; `--list` shows the checkouts, `--gc [DAYS]` removes old ones. ```sh tools/remote.sh .claude/worktrees/my-fix cargo test -p horizon-world --lib # 33 s, warm @@ -64,7 +64,7 @@ A harness can declare, at the top level of its script: ### Which harnesses a change affects -`--changed` and `--changed-files` narrow each harness's Rust sources to those its probes can reach (`tools/parity_reach.py`), so a change to one module of `horizon-client` no longer reruns every harness whose probe links the crate. The narrowing works on items, not files: from the probe modules a harness ran (or the binary it built), a free item (fn, type, const, static) is reached when a reached item names it in its own module, through a path or an import of a module that is named, or through a glob import; an inherent impl's methods count one by one once their type is reached and their name is mentioned; a trait impl counts once its trait and its type are reached (std's traits and types always are); a macro counts once invoked. Names match by spelling, so the result only over-approximates. A reached file's parent modules count through their `mod` declarations of it, compared with the merge base; Rust files a change adds take part, a dependency that was deleted counts as changed, code under `#[cfg(test)]` never counts, and a harness whose probe can't be found keeps every source. Parses are cached by content in `reach-cache.json` of the shared parity folder (beside `passes/`), so a new worktree starts warm; a harness's search stops as soon as it reaches a changed file, and after `PARITY_REACH_BUDGET` seconds (default 180) the remaining harnesses count every source their probes link, so choosing never holds a slow machine for long. `--by-crate` turns the narrowing off. On the last 20 pull requests merged on 2026-10-25, the harnesses picked went from 2255 to 1061 (2384 to 1592 harness-minutes; game-binary harnesses, which link all of `game/`, set the floor), and every harness a CI parity run failed in the week before was still picked; every source file a sample of probes executed (LLVM `-C instrument-coverage`) is among those kept. Building the graph takes 15 s cold, under a second warm, and up to a minute and a half on a change that reaches many harnesses. +`--changed` and `--changed-files` narrow each harness's Rust sources to those its probes can reach (`tools/parity_reach.py`), so a change to one module of `horizon-client` no longer reruns every harness whose probe links the crate. The narrowing works on items, not files: from the probe modules a harness ran (or the binary it built), a free item (fn, type, const, static) is reached when a reached item names it in its own module, through a path or an import of a module that is named, or through a glob import; an inherent impl's methods count one by one once their type is reached and their name is mentioned; a trait impl counts once its trait and its type are reached (std's traits and types always are); a macro counts once invoked. Names match by spelling, so the result only over-approximates. A reached file's parent modules count through their `mod` declarations of it, compared with the merge base; Rust files a change adds take part, a dependency that was deleted counts as changed, code under `#[cfg(test)]` never counts, and a harness whose probe can't be found keeps every source. Parses are cached by content in `reach-cache.json` of the shared parity folder (beside `passes/`), so a new worktree starts warm; a harness's search stops as soon as it reaches a changed file, and after `PARITY_REACH_BUDGET` seconds (default 180) the remaining harnesses count every source their probes link, so choosing never holds a slow machine for long. `--by-crate` turns the narrowing off. With `--changed`, `Cargo.lock` and `Cargo.toml` changes that only add, remove or move workspace crates (a crate split: no registry or git package, version, feature, dependency or build setting changed across them, compared with the merge base) don't count: the moved code counts through its sources. A workspace crate's feature that such a change defines or turns on is allowed only where every source naming it changed too (the new crate's own files). #2160's split went from 352 harnesses to 123 this way (its own changes to the runner still select them all). On the last 20 pull requests merged on 2026-10-25, the harnesses picked went from 2255 to 1061 (2384 to 1592 harness-minutes; game-binary harnesses, which link all of `game/`, set the floor), and every harness a CI parity run failed in the week before was still picked; every source file a sample of probes executed (LLVM `-C instrument-coverage`) is among those kept. Building the graph takes 15 s cold, under a second warm, and up to a minute and a half on a change that reaches many harnesses. ## The gate diff --git a/docs/release-flow.md b/docs/release-flow.md index ed7be2418..be0ccbee8 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -108,12 +108,12 @@ and its failures bisect and comment on merges. AMD EPYC threads, 30 GB, in Detroit; reachable only through the maintainer's tailnet). Nobody sits at it, so the watcher never pauses it except by hand. It gets half the machine: `RUNNER_MEMORY=24`, `CARGO_BUILD_JOBS` and the harness slots at 4, and a drop-in (`~/.config/systemd/user/horizon-runner.service.d/cpus.conf`) that starts it under -`taskset -c 4-7`, so CPUs 0-3 stay free for benchmarks pinned there (the user slice can't set `AllowedCPUs`: systemd -doesn't delegate the cpuset controller to it). +`taskset -c 4-7` (the user slice can't set `AllowedCPUs`: systemd doesn't delegate the cpuset controller to it). +Agents' `tools/remote.sh` runs and benchmarks share CPUs 0-3, so they never slow a pull request's job. Without Nix, `linux-runner.sh` takes the build libraries, the JDK, sccache, Xvfb and Mesa's software Vulkan (lavapipe; there is no GPU) from apt, and Python 3.13 from uv. The partner can reach the machine, so gh is not logged in there: the registration token comes from another machine (`RUNNER_TOKEN`), and no job with secrets may -run there (parity has none). It is also a parity host (`playhorizon` in `tools/parity_hosts.json`, 6 jobs). Since +run there (parity has none). It is also a parity host (`playhorizon` in `tools/parity_hosts.json`, 3 jobs on CPUs 0-3). Since 2026-10-26 it has the `horizon-game` label: pull requests' parity jobs run there or on the Mac mini, and `full-parity` ones only there. @@ -432,6 +432,9 @@ Releases ship often, so nothing they leave behind may grow without bound. (`~/.actions-runners/runner-gc.sh`, plist `dev.horizon.runner-gc`), never from a pull request's checkout. It skips a runner in a job, removes a checkout's cargo build folders past 12 GB (`MAX_TARGET_GB`) and harness work folders under `.local/` untouched for 3 days (`STALE_DAYS`), and keeps the 2 newest shared preparations (`KEEP_PREPARED`) - while no runner works. Runner builds go through the machine's sccache (`tools/ci/runner-env.sh`), so what it removes + while no runner works. It also stops harness JVMs (vanilla servers, oracles) left orphaned for 3 hours + (`ORPHAN_HOURS`): parent gone, command line under a runner's checkout or a worktree's `.local/`. `tools/parity.py` + stops its own harnesses on SIGTERM and SIGHUP (a cancelled job), so these come only from a SIGKILL or a harness run + by hand. Runner builds go through the machine's sccache (`tools/ci/runner-env.sh`), so what it removes comes back from the cache. Update the copy after changing the script: `ssh macmini 'curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/tools/ci/runner-gc.sh -o ~/.actions-runners/runner-gc.sh'`. diff --git a/docs/version-ports.md b/docs/version-ports.md index 623e3c082..4ecad210f 100644 --- a/docs/version-ports.md +++ b/docs/version-ports.md @@ -43,7 +43,7 @@ to players. Players still prepare their own copy from their official launcher (` | `crates/horizon-client/src/lan/tracking.rs` | `generate_entity_tracking.py` | decompiled `EntityTypes` | | `crates/horizon-client/src/lan/command_suggestions.rs` | `generate_command_suggestions.py` | `VanillaCommandSuggestionsExporter` | | `crates/horizon-client/src/lan/command_order.rs` | `generate_lan_command_order.py` | vanilla's command tree | - | `crates/horizon-client/src/command/vanilla_order.rs` | `generate_command_order.py` | command-parse harness export | + | `crates/horizon-command/src/vanilla_order.rs` | `generate_command_order.py` | command-parse harness export | | `crates/horizon-world/src/datafix/block_state_data.txt` | `gen_block_state_data.py` | decompiled `BlockStateData` | | `crates/horizon-world/src/datafix/flat_tables.rs` | `gen_flat_tables.py` | 1.13 flattening fixers (never change) | diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock index dd9313df6..422c2ace9 100644 --- a/launcher/Cargo.lock +++ b/launcher/Cargo.lock @@ -70,6 +70,15 @@ dependencies = [ "equator", ] +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + [[package]] name = "anstream" version = "1.0.0" @@ -919,6 +928,17 @@ dependencies = [ "zeroize", ] +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link 0.2.1", +] + [[package]] name = "cipher" version = "0.4.4" @@ -981,6 +1001,15 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" +[[package]] +name = "cobs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "cocoa" version = "0.25.0" @@ -1635,6 +1664,18 @@ dependencies = [ "winreg", ] +[[package]] +name = "embedded-io" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced" + +[[package]] +name = "embedded-io" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" + [[package]] name = "encoding_rs" version = "0.8.42" @@ -2354,7 +2395,7 @@ dependencies = [ "wayland-protocols-plasma", "windows 0.61.3", "windows-core 0.61.2", - "windows-numerics", + "windows-numerics 0.2.0", "windows-registry 0.5.3", "x11-clipboard", "x11rb", @@ -2693,6 +2734,8 @@ dependencies = [ name = "horizon-launcher" version = "0.2.0" dependencies = [ + "base64", + "chrono", "clap", "dirs 5.0.1", "flate2", @@ -2708,6 +2751,7 @@ dependencies = [ "horizon-release-sign", "horizon-telemetry", "horizon-theme", + "horizon-world", "image", "keyring", "objc2-app-kit", @@ -2720,6 +2764,8 @@ dependencies = [ "sha1", "sha2 0.10.9", "tar", + "toml 1.1.8+spec-1.1.0", + "trash", "ureq", "winresource", "zip", @@ -2801,6 +2847,21 @@ dependencies = [ name = "horizon-theme" version = "0.1.0" +[[package]] +name = "horizon-world" +version = "0.1.0" +dependencies = [ + "flate2", + "horizon-core", + "libm", + "lz4_flex", + "postcard", + "serde", + "serde_json", + "sha2 0.10.9", + "xxhash-rust", +] + [[package]] name = "http" version = "1.5.0" @@ -2907,6 +2968,30 @@ dependencies = [ "tracing", ] +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core 0.61.2", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + [[package]] name = "icu_collections" version = "2.3.0" @@ -3425,6 +3510,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "lz4_flex" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecbdfe44b1bd960b68170b417450a628c43f7cf56bb3c5317e61cb230ee7f226" + [[package]] name = "mac" version = "0.1.1" @@ -4263,6 +4354,18 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "postcard" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" +dependencies = [ + "cobs", + "embedded-io 0.4.0", + "embedded-io 0.6.1", + "serde", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -6187,6 +6290,24 @@ dependencies = [ "once_cell", ] +[[package]] +name = "trash" +version = "5.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be89b3fe156965d29ac4f8522f3a640c655affdd9f21cb4f36857f0c92c00317" +dependencies = [ + "chrono", + "libc", + "log", + "objc2", + "objc2-foundation", + "once_cell", + "percent-encoding", + "scopeguard", + "urlencoding", + "windows 0.62.2", +] + [[package]] name = "try-lock" version = "0.2.5" @@ -6367,6 +6488,12 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "urlencoding" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + [[package]] name = "usvg" version = "0.45.1" @@ -6820,11 +6947,23 @@ version = "0.61.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" dependencies = [ - "windows-collections", + "windows-collections 0.2.0", "windows-core 0.61.2", - "windows-future", + "windows-future 0.2.1", "windows-link 0.1.3", - "windows-numerics", + "windows-numerics 0.2.0", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections 0.3.2", + "windows-core 0.62.2", + "windows-future 0.3.2", + "windows-numerics 0.3.1", ] [[package]] @@ -6837,7 +6976,7 @@ dependencies = [ "rayon", "thiserror 2.0.21", "windows 0.61.3", - "windows-future", + "windows-future 0.2.1", ] [[package]] @@ -6849,6 +6988,15 @@ dependencies = [ "windows-core 0.61.2", ] +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core 0.62.2", +] + [[package]] name = "windows-core" version = "0.57.0" @@ -6874,6 +7022,19 @@ dependencies = [ "windows-strings 0.4.2", ] +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement 0.60.2", + "windows-interface 0.59.3", + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + [[package]] name = "windows-future" version = "0.2.1" @@ -6882,7 +7043,18 @@ checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" dependencies = [ "windows-core 0.61.2", "windows-link 0.1.3", - "windows-threading", + "windows-threading 0.1.0", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core 0.62.2", + "windows-link 0.2.1", + "windows-threading 0.2.1", ] [[package]] @@ -6951,6 +7123,16 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core 0.62.2", + "windows-link 0.2.1", +] + [[package]] name = "windows-registry" version = "0.4.0" @@ -6991,6 +7173,15 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link 0.2.1", +] + [[package]] name = "windows-strings" version = "0.3.1" @@ -7009,6 +7200,15 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link 0.2.1", +] + [[package]] name = "windows-sys" version = "0.48.0" @@ -7111,6 +7311,15 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link 0.2.1", +] + [[package]] name = "windows_aarch64_gnullvm" version = "0.48.5" @@ -7423,6 +7632,12 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" +[[package]] +name = "xxhash-rust" +version = "0.8.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7" + [[package]] name = "y4m" version = "0.8.0" diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml index a97f128b8..356e8ae2e 100644 --- a/launcher/Cargo.toml +++ b/launcher/Cargo.toml @@ -19,6 +19,7 @@ sha2 = "0.10" pulldown-cmark = { version = "0.12", default-features = false } flate2 = "1" tar = { version = "0.4", default-features = false } +toml = "1.1" zip = { version = "2", default-features = false, features = ["deflate"] } dirs = "5" self-replace = "1" @@ -37,6 +38,13 @@ horizon-mods = { path = "../crates/horizon-mods", features = ["index"] } horizon-release-sign = { path = "../crates/horizon-release-sign" } # Opt-in data collection: the consent, the outbox and its upload (docs/telemetry.md). horizon-telemetry = { path = "../crates/horizon-telemetry" } +# level.dat and servers.dat (the worlds and server lists of instances) +horizon-world = { path = "../crates/horizon-world" } +# Deleting a world moves it to the system's trash +trash = "5" +# Backup names carry the local time, as vanilla's do +base64 = "0.22" +chrono = { version = "0.4", default-features = false, features = ["clock"] } # The session file's random name. getrandom = "0.3" # Players' heads on the Servers page, from the default skins in the player's own game files (already diff --git a/launcher/README.md b/launcher/README.md index 9c6f3a9d9..6077e6a80 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -28,8 +28,8 @@ The opening, then Play ([clip](docs/opening.webm)): packs and modpacks, each marked Works, Partly or Doesn't run in Horizon; Java mod jars are never offered. Install puts a pack and what it needs in `resourcepacks/` only after its SHA-512 matches, and a - modpack goes to the Modpacks page; installed packs show their source and checksum, with Update - and Remove ([docs/mod-browser.md](../docs/mod-browser.md)). + modpack goes to the Modpacks page; installed packs show their source and checksum, with Update, + **Update all** and Remove ([docs/mod-browser.md](../docs/mod-browser.md)). - **Modpacks**: import a Java modpack (a Modrinth `.mrpack`, a CurseForge zip, or a Prism, MultiMC or CurseForge instance folder) and see its coverage report: per mod, ported, partial, not yet or not needed, with the reason ([docs/modpacks.md](../docs/modpacks.md)). **Port** @@ -69,6 +69,74 @@ The opening, then Play ([clip](docs/opening.webm)): access controls, one click changes them so friends you share with reach only the server's port (Remove the limit undoes it); custom access controls are never rewritten, the page gives the rule to add instead. Horizon never turns on Funnel. +- **Instances**: separate game folders, each with its own worlds, options and packs. The game's + folder stays the first one, "Horizon", exactly where it was; imported and registry modpacks are + instances too, in their own folders as before; new ones go to `instances//` in the game's + folder, empty but for the player's options and name, or a copy of another instance (never its + sign-in sessions, logs or data collection state). Names, icons (a block or item texture from the + player's prepared files, or a colour) and groups are kept in `instances.json` in the launcher's + data folder, so renaming moves nothing. Every instance follows the launcher's data collection + answer and No AI. In the window, **+** beside Instances makes one, the sidebar lists them by + group (click one to play it), and Home's Instance row has Edit (name, group, icon), Copy and + Open folder. The Instance row shows its play time and when it was last played: every run started + from the window or `horizon-launcher play` adds to it (`instance list` shows it too). Each + instance plays the launcher's version, which follows updates, unless the Play page's version + picker keeps it on another installed one (to keep an old world on the version it was made + with); picking the version marked "follows updates" lets it follow again. +- **Export**: Home's Instance row has **Export…**: the selected instance (or a port) as a `.mrpack` + (Modrinth's modpack format: resource packs the browser installed from Modrinth are listed by + their download, the rest is in `overrides/`) or a `.zip` of the game folder's layout, with the + worlds switched on. It is written to `exports/` in the launcher's data folder (**Show in + folder**). Only settings (options.txt, horizon-*.txt, servers.dat), resource and shader packs, + `horizon-mods/` and `config/` go in: never logs, screenshots, backups, caches or account files; + a world goes without `playerdata/`, `stats/` and `advancements/`, and its level.dat without the + player's UUID. `horizon-launcher instance export [] [--format mrpack|zip] [--world + ]… [--out ]`. +- **Import by dropping a file**: a file dropped anywhere on the window is imported for what it is + (`horizon_launcher::import`). A shared instance (a `.mrpack` that needs no mod loader, such as + Export writes, or a game folder `.zip`) becomes a new instance, opened on Home. Its `.mrpack` + downloads come from Modrinth with their SHA-512 checked, and only what an instance keeps is + taken, inside its folder. A Java modpack goes to the Modpacks import, and a resource or shader + pack into the selected instance. A data pack is pointed at the world rows, and the Packs section + and the world rows keep taking their own drops. A note in the corner says what happened. + `horizon-launcher instance import `. +- **Console**: Home's Console shows the game's output of this run as it comes: a search (every + word, any case), Follow to keep the newest line in view, Copy, and Open logs folder. Warnings + and errors stand out. **Share log…** uploads the log to [mclo.gs](https://mclo.gs), a paste + service for Minecraft logs, only after the player confirms; the home folder, the user name and + the account names are taken out first (`horizon_launcher::game_log`), and **Delete it** removes + the paste. `horizon-launcher share-log [--instance]` and `unshare-log `; + `HORIZON_LAUNCHER_PASTE_URL` points it at a test server. +- **Worlds**: Home lists the selected instance's worlds (picture, mode, version, last played, + size). **Back up** zips one into the instance's `backups/` as the game's Make Backup does + (`_