diff --git a/crates/horizon-client-core/src/component.rs b/crates/horizon-client-core/src/component.rs index 5b828b305..afb68fa98 100644 --- a/crates/horizon-client-core/src/component.rs +++ b/crates/horizon-client-core/src/component.rs @@ -173,6 +173,22 @@ fn object_style(o: &serde_json::Map) -> Style { if let Some(e) = o.get("click_event").and_then(Value::as_object) { let text = |k: &str| e.get(k).and_then(Value::as_str).map(str::to_owned); style.click = match e.get("action").and_then(Value::as_str) { + // ClickEvent.OpenUrl.CODEC: ExtraCodecs.UNTRUSTED_URI allows http and + // https only, the scheme in any case (Util.parseAndValidateUntrustedUri). + Some("open_url") => text("url") + .filter(|u| { + u.split_once(':').is_some_and(|(scheme, _)| { + scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https") + }) + }) + .map(crate::text::ClickEvent::OpenUrl), + // ClickEvent.ChangePage.CODEC: ExtraCodecs.POSITIVE_INT. + Some("change_page") => e + .get("page") + .and_then(Value::as_i64) + .and_then(|p| i32::try_from(p).ok()) + .filter(|p| *p >= 1) + .map(crate::text::ClickEvent::ChangePage), Some("suggest_command") => text("command").map(crate::text::ClickEvent::SuggestCommand), Some("copy_to_clipboard") => { text("value").map(crate::text::ClickEvent::CopyToClipboard) diff --git a/crates/horizon-client-core/src/text.rs b/crates/horizon-client-core/src/text.rs index 0a2b6eadb..3a0bf301b 100644 --- a/crates/horizon-client-core/src/text.rs +++ b/crates/horizon-client-core/src/text.rs @@ -42,6 +42,10 @@ pub fn named_color(name: &str) -> Option { /// Click actions carried by locally constructed text components. #[derive(Clone, Debug, PartialEq, Eq)] pub enum ClickEvent { + /// `ClickEvent.OpenUrl`: an http or https link. + OpenUrl(String), + /// `ClickEvent.ChangePage`: a book's page, counted from 1. + ChangePage(i32), SuggestCommand(String), CopyToClipboard(String), /// A local file to open with the system handler. @@ -529,6 +533,8 @@ fn style_json(style: &Style) -> Vec<(String, Value)> { } if let Some(click) = &style.click { let event = match click { + ClickEvent::OpenUrl(url) => json!({ "action": "open_url", "url": url }), + ClickEvent::ChangePage(page) => json!({ "action": "change_page", "page": page }), ClickEvent::SuggestCommand(command) => { json!({ "action": "suggest_command", "command": command }) } diff --git a/crates/horizon-client/examples/probe/mob_ai_probe.rs b/crates/horizon-client/examples/probe/mob_ai_probe.rs index 94578ea38..07f2bf22a 100644 --- a/crates/horizon-client/examples/probe/mob_ai_probe.rs +++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs @@ -1072,6 +1072,8 @@ pub fn main() -> horizon_client::Result<()> { for (i, m) in mobs.iter().enumerate() { print(&mut out, 0, i, m, s.creative, world.game_time); } + // No player has a chest open in the scenarios. + let lid_openers = std::collections::HashMap::new(); // The MobWorld every step sees, over a snapshot of the mobs. macro_rules! mob_world { ($snapshot:expr) => { @@ -1108,6 +1110,7 @@ pub fn main() -> horizon_client::Result<()> { // FlatLevelSource.getSeaLevel. sea_level: -63, items: Some(&items), + lid_openers: &lid_openers, } }; } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index ced3d3903..03c53a05b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1283,6 +1283,8 @@ struct Game<'a> { pending_pack_reload: bool, /// A server's resource packs (game/server_packs.rs). server_packs: server_packs::ServerPackState, + /// The link a chat click asks to open (`ConfirmLinkScreen`). + link_prompt: Option, dialogs: dialogs::DialogState, world_renderer_ready: bool, collision: &'a BlockCollisionRegistry<'a>, @@ -5069,9 +5071,14 @@ impl Game<'_> { if let Some(host) = &self.lan { host.hub.entity_event(host.host_entity, 3, feet); } - self.screen = Screen::Dead; - self.capture(false); - self.ui.death_time = 0; + if self.ui.rules.bool("immediate_respawn") { + // Gui.setScreen: without the death screen the player respawns at once. + self.respawn_player()?; + } else { + self.screen = Screen::Dead; + self.capture(false); + self.ui.death_time = 0; + } } else if dead { // LivingEntity.tickDeath: 20 ticks after dying the player is // removed, and Player.remove's inventoryMenu.removed drops what @@ -5555,6 +5562,7 @@ impl Game<'_> { }; self.draw_dialog(&mut batch); self.draw_pack_prompt(&mut batch); + self.draw_link_prompt(&mut batch); // Gui.extractRenderState: the debug overlay comes after the screen // and the toasts, so it is over everything, menus included. self.draw_debug_overlay(&mut batch, size); @@ -5616,7 +5624,11 @@ impl Game<'_> { let delay = horizon_client::attack_strength::delay(self.main_hand_attack_speed()); let strength = self.hand_strength.scale(0.0, self.main_hand_attack_speed()); // The 3D crosshair (F3) takes the 2D one's place. - if self.camera_type.first_person() && !spectator && !self.debug_crosshair() { + // Hud.extractCrosshair: a spectator only sees it over something to open. + if self.camera_type.first_person() + && (!spectator || self.spectator_crosshair()) + && !self.debug_crosshair() + { let attack = (indicator == 1).then_some(strength); let full = attack.is_some_and(|a| { hud_layout::full_attack_indicator(a, delay, self.crosshair_living()) @@ -12351,6 +12363,11 @@ impl ApplicationHandler for Game<'_> { self.advancements_scroll(scaled(raw_x) as f32, d); } } + WindowEvent::MouseInput { state, button, .. } if self.link_prompt.is_some() => { + if state == ElementState::Pressed && button == MouseButton::Left { + self.link_prompt_click(); + } + } WindowEvent::MouseInput { state, button, .. } if self.server_packs.prompt.is_some() => { @@ -12580,6 +12597,13 @@ impl ApplicationHandler for Game<'_> { } } // ConfirmScreen.keyPressed: Escape answers no. + WindowEvent::KeyboardInput { event, .. } if self.link_prompt.is_some() => { + if event.state == ElementState::Pressed + && event.physical_key == PhysicalKey::Code(KeyCode::Escape) + { + self.answer_link_prompt(false); + } + } WindowEvent::KeyboardInput { event, .. } if self.server_packs.prompt.is_some() => { if event.state == ElementState::Pressed && event.physical_key == PhysicalKey::Code(KeyCode::Escape) @@ -13113,6 +13137,7 @@ impl<'a> Game<'a> { world_loader: None, pending_pack_reload: false, server_packs: Default::default(), + link_prompt: None, dialogs: Default::default(), world_renderer_ready: false, collision: res.collision(), diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index b09803e49..ddbe47481 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -8,7 +8,7 @@ use horizon_client::{ containers::{BlockEntity, Lectern}, first_person::Hand, hud::{HudBatch, rgba}, - item_data::WrittenBook, + item_data::{StackData, WrittenBook}, items::ItemStack, menu::{Kind, Menu}, text::Text, @@ -59,14 +59,86 @@ pub(super) enum BookScreen { page_edit: ui::EditBox, }, View { - pages: Vec, + pages: Vec, page: usize, lectern: Option<(i32, i32, i32)>, }, } +/// The pages a book screen reads: a written book's components (so their +/// click events stay), else a writable book's text. +fn view_pages(data: Option<&StackData>) -> Vec { + let Some(data) = data else { return Vec::new() }; + let Some(w) = &data.written else { + return data.writable_pages.iter().map(Text::literal).collect(); + }; + let tagged = w.page_tags.len() == w.pages.len(); + w.pages + .iter() + .enumerate() + .map(|(i, page)| match tagged.then(|| &w.page_tags[i]) { + Some(tag @ horizon_world::nbt::Tag::Compound(_)) => { + horizon_client::entity_nbt::name_text(tag) + } + _ => Text::literal(page), + }) + .collect() +} impl Game<'_> { fn book_lines(&self, page: &str) -> Vec { - self.gui.atlas.font.split(&Text::literal(page), 114.0) + self.page_lines(&Text::literal(page)) + } + fn page_lines(&self, page: &Text) -> Vec { + self.gui.atlas.font.split(page, 114.0) + } + /// `BookViewScreen.mouseClicked`: the click event of the text under the + /// cursor on the page. + fn book_link_at(&self, page: &Text, left: f32) -> Option { + let (mx, my) = self.cursor; + let row = ((my - 32.0) / 9.0).floor(); + if row < 0.0 || row >= LINES as f32 { + return None; + } + let lines = self.page_lines(page); + let line = lines.get(row as usize)?.resolve_legacy(); + let mut x = mx - (left + 36.0); + if x < 0.0 { + return None; + } + for (c, style) in line.chars() { + x -= self.gui.atlas.font.advance(c, style); + if x < 0.0 { + return style.click.clone(); + } + } + None + } + /// `BookViewScreen.handleClickEvent`: a page link turns to its page + /// (`forcePage`), a web link goes through the confirm-link flow. + fn book_follow_link( + &mut self, + link: horizon_client::text::ClickEvent, + count: usize, + lectern: Option<(i32, i32, i32)>, + ) { + use horizon_client::text::ClickEvent; + match link { + ClickEvent::ChangePage(target) => { + let target = (target - 1).clamp(0, count.saturating_sub(1) as i32); + let Some(BookScreen::View { page, .. }) = self.book.as_mut() else { + return; + }; + if let Some(key) = lectern { + // LecternScreen.forcePage: the menu's button 100 + page. + if target != *page as i32 { + self.lectern_button(key, 100 + target); + } + } else if target != *page as i32 { + *page = target as usize; + } + } + ClickEvent::OpenUrl(url) => self.click_url(url), + _ => {} + } } /// `WritableBookItem.use` / `WrittenBookItem.use` (`Player.openItemGui`). /// A server's player writes in its own client's editor @@ -115,11 +187,7 @@ impl Game<'_> { } } "minecraft:written_book" => BookScreen::View { - pages: stack - .data() - .and_then(|d| d.written.as_ref()) - .map(|w| w.pages.clone()) - .unwrap_or_default(), + pages: view_pages(stack.data()), page: 0, lectern: None, }, @@ -215,6 +283,7 @@ impl Game<'_> { author, generation: 0, pages, + page_tags: Vec::new(), }); *stack = written; } else { @@ -685,11 +754,7 @@ impl Game<'_> { return false; }; let Some(book) = &l.book else { return false }; - let data = book.data(); - let pages = data - .and_then(|d| d.written.as_ref().map(|w| w.pages.clone())) - .or_else(|| data.map(|d| d.writable_pages.clone())) - .unwrap_or_default(); + let pages = view_pages(book.data()); let page = (l.page.max(0) as usize).min(pages.len().saturating_sub(1)); self.stats.custom("interact_with_lectern", 1); self.open_book(BookScreen::View { @@ -811,11 +876,7 @@ impl Game<'_> { page, }) = self.book.as_mut() { - let data = book.as_ref().and_then(ItemStack::data); - *pages = data - .and_then(|d| d.written.as_ref().map(|w| w.pages.clone())) - .or_else(|| data.map(|d| d.writable_pages.clone())) - .unwrap_or_default(); + *pages = view_pages(book.as_ref().and_then(ItemStack::data)); *page = (*page).min(pages.len().saturating_sub(1)); } } @@ -955,7 +1016,10 @@ impl Game<'_> { lectern, }) => { let (page, count, lectern) = (*page, pages.len(), *lectern); - if page + 1 < count && inside(left + 116.0, 159.0, 23.0, 13.0) { + // The text's click event first, then the buttons. + if let Some(link) = pages.get(page).and_then(|t| self.book_link_at(t, left)) { + self.book_follow_link(link, count, lectern); + } else if page + 1 < count && inside(left + 116.0, 159.0, 23.0, 13.0) { self.turn_page(true); } else if page > 0 && inside(left + 43.0, 159.0, 23.0, 13.0) { self.turn_page(false); @@ -1198,7 +1262,7 @@ impl Game<'_> { } => { indicator(batch, *page, pages.len()); if let Some(text) = pages.get(*page) { - for (i, line) in self.book_lines(text).iter().take(LINES).enumerate() { + for (i, line) in self.page_lines(text).iter().take(LINES).enumerate() { batch.text_styled( atlas, line, diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index c392f3ea6..7344c0e9d 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -695,12 +695,78 @@ impl Game<'_> { Some(ClickEvent::OpenFile(path)) => { super::packs::open_folder(std::path::Path::new(&path)); } + Some(ClickEvent::OpenUrl(url)) => self.click_url(url), Some(ClickEvent::SuggestCommand(command)) => { if let Some(screen) = self.ui.chat_screen.as_mut() { screen.suggest_command(&m, &c, &command); } } - None => {} + // Screen.defaultHandleClickEvent: a page link means nothing in chat. + Some(ClickEvent::ChangePage(_)) | None => {} + } + } + /// `Screen.clickUrlAction`: nothing with Web Links off, else the link + /// opens, after the confirmation unless Prompt on Links is off. + pub(super) fn click_url(&mut self, url: String) { + if !self.settings.chat_links { + return; + } + if self.settings.file.bool("chatLinksPrompt") { + self.link_prompt = Some(url); + } else { + super::packs::open_uri(&url); + } + } + /// `ConfirmLinkScreen` (untrusted): the link and its warning over the + /// chat, answered yes to open it. + fn link_prompt_layout( + &self, + url: &str, + size: (f32, f32), + ) -> horizon_client::confirm_screen::Confirm { + let warning = Text::translate("chat.link.warning", &[]).with_color(0xFF_CCCC); + let message = Text::literal(url) + .append(Text::literal("\n")) + .append(warning); + horizon_client::confirm_screen::Confirm::new( + &self.gui.atlas.font, + size, + &Text::translate("chat.link.confirm", &[]), + &message, + ) + } + pub(super) fn draw_link_prompt(&self, batch: &mut HudBatch) { + let Some(url) = &self.link_prompt else { + return; + }; + let atlas = &self.gui.atlas; + let (w, h) = (batch.width, batch.height); + horizon_client::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); + let (yes, no) = ( + Text::translate("gui.yes", &[]), + Text::translate("gui.no", &[]), + ); + self.link_prompt_layout(url, (w, h)) + .draw(batch, atlas, self.cursor, [&yes, &no]); + } + /// The prompt's answer: the link opens on yes; either way the chat is back. + pub(super) fn answer_link_prompt(&mut self, yes: bool) { + if let Some(url) = self.link_prompt.take() + && yes + { + super::packs::open_uri(&url); + } + } + pub(super) fn link_prompt_click(&mut self) { + let Some(url) = &self.link_prompt else { + return; + }; + let answer = self + .link_prompt_layout(url, self.gui_size()) + .answer_at(self.cursor); + if let Some(yes) = answer { + self.audio.play_button_click(); + self.answer_link_prompt(yes); } } /// Chat lines over the HUD (focused while the chat screen is open). diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 927aa8c29..34319d462 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -442,6 +442,7 @@ impl Game<'_> { sea_level: if self.dim == Dim::Nether { 32 } else { 63 }, teams: std::sync::Arc::new(self.mob_teams()), items: Some(self.res.items()), + lid_openers: &self.lid_openers, difficulty: self.local_difficulty( self.player .as_ref() @@ -1243,9 +1244,9 @@ impl Game<'_> { [0.0, 0.2, 0.0], 10, ), - MobEvent::SetBlock { pos, state } => { - self.world.set(pos[0], pos[1], pos[2], state)? - } + // `Level.setBlockAndUpdate`: neighbour and shape updates, so a crop + // above trampled farmland breaks and drops. + MobEvent::SetBlock { pos, state } => self.level_set(pos, state)?, MobEvent::SetDoorOpen { pos, open } => { let pos = BlockPos::new(pos[0], pos[1], pos[2]); self.with_level(|b, level, ticks| b.set_door_open(level, ticks, pos, open)); @@ -2622,10 +2623,24 @@ impl Game<'_> { hurt } }; - // doKnockback: Punch pushes along the flight. + // doKnockback: Punch pushes along the flight, less the target's + // knockback resistance. let flight = (p.velocity.x * p.velocity.x + p.velocity.z * p.velocity.z).sqrt(); - if hurt && p.bonus.punch > 0 && flight > 1e-6 { - let k = f64::from(p.bonus.punch) * 0.6 / flight; + let resistance = match who { + Who::Player => self + .player + .as_mut() + .and_then(|pl| pl.attribute("minecraft:knockback_resistance").ok()) + .unwrap_or(0.0), + Who::Mob(id) => self + .mobs + .iter() + .find(|m| m.id == id) + .map_or(0.0, |m| m.attrs.knockback_resistance), + }; + let push = f64::from(p.bonus.punch) * 0.6 * (1.0 - resistance).max(0.0); + if hurt && push > 0.0 && flight > 1e-6 { + let k = push / flight; self.handle_mob_events(vec![MobEvent::Push { target: who, velocity: [p.velocity.x * k, 0.1, p.velocity.z * k], @@ -3092,6 +3107,7 @@ impl Game<'_> { .items() .get(&item) .is_some_and(|i| i.max_damage > 0); + let acting = self.acting_player_uuid(); let m = &mut self.mobs[index]; if !m.alive() { return Ok(false); @@ -3196,6 +3212,7 @@ impl Game<'_> { } Species::Wolf if m.extra.tame + && m.extra.owner == Some(acting) && item.ends_with("_dye") && horizon_client::mobs::render::DYE_NAMES .iter() @@ -3218,7 +3235,9 @@ impl Game<'_> { consume = true; } Species::Wolf - if m.extra.tame && !(is_food && m.extra.age == 0 && m.extra.in_love <= 0) => + if m.extra.tame + && m.extra.owner == Some(acting) + && !(is_food && m.extra.age == 0 && m.extra.in_love <= 0) => { m.extra.sitting = !m.extra.sitting; m.ai.jumping = false; @@ -3238,7 +3257,7 @@ impl Game<'_> { let tamed = m.random.next_int_bound(3).unwrap_or(1) == 0; if tamed { horizon_client::mobs::tame::set_tame(m, true); - m.extra.owner = self.level.player_uuid.or(Some([0, 0, 0, 1])); + m.extra.owner = Some(acting); m.persistent = true; m.nav_stop(); m.ai.target = None; @@ -3259,6 +3278,7 @@ impl Game<'_> { // Cat.mobInteract: dye, heal or sit when tame; fish may tame a wild one. Species::Cat if m.extra.tame + && m.extra.owner == Some(acting) && item.ends_with("_dye") && horizon_client::mobs::render::DYE_NAMES .iter() @@ -3281,7 +3301,12 @@ impl Game<'_> { m.persistent = true; consume = true; } - Species::Cat if m.extra.tame && is_food && m.health < m.attrs.max_health => { + Species::Cat + if m.extra.tame + && m.extra.owner == Some(acting) + && is_food + && m.health < m.attrs.max_health => + { let heal = self .res .items() @@ -3294,7 +3319,9 @@ impl Game<'_> { eat = eating_sound(m, &mut self.world.random); } Species::Cat - if m.extra.tame && !(is_food && m.extra.age == 0 && m.extra.in_love <= 0) => + if m.extra.tame + && m.extra.owner == Some(acting) + && !(is_food && m.extra.age == 0 && m.extra.in_love <= 0) => { m.extra.sitting = !m.extra.sitting; self.world.modified.insert(( @@ -3308,7 +3335,7 @@ impl Game<'_> { let tamed = m.random.next_int_bound(3).unwrap_or(1) == 0; if tamed { m.extra.tame = true; - m.extra.owner = self.level.player_uuid.or(Some([0, 0, 0, 1])); + m.extra.owner = Some(acting); m.extra.sitting = true; } eat = eating_sound(m, &mut self.world.random); diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index b24a62520..5688a3226 100644 --- a/crates/horizon-client/src/game/enchant_effects.rs +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -157,8 +157,10 @@ impl Game<'_> { items: Some(self.res.items()), ..Default::default() }; - // minecraft:post_attack ignite effects of the attacker's weapon (fire aspect). + // minecraft:post_attack effects of the attacker's weapon on the victim: + // ignite (fire aspect) and apply_mob_effect (bane of arthropods). let mut ignite = 0.0f32; + let mut mob_effects = Vec::new(); for (id, level) in held.enchantments() { let Some(def) = self.res.stations().enchantments.get(id) else { continue; @@ -168,24 +170,33 @@ impl Game<'_> { .into_iter() .flatten() { - if effect["enchanted"] == "attacker" - && effect["affected"] == "victim" - && effect["effect"]["type"] == "minecraft:ignite" + let e = &effect["effect"]; + let kind_of = e["type"].as_str(); + if effect["enchanted"] != "attacker" + || effect["affected"] != "victim" + || !matches!( + kind_of, + Some("minecraft:ignite" | "minecraft:apply_mob_effect") + ) { - let mut random = self.world.random.clone(); - let ok = effect.get("requirements").is_none_or(|r| { - self.res - .stations() - .enchantments - .condition(r, *level, &ctx, &mut random) - }); - self.world.random = random; - if ok { - ignite = ignite.max(horizon_client::enchant::level_value( - &effect["effect"]["duration"], - *level, - )); - } + continue; + } + let mut random = self.world.random.clone(); + let ok = effect.get("requirements").is_none_or(|r| { + self.res + .stations() + .enchantments + .condition(r, *level, &ctx, &mut random) + }); + self.world.random = random; + if !ok { + continue; + } + if kind_of == Some("minecraft:ignite") { + ignite = + ignite.max(horizon_client::enchant::level_value(&e["duration"], *level)); + } else { + mob_effects.push((e.clone(), *level)); } } } @@ -195,8 +206,41 @@ impl Game<'_> { { m.ignite_for_ticks((ignite * 20.0) as i32); } + for (effect, level) in mob_effects { + self.apply_mob_effect(mob, &effect, level); + } self.post_attack_bursts(&held, &kind); } + /// `ApplyMobEffect.apply`: one of `to_apply` (a single id or a list) for a + /// random duration and amplifier between the level-based bounds. + fn apply_mob_effect(&mut self, mob: usize, effect: &serde_json::Value, level: u32) { + use horizon_client::enchant::level_value; + let Some(m) = self.mobs.get_mut(mob) else { + return; + }; + let ids: Vec<&str> = match &effect["to_apply"] { + serde_json::Value::String(id) => vec![id.as_str()], + serde_json::Value::Array(list) => list.iter().filter_map(|v| v.as_str()).collect(), + _ => Vec::new(), + }; + if ids.is_empty() { + return; + } + // HolderSet.getRandomElement, then Mth.randomBetween for both values. + let pick = m.random.next_int_bound(ids.len() as i32).unwrap_or(0) as usize; + let mut between = |min: &str, max: &str| { + let (lo, hi) = ( + level_value(&effect[min], level), + level_value(&effect[max], level), + ); + m.random.next_float() * (hi - lo) + lo + }; + let ticks = (between("min_duration", "max_duration") * 20.0).round() as i32; + let amplifier = (between("min_amplifier", "max_amplifier").round() as i32).max(0); + if let Some(id) = super::potions::mob_effect_id(ids[pick]) { + m.add_effect(id, ticks, amplifier); + } + } /// `minecraft:post_attack` explode effects on the attacker (wind burst): /// a burst at the player's feet that only knocks back and triggers /// blocks (`ExplodeEffect` with `block_interaction: trigger`). @@ -307,8 +351,10 @@ impl Game<'_> { continue; } hits.push(1.0 + self.world.random.next_float() * 4.0); + // ChangeItemDamage -> ItemStack.hurtAndBreak: unbreaking applies. + let loss = self.durability_loss(&stack, 2); if let Some(s) = self.armor[slot].as_mut() { - s.damage += 2; + s.damage += loss; if self .res .items() diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index bed204b50..41c4e1628 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -659,7 +659,9 @@ impl Game<'_> { /// EnderDragonFight without a dragon: once the centre of the main island /// is loaded, place the active exit portal (EndPodiumFeature) and the - /// first gateway (spawnNewGateway) if the portal is not there yet. + /// first gateway (spawnNewGateway) if the portal is not there yet. Like + /// scanState and spawnExitPortal, only while the fight has no exit portal + /// location: a podium that is later broken stays broken. fn ensure_exit_portal(&mut self) -> Result<()> { if self.travelling.is_some() || !(-1..=0).all(|cz| (-1..=0).all(|cx| self.streaming.is_lit(cx, cz))) @@ -669,8 +671,14 @@ impl Game<'_> { } let won = self.fight.previously_killed; let gateway = self.first_gateway(); - if (0..256).any(|y| &*self.block_name([0, y, 0]) == "minecraft:bedrock") { - // The podium exists; the gateway may have been out of range when it was placed. + if self.exit_portal().is_none() { + // findExitPortal remembers the location of a podium that is already there. + if let Some(level) = self.podium_level() { + self.set_exit_portal([0, level, 0]); + } + } + if self.exit_portal().is_some() { + // The gateway may have been out of range when it was placed. if won && self.world.loaded(gateway[0], gateway[2]) && &*self.block_name(gateway) != "minecraft:end_gateway" @@ -701,17 +709,40 @@ impl Game<'_> { } Ok(()) } + /// The portal level of the podium around the centre column, read from the + /// bedrock that EndPodiumFeature places (rim at the portal level, disc + /// below it, the torch column) so a broken column does not hide it. + fn podium_level(&self) -> Option { + let mut offsets: Vec<[i32; 3]> = (0..4).map(|dy| [0, dy, 0]).collect(); + for z in -4..=4i32 { + for x in -4..=4i32 { + let flat = f64::from(x * x + z * z); + if (6.25..12.25).contains(&flat) { + offsets.push([x, 0, z]); + } else if flat + 1.0 < 6.25 { + offsets.push([x, -1, z]); + } + } + } + (1..253) + .map(|y| { + let score = offsets + .iter() + .filter(|o| &*self.block_name([o[0], y + o[1], o[2]]) == "minecraft:bedrock") + .count(); + (score, y) + }) + .filter(|&(score, _)| score >= 3) + .max() + .map(|(_, y)| y) + } /// `spawnExitPortal(true)` after the dragon dies. pub(super) fn activate_exit_portal(&mut self) -> Result<()> { let origin = match self.exit_portal() { Some(o) => o, None => { - // The rim's level: the top of the bedrock column minus three. - let top = (0..256) - .rev() - .find(|&y| &*self.block_name([0, y, 0]) == "minecraft:bedrock") - .unwrap_or(64); - [0, top - 3, 0] + // The rim's level, found without assuming the centre column is intact. + [0, self.podium_level().unwrap_or(61), 0] } }; self.place_podium(origin, true) diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index d91d3b979..60869952f 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -3,7 +3,7 @@ //! `continueAttack`, `MultiPlayerGameMode` block breaking), the arm swing //! (`LivingEntity.SwingState`) and the first-person equip heights //! (`FirstPersonHandsAndItems`) with the item swap ticker they read. -use super::{Game, Mining, Screen}; +use super::{Game, Mining, Screen, minecarts::CartKind}; use horizon_client::{ Result, attack_strength::HeldStack, @@ -289,6 +289,64 @@ impl Game<'_> { // Only alive mobs are hit, so a picked living entity is alive. Some(true) } + /// `Hud.canRenderCrosshairForSpectator` for the nearest hit in reach: an + /// entity that is a `MenuProvider` (a chest or hopper minecart, a chest + /// boat), or a block whose `showAsInteractableInSpectatorMode` holds. + pub(super) fn spectator_crosshair(&self) -> bool { + let cart = self.cart_hit().map(|(i, d)| { + let kind = &self.carts[i].kind; + (d, matches!(kind, CartKind::Chest | CartKind::Hopper)) + }); + let boat = self.boat_hit().map(|(i, d)| (d, self.boats[i].chest)); + let others = [ + self.mob_hit().map(|h| h.1), + self.armor_stand_hit().map(|h| h.1), + self.cushion_hit().map(|h| h.1), + self.painting_hit().map(|h| h.1), + self.frame_hit().map(|h| h.1), + self.dragon_hit().map(|h| h.1), + ]; + let nearest = cart + .into_iter() + .chain(boat) + .chain(others.into_iter().flatten().map(|d| (d, false))) + .min_by(|a, b| a.0.total_cmp(&b.0)); + if let Some((distance, menu)) = nearest + && self.before_block(distance) + { + return menu; + } + let Some(hit) = self.pick() else { + return false; + }; + let name = &*self + .res + .facts() + .get(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2])) + .name; + let name = name.trim_start_matches("minecraft:"); + match name { + // BlockBehaviour.getMenuProvider and `instanceof Portal`. + "crafting_table" | "enchanting_table" | "anvil" | "chipped_anvil" | "damaged_anvil" + | "stonecutter" | "loom" | "cartography_table" | "grindstone" | "smithing_table" + | "barrel" | "furnace" | "blast_furnace" | "smoker" | "brewing_stand" | "hopper" + | "dispenser" | "dropper" | "crafter" | "lectern" | "beacon" | "nether_portal" + | "end_portal" | "end_gateway" => true, + // ChestBlock.getMenuProvider: none while a redstone conductor + // sits on top of either half (a sitting cat aside). + "chest" | "trapped_chest" => { + let key = (hit.pos[0], hit.pos[1], hit.pos[2]); + let blocked = |p: (i32, i32, i32)| { + let above = self.world.block(p.0, p.1 + 1, p.2); + self.res.behaviours().facts(above).flags + & horizon_world::level::data::state_flags::CONDUCTOR + != 0 + }; + !blocked(key) && self.chest_other_half(key).is_none_or(|o| !blocked(o)) + } + _ => name.ends_with("shulker_box"), + } + } /// `Attributes.ATTACK_SPEED` with the main-hand item's modifier. pub(super) fn main_hand_attack_speed(&self) -> f64 { horizon_client::attack_strength::BASE_ATTACK_SPEED diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index d91de60f0..506c6c419 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1169,6 +1169,8 @@ impl Game<'_> { self.ui.rules.bool("player_movement_check"), self.ui.rules.bool("elytra_movement_check"), ); + host.hub + .set_immediate_respawn(self.ui.rules.bool("immediate_respawn")); // A server with several levels runs a pass for each // (`tick_server`): the network is read once, before the first. let pass = self.level_pass; diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 096bdcf6a..49eedbe55 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -5,7 +5,7 @@ //! (hits, pushes, fire, its projectiles) runs with that guest swapped in. use super::{Game, lan::LanHost}; use horizon_client::{ - mobs::{Mob, MobEvent, PlayerView, Who}, + mobs::{Mob, MobEvent, PlayerView, Species, Who}, projectiles::{Hit, Projectile}, }; use horizon_core::geometry::{Aabb, Vec3}; @@ -28,6 +28,22 @@ pub(super) fn player_for( ) -> Option { let targeting = m.ai.target == Some(Who::Player) || m.ai.last_hurt_by == Some(Who::Player) && m.age as i32 - m.ai.last_hurt_by_time <= 100; + // A tame wolf or cat sees its owner (`TamableAnimal.getOwner`), while they + // are in play, whoever is nearer. Not while it targets or was just hurt by + // a player: then `Who::Player` is that attacker, whoever it is, and the + // owner goals ignore it until the wolf lets go. + if !targeting + && matches!(m.species(), Species::Wolf | Species::Cat) + && m.extra.tame + && let Some(owner) = m.extra.owner + { + if host.is_some_and(|v| v.alive && v.uuid == owner) { + return None; + } + if let Some((conn, _)) = guests.iter().find(|(_, v)| v.alive && v.uuid == owner) { + return Some(*conn); + } + } choose(m.position, targeting, host, guests, bound) } diff --git a/crates/horizon-client/src/game/natural_spawning.rs b/crates/horizon-client/src/game/natural_spawning.rs index 0035f5082..5afa72416 100644 --- a/crates/horizon-client/src/game/natural_spawning.rs +++ b/crates/horizon-client/src/game/natural_spawning.rs @@ -504,7 +504,8 @@ impl<'a> Game<'a> { m.position.z.floor() as i32, ], is_mob: true, - persistent: m.persistent, + persistent: m.persistent + || horizon_client::mobs::ai::requires_custom_persistence(m), }) .collect(); let players = players diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 139e6be72..c0d7f1e3c 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -70,7 +70,7 @@ impl PotionCloud { } } /// A mob's effect ids carry the `minecraft:` namespace. -fn mob_effect_id(id: &str) -> Option<&'static str> { +pub(super) fn mob_effect_id(id: &str) -> Option<&'static str> { use std::{collections::HashMap, sync::OnceLock}; static IDS: OnceLock> = OnceLock::new(); let id = id.trim_start_matches("minecraft:"); diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index c51fbdc0b..8fbcfc6dd 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -762,7 +762,7 @@ impl Game<'_> { } positions.push((m.id, m.position, s.active_raid)); } - let banners: Vec<(usize, Vec3)> = self + let banners: Vec<(usize, u32, Vec3)> = self .dropped .iter() .enumerate() @@ -771,7 +771,7 @@ impl Game<'_> { && e.stack.data().is_some_and(|d| d.ominous_banner) && e.pickup_delay == 0 }) - .map(|(i, e)| (i, e.position)) + .map(|(i, e)| (i, e.id, e.position)) .collect(); let mut taken: Vec = Vec::new(); let mut collectors: Vec<(usize, u32)> = Vec::new(); @@ -858,20 +858,33 @@ impl Game<'_> { && raids.get(id).is_some_and(|r| r.leader(s.wave).is_none()) && !leaders.contains(&(id, s.wave)) { + let in_reach = |(i, _, p): &&(usize, u32, Vec3)| { + !taken.contains(i) + && (p.x - position.x).abs() <= range + && (p.z - position.z).abs() <= range + && (p.y - position.y).abs() <= 8.0 + }; + let by_distance = |a: &&(usize, u32, Vec3), b: &&(usize, u32, Vec3)| { + a.2.distance_squared(position) + .total_cmp(&b.2.distance_squared(position)) + }; + // The unreachable cache only picks the navigation target; + // a banner next to the raider is still picked up. let near = banners .iter() - .filter(|(i, p)| { - !taken.contains(i) - && (p.x - position.x).abs() <= range - && (p.z - position.z).abs() <= range - && (p.y - position.y).abs() <= 8.0 + .filter(in_reach) + .filter(|(_, item, _)| { + !s.unreachable_banners + .iter() + .any(|&(b, until)| b == *item && now < until) }) - .min_by(|a, b| { - a.1.distance_squared(position) - .total_cmp(&b.1.distance_squared(position)) - }); - if let Some((i, p)) = near { + .min_by(by_distance); + let nearest = banners.iter().filter(in_reach).min_by(by_distance); + let adjacent = + nearest.filter(|(_, _, p)| p.distance_squared(position) < 1.414 * 1.414); + if let Some((i, item, p)) = adjacent.or(near) { s.banner_at = Some([p.x, p.y, p.z]); + s.banner_item = *item; if p.distance_squared(position) < 1.414 * 1.414 { // pickUpItem: the banner becomes the wave's leader. taken.push(*i); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 117352e10..8720cb8fa 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -203,6 +203,8 @@ pub(super) struct Remote { stop_mining: bool, placing: Option<([i32; 3], u64)>, death_message: Option, + /// `LocalPlayer.showDeathScreen`: off with `immediate_respawn`. + show_death_screen: bool, player_type: Option>, /// Inventory as last synchronised, for creative-mode slot updates. synced: Vec>, @@ -496,6 +498,7 @@ impl Game<'_> { stop_mining: false, placing: None, death_message: None, + show_death_screen: true, player_type, synced: vec![None; 36], decode_errors: 0, @@ -1664,6 +1667,7 @@ impl Game<'_> { r.online_mode = p.online_mode; r.entity_id = p.player_id; r.view_distance = p.chunk_radius; + r.show_death_screen = p.show_death_screen; } self.streaming.radius = self.settings.render_distance.min(p.chunk_radius + 1).max(2); @@ -2358,7 +2362,11 @@ impl Game<'_> { pl.health.flash_health_change(p.health); } self.apply_remote_health(); - if p.health <= 0.0 && self.screen != Screen::Dead && self.player.is_some() { + // The death screen opens (or the respawn is asked for) with the + // death packet when the rule hides it. + let shown = self.remote.as_ref().is_none_or(|r| r.show_death_screen); + if p.health <= 0.0 && shown && self.screen != Screen::Dead && self.player.is_some() + { self.screen = Screen::Dead; self.ui.death_time = 0; self.capture(false); @@ -2374,11 +2382,16 @@ impl Game<'_> { r.death_message = Some(message); } // ClientPacketListener.handlePlayerCombatKill: the death - // screen, whatever health was last sent. + // screen, whatever health was last sent, or `respawn()` at + // once when it is hidden. if me && self.screen != Screen::Dead && self.player.is_some() { - self.screen = Screen::Dead; - self.ui.death_time = 0; - self.capture(false); + if self.remote.as_ref().is_none_or(|r| r.show_death_screen) { + self.screen = Screen::Dead; + self.ui.death_time = 0; + self.capture(false); + } else { + self.respawn_player()?; + } } } C::TrackedWaypoint(p) => self.handle_waypoint(&p), @@ -2454,6 +2467,12 @@ impl Game<'_> { r.game_mode = mode; } } + // IMMEDIATE_RESPAWN: LocalPlayer.setShowDeathScreen. + 11 => { + if let Some(r) = self.remote.as_mut() { + r.show_death_screen = p.param == 0.0; + } + } 7 => { self.world.weather.rain_level = (p.param, p.param); self.world.weather.raining = p.param > 0.0; diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index 750895adb..4b5c4c333 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -322,6 +322,58 @@ impl Game<'_> { ); } } + /// LocalPlayer.respawn: the player comes back (the death screen's + /// button, or at once with `immediate_respawn`). + pub(super) fn respawn_player(&mut self) -> Result<()> { + if self.remote.is_none() { + // PlayerList.respawn removes the dead player, and Player.remove's + // inventoryMenu.removed drops what the cursor held, whatever + // keep_inventory says (the 20-tick branch handles a later respawn). + if let Some(stack) = self.carried.take() + && let Some(eye) = self.eye_position() + { + self.throw_from_eyes(stack, eye, false); + } + let keep = self.ui.rules.bool("keep_inventory") || self.spectator(); + self.experience.respawn(keep); + // The guests are sent the respawned host as a new entity, not the dead body. + if let Some(host) = self.lan.as_mut() { + let id = host.host_entity; + host.hub.respawned(id); + } + // Autosaves keep a login position; death must resolve the respawn point instead. + self.level.position = None; + } + if self.remote.is_some() { + self.ui.death_text = None; + self.toggles.respawn(); + self.remote_respawn(); + } else if self.respawn_config.is_some() { + // LocalPlayer.respawn: KeyMapping.resetToggleKeys. + self.toggles.respawn(); + // PlayerList.respawn at the respawn anchor, once it is loaded. + self.begin_anchor_respawn()?; + self.screen = Screen::Playing; + self.ui.death_text = None; + self.spawn_player()?; + self.capture(true); + } else { + // LocalPlayer.respawn: KeyMapping.resetToggleKeys. + self.toggles.respawn(); + self.respawn_out_of_end()?; + self.player = None; + self.screen = Screen::Playing; + self.ui.death_text = None; + self.spawn_player()?; + self.capture(true); + } + // ServerGamePacketListenerImpl.handleClientCommand: a hardcore world's + // respawned player only watches. + if self.remote.is_none() && self.level.hardcore { + self.set_mode(GameMode::Spectator); + } + Ok(()) + } pub(super) fn death_click(&mut self) -> Result<()> { if self .ui @@ -339,51 +391,11 @@ impl Game<'_> { .into_iter() .find(|d| ui::hovered(self.cursor, d.0, d.1, 200.0, 20.0)) .map(|d| d.3); - if hit == Some(0) && self.remote.is_none() { - let keep = self.ui.rules.bool("keep_inventory") || self.spectator(); - self.experience.respawn(keep); - // The guests are sent the respawned host as a new entity, not the dead body. - if let Some(host) = self.lan.as_mut() { - let id = host.host_entity; - host.hub.respawned(id); - } - // Autosaves keep a login position; death must resolve the respawn point instead. - self.level.position = None; - } match hit { - Some(0) if self.remote.is_some() => { - self.ui.death_text = None; - self.toggles.respawn(); - self.remote_respawn(); - } - Some(0) if self.respawn_config.is_some() => { - // LocalPlayer.respawn: KeyMapping.resetToggleKeys. - self.toggles.respawn(); - // PlayerList.respawn at the respawn anchor, once it is loaded. - self.begin_anchor_respawn()?; - self.screen = Screen::Playing; - self.ui.death_text = None; - self.spawn_player()?; - self.capture(true); - } - Some(0) => { - // LocalPlayer.respawn: KeyMapping.resetToggleKeys. - self.toggles.respawn(); - self.respawn_out_of_end()?; - self.player = None; - self.screen = Screen::Playing; - self.ui.death_text = None; - self.spawn_player()?; - self.capture(true); - } + Some(0) => self.respawn_player()?, Some(1) => self.close_world()?, _ => {} } - // ServerGamePacketListenerImpl.handleClientCommand: a hardcore world's - // respawned player only watches. - if hit == Some(0) && self.remote.is_none() && self.level.hardcore { - self.set_mode(GameMode::Spectator); - } if hit.is_some() { self.audio.play_button_click(); } diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index 473509f0a..65dfede1a 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -1515,6 +1515,16 @@ impl Game<'_> { fn tick_entity_events(&mut self) { self.tick_player_sculk_events(); self.tick_mob_sculk_events(); + // Dropped items are entities too: Entity.applyEffectsFromBlocks. + let items: Vec<[f64; 3]> = self + .dropped + .iter() + .filter(|i| i.on_ground) + .map(|i| [i.position.x, i.position.y, i.position.z]) + .collect(); + for at in items { + self.step_on_redstone_ore(at, false); + } } /// Entity.move emits on the authoritative server too, for each ServerPlayer. @@ -1530,6 +1540,9 @@ impl Game<'_> { }); if let Some((at, on_ground, health, flying)) = player { let crouch = self.keys.contains(&KeyCode::ShiftLeft); + if on_ground && !self.spectator() { + self.step_on_redstone_ore(at, crouch); + } let in_water = self.in_water_at(at); self.entity_motion_events( Who::Player, @@ -1548,6 +1561,26 @@ impl Game<'_> { } } + /// `RedStoneOreBlock.stepOn`: standing on the ore lights it, unless the + /// entity is stepping carefully (`attack_block` only lights an unlit ore). + fn step_on_redstone_ore(&mut self, at: [f64; 3], carefully: bool) { + if carefully { + return; + } + // getOnPosLegacy: 0.2 below the feet. + let pos = [ + at[0].floor() as i32, + (at[1] - 0.2).floor() as i32, + at[2].floor() as i32, + ]; + if matches!( + &*self.block_name(pos), + "minecraft:redstone_ore" | "minecraft:deepslate_redstone_ore" + ) { + let _ = self.attack_block(pos); + } + } + fn tick_mob_sculk_events(&mut self) { let snapshot: Vec<(u32, [f64; 3], bool, bool, Species, Option)> = self .mobs @@ -1565,6 +1598,9 @@ impl Game<'_> { }) .collect(); for (id, at, on_ground, in_water, species, damaged) in snapshot { + if on_ground { + self.step_on_redstone_ore(at, false); + } let emits = !matches!(species, Species::Shulker); if emits { self.entity_motion_events(Who::Mob(id), at, on_ground, in_water, false, false); diff --git a/crates/horizon-client/src/game/shield.rs b/crates/horizon-client/src/game/shield.rs index c4f7f98d1..a26bc5d75 100644 --- a/crates/horizon-client/src/game/shield.rs +++ b/crates/horizon-client/src/game/shield.rs @@ -182,12 +182,17 @@ impl Game<'_> { return; }; let (mx, mz) = (m.position.x, m.position.z); - let disable = m - .extra - .main_hand - .as_deref() - .and_then(|item| self.res.items().get(item)) - .map_or(0.0, |i| i.disable_blocking_seconds); + // LivingEntity.getSecondsToDisableBlocking: the held weapon's value; + // Warden overrides it with a flat 5 seconds. + let disable = if m.species() == horizon_client::mobs::Species::Warden { + 5.0 + } else { + m.extra + .main_hand + .as_deref() + .and_then(|item| self.res.items().get(item)) + .map_or(0.0, |i| i.disable_blocking_seconds) + }; // Ravager.blockedByItem: stunned half the time (the defender pushed // apart), else the defender flung away; no roar in progress. if m.species() == horizon_client::mobs::Species::Ravager { diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index a5104ee12..bca582d1a 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -6,6 +6,7 @@ use super::{Game, view_vector}; use horizon_client::{ collisions::SceneCollisions, + enchant::EffectContext, items::ItemStack, mesher::Vertex, mobs::{Damage, DamageKind, Who, anim::Poses}, @@ -392,11 +393,29 @@ impl Game<'_> { } } if let Some((id, _)) = hit_mob { - let impaling = t.stack.enchantment_level("minecraft:impaling") as f32; - let aquatic = self.mobs.iter().find(|m| m.id == id).is_some_and(|m| { - m.kind.flags.aquatic_swimmer || m.kind.flags.breathes_water - }); - let damage = 8.0 + if aquatic { 2.5 * impaling } else { 0.0 }; + // ThrownTrident.getDamage: `EnchantmentHelper.modifyDamage` on 8 + // (impaling hits `#sensitive_to_impaling`, the aquatic tag). + let victim = self + .mobs + .iter() + .find(|m| m.id == id) + .map(|m| m.kind.id.clone()); + let ctx = EffectContext { + this: victim.as_deref(), + attacker: Some("minecraft:player"), + direct_attacker: Some("minecraft:trident"), + is_direct: true, + damage_type: Some("minecraft:trident"), + items: Some(self.res.items()), + ..Default::default() + }; + let damage = self.res.stations().enchantments.modify_value( + Some(&t.stack), + "minecraft:damage", + &ctx, + &mut self.world.random, + 8.0, + ); t.dealt_damage = true; let mut hurt_at = None; if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index d55e44d99..cb097c114 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -5,8 +5,7 @@ use crate::{ graphics::{FarDetail, GraphicsApi, Overlay, Pacing, PresentMode, Preset}, graphics_style::{Cost, STYLE}, hud::{HudAtlas, HudBatch}, - options_ui::Opt, - settings::Settings, + settings::{Opt, Settings}, text::Text, ui, }; diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index c0e7be5c8..28391c496 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -25,29 +25,7 @@ use std::{fs, io, path::Path}; pub(crate) type Attributes = LiveAttributes i32>>; pub(crate) type State = HurtState; -#[derive(Clone, Copy, Debug)] -pub struct HealthRules { - pub difficulty: Difficulty, - pub natural_regeneration: bool, - /// The `drowning_damage`, `fall_damage`, `fire_damage` and - /// `freeze_damage` rules `Player.isInvulnerableTo` reads. - pub drowning_damage: bool, - pub fall_damage: bool, - pub fire_damage: bool, - pub freeze_damage: bool, -} -impl Default for HealthRules { - fn default() -> Self { - Self { - difficulty: Difficulty::Normal, - natural_regeneration: true, - drowning_damage: true, - fall_damage: true, - fire_damage: true, - freeze_damage: true, - } - } -} +pub use crate::world::HealthRules; pub struct HealthResources { pub damage: Catalog, pub ids: PlayerFloatIds, diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index 27a28902a..1bd80437f 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -143,6 +143,9 @@ pub struct WrittenBook { pub author: String, pub generation: u8, pub pages: Vec, + /// Each page's component when it is not a plain string, so that its + /// click events survive; empty or one per page. + pub page_tags: Vec, } impl StackData { pub fn is_empty(&self) -> bool { @@ -322,6 +325,21 @@ fn read_levels(t: Option<&Tag>) -> Levels { } /// A text component as stored by vanilla: a plain string or `{"text": ...}`. /// A `Filterable`: the value itself or `{raw: value}`. +/// `ComponentSerialization.CODEC`'s short form: a plain text component with +/// no style and no siblings is written as its string. +fn plain_component(t: &Tag) -> Tag { + if let Tag::Compound(c) = t + && let Some(text @ Tag::String(_)) = c.get(&"text".into()) + && c.iter().all(|(k, v)| { + k.to_string_lossy() == "text" + || (k.to_string_lossy() == "type" + && matches!(v, Tag::String(s) if s.to_string_lossy() == "text")) + }) + { + return text.clone(); + } + t.clone() +} fn filterable_text(t: &Tag) -> Option { match t.get("raw") { Some(raw) => read_text(raw), @@ -553,11 +571,14 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { )); } if let Some(w) = &d.written { - let pages = w - .pages - .iter() - .map(|p| raw(Tag::String(p.as_str().into()))) - .collect(); + let pages = if w.page_tags.len() == w.pages.len() { + w.page_tags.iter().cloned().map(raw).collect() + } else { + w.pages + .iter() + .map(|p| raw(Tag::String(p.as_str().into()))) + .collect() + }; entries.push(( "minecraft:written_book_content", Tag::compound({ @@ -738,6 +759,13 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option pages.iter().filter_map(filterable_text).collect(), _ => Vec::new(), }, + page_tags: match b.get("pages") { + Some(Tag::List(pages)) => pages + .iter() + .map(|p| plain_component(p.get("raw").unwrap_or(p))) + .collect(), + _ => Vec::new(), + }, }), fireworks: c .get("minecraft:fireworks") diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 2deb5905e..9f83e1457 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -669,11 +669,14 @@ fn network_stack( title: w.title.clone(), author: w.author.clone(), generation: i32::from(w.generation), - pages: w - .pages - .iter() - .map(|p| horizon_protocol::text::literal(p)) - .collect(), + pages: if w.page_tags.len() == w.pages.len() { + w.page_tags.clone() + } else { + w.pages + .iter() + .map(|p| horizon_protocol::text::literal(p)) + .collect() + }, resolved: true, }, ), diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 7395cc0a4..12967d778 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -43,6 +43,7 @@ pub mod game_event { pub const RAIN_LEVEL: u8 = 7; pub const THUNDER_LEVEL: u8 = 8; pub const GUARDIAN_ELDER_EFFECT: u8 = 10; + pub const IMMEDIATE_RESPAWN: u8 = 11; pub const LEVEL_CHUNKS_LOAD_START: u8 = 13; } @@ -172,6 +173,8 @@ pub struct Hub { /// The `player_movement_check` and `elytra_movement_check` game rules, /// set by the game before each tick. pub movement_checks: (bool, bool), + /// The `immediate_respawn` game rule, as the players were last told. + immediate_respawn: bool, /// An integrated server's owner (`MinecraftServer.isSingleplayerOwner`), /// whose moves are never checked. pub singleplayer_owner: Option, @@ -352,6 +355,7 @@ impl Hub { guests: Vec::new(), sync, ticks: 0, + immediate_respawn: false, movement_checks: (true, true), singleplayer_owner: None, riding: Default::default(), @@ -429,6 +433,17 @@ impl Hub { g.sender.send(body.clone()); } } + /// MinecraftServer.onGameRuleChanged: every player is told when + /// `immediate_respawn` changes; a joining player's Login carries it. + pub fn set_immediate_respawn(&mut self, on: bool) { + if self.immediate_respawn != on { + self.immediate_respawn = on; + self.broadcast(&C::GameEvent(play::GameEvent { + event: game_event::IMMEDIATE_RESPAWN, + param: if on { 1.0 } else { 0.0 }, + })); + } + } /// PlayerList.setViewDistance: every player is told the new radius, /// and each one's chunks follow it, up to what they asked for /// (ChunkMap.getPlayerViewDistance). @@ -663,7 +678,7 @@ impl Hub { chunk_radius: self.config.view_distance, simulation_distance: self.config.simulation_distance, reduced_debug_info: false, - show_death_screen: true, + show_death_screen: !self.immediate_respawn, limited_crafting: false, spawn: self.spawn_info(mode), // MinecraftServer.usesAuthentication, enforceSecureProfile. diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index d21e762ed..f4ab3f834 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1686,6 +1686,8 @@ pub struct MobWorld<'a> { pub teams: std::sync::Arc>, /// Item data (max stack sizes), when the host has it. pub items: Option<&'a crate::items::Items>, + /// `ChestBlockEntity.getOpenCount`: the players with each chest open. + pub lid_openers: &'a HashMap<(i32, i32, i32), i32>, } /// `Entity.getTeam` of the player and of the mobs on a team. #[derive(Clone, Debug, Default)] diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index a0d0b84ca..ad130ea68 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -1201,6 +1201,19 @@ pub fn despawn_check(m: &mut Mob, w: &MobWorld) -> bool { } true } +/// `Mob.requiresCustomPersistence` and its overrides: a passenger or a leashed +/// mob, a raider in a raid, an enderman carrying a block, a tame nautilus, a +/// sulfur cube holding a block or let out of a bucket. The spawn caps do not +/// count these mobs either (`NaturalSpawner.createState`). +pub fn requires_custom_persistence(m: &Mob) -> bool { + super::riders::keeps_alive(m) + || m.extra.leash.is_some() + || super::raider::state(m).is_some_and(|s| s.raid_id.is_some()) + || m.species() == Species::Enderman && m.extra.carried.is_some() + || super::nautilus::is_nautilus(m.species()) && m.extra.tame + || m.species() == Species::SulfurCube + && (super::sulfur_cube::has_body(m) || m.extra.scratch[3] != 0) +} /// Mob.checkDespawn, before the tick (players are the only despawn /// reference). Returns false when the mob is discarded. fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool { @@ -1216,12 +1229,7 @@ fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool { return true; }; let d = m.distance_sqr(p); - // requiresCustomPersistence: raiders in a raid, a tame nautilus, a sulfur - // cube holding a block or let out of a bucket. - let persistent = m.persistent - || super::nautilus::is_nautilus(m.species()) && m.extra.tame - || m.species() == Species::SulfurCube - && (super::sulfur_cube::has_body(m) || m.extra.scratch[3] != 0); + let persistent = m.persistent || requires_custom_persistence(m); // removeWhenFarAway: animals, villagers, golems, patrols and raiders, // zombie villagers being cured and ridden mobs stay. let creature = m.kind.category == "creature"; diff --git a/crates/horizon-client/src/mobs/control.rs b/crates/horizon-client/src/mobs/control.rs index bd17d7b5f..e6874ea0b 100644 --- a/crates/horizon-client/src/mobs/control.rs +++ b/crates/horizon-client/src/mobs/control.rs @@ -417,6 +417,13 @@ impl Mob { } /// BodyRotationControl.clientTick (Mob.tickHeadTurn). pub fn body_rotation_tick(&mut self) { + // Shulker.ShulkerBodyRotationControl.clientTick is empty: the body + // stays at 0 (recreateFromPacket), only the head turns. + if self.species() == super::Species::Shulker { + self.body_yaw = 0.0; + self.previous_body_yaw = 0.0; + return; + } let dx = self.position.x - self.previous.x; let dz = self.position.z - self.previous.z; let max = self.kind.max_head_y_rot; diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index fa9725075..10388d0c0 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -586,11 +586,36 @@ impl Mob { } if self.on_ground { if self.fall_distance > 0.0 { + self.trample_farmland(w, events); self.cause_fall_damage(events); } self.fall_distance = 0.0; } } + /// `FarmlandBlock.fallOn`: a landing on farmland turns it to dirt with + /// chance `fallDistance - 0.5`, if mobs may grief and the mob's + /// `width * width * height` is over 0.512. `Block.pushEntitiesUp` lifts + /// the mob onto the dirt, which is a full block. + fn trample_farmland(&mut self, w: &MobWorld, events: &mut Vec) { + let p = self.block_on_legacy(w); + if w.block_name(p[0], p[1], p[2]) != "minecraft:farmland" { + return; + } + let roll = f64::from(self.random.next_float()); + let Some(dirt) = w.registry.default_state("minecraft:dirt") else { + return; + }; + if roll < self.fall_distance - 0.5 + && w.mob_griefing + && self.width() * self.width() * self.height() > 0.512 + { + events.push(MobEvent::SetBlock { + pos: p, + state: dirt, + }); + self.position.y = self.position.y.max(f64::from(p[1]) + 1.0); + } + } /// Entity.updateFluidInteraction: the fluid state, then touching water /// resets the fall and entering it (after the first tick) splashes. pub(super) fn update_fluids(&mut self, w: &MobWorld, events: &mut Vec) { diff --git a/crates/horizon-client/src/mobs/raider.rs b/crates/horizon-client/src/mobs/raider.rs index d2ed62374..9b1d17eed 100644 --- a/crates/horizon-client/src/mobs/raider.rs +++ b/crates/horizon-client/src/mobs/raider.rs @@ -41,6 +41,11 @@ pub struct State { pub in_village: bool, /// A dropped ominous banner this raider may fetch. pub banner_at: Option<[f64; 3]>, + /// The item entity of `banner_at`. + pub banner_item: u32, + /// Banners with no path to them, and until when (game time): + /// `unreachableBannerCache`. + pub unreachable_banners: Vec<(u32, i64)>, /// Beds around the raid's centre. pub homes: Option>>, /// A ravager carrying a raider, set every tick from `Extra::rider`. @@ -116,7 +121,7 @@ pub fn register(m: &mut Mob) { } m.extra.raider = Some(Box::default()); m.ai.goals.add(4, LongDistancePatrol::new(0.7, 0.595)); - m.ai.goals.add(1, ObtainBanner); + m.ai.goals.add(1, ObtainBanner::default()); m.ai.goals.add(3, PathfindToRaid); m.ai.goals.add(4, MoveThroughVillage::new(1.05, 1.0)); m.ai.goals.add(5, Celebration); @@ -339,23 +344,37 @@ fn close_to_center(p: [i32; 3], at: Vec3, distance: f64) -> bool { /// `Raider.ObtainRaidLeaderBannerGoal`: walk to a fallen ominous banner when /// the wave has no living leader (the game finds the banner and picks it up). -#[derive(Clone, Debug)] -pub struct ObtainBanner; +#[derive(Clone, Debug, Default)] +pub struct ObtainBanner { + path_to_banner: Option, +} impl Goal for ObtainBanner { goal_clone!(); fn flags(&self) -> u8 { MOVE } - fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { - state(m).is_some_and(|s| s.banner_at.is_some()) + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some((at, item)) = state(m).and_then(|s| s.banner_at.map(|at| (at, s.banner_item))) + else { + return false; + }; + // A banner with no path to it is skipped for 600 ticks. + let path = m.create_path_to_entity(cx.w, at, 1); + if path.as_ref().is_some_and(|p| p.reached) { + self.path_to_banner = path; + return true; + } + let now = cx.w.game_time; + let s = state_mut(m); + s.unreachable_banners.retain(|&(_, until)| now < until); + s.unreachable_banners.push((item, now + 600)); + false } fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { !m.ai.nav.is_done() && state(m).is_some_and(|s| s.banner_at.is_some()) } - fn start(&mut self, m: &mut Mob, cx: &mut Cx) { - if let Some(at) = state(m).and_then(|s| s.banner_at) { - m.nav_move_to(cx.w, at, 1.15); - } + fn start(&mut self, m: &mut Mob, _cx: &mut Cx) { + m.nav_move_to_path(self.path_to_banner.take(), 1.15); } } diff --git a/crates/horizon-client/src/mobs/tame.rs b/crates/horizon-client/src/mobs/tame.rs index 0b2075c96..f38296d4b 100644 --- a/crates/horizon-client/src/mobs/tame.rs +++ b/crates/horizon-client/src/mobs/tame.rs @@ -2,7 +2,7 @@ //! sitting, following and defending the owner, begging, anger and shaking //! off water (`Wolf`, `WolfModel`). use super::{ - Damage, Mob, MobEvent, MobWorld, Species, Who, + Damage, Mob, MobEvent, MobWorld, PlayerView, Species, Who, anim::{Poses, State}, goals::{ Breed, Cx, Float, Goal, HurtByTarget, JUMP, LOOK, LeapAtTarget, LookAtPlayer, MOVE, @@ -124,17 +124,23 @@ pub fn set_tame(m: &mut Mob, tame: bool) { m.attrs.max_health = 8.0; } } -/// The owner (the local player) when tame. -fn owner(m: &Mob, w: &MobWorld) -> Option<(Vec3, f64, bool)> { +/// `TamableAnimal.getOwner`: the player the saved owner UUID names, when it +/// is the one this mob sees; anyone else nearby is not its owner. +fn owner_view<'a>(m: &Mob, w: &'a MobWorld) -> Option<&'a PlayerView> { if !m.extra.tame { return None; } let p = w.player.as_ref()?; + (m.extra.owner == Some(p.uuid)).then_some(p) +} +/// The owner's position, eye height and spectator flag when tame. +fn owner(m: &Mob, w: &MobWorld) -> Option<(Vec3, f64, bool)> { + let p = owner_view(m, w)?; Some((p.position, p.eye[1], p.spectator)) } /// `TamableAnimal.unableToMoveToOwner`. fn unable_to_move_to_owner(m: &Mob, w: &MobWorld) -> bool { - m.extra.sitting || w.player.as_ref().is_some_and(|p| p.spectator) + m.extra.sitting || owner_view(m, w).is_some_and(|p| p.spectator) } /// `TamableAnimal.tryToTeleportToOwner`: ten tries around the owner. fn teleport_to_owner(m: &mut Mob, w: &MobWorld) { @@ -240,7 +246,7 @@ impl Goal for SitWhenOrdered { match owner_distance_sqr(m, cx.w) { None => true, Some(d) => { - let attacked = cx.w.player.as_ref().is_some_and(|p| p.hurt_by.is_some()); + let attacked = owner_view(m, cx.w).is_some_and(|p| p.hurt_by.is_some()); !(d < 144.0 && attacked) && m.extra.sitting } } @@ -388,7 +394,7 @@ impl Goal for OwnerHurtBy { if !m.extra.tame || m.extra.sitting { return false; } - let Some((who, at)) = cx.w.player.as_ref().and_then(|p| p.hurt_by) else { + let Some((who, at)) = owner_view(m, cx.w).and_then(|p| p.hurt_by) else { return false; }; at != self.timestamp && wants_to_attack(m, cx.w, who) @@ -399,7 +405,7 @@ impl Goal for OwnerHurtBy { .is_some_and(|t| t.alive) } fn start(&mut self, m: &mut Mob, cx: &mut Cx) { - if let Some((who, at)) = cx.w.player.as_ref().and_then(|p| p.hurt_by) { + if let Some((who, at)) = owner_view(m, cx.w).and_then(|p| p.hurt_by) { m.ai.target = Some(who); self.timestamp = at; } @@ -422,7 +428,7 @@ impl Goal for OwnerHurt { if !m.extra.tame || m.extra.sitting { return false; } - let Some((who, at)) = cx.w.player.as_ref().and_then(|p| p.last_hurt) else { + let Some((who, at)) = owner_view(m, cx.w).and_then(|p| p.last_hurt) else { return false; }; at != self.timestamp && wants_to_attack(m, cx.w, who) @@ -433,7 +439,7 @@ impl Goal for OwnerHurt { .is_some_and(|t| t.alive) } fn start(&mut self, m: &mut Mob, cx: &mut Cx) { - if let Some((who, at)) = cx.w.player.as_ref().and_then(|p| p.last_hurt) { + if let Some((who, at)) = owner_view(m, cx.w).and_then(|p| p.last_hurt) { m.ai.target = Some(who); self.timestamp = at; } @@ -822,7 +828,7 @@ impl Goal for CatLieOnBlock { m.extra.flag = self.0.reached; } } -/// `CatSitOnBlockGoal`: chests, lit furnaces and beds. +/// `CatSitOnBlockGoal`: unopened chests, lit furnaces and the foot of beds. #[derive(Clone, Debug)] struct CatSitOnBlock(super::goals::MoveToBlock); fn can_sit_on(w: &MobWorld, p: [i32; 3]) -> bool { @@ -833,7 +839,15 @@ fn can_sit_on(w: &MobWorld, p: [i32; 3]) -> bool { match f.name.as_ref() { // The lit state is the only light source a furnace has. "minecraft:furnace" => f.emission > 0, - _ => true, + // `ChestBlockEntity.getOpenCount(level, pos) < 1`: players' openers + // and the copper golems' own count. + "minecraft:chest" => { + let key = (p[0], p[1], p[2]); + !w.lid_openers.contains_key(&key) + && w.world.chest_openers.get(&key).is_none_or(|o| o.0 < 1) + } + // A bed's foot only (`BedBlock.PART != HEAD`). + _ => w.prop(p[0], p[1], p[2], "part") != Some("head"), } } impl Goal for CatSitOnBlock { diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 9d38744b7..2b852a4af 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -4,6 +4,8 @@ //! OptionsList screens and drawn with the shared widgets. use std::time::Instant; +pub use crate::settings::Opt; + use crate::{ gamepad::{self, GlyphStyle}, hud::{HudAtlas, HudBatch, rgba}, @@ -14,95 +16,6 @@ use crate::{ ui, }; -/// One option instance. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Opt { - Fov, - RenderDistance, - SimulationDistance, - Sensitivity, - WheelSensitivity, - InvertY, - DiscreteScroll, - Volume(usize), - GuiScale, - ViewBobbing, - Gamma, - MaxFps, - Vsync, - Fullscreen, - SmoothLighting, - Clouds, - CloudRange, - Particles, - EntityDistance, - EntityShadows, - BiomeBlend, - Preset, - Mipmaps, - WeatherRadius, - ChunkFade, - Vignette, - Autosave, - CutoutLeaves, - ImprovedTransparency, - AttackIndicator, - InactivityFps, - ChunkBuilder, - MenuBlur, - ToggleCrouch, - ToggleSprint, - AutoJump, - ChatVisibility, - ChatColors, - ChatLinks, - ChatLinksPrompt, - ChatOpacity, - TextBackgroundOpacity, - ChatScale, - ChatWidth, - ChatHeightFocused, - ChatHeightUnfocused, - ChatLineSpacing, - AutoSuggestions, - ReducedDebugInfo, - HighContrast, - ShowSubtitles, - MusicFrequency, - NotificationDisplayTime, - Narrator, - TextBackground, - ChatDelay, - DistortionEffects, - FovEffects, - DarknessPulsing, - DamageTilt, - GlintSpeed, - GlintStrength, - HideLightningFlashes, - MonochromeLogo, - PanoramaSpeed, - HideSplashTexts, - NarratorHotkey, - RotateWithMinecarts, - HighContrastBlockOutlines, - ForceUnicode, - JapaneseGlyphs, - /// Horizon's controller settings (`horizon-controller.txt`). - PadEnabled, - PadVibration, - PadAdaptiveTriggers, - PadLightbar, - PadLookSensitivity, - PadInvertX, - PadInvertY, - PadToggleSneak, - PadMoveDeadzone, - PadLookDeadzone, - PadGlyphs, - PadMenuNav, - PadKeyboard, -} fn tr(key: &str) -> Text { Text::translate(key, &[]) } diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 09d7ae3ff..0c59c18f9 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -608,6 +608,96 @@ impl Settings { } } +/// One option instance. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Opt { + Fov, + RenderDistance, + SimulationDistance, + Sensitivity, + WheelSensitivity, + InvertY, + DiscreteScroll, + Volume(usize), + GuiScale, + ViewBobbing, + Gamma, + MaxFps, + Vsync, + Fullscreen, + SmoothLighting, + Clouds, + CloudRange, + Particles, + EntityDistance, + EntityShadows, + BiomeBlend, + Preset, + Mipmaps, + WeatherRadius, + ChunkFade, + Vignette, + Autosave, + CutoutLeaves, + ImprovedTransparency, + AttackIndicator, + InactivityFps, + ChunkBuilder, + MenuBlur, + ToggleCrouch, + ToggleSprint, + AutoJump, + ChatVisibility, + ChatColors, + ChatLinks, + ChatLinksPrompt, + ChatOpacity, + TextBackgroundOpacity, + ChatScale, + ChatWidth, + ChatHeightFocused, + ChatHeightUnfocused, + ChatLineSpacing, + AutoSuggestions, + ReducedDebugInfo, + HighContrast, + ShowSubtitles, + MusicFrequency, + NotificationDisplayTime, + Narrator, + TextBackground, + ChatDelay, + DistortionEffects, + FovEffects, + DarknessPulsing, + DamageTilt, + GlintSpeed, + GlintStrength, + HideLightningFlashes, + MonochromeLogo, + PanoramaSpeed, + HideSplashTexts, + NarratorHotkey, + RotateWithMinecarts, + HighContrastBlockOutlines, + ForceUnicode, + JapaneseGlyphs, + /// Horizon's controller settings (`horizon-controller.txt`). + PadEnabled, + PadVibration, + PadAdaptiveTriggers, + PadLightbar, + PadLookSensitivity, + PadInvertX, + PadInvertY, + PadToggleSneak, + PadMoveDeadzone, + PadLookDeadzone, + PadGlyphs, + PadMenuNav, + PadKeyboard, +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index c5ed5d881..14dfedb49 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -151,8 +151,12 @@ pub struct AnvilResult { pub repair_item_count_cost: u32, pub only_renaming: bool, } +/// `ItemStack.isDamageableItem`: durability, and not `minecraft:unbreakable`. pub fn is_damageable(items: &Items, stack: &ItemStack) -> bool { items.get(&stack.item).is_some_and(|i| i.max_damage > 0) + && stack + .data() + .is_none_or(|d| d.other("minecraft:unbreakable").is_none()) } fn max_damage(items: &Items, stack: &ItemStack) -> i32 { items.get(&stack.item).map_or(0, |i| i.max_damage as i32) diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index 9eb8946df..27e1417d6 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -53,7 +53,7 @@ pub struct World { pub chunks: crate::chunk_map::ChunkMap, pub random: LegacyRandom, pub revision: u64, - pub health_rules: crate::health::HealthRules, + pub health_rules: HealthRules, pub air: BlockStateId, /// Sections whose geometry changed and need remeshing. pub dirty_sections: DirtySections, @@ -170,7 +170,7 @@ impl World { chunks: Default::default(), random: LegacyRandom::new(seed), revision: 0, - health_rules: crate::health::HealthRules::default(), + health_rules: HealthRules::default(), air, fast_lava: false, dirty_sections: Default::default(), @@ -377,6 +377,32 @@ impl World { } } +/// The game rules and difficulty a player's health reads (`Player.isInvulnerableTo`, +/// natural regeneration), kept with the world they belong to. +#[derive(Clone, Copy, Debug)] +pub struct HealthRules { + pub difficulty: horizon_world::food::Difficulty, + pub natural_regeneration: bool, + /// The `drowning_damage`, `fall_damage`, `fire_damage` and + /// `freeze_damage` rules `Player.isInvulnerableTo` reads. + pub drowning_damage: bool, + pub fall_damage: bool, + pub fire_damage: bool, + pub freeze_damage: bool, +} +impl Default for HealthRules { + fn default() -> Self { + Self { + difficulty: horizon_world::food::Difficulty::Normal, + natural_regeneration: true, + drowning_damage: true, + fall_damage: true, + fire_damage: true, + freeze_damage: true, + } + } +} + #[cfg(test)] mod tests { use super::World;