diff --git a/crates/horizon-client/src/debug_keys.rs b/crates/horizon-client/src/debug_keys.rs index 43e9c10bf..8f37174c2 100644 --- a/crates/horizon-client/src/debug_keys.rs +++ b/crates/horizon-client/src/debug_keys.rs @@ -433,6 +433,23 @@ mod tests { assert_eq!(h.overlay, 0); } + #[test] + fn switcher_modifier_release_does_not_toggle_the_debug_overlay() { + let (mut k, mut h, mut b) = (DebugKeys::default(), Host::default(), KeyBinds::default()); + // Screen release handling must also work with rebound debug keys. + b.set("key.debug.modifier", "key.keyboard.f7"); + b.set("key.debug.overlay", "key.keyboard.f7"); + b.set("key.debug.switchGameMode", "key.keyboard.f8"); + press(&mut k, &mut h, &b, "key.keyboard.f7", 0); + assert!(!press(&mut k, &mut h, &b, "key.keyboard.f8", 1)); + assert_eq!(h.actions, [(DebugAction::SwitchGameMode, false)]); + h.screen = Some(OpenScreen::GameModeSwitcher); + release(&mut k, &mut h, &b, "key.keyboard.f8"); + release(&mut k, &mut h, &b, "key.keyboard.f7"); + assert!(!k.modifier_down); + assert_eq!(h.overlay, 0); + } + #[test] fn a_separate_overlay_key_toggles_on_press() { let (mut k, mut h, mut b) = (DebugKeys::default(), Host::default(), KeyBinds::default()); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 4c7754e2d..98109d8da 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -42,6 +42,7 @@ mod fov; mod frames; mod functions; mod game_mode; +mod gamemode_switcher; mod ghasts; mod golems; mod growth; @@ -351,6 +352,7 @@ impl Options { #[derive(Clone, Copy, PartialEq, Eq)] enum Screen { Playing, + GameModeSwitcher, Paused, Options, Chat, @@ -937,6 +939,7 @@ struct Game<'a> { pause_menu: bool, /// MultiPlayerGameMode.previousLocalPlayerMode (F3+N goes back to it). previous_mode: Option, + gamemode_switcher: Option, /// The system clipboard (`KeyboardHandler.clipboardManager`). clipboard: horizon_client::clipboard::SystemClipboard, /// Select All in the append-only text fields. @@ -3697,6 +3700,7 @@ impl Game<'_> { true, ); } + Screen::GameModeSwitcher => self.draw_gamemode_switcher(&mut batch), Screen::Dead => self.draw_death_screen(&mut batch), Screen::Stats => self.draw_stats(&mut batch), Screen::Advancements => self.draw_advancements(&mut batch), @@ -8225,6 +8229,7 @@ impl Game<'_> { self.pause_menu = true; self.capture(true); } + Screen::GameModeSwitcher => self.close_gamemode_switcher(false), Screen::Dead => {} Screen::Stats => self.screen = Screen::Paused, Screen::Advancements => self.close_advancements(), @@ -9506,6 +9511,7 @@ pub fn run() -> Result<()> { show_chunk_borders: false, pause_menu: true, previous_mode: None, + gamemode_switcher: None, clipboard: Default::default(), text_selection: Default::default(), saved_for_exit: false, diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index e554cd520..af70b738a 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -368,6 +368,7 @@ impl Game<'_> { } match self.screen { Screen::Playing => "playing", + Screen::GameModeSwitcher => "gamemode-switcher", Screen::Paused => "paused", Screen::Options => "options", Screen::Inventory if self.station.is_some() => "station", diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 61c0cce0a..b04b2b520 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -562,6 +562,7 @@ impl Game<'_> { } match self.screen { Screen::Playing => "playing", + Screen::GameModeSwitcher => "gamemode-switcher", Screen::Paused => "paused", Screen::Options => "options", Screen::Inventory => "inventory", @@ -713,6 +714,7 @@ fn key_code(name: &str) -> Option { "f1" => KeyCode::F1, "f2" => KeyCode::F2, "f3" => KeyCode::F3, + "f4" => KeyCode::F4, "f5" => KeyCode::F5, "f11" => KeyCode::F11, "slash" | "/" => KeyCode::Slash, diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index 20d71ae85..3e920e60c 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -49,6 +49,7 @@ impl DebugHost for Host<'_, '_> { impl Game<'_> { fn open_screen(&self) -> OpenScreen { match self.screen { + Screen::GameModeSwitcher => OpenScreen::GameModeSwitcher, Screen::Playing if self.book.is_none() && self.sign_edit.is_none() => OpenScreen::None, Screen::Paused if !self.pause_menu => OpenScreen::PauseWithoutMenu, _ => OpenScreen::Other, @@ -62,6 +63,19 @@ impl Game<'_> { return false; }; let pressed = action != KeyAction::Release; + let switcher_open = self.screen == Screen::GameModeSwitcher; + if switcher_open && pressed { + if name == self.settings.keys.get("key.debug.switchGameMode") { + if let Some(switcher) = &mut self.gamemode_switcher { + switcher.cycle(); + } + } else if key == KeyCode::Escape { + self.close_gamemode_switcher(false); + } else if matches!(key, KeyCode::F2 | KeyCode::F11) { + return false; + } + return true; + } // Screens with a text box take every key press first // (EditBox.keyPressed); releases still reach KeyboardHandler. let typing = matches!( @@ -116,6 +130,13 @@ impl Game<'_> { now, ); self.debug_keys = keys; + if switcher_open { + if name == binds.get("key.debug.modifier") { + self.close_gamemode_switcher(true); + return true; + } + return false; + } if !pressed { return false; } @@ -190,7 +211,7 @@ impl Game<'_> { self.settings.reduced_debug_info || self.ui.rules.bool("reduced_debug_info") } /// `Permissions.COMMANDS_GAMEMASTER` (`GameModeCommand.PERMISSION_CHECK`). - fn gamemaster(&self) -> bool { + pub(super) fn gamemaster(&self) -> bool { self.ui.registries.permission >= 2 } fn toggle_option(&mut self, key: &str) -> bool { @@ -268,10 +289,10 @@ impl Game<'_> { true } DebugAction::SwitchGameMode if self.open_screen() == OpenScreen::None => { - // Minecraft.canSwitchGameMode and the permission; the - // GameModeSwitcherScreen itself is not drawn yet. if self.player.is_none() || !self.gamemaster() { self.debug_translated("debug.gamemodes.error"); + } else { + self.open_gamemode_switcher(); } true } @@ -343,8 +364,15 @@ impl Game<'_> { /// `ServerboundChangeGameModePacket` handled by the integrated server: /// `GameModeCommand.setGameMode` with its feedback. pub(super) fn change_game_mode(&mut self, mode: GameMode) { - // On a server the packet decides; Horizon's client does not send it yet. if self.remote.is_some() { + use horizon_protocol::packets::play::{ChangeGameMode, Serverbound}; + let mode = match mode { + GameMode::Survival => 0, + GameMode::Creative => 1, + GameMode::Adventure => 2, + GameMode::Spectator => 3, + }; + self.send(Serverbound::ChangeGameMode(ChangeGameMode { mode })); return; } if self.set_game_mode(mode) { diff --git a/crates/horizon-client/src/game/gamemode_switcher.rs b/crates/horizon-client/src/game/gamemode_switcher.rs new file mode 100644 index 000000000..e7826ba22 --- /dev/null +++ b/crates/horizon-client/src/game/gamemode_switcher.rs @@ -0,0 +1,86 @@ +//! The non-pausing F3+F4 screen (`GameModeSwitcherScreen`). +use super::{Game, ItemStack, Screen}; +use horizon_client::{ + game_mode_switcher::{GameModeSwitcher, ICONS, MODES, slot_origin}, + hud::HudBatch, + keybinds, + text::Text, +}; + +impl Game<'_> { + pub(super) fn open_gamemode_switcher(&mut self) { + self.gamemode_switcher = Some(GameModeSwitcher::new(self.mode, self.previous_mode)); + self.screen = Screen::GameModeSwitcher; + self.keys.clear(); + self.left = false; + self.right = false; + self.mining = None; + self.capture(false); + } + + pub(super) fn close_gamemode_switcher(&mut self, apply: bool) { + let selected = self.gamemode_switcher.take().map(|s| s.selected); + self.screen = Screen::Playing; + self.capture(true); + if apply + && self.player.is_some() + && self.gamemaster() + && let Some(mode) = selected + && mode != self.mode + { + self.change_game_mode(mode); + } + } + + pub(super) fn draw_gamemode_switcher(&mut self, batch: &mut HudBatch) { + let (w, h) = (batch.width as i32, batch.height as i32); + let Some(switcher) = &mut self.gamemode_switcher else { + return; + }; + switcher.hover(w, h, (self.cursor.0 as i32, self.cursor.1 as i32)); + let selected = switcher.selected; + let atlas = &self.res.atlas; + batch.sprite_region( + atlas, + "gui/container/gamemode_switcher", + [(w / 2 - 62) as f32, (h / 2 - 58) as f32, 125.0, 75.0], + 128.0, + 128.0, + ); + let title = Text::translate(&format!("gameMode.{}", selected.name()), &[]); + let help = Text::translate( + "debug.gamemodes.select_next", + &[ + keybinds::display_name(self.settings.keys.get("key.debug.switchGameMode")) + .with_color(0x55FFFF), + ], + ); + for (text, y) in [(title, h / 2 - 51), (help, h / 2 + 5)] { + let x = w / 2 - (HudBatch::text_width(atlas, &text.plain()) / 2.0) as i32; + batch.text_styled(atlas, &text, x as f32, y as f32, u32::MAX, true); + } + for (index, mode) in MODES.into_iter().enumerate() { + let (x, y) = slot_origin(w, h, index); + batch.sprite( + &self.res.atlas, + "gui/sprites/gamemode_switcher/slot", + x as f32, + y as f32, + ); + if mode == selected { + batch.sprite( + &self.res.atlas, + "gui/sprites/gamemode_switcher/selection", + x as f32, + y as f32, + ); + } + self.draw_item_model( + batch, + &ItemStack::new(ICONS[index], 1), + (x + 5) as f32, + (y + 5) as f32, + ); + } + } +} diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 293afdcdd..7faba7f6c 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -412,6 +412,32 @@ impl Game<'_> { } } S::ChatCommand(c) => self.guest_command(host, conn, &c.command), + S::ChangeGameMode(p) if host.hub.guests[gi].permission >= 2 => { + if let Some(mode) = usize::try_from(p.mode) + .ok() + .and_then(|index| horizon_client::command::args::GameMode::ALL.get(index)) + { + let lines = self.as_guest(host, conn, |g| { + g.chat_capture = Some(Vec::new()); + g.change_game_mode(*mode); + g.chat_capture + .take() + .unwrap_or_default() + .iter() + .map(|t| horizon_client::lan::data::component_nbt(&t.component())) + .collect::>() + }); + for content in lines.unwrap_or_default() { + host.hub.send_to( + conn, + &C::SystemChat(play::SystemChat { + content, + overlay: false, + }), + ); + } + } + } S::Unknown(8, payload) => { // A signed command: the text comes first. if let Ok(text) = horizon_protocol::buf::Reader::new(&payload).string(32767) { diff --git a/crates/horizon-client/src/game_mode_switcher.rs b/crates/horizon-client/src/game_mode_switcher.rs new file mode 100644 index 000000000..a3a4c4f5f --- /dev/null +++ b/crates/horizon-client/src/game_mode_switcher.rs @@ -0,0 +1,119 @@ +//! Selection and hit testing for the debug game-mode switcher. +use crate::command::args::GameMode; + +pub const MODES: [GameMode; 4] = [ + GameMode::Creative, + GameMode::Survival, + GameMode::Adventure, + GameMode::Spectator, +]; + +pub const ICONS: [&str; 4] = [ + "minecraft:grass_block", + "minecraft:iron_sword", + "minecraft:buried_treasure_map", + "minecraft:ender_eye", +]; + +pub const SLOT_SIZE: i32 = 26; + +pub fn slot_origin(width: i32, height: i32, index: usize) -> (i32, i32) { + (width / 2 - 59 + index as i32 * 31, height / 2 - 31) +} + +pub struct GameModeSwitcher { + pub selected: GameMode, + first_mouse: Option<(i32, i32)>, +} + +impl GameModeSwitcher { + pub fn new(current: GameMode, previous: Option) -> Self { + Self { + selected: previous.unwrap_or(if current == GameMode::Creative { + GameMode::Survival + } else { + GameMode::Creative + }), + first_mouse: None, + } + } + + pub fn cycle(&mut self) { + let index = MODES.iter().position(|m| *m == self.selected).unwrap(); + self.selected = MODES[(index + 1) % MODES.len()]; + self.first_mouse = None; + } + + pub fn hover(&mut self, width: i32, height: i32, cursor: (i32, i32)) { + if *self.first_mouse.get_or_insert(cursor) == cursor { + return; + } + for (index, mode) in MODES.iter().enumerate() { + let (x, y) = slot_origin(width, height, index); + if cursor.0 >= x + && cursor.0 < x + SLOT_SIZE + && cursor.1 >= y + && cursor.1 < y + SLOT_SIZE + { + self.selected = *mode; + return; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn initial_selection_and_cycle_follow_debug_order() { + assert_eq!( + GameModeSwitcher::new(GameMode::Creative, None).selected, + GameMode::Survival + ); + for current in [GameMode::Survival, GameMode::Adventure, GameMode::Spectator] { + assert_eq!( + GameModeSwitcher::new(current, None).selected, + GameMode::Creative + ); + } + let mut state = GameModeSwitcher::new(GameMode::Survival, Some(GameMode::Adventure)); + for mode in [ + GameMode::Adventure, + GameMode::Spectator, + GameMode::Creative, + GameMode::Survival, + ] { + assert_eq!(state.selected, mode); + state.cycle(); + } + } + + #[test] + fn stationary_mouse_does_not_override_keyboard_selection() { + let mut state = GameModeSwitcher::new(GameMode::Creative, None); + let cursor = slot_origin(320, 240, 0); + state.hover(320, 240, cursor); + state.hover(320, 240, cursor); + assert_eq!(state.selected, GameMode::Survival); + state.hover(320, 240, (cursor.0 + 1, cursor.1)); + assert_eq!(state.selected, GameMode::Creative); + state.cycle(); + state.hover(320, 240, (cursor.0 + 1, cursor.1)); + assert_eq!(state.selected, GameMode::Survival); + } + + #[test] + fn hover_slots_exclude_gaps_and_right_and_bottom_edges() { + let mut state = GameModeSwitcher::new(GameMode::Creative, None); + state.hover(320, 240, (0, 0)); + let (x, y) = slot_origin(320, 240, 2); + for cursor in [(x - 1, y), (x + 26, y), (x, y - 1), (x, y + 26)] { + state.hover(320, 240, cursor); + assert_eq!(state.selected, GameMode::Survival); + } + state.hover(320, 240, (x + 25, y + 25)); + assert_eq!(state.selected, GameMode::Adventure); + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index a7e3913bb..5085befee 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -59,6 +59,7 @@ pub mod flatgen; pub mod fog; pub mod font; pub mod front; +pub mod game_mode_switcher; pub mod gamepad; pub mod gamerules; pub mod gfx; diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index c9cddabb6..49f75f7f3 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -1073,6 +1073,10 @@ packet!( packet!(AcceptTeleportation { id: i32 => VarInt, x: f64 => Double, y: f64 => Double, z: f64 => Double, yaw: f32 => Float, pitch: f32 => Float }); packet!(Attack { id: i32 => VarInt }); +packet!( + /// GameType ids: 0 survival, 1 creative, 2 adventure, 3 spectator. + ChangeGameMode { mode: i32 => VarInt } +); packet!(LastSeenUpdate { offset: i32 => VarInt, acknowledged: [u8; 3] => Fixed3, checksum: i8 => Byte }); /// LastSeenMessages.Update's fixed 20-bit BitSet (3 bytes). pub struct Fixed3; @@ -1177,6 +1181,7 @@ impl Codec<[f32; 3]> for Cursor { packet_enum!(Serverbound, crate::ids::play::serverbound { AcceptTeleportation(AcceptTeleportation) = ACCEPT_TELEPORTATION, Attack(Attack) = ATTACK, + ChangeGameMode(ChangeGameMode) = CHANGE_GAME_MODE, Chat(Chat) = CHAT, ChatCommand(ChatCommand) = CHAT_COMMAND, ChunkBatchReceived(ChunkBatchReceived) = CHUNK_BATCH_RECEIVED, @@ -1616,6 +1621,15 @@ mod tests { ); } + #[test] + fn change_game_mode_uses_the_game_type_varint() { + for mode in 0..=3 { + let packet = Serverbound::ChangeGameMode(ChangeGameMode { mode }); + assert_eq!(packet.encode(), vec![5, mode as u8]); + round_trip(packet, Serverbound::encode, Serverbound::decode); + } + } + #[test] fn move_entity_deltas_decode_like_vec_delta_codec() { let base = [10.0, 64.0, -3.5];