Files
horizon-airdef/crates/horizon-client/src/game/control.rs
T
Ludovic Marie 682927cb69 Hear game events from players and mobs, light the darkness effect and persist the warden warning
Players and mobs now report footsteps, swimming, landings, splashes, damage, deaths, eating, drinking, container use, shots and landed projectiles, blasts, lightning and primed TNT to the vibration system, with sneaking and wool respected. The darkness effect fades in and out over 22 ticks, closes the fog in to 15 blocks, dims the lightmap with its pulse and hides the sun, moon and stars. Active sculk sensors shed redstone dust, charge and shriek level events show their particles, and the player's warning level is saved with the player data.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-09 13:43:56 +02:00

586 lines
23 KiB
Rust

//! Commands from the control socket (`horizon-ctl`), run on the game thread.
use super::{Game, Screen};
use horizon_client::{Result, items::ItemStack};
use horizon_core::geometry::Vec3;
use serde_json::{Value, json};
use std::{
sync::mpsc::Sender,
time::{Duration, Instant},
};
use winit::{event::MouseButton, event_loop::ActiveEventLoop, keyboard::KeyCode};
const HELP: &[&str] = &[
"status game, player, streaming and renderer state",
"key KEY down|up|tap press or release a key (w a s d space shift ctrl e q esc f3 1-9 arrows ...)",
"release release every key and mouse button",
"mouse left|right|middle down|up|click",
"look YAW PITCH set the view direction in degrees",
"turn DYAW DPITCH rotate the view",
"tp X Y Z teleport the player",
"hotbar 1-9 select a hotbar slot",
"give ITEM [COUNT] add items to the inventory",
"render-distance N chunks, 2..64",
"time TICKS set the time of day",
"summon KIND [X Y Z] [baby] spawn a mob (in front of the player without a position)",
"mobs [RADIUS] list mobs near the player with their AI state",
"fill X1 Y1 Z1 X2 Y2 Z2 BLOCK set a box of loaded blocks",
"resume leave the pause menu",
"screenshot PATH write the next frame as PNG",
"chat TEXT send a chat line or /command as if typed",
"type TEXT type into the open chat box (key enter tap sends)",
"chat-log [N] the newest N chat messages (default 10)",
"options [PAGE] open the options (video sound controls keybinds mouse chat accessibility language font packs)",
"stats [reset] frame-time summary since the last reset",
"bench SECONDS reset stats, wait, then reply with the summary",
"open WORLD [SEED] [creative] open or create a world from the title screen",
"save save the world",
"connect HOST[:PORT] [NAME] join a multiplayer server (offline mode) from the title screen",
"chat MESSAGE send chat or a /command to the server",
"disconnect leave the server for the server list",
"respawn respawn after death on a server",
"quit save and exit",
];
impl Game<'_> {
pub(super) fn poll_control(&mut self, event_loop: &ActiveEventLoop) {
if let Some((deadline, reply)) = self.pending_bench.take() {
if Instant::now() >= deadline {
let _ = reply.send(self.frame_stats.summary().to_string());
} else {
self.pending_bench = Some((deadline, reply));
}
}
while let Some(request) = self.control.as_ref().and_then(|c| c.try_recv()) {
let reply = match self.control_command(&request.line, &request.reply, event_loop) {
Ok(Some(value)) => value,
// Deferred: the command keeps its own reply channel.
Ok(None) => continue,
Err(e) => json!({ "error": e.to_string() }),
};
let _ = request.reply.send(reply.to_string());
}
}
fn control_command(
&mut self,
line: &str,
reply: &Sender<String>,
event_loop: &ActiveEventLoop,
) -> Result<Option<Value>> {
let words: Vec<&str> = line.split_whitespace().collect();
let arg = |i: usize| {
words
.get(i)
.copied()
.ok_or_else(|| format!("missing argument {i} for {}", words[0]))
};
let ok = || Ok(Some(json!({ "ok": true })));
if let Some(value) = self.block_command(&words)? {
return Ok(Some(value));
}
match words[0] {
"help" => Ok(Some(json!({ "commands": HELP
.iter()
.chain(super::station_control::HELP)
.chain(super::blockctl::HELP)
.chain(super::render_control::HELP)
.chain(super::sculk::HELP)
.collect::<Vec<_>>() }))),
"setblock" | "fill" | "particle" | "signedit" => self.render_command(&words),
"sculk" => Ok(Some(self.sculk_command(&words)?)),
"status" => Ok(Some(self.control_status())),
"key" => {
let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?;
self.require_world()?;
// Physical key presses follow the key binds like the keyboard does.
let key = if matches!(self.screen, Screen::Chat | Screen::Options) {
key
} else {
match self.settings.keys.translate(key) {
Some(Ok(k)) => k,
Some(Err(button)) => {
let action = arg(2)?;
if self.screen == Screen::Playing {
if action != "up" {
self.play_mouse(button, true)?;
}
if action != "down" {
self.play_mouse(button, false)?;
}
}
return ok();
}
None => return ok(),
}
};
match arg(2)? {
"down" => self.control_key_down(key)?,
"up" => {
self.keys.remove(&key);
}
"tap" => {
self.control_key_down(key)?;
self.keys.remove(&key);
}
other => {
return Err(
format!("key action must be down, up or tap, not {other}").into()
);
}
}
ok()
}
"release" => {
self.keys.clear();
self.left = false;
self.right = false;
ok()
}
"mouse" => {
let button = match arg(1)? {
"left" => MouseButton::Left,
"right" => MouseButton::Right,
"middle" => MouseButton::Middle,
other => return Err(format!("unknown mouse button {other}").into()),
};
self.require_world()?;
if self.screen != Screen::Playing {
return Err(format!(
"mouse needs the playing screen, not {}",
self.screen_name()
)
.into());
}
match arg(2)? {
"down" => self.play_mouse(button, true)?,
"up" => self.play_mouse(button, false)?,
"click" => {
self.play_mouse(button, true)?;
self.play_mouse(button, false)?;
}
other => {
return Err(
format!("mouse action must be down, up or click, not {other}").into(),
);
}
}
ok()
}
"look" => {
self.yaw = arg(1)?.parse()?;
self.pitch = arg(2)?.parse::<f32>()?.clamp(-90.0, 90.0);
ok()
}
"turn" => {
self.yaw += arg(1)?.parse::<f32>()?;
self.pitch = (self.pitch + arg(2)?.parse::<f32>()?).clamp(-90.0, 90.0);
ok()
}
"tp" => {
let to = Vec3::new(arg(1)?.parse()?, arg(2)?.parse()?, arg(3)?.parse()?);
let player = self.player.as_mut().ok_or("no player yet")?;
player.position = to;
player.velocity = Vec3::new(0.0, 0.0, 0.0);
player.fall_distance = 0.0;
self.previous_position = to;
ok()
}
"hotbar" => {
let slot: usize = arg(1)?.parse()?;
if !(1..=9).contains(&slot) {
return Err("hotbar slot must be 1..9".into());
}
self.selected = slot - 1;
ok()
}
"give" => {
self.require_world()?;
let name = arg(1)?;
let item = if name.contains(':') {
name.to_owned()
} else {
format!("minecraft:{name}")
};
let info = self
.res
.items
.get(&item)
.ok_or_else(|| format!("unknown item {item}"))?;
let count: u32 = words.get(2).map_or(Ok(1), |c| c.parse())?;
let max = info.max_stack;
let mut given = 0;
// Stop once the inventory is full.
while given < count {
let n = (count - given).min(max);
let rest = self
.give(ItemStack {
item: item.as_str().into(),
count: n,
damage: 0,
extra: None,
})
.map_or(0, |r| r.count);
given += n - rest;
if rest > 0 {
break;
}
}
Ok(Some(json!({ "ok": true, "given": given })))
}
"render-distance" => {
let n: i32 = arg(1)?.parse()?;
if !(2..=64).contains(&n) {
return Err("render distance must be 2..64".into());
}
self.settings.render_distance = n;
self.apply_settings();
ok()
}
"time" => {
self.world.day_time = arg(1)?.parse()?;
ok()
}
"summon" => {
self.require_world()?;
let baby = words.contains(&"baby");
let nums: Vec<f64> = words[2..].iter().filter_map(|w| w.parse().ok()).collect();
let at = (nums.len() >= 3).then(|| [nums[0], nums[1], nums[2]]);
let id = self.summon(arg(1)?, at, baby)?;
Ok(Some(json!({ "ok": true, "id": id })))
}
"mobs" => {
self.require_world()?;
let radius: f64 = words.get(1).map_or(Ok(64.0), |r| r.parse())?;
Ok(Some(self.control_mobs(radius)))
}
"resume" => {
if self.screen == Screen::Paused {
self.screen = Screen::Playing;
}
ok()
}
"screenshot" => {
let renderer = self.renderer.as_mut().ok_or("no renderer yet")?;
if self.pending_screenshot.is_some() {
return Err("a screenshot is already pending".into());
}
renderer.screenshot = Some(arg(1)?.into());
self.pending_screenshot = Some(reply.clone());
Ok(None)
}
"chat" => {
let text = line.trim_start().strip_prefix("chat").unwrap_or("").trim();
if self.remote.is_some() {
self.send_chat(text);
return ok();
}
self.require_world()?;
self.handle_chat_input(text);
Ok(Some(
json!({ "ok": true, "chat": self.ui.chat.recent_lines(5) }),
))
}
"type" => {
self.require_world()?;
let text = line
.trim_start()
.strip_prefix("type")
.unwrap_or("")
.strip_prefix(' ')
.unwrap_or("");
if self.book.is_some() {
self.book_type(text);
return ok();
}
match self.screen {
Screen::Chat => self.chat_type(text),
Screen::Options => self.ui.options.type_text(text),
_ => {
return Err(
"type needs the chat screen (key t tap) or the language search".into(),
);
}
}
ok()
}
"options" => {
use horizon_client::options_ui::Page;
let page = match words.get(1).copied().unwrap_or("main") {
"main" => Page::Main,
"video" => Page::Video,
"sound" => Page::Sound,
"controls" => Page::Controls,
"keybinds" => Page::KeyBinds,
"mouse" => Page::Mouse,
"chat" => Page::Chat,
"accessibility" => Page::Accessibility,
"language" => Page::Language,
"font" => Page::Font,
"packs" => Page::Packs,
other => return Err(format!("unknown options page {other}").into()),
};
if self.screen == Screen::Playing && self.title.is_none() {
self.capture(false);
}
self.open_options(self.title.is_some());
self.ui.options.show(page);
ok()
}
"chat-log" => {
let n = words.get(1).map_or(Ok(10), |n| n.parse())?;
Ok(Some(json!({ "chat": self.ui.chat.recent_lines(n) })))
}
"stats" => {
let summary = self.frame_stats.summary();
if words.get(1) == Some(&"reset") {
self.frame_stats.reset();
}
Ok(Some(summary))
}
"bench" => {
let seconds: f64 = arg(1)?.parse()?;
if self.pending_bench.is_some() {
return Err("a benchmark is already running".into());
}
self.frame_stats.reset();
self.pending_bench = Some((
Instant::now() + Duration::from_secs_f64(seconds),
reply.clone(),
));
Ok(None)
}
"open" => {
if self.title.is_none() {
return Err("a world is already open".into());
}
let folder = arg(1)?;
let seed = words.get(2).map(|s| s.parse::<i64>()).transpose()?;
let creative = words.get(3) == Some(&"creative");
self.open_world(folder, Some(folder), seed, creative)?;
ok()
}
"connect" => {
if self.title.is_none() {
return Err("leave the current world first".into());
}
let name = words
.get(2)
.map_or_else(|| self.options.player_name.clone(), |n| (*n).to_owned());
self.connect_server(arg(1)?, &name)?;
ok()
}
"respawn" => {
if self.remote.is_none() || self.screen != Screen::Dead {
return Err("respawn needs the death screen on a server".into());
}
self.remote_respawn();
ok()
}
"disconnect" => {
if self.remote.is_none() {
return Err("not connected to a server".into());
}
self.leave_server(None)?;
ok()
}
"save" => {
self.require_world()?;
self.save_game()?;
ok()
}
"dragon-hurt" => {
// Test hook: damage the dragon's head as the player would.
let amount: f32 = arg(1)?.parse()?;
self.hit_special(super::dragon::SPECIAL, amount, true);
ok()
}
"quit" => {
if self.title.is_none() {
// Player.closeContainer: menu items go back before saving.
self.close_container();
if self.remote.is_none() {
self.stats.custom("leave_game", 1);
}
self.save_game()?;
}
event_loop.exit();
ok()
}
other => match self.station_command(&words)? {
Some(value) => Ok(Some(value)),
None => Err(format!("unknown command {other}; try help").into()),
},
}
}
fn require_world(&self) -> Result<()> {
if self.title.is_some() {
return Err("no world open; use: open WORLD [SEED] [creative]".into());
}
Ok(())
}
fn control_key_down(&mut self, key: KeyCode) -> Result<()> {
if self.screen == Screen::Chat {
self.chat_key_code(key, None);
return Ok(());
}
if self.screen == Screen::Options {
return self.options_key(key, None);
}
if self.keys.insert(key) {
self.key_pressed(key)?;
}
Ok(())
}
fn screen_name(&self) -> &'static str {
if self.title.is_some() {
return "title";
}
match self.screen {
Screen::Playing => "playing",
Screen::Paused => "paused",
Screen::Options => "options",
Screen::Inventory => "inventory",
Screen::Creative => "creative",
Screen::Dead => "dead",
Screen::Chat => "chat",
Screen::Stats => "stats",
Screen::Advancements => "advancements",
}
}
fn control_status(&self) -> Value {
let player = self.player.as_ref().map(|p| {
json!({
"position": [p.position.x, p.position.y, p.position.z],
"velocity": [p.velocity.x, p.velocity.y, p.velocity.z],
"on_ground": p.ground.on_ground,
"health": p.health.health(),
"food": p.health.food.food,
})
});
let target = self.pick().map(|hit| {
let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]);
json!({ "pos": hit.pos, "block": &*self.res.facts.get(state).name })
});
let renderer = self.renderer.as_ref().map(|r| {
json!({
"gpu": r.info.name,
"backend": format!("{:?}", r.info.backend),
"size": [r.config.width, r.config.height],
"present_mode": format!("{:?}", r.config.present_mode),
"drawn_sections": r.drawn_sections,
"uploaded_bytes": r.uploaded_bytes,
})
});
json!({
"screen": self.screen_name(),
"dimension": self.dim.id(),
"creative": self.creative,
"player": player,
"yaw": self.yaw,
"pitch": self.pitch,
"target": target,
"selected": self.selected + 1,
"held": self.held().map(|s| json!({ "item": &*s.item, "count": s.count })),
"offhand": self.offhand.as_ref().map(|s| json!({ "item": &*s.item, "count": s.count, "damage": s.damage })),
"keys": self.keys.iter().map(|k| format!("{k:?}")).collect::<Vec<_>>(),
"fps": self.fps,
"frames": self.frames,
"ticks": self.ticks,
"day_time": self.world.day_time,
"music": self.music.current(),
"fishing": self.hook_status(),
"tridents": self.tridents.len(),
"rockets": self.rockets.len(),
"fight": self.dragon_status(),
"carts": self.carts.iter().map(|c| serde_json::json!({"kind": c.kind.id(), "position": [c.position.x, c.position.y, c.position.z], "velocity": [c.velocity.x, c.velocity.y, c.velocity.z]})).collect::<Vec<_>>(),
"riding": self.riding,
"using": self.using,
"render_distance": self.streaming.radius,
"chunks": self.world.chunks.len(),
"pending_chunks": self.streaming.pending(),
"generated_chunks": self.streaming.generated_total,
"meshed_sections": self.streaming.meshed_total,
"renderer": renderer,
"uptime_seconds": self.started.elapsed().as_secs_f64(),
"server": self.remote_status(),
})
}
}
fn key_code(name: &str) -> Option<KeyCode> {
let name = name.to_ascii_lowercase();
let letters = [
KeyCode::KeyA,
KeyCode::KeyB,
KeyCode::KeyC,
KeyCode::KeyD,
KeyCode::KeyE,
KeyCode::KeyF,
KeyCode::KeyG,
KeyCode::KeyH,
KeyCode::KeyI,
KeyCode::KeyJ,
KeyCode::KeyK,
KeyCode::KeyL,
KeyCode::KeyM,
KeyCode::KeyN,
KeyCode::KeyO,
KeyCode::KeyP,
KeyCode::KeyQ,
KeyCode::KeyR,
KeyCode::KeyS,
KeyCode::KeyT,
KeyCode::KeyU,
KeyCode::KeyV,
KeyCode::KeyW,
KeyCode::KeyX,
KeyCode::KeyY,
KeyCode::KeyZ,
];
let digits = [
KeyCode::Digit0,
KeyCode::Digit1,
KeyCode::Digit2,
KeyCode::Digit3,
KeyCode::Digit4,
KeyCode::Digit5,
KeyCode::Digit6,
KeyCode::Digit7,
KeyCode::Digit8,
KeyCode::Digit9,
];
if let [c] = name.as_bytes() {
return match c {
b'a'..=b'z' => Some(letters[usize::from(c - b'a')]),
b'0'..=b'9' => Some(digits[usize::from(c - b'0')]),
_ => None,
};
}
Some(match name.as_str() {
"space" => KeyCode::Space,
"shift" | "lshift" => KeyCode::ShiftLeft,
"ctrl" | "control" | "lctrl" => KeyCode::ControlLeft,
"esc" | "escape" => KeyCode::Escape,
"tab" => KeyCode::Tab,
"enter" | "return" => KeyCode::Enter,
"f1" => KeyCode::F1,
"f2" => KeyCode::F2,
"f3" => KeyCode::F3,
"f5" => KeyCode::F5,
"f11" => KeyCode::F11,
"slash" | "/" => KeyCode::Slash,
"backspace" => KeyCode::Backspace,
"pageup" => KeyCode::PageUp,
"pagedown" => KeyCode::PageDown,
"left" => KeyCode::ArrowLeft,
"right" => KeyCode::ArrowRight,
"up" => KeyCode::ArrowUp,
"down" => KeyCode::ArrowDown,
_ => return None,
})
}