Files
horizon-airdef/crates/horizon-client/src/game/chat.rs
T
Ludovic Marie df14adbfba Format the workspace with rustfmt
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 00:28:32 +02:00

653 lines
24 KiB
Rust

//! Chat, the command registries and the per-world state behind commands
//! (game rules, the world clock, difficulty), bound to the game.
use super::{Dim, Game, Screen};
use horizon_client::{
chat::{Chat, ChatScreen, SYSTEM_INDICATOR},
command::{Registries, vanilla},
gamerules::GameRules,
hud::{HudBatch, rgba},
text::Text,
};
use std::collections::BTreeMap;
use winit::{
event::KeyEvent,
keyboard::{KeyCode, PhysicalKey},
};
/// The local player's name (offline single player).
pub const PLAYER_NAME: &str = "Player";
/// ServerClockManager.ServerClockInstance for the overworld clock (its
/// total ticks are the world's day time).
#[derive(Clone, Copy, Debug)]
pub struct WorldClock {
pub partial: f32,
pub rate: f32,
pub paused: bool,
}
impl Default for WorldClock {
fn default() -> Self {
Self {
partial: 0.0,
rate: 1.0,
paused: false,
}
}
}
/// A clock time marker from the timelines (ClockTimeMarker).
#[derive(Clone, Copy, Debug)]
pub struct TimeMarker {
pub ticks: i64,
pub period: Option<i64>,
pub show: bool,
}
impl TimeMarker {
pub fn occurs_at(&self, total: i64) -> bool {
match self.period {
Some(p) => self.ticks == total.rem_euclid(p),
None => self.ticks == total,
}
}
pub fn resolve(&self, total: i64) -> i64 {
match self.period {
Some(p) => {
let d = self.ticks - total.rem_euclid(p);
total + if d > 0 { d } else { p + d }
}
None => self.ticks,
}
}
}
/// UI and command state that lives beside the game.
#[derive(Default)]
pub struct UiState {
pub chat: Chat,
pub chat_screen: Option<ChatScreen>,
pub registries: Registries,
pub rules: GameRules,
pub clock: WorldClock,
/// Time markers and timelines of the overworld clock.
pub markers: BTreeMap<String, TimeMarker>,
pub timelines: BTreeMap<String, Option<i64>>,
/// 0 peaceful .. 3 hard.
pub difficulty: u8,
/// F1: hide the HUD.
pub hide_gui: bool,
/// Death message key set by the cause of death (e.g. /kill).
pub death_cause: Option<String>,
/// File name of an F2 screenshot waiting for its frame.
pub screenshot_message: Option<String>,
/// The options screens.
pub options: horizon_client::options_ui::OptionsUi,
/// The prepared resources before resource packs are layered on.
pub vanilla_root: std::path::PathBuf,
/// Death screen cause and when the player died (buttons wait 20 ticks).
pub death_text: Option<Text>,
pub died_at: Option<std::time::Instant>,
}
impl Game<'_> {
/// Registry contents for argument parsing (built when a world opens).
pub(super) fn build_registries(&mut self) {
let reg = &mut self.ui.registries;
reg.permission = 4;
let mut items: Vec<String> = self.res.items.order.iter().map(|s| s.to_string()).collect();
items.sort();
reg.items = items;
reg.item_tags = self
.res
.items
.item_tags
.keys()
.map(|k| horizon_client::command::args::normalize(k))
.collect();
reg.item_tags.sort();
reg.block_tags = self
.res
.items
.block_tags
.keys()
.map(|k| horizon_client::command::args::normalize(k))
.collect();
reg.block_tags.sort();
let registry = self.res.assets.registry;
let mut blocks: BTreeMap<String, BTreeMap<String, Vec<String>>> = BTreeMap::new();
for id in 0..registry.len() {
let Some(state) = registry.state(horizon_world::registry::BlockStateId(id as u32))
else {
continue;
};
let props = blocks.entry(state.name.clone()).or_default();
for (k, v) in &state.properties {
let values = props.entry(k.clone()).or_default();
if !values.contains(v) {
values.push(v.clone());
}
}
}
reg.blocks = blocks
.into_iter()
.map(|(k, v)| (k, v.into_iter().collect()))
.collect();
let mut summonable: Vec<String> = self
.res
.mob_types
.keys()
.map(|k| horizon_client::command::args::normalize(k))
.collect();
summonable.extend(
[
"minecraft:item",
"minecraft:experience_orb",
"minecraft:falling_block",
"minecraft:arrow",
]
.map(String::from),
);
summonable.sort();
summonable.dedup();
reg.summonable = summonable;
let root = self.options.resources.clone();
let mut types: Vec<String> = serde_json::from_slice::<serde_json::Value>(
&std::fs::read(root.join("entity-types.json")).unwrap_or_default(),
)
.ok()
.and_then(|v| {
v.as_object().map(|o| {
o.keys()
.map(|k| horizon_client::command::args::normalize(k))
.collect()
})
})
.unwrap_or_default();
if types.is_empty() {
types = reg.summonable.clone();
types.push("minecraft:player".into());
}
types.sort();
reg.entity_types = types;
let list = |dir: &str| -> Vec<String> {
let mut out: Vec<String> = std::fs::read_dir(root.join(dir))
.into_iter()
.flatten()
.flatten()
.filter_map(|e| {
e.file_name()
.to_str()?
.strip_suffix(".json")
.map(|n| format!("minecraft:{n}"))
})
.collect();
out.sort();
out
};
reg.enchantments = list("data/minecraft/enchantment");
reg.structures = list("data/minecraft/worldgen/structure");
reg.biomes = list("data/minecraft/worldgen/biome");
reg.clocks = list("data/minecraft/world_clock");
reg.dimensions = vec!["minecraft:overworld".into(), "minecraft:the_nether".into()];
reg.players = vec![PLAYER_NAME.into()];
// Timelines of the overworld clock and their time markers.
self.ui.markers.clear();
self.ui.timelines.clear();
for name in list("data/minecraft/timeline") {
let path = root.join(format!(
"data/minecraft/timeline/{}.json",
name.trim_start_matches("minecraft:")
));
let Ok(v) = serde_json::from_slice::<serde_json::Value>(
&std::fs::read(path).unwrap_or_default(),
) else {
continue;
};
if v["clock"].as_str() != Some("minecraft:overworld") {
continue;
}
let period = v["period_ticks"].as_i64();
self.ui.timelines.insert(name.clone(), period);
for (marker, def) in v["time_markers"].as_object().into_iter().flatten() {
let (ticks, show) = match def {
serde_json::Value::Number(n) => (n.as_i64().unwrap_or(0), false),
other => (
other["ticks"].as_i64().unwrap_or(0),
other["show_in_commands"].as_bool().unwrap_or(false),
),
};
self.ui.markers.insert(
marker.clone(),
TimeMarker {
ticks,
period,
show,
},
);
}
}
let reg = &mut self.ui.registries;
reg.timelines = self.ui.timelines.keys().cloned().collect();
reg.time_markers = self
.ui
.markers
.iter()
.filter(|(_, m)| m.show)
.map(|(k, _)| k.clone())
.collect();
}
/// The block the player is looking at, for coordinate suggestions.
fn refresh_dynamic_registries(&mut self) {
self.ui.registries.target_block = self.pick().map(|h| h.pos);
}
pub(super) fn open_chat(&mut self, initial: &str) {
if self.player.is_none() {
return;
}
self.refresh_dynamic_registries();
let size = self
.renderer
.as_ref()
.map_or([1280, 720], |r| [r.config.width, r.config.height]);
let b = HudBatch::new(size);
let mut screen = ChatScreen::new(initial, self.ui.chat.recent.len(), b.width, b.height);
screen.auto_suggestions = true;
self.ui.chat_screen = Some(screen);
self.screen = Screen::Chat;
self.keys.clear();
self.left = false;
self.right = false;
self.capture(false);
}
pub(super) fn close_chat(&mut self) {
self.ui.chat_screen = None;
self.ui.chat.reset_scroll();
if self.screen == Screen::Chat {
self.screen = Screen::Playing;
self.capture(true);
}
}
/// A chat message from the game (ChatComponent.addServerSystemMessage).
pub(super) fn system_message(&mut self, text: Text) {
let focused = self.screen == Screen::Chat;
self.ui.chat.add(
&self.res.atlas,
text,
Some(SYSTEM_INDICATOR),
self.ticks,
focused,
);
}
/// Keys while the chat screen is open.
pub(super) fn chat_key(&mut self, event: &KeyEvent) {
let PhysicalKey::Code(key) = event.physical_key else {
return;
};
self.chat_key_code(key, event.text.as_deref());
}
/// A key (and the text it typed) while the chat screen is open.
pub(super) fn chat_key_code(&mut self, key: KeyCode, typed_text: Option<&str>) {
let ctrl =
self.keys.contains(&KeyCode::ControlLeft) || self.keys.contains(&KeyCode::ControlRight);
let shift =
self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight);
let Some(mut screen) = self.ui.chat_screen.take() else {
return;
};
let atlas = &self.res.atlas;
let d = vanilla::dispatcher();
if screen.suggestion_key(atlas, d, &self.ui.registries, key, shift) {
self.ui.chat_screen = Some(screen);
return;
}
let mut close = false;
let mut submit = None;
match key {
KeyCode::Escape => close = true,
KeyCode::Enter | KeyCode::NumpadEnter => {
submit = Some(screen.normalized());
close = true;
}
KeyCode::ArrowUp => screen.move_in_history(&self.ui.chat.recent, -1),
KeyCode::ArrowDown => screen.move_in_history(&self.ui.chat.recent, 1),
KeyCode::PageUp => {
let n = self.ui.chat.lines_per_page(true) as i32 - 1;
self.ui.chat.scroll_by(n, true);
}
KeyCode::PageDown => {
let n = self.ui.chat.lines_per_page(true) as i32 - 1;
self.ui.chat.scroll_by(-n, true);
}
_ => {
if screen.input.key(key, ctrl, shift) {
screen.edited();
} else if let Some(text) = typed_text
&& !ctrl
{
let typed: String = text.chars().filter(|c| !c.is_control()).collect();
if !typed.is_empty() {
screen.input.insert_text(&typed);
screen.edited();
}
}
}
}
if close {
self.close_chat();
} else {
self.ui.chat_screen = Some(screen);
}
if let Some(message) = submit
&& !message.is_empty()
{
self.handle_chat_input(&message);
}
}
/// Text typed into the chat box (control socket `chat`).
pub(super) fn chat_type(&mut self, text: &str) {
if let Some(screen) = self.ui.chat_screen.as_mut() {
screen.input.insert_text(text);
screen.edited();
}
}
/// ChatScreen.handleChatInput: history, then a command or a chat line.
pub(super) fn handle_chat_input(&mut self, message: &str) {
self.ui.chat.add_recent(message);
if let Some(command) = message.strip_prefix('/') {
self.run_command(command);
} else {
let line = Text::translate(
"chat.type.text",
&[Text::literal(PLAYER_NAME), Text::literal(message)],
);
let focused = self.screen == Screen::Chat;
self.ui
.chat
.add(&self.res.atlas, line, None, self.ticks, focused);
}
}
pub(super) fn chat_scroll(&mut self, amount: f32) {
let cursor = self.cursor;
let height = self.renderer.as_ref().map_or(720.0, |r| {
HudBatch::new([r.config.width, r.config.height]).height
});
if let Some(screen) = self.ui.chat_screen.as_mut()
&& screen.scroll_suggestions(cursor, height, amount)
{
return;
}
let shift = self.keys.contains(&KeyCode::ShiftLeft);
let amount = amount.clamp(-1.0, 1.0) * if shift { 1.0 } else { 7.0 };
self.ui.chat.scroll_by(amount as i32, true);
}
pub(super) fn chat_click(&mut self) {
let cursor = self.cursor;
let height = self.renderer.as_ref().map_or(720.0, |r| {
HudBatch::new([r.config.width, r.config.height]).height
});
if let Some(screen) = self.ui.chat_screen.as_mut()
&& !screen.click(cursor, height)
&& screen.input.y <= cursor.1
{
let i = screen.input.index_at(&self.res.atlas, cursor.0);
screen.input.set_cursor(i, false);
}
}
/// Chat lines over the HUD (focused while the chat screen is open).
pub(super) fn draw_chat(&mut self, batch: &mut HudBatch) {
let focused = self.screen == Screen::Chat;
if self.ui.hide_gui && !focused {
return;
}
self.ui
.chat
.draw(batch, &self.res.atlas, self.ticks, focused);
}
pub(super) fn draw_chat_screen(&mut self, batch: &mut HudBatch) {
let Some(mut screen) = self.ui.chat_screen.take() else {
return;
};
screen.resize(batch.width, batch.height);
let bg = self.ui.chat.options.background_opacity;
screen.draw(
batch,
&self.res.atlas,
vanilla::dispatcher(),
&self.ui.registries,
self.cursor,
bg,
);
self.ui.chat_screen = Some(screen);
}
/// Advance the overworld clock (ServerClockManager.tick) when
/// `advance_time` allows it.
pub(super) fn advance_clock(&mut self) {
if !self.ui.rules.bool("advance_time")
|| self.ui.clock.paused
|| self.dim == Dim::Nether && false
{
return;
}
let c = &mut self.ui.clock;
c.partial += c.rate;
let whole = c.partial.floor();
c.partial -= whole;
self.world.day_time += whole as i64;
}
/// The engine-side rule values (block behaviour and health).
pub(super) fn level_rules(&self) -> horizon_world::level::GameRules {
let r = &self.ui.rules;
horizon_world::level::GameRules {
water_source_conversion: r.bool("water_source_conversion"),
lava_source_conversion: r.bool("lava_source_conversion"),
random_tick_speed: r.int("random_tick_speed"),
block_drops: r.bool("block_drops"),
mob_griefing: r.bool("mob_griefing"),
max_snow_accumulation_height: r.int("max_snow_accumulation_height"),
}
}
/// Apply rules mirrored in other state (natural regeneration, difficulty).
pub(super) fn sync_rules(&mut self) {
self.world.health_rules.natural_regeneration =
self.ui.rules.bool("natural_health_regeneration");
use horizon_world::food::Difficulty;
self.world.health_rules.difficulty = match self.ui.difficulty {
0 => Difficulty::Peaceful,
1 => Difficulty::Easy,
3 => Difficulty::Hard,
_ => Difficulty::Normal,
};
}
/// Load per-world command state when a world opens.
pub(super) fn load_world_state(&mut self) {
self.ui.rules = GameRules::load(&self.world_root);
self.ui.clock = WorldClock::default();
self.ui.difficulty = read_difficulty(&self.world_root).unwrap_or(2);
if let Ok(bytes) = std::fs::read(self.world_root.join("data/minecraft/world_clocks.dat"))
&& let Ok(raw) = horizon_world::compression::Compression::Gzip.decode(&bytes, 1 << 20)
&& let Ok((root, _)) =
horizon_world::nbt::read_named(&raw, horizon_world::nbt::Limits::default())
&& let Some(c) = root
.tag
.get("data")
.and_then(|d| d.get("minecraft:overworld"))
{
use horizon_world::nbt::Tag;
if let Some(Tag::Float(r)) = c.get("rate") {
self.ui.clock.rate = f32::from_bits(*r);
}
if let Some(Tag::Float(p)) = c.get("partial_tick") {
self.ui.clock.partial = f32::from_bits(*p);
}
if let Some(Tag::Byte(p)) = c.get("paused") {
self.ui.clock.paused = *p != 0;
}
}
self.ui.chat.clear();
self.build_registries();
self.sync_rules();
}
/// Save game rules, the clock and the difficulty beside level.dat.
pub(super) fn save_world_state(&mut self) {
if self.world_root.as_os_str().is_empty() {
return;
}
if let Err(e) = self.ui.rules.save(&self.world_root) {
eprintln!("Horizon: failed to save game rules: {e}");
}
use horizon_world::nbt::{Limits, NamedTag, Tag};
let c = self.ui.clock;
let clock = Tag::compound([
("total_ticks", Tag::Long(self.world.day_time)),
("partial_tick", Tag::Float(c.partial.to_bits())),
("rate", Tag::Float(c.rate.to_bits())),
("paused", Tag::Byte(i8::from(c.paused))),
]);
let root = NamedTag {
name: "".into(),
tag: Tag::compound([
("data", Tag::compound([("minecraft:overworld", clock)])),
("DataVersion", Tag::Int(horizon_world::DATA_VERSION)),
]),
};
if let Ok(bytes) = horizon_world::nbt::write_named(&root, Limits::default())
&& let Ok(gz) = horizon_world::compression::Compression::Gzip.encode(&bytes)
{
let dir = self.world_root.join("data/minecraft");
let _ = std::fs::create_dir_all(&dir);
let _ = std::fs::write(dir.join("world_clocks.dat"), gz);
}
let _ = write_difficulty(&self.world_root, self.ui.difficulty);
}
/// Death message in chat (CombatTracker.getDeathMessage, as far as the
/// cause is known to the client).
pub(super) fn death_message(&mut self) {
let cause = self.ui.death_cause.take();
self.ui.died_at = Some(std::time::Instant::now());
self.ui.death_text = None;
if !self.ui.rules.bool("show_death_messages") {
return;
}
let Some(p) = self.player.as_ref() else {
return;
};
let key = cause.unwrap_or_else(|| {
let feet = [
p.position.x.floor() as i32,
p.position.y.floor() as i32,
p.position.z.floor() as i32,
];
let fluid = self
.res
.facts
.get(self.world.block(feet[0], feet[1], feet[2]))
.fluid;
if p.position.y < f64::from(horizon_client::chunk::MIN_Y - 64) {
"death.attack.outOfWorld".into()
} else if fluid == horizon_client::blocks::Fluid::Lava {
"death.attack.lava".into()
} else if p.fall_distance > 3.0 || p.ground.on_ground && p.velocity.y < -0.5 {
"death.attack.fall".into()
} else {
"death.attack.generic".into()
}
});
let message = Text::translate(&key, &[Text::literal(PLAYER_NAME)]);
self.ui.death_text = Some(message.clone());
self.system_message(message);
}
/// F1 hides the HUD (and hand); the screenshot key still works.
pub(super) fn toggle_hide_gui(&mut self) {
self.ui.hide_gui = !self.ui.hide_gui;
}
/// F2: ScreenShot.grab into `screenshots/` with vanilla's file name.
pub(super) fn take_screenshot(&mut self) {
let dir = std::env::current_dir()
.unwrap_or_default()
.join("screenshots");
if std::fs::create_dir_all(&dir).is_err() {
return;
}
let name = screenshot_name(&dir);
let Some(renderer) = self.renderer.as_mut() else {
return;
};
renderer.screenshot = Some(dir.join(&name));
self.ui.screenshot_message = Some(name);
}
/// After a frame: report a finished F2 screenshot in chat.
pub(super) fn finish_screenshot(&mut self, result: &std::result::Result<[u32; 2], String>) {
let Some(name) = self.ui.screenshot_message.take() else {
return;
};
let message = match result {
Ok(_) => Text::translate("screenshot.success", &[Text::literal(name).underlined()]),
Err(e) => Text::translate("screenshot.failure", &[Text::literal(e.clone())]),
};
let focused = self.screen == Screen::Chat;
self.ui
.chat
.add(&self.res.atlas, message, None, self.ticks, focused);
}
#[allow(dead_code)]
fn chat_debug_fill(&self, batch: &mut HudBatch) {
batch.fill(&self.res.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0));
}
}
/// `yyyy-MM-dd_HH.mm.ss[_n].png` (Util.getFilenameFormattedDateTime, local time
/// approximated as UTC).
pub fn screenshot_name(dir: &std::path::Path) -> String {
let secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
let days = (secs / 86400) as i64;
let (h, m, s) = ((secs % 86400) / 3600, (secs % 3600) / 60, secs % 60);
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let mo = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(mo <= 2);
let base = format!("{y}-{mo:02}-{d:02}_{h:02}.{m:02}.{s:02}");
let mut n = 1;
loop {
let name = if n == 1 {
format!("{base}.png")
} else {
format!("{base}_{n}.png")
};
if !dir.join(&name).exists() {
return name;
}
n += 1;
}
}
fn read_difficulty(world: &std::path::Path) -> Option<u8> {
let bytes = std::fs::read(world.join("level.dat")).ok()?;
let raw = horizon_world::compression::Compression::Gzip
.decode(&bytes, 64 << 20)
.ok()?;
let (root, _) =
horizon_world::nbt::read_named(&raw, horizon_world::nbt::Limits::default()).ok()?;
match root.tag.get("Data")?.get("Difficulty")? {
horizon_world::nbt::Tag::Byte(b) => Some((*b).clamp(0, 3) as u8),
_ => None,
}
}
/// Patch `Data.Difficulty` in level.dat (Level::write stores the default).
fn write_difficulty(world: &std::path::Path, difficulty: u8) -> horizon_client::Result<()> {
use horizon_world::{compression::Compression, nbt};
let path = world.join("level.dat");
let bytes = std::fs::read(&path)?;
let raw = Compression::Gzip.decode(&bytes, 64 << 20)?;
let (mut root, _) = nbt::read_named(&raw, nbt::Limits::default()).map_err(|e| e.to_string())?;
if let Some(data) = root.tag.get_mut("Data")
&& let Some(d) = data.get_mut("Difficulty")
{
*d = nbt::Tag::Byte(difficulty as i8);
}
let out = nbt::write_named(&root, nbt::Limits::default()).map_err(|e| e.to_string())?;
std::fs::write(&path, Compression::Gzip.encode(&out)?)?;
Ok(())
}