Add chat, the vanilla command set and game rules to the game

ChatComponent/ChatScreen port: wrapped 100-line history with the 200-tick
fade, scrolling, system message indicator, input history, argument
colouring, usage hints, parse errors and tab completion. Commands:
help, gamemode, defaultgamemode, give, teleport/tp, time (26.3 clocks and
markers), weather, kill, summon, setblock, fill, clone, experience/xp,
gamerule, difficulty, seed, spawnpoint, setworldspawn, clear, locate biome,
say, me, msg, list. Game rules gate the clock, weather, random ticks,
keep_inventory, death messages and command feedback, and are saved to
data/minecraft/game_rules.dat. F1 hides the HUD, F2 saves screenshots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-08 15:29:51 +02:00
parent 67f51123e8
commit c9eeed0300
8 changed files with 2905 additions and 6 deletions
+590
View File
@@ -0,0 +1,590 @@
//! Chat: the message list (ChatComponent: wrapping, 100-line history,
//! 200-tick fade, scrolling, system message indicator) and the chat screen
//! (ChatScreen + EditBox + CommandSuggestions: history navigation, argument
//! colouring, usage hints, parse errors and tab completion).
use crate::{
command::{Dispatcher, ParseResults, Registries, Suggestion},
hud::{HudAtlas, HudBatch, rgba},
text::{self, Style, Text},
ui::{EditBox, char_len},
};
/// GuiMessageTag.systemSinglePlayer's indicator colour.
pub const SYSTEM_INDICATOR: u32 = 0xD0D0D0;
#[derive(Clone, Copy, Debug)]
pub struct ChatOptions {
pub opacity: f32,
pub background_opacity: f32,
pub scale: f32,
pub width: f32,
pub height_focused: f32,
pub height_unfocused: f32,
pub line_spacing: f32,
}
impl Default for ChatOptions {
fn default() -> Self {
Self { opacity: 1.0, background_opacity: 0.5, scale: 1.0, width: 1.0, height_focused: 1.0, height_unfocused: 70.0 / 160.0, line_spacing: 0.0 }
}
}
impl ChatOptions {
/// ChatComponent.getWidth/getHeight.
pub fn width_px(&self) -> f32 {
(self.width * 280.0 + 40.0).floor()
}
pub fn height_px(&self, focused: bool) -> f32 {
((if focused { self.height_focused } else { self.height_unfocused }) * 160.0 + 20.0).floor()
}
pub fn line_height(&self) -> f32 {
(9.0 * (self.line_spacing + 1.0)).floor()
}
}
#[derive(Clone, Debug)]
struct Message {
added: u64,
content: Text,
indicator: Option<u32>,
}
#[derive(Clone, Debug)]
struct Line {
added: u64,
content: Text,
indicator: Option<u32>,
}
#[derive(Default)]
pub struct Chat {
messages: Vec<Message>,
/// Wrapped lines, newest first.
lines: Vec<Line>,
/// Sent messages and commands (ChatComponent.recentChat).
pub recent: Vec<String>,
scroll: usize,
new_since_scroll: bool,
pub options: ChatOptions,
/// Messages printed to stdout as `[CHAT]` (vanilla logs them).
pub log: bool,
}
impl Chat {
pub fn lines_per_page(&self, focused: bool) -> usize {
(self.options.height_px(focused) / self.options.line_height().max(1.0)) as usize
}
fn max_width(&self) -> f32 {
(self.options.width_px() / self.options.scale.max(0.01)).floor()
}
/// ChatComponent.addMessage: wrap, prepend and trim to 100 lines.
pub fn add(&mut self, atlas: &HudAtlas, content: Text, indicator: Option<u32>, ticks: u64, focused: bool) {
if self.log {
println!("[CHAT] {}", content.plain());
}
let message = Message { added: ticks, content, indicator };
self.add_lines(atlas, &message, focused);
self.messages.insert(0, message);
self.messages.truncate(100);
}
fn add_lines(&mut self, atlas: &HudAtlas, message: &Message, focused: bool) {
let width = self.max_width();
for line in atlas.font.split(&message.content, width) {
if focused && self.scroll > 0 {
self.new_since_scroll = true;
self.scroll_by(1, focused);
}
self.lines.insert(0, Line { added: message.added, content: line, indicator: message.indicator });
}
self.lines.truncate(100);
}
/// Re-wrap after a width or scale change (ChatComponent.rescaleChat).
pub fn rescale(&mut self, atlas: &HudAtlas) {
self.scroll = 0;
self.new_since_scroll = false;
self.lines.clear();
let messages: Vec<Message> = self.messages.iter().rev().cloned().collect();
for m in &messages {
self.add_lines(atlas, m, false);
}
}
pub fn clear(&mut self) {
self.messages.clear();
self.lines.clear();
self.scroll = 0;
}
pub fn add_recent(&mut self, message: &str) {
if self.recent.last().map(String::as_str) != Some(message) {
if self.recent.len() >= 100 {
self.recent.remove(0);
}
self.recent.push(message.to_owned());
}
}
pub fn reset_scroll(&mut self) {
self.scroll = 0;
self.new_since_scroll = false;
}
pub fn scroll_by(&mut self, dir: i32, focused: bool) {
let max = self.lines.len().saturating_sub(self.lines_per_page(focused)) as i32;
let pos = (self.scroll as i32 + dir).min(max);
if pos <= 0 {
self.scroll = 0;
self.new_since_scroll = false;
} else {
self.scroll = pos as usize;
}
}
/// ChatComponent.extractRenderState.
pub fn draw(&self, batch: &mut HudBatch, atlas: &HudAtlas, ticks: u64, focused: bool) {
if self.lines.is_empty() {
return;
}
let o = &self.options;
let scale = o.scale;
if scale <= 0.0 {
return;
}
let max_width = (o.width_px() / scale).ceil();
let chat_bottom = ((batch.height - 40.0) / scale).floor();
let text_opacity = o.opacity * 0.9 + 0.1;
let entry_height = o.line_height();
let bottom_to_text = (8.0 * (o.line_spacing + 1.0) - 4.0 * o.line_spacing).round();
let per_page = self.lines_per_page(focused);
let alpha_of = |line: &Line| -> f32 {
if focused {
return 1.0;
}
let t = ((1.0 - (ticks.saturating_sub(line.added)) as f64 / 200.0) * 10.0).clamp(0.0, 1.0);
(t * t) as f32
};
let visible = self.lines.len().saturating_sub(self.scroll).min(per_page);
let mut count = 0;
// Pass 1: backgrounds; pass 2: text (same order as vanilla).
let s = |v: f32| v * scale;
for i in (0..visible).rev() {
let line = &self.lines[i + self.scroll];
let alpha = alpha_of(line);
if alpha <= 1.0e-5 {
continue;
}
count += 1;
let bottom = chat_bottom - i as f32 * entry_height;
let top = bottom - entry_height;
batch.fill(atlas, 0.0, s(top), s(max_width + 8.0), s(entry_height), rgba(0, 0, 0, (alpha * o.background_opacity * 255.0) as u8));
}
for i in (0..visible).rev() {
let line = &self.lines[i + self.scroll];
let alpha = alpha_of(line);
if alpha <= 1.0e-5 {
continue;
}
let bottom = chat_bottom - i as f32 * entry_height;
let top = bottom - entry_height;
let text_top = bottom - bottom_to_text;
let a = (alpha * text_opacity * 255.0) as u8;
if let Some(c) = line.indicator {
batch.fill(atlas, 0.0, s(top), s(2.0), s(entry_height), rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, a));
}
if a > 3 {
batch.text_styled(atlas, &line.content, s(4.0), s(text_top), rgba(255, 255, 255, a), true);
}
}
// Scroll bar while focused and scrolled content exists.
if focused && count > 0 {
let total = self.lines.len() as f32;
let chat_height = count as f32 * entry_height;
let virtual_height = total * entry_height;
if virtual_height != chat_height {
let y = self.scroll as f32 * chat_height / total - chat_bottom;
let height = chat_height * chat_height / virtual_height;
let alpha = if y > 0.0 { 170 } else { 96 };
let c = if self.new_since_scroll { 0xCC3333 } else { 0x3333AA };
let x = max_width + 4.0 + 4.0;
batch.fill(atlas, s(x), s(-y - height), s(2.0), s(height), rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, alpha));
batch.fill(atlas, s(x + 1.0), s(-y - height), s(1.0), s(height), rgba(0xCC, 0xCC, 0xCC, alpha));
}
}
}
/// Plain text of the newest messages (for tests and the control socket).
pub fn recent_lines(&self, n: usize) -> Vec<String> {
self.messages.iter().take(n).map(|m| m.content.plain()).collect()
}
}
/// CommandSuggestions.SuggestionsList.
#[derive(Clone, Debug)]
struct SuggestionList {
x: f32,
width: f32,
list: Vec<Suggestion>,
offset: usize,
current: usize,
original: String,
tab_cycles: bool,
last_mouse: (f32, f32),
}
/// The open chat screen.
pub struct ChatScreen {
pub input: EditBox,
history_pos: usize,
history_buffer: String,
parse: Option<ParseResults>,
usage: Vec<Text>,
usage_x: f32,
suggestions: Option<SuggestionList>,
pending: Vec<Suggestion>,
pending_start: usize,
keep_suggestions: bool,
allow_suggestions: bool,
pub auto_suggestions: bool,
dirty: bool,
}
const FILL: u32 = 0xD000_0000;
fn fill_color() -> u32 {
rgba(0, 0, 0, (FILL >> 24) as u8)
}
impl ChatScreen {
pub fn new(initial: &str, history_len: usize, width: f32, height: f32) -> Self {
let mut input = EditBox::new(4.0, height - 12.0, width - 4.0, 12.0);
input.bordered = false;
input.max_length = 256;
input.set_value(initial);
Self {
input,
history_pos: history_len,
history_buffer: String::new(),
parse: None,
usage: Vec::new(),
usage_x: 0.0,
suggestions: None,
pending: Vec::new(),
pending_start: 0,
keep_suggestions: false,
allow_suggestions: false,
auto_suggestions: true,
dirty: true,
}
}
/// Keep the input box at the bottom when the window resizes.
pub fn resize(&mut self, width: f32, height: f32) {
self.input.x = 4.0;
self.input.y = height - 12.0;
self.input.width = width - 4.0;
}
pub fn value(&self) -> &str {
&self.input.value
}
/// ChatScreen.onEdited.
pub fn edited(&mut self) {
self.allow_suggestions = true;
self.dirty = true;
}
/// CommandSuggestions.updateCommandInfo (run lazily before drawing/keys).
pub fn update(&mut self, atlas: &HudAtlas, d: &Dispatcher, reg: &Registries) {
if !self.dirty {
return;
}
self.dirty = false;
let command = self.input.value.clone();
if self.parse.as_ref().is_some_and(|p| p.input != command) {
self.parse = None;
}
if !self.keep_suggestions {
self.input.suggestion = None;
self.suggestions = None;
}
self.usage.clear();
self.pending.clear();
let cursor_chars = self.input.cursor;
let cursor = command.char_indices().nth(cursor_chars).map_or(command.len(), |(i, _)| i);
if !command.starts_with('/') {
return;
}
if self.parse.is_none() {
self.parse = Some(d.parse_at(&command, 1, reg));
}
let Some(parse) = &self.parse else { return };
if cursor >= 1 && (self.suggestions.is_none() || !self.keep_suggestions) {
let (range, list) = d.suggestions(parse, cursor, reg);
self.pending = list;
self.pending_start = range.0;
// CommandSuggestions.updateUsageInfo.
let mut trailing = false;
if cursor == command.len() {
if self.pending.is_empty() && !parse.errors.is_empty() {
let mut literals = 0;
for (_, e) in &parse.errors {
if e.literal_incorrect {
literals += 1;
} else {
self.usage.push(e.with_context().with_color(text::RED));
}
}
if literals > 0 {
let reader = crate::command::Reader { string: &parse.input, cursor: parse.cursor };
self.usage.push(crate::command::CommandError::tr_at("command.unknown.argument", &[], &reader).with_context().with_color(text::RED));
}
} else if parse.can_read() {
trailing = true;
}
}
let (node, start, _) = parse.context.suggestion_context(cursor);
if self.usage.is_empty() {
let mut lines: Vec<Text> = d
.smart_usage(node, reg.permission)
.into_iter()
.filter(|(n, _)| !matches!(d.nodes[*n].kind, crate::command::NodeKind::Literal(_)))
.map(|(_, u)| Text::colored(u, text::GRAY))
.collect();
if lines.is_empty()
&& trailing
&& let Some(e) = parse.error()
{
lines.push(e.with_context().with_color(text::RED));
}
self.usage = lines;
}
let usage_width = self.usage.iter().map(|u| atlas.font.width_text(u)).fold(0.0, f32::max);
let start_chars = char_len(&command[..start.min(command.len())]);
self.usage_x = if self.usage.is_empty() {
0.0
} else {
self.input.screen_x(atlas, start_chars).clamp(0.0, (self.input.screen_x(atlas, 0) + self.input.inner_width() - usage_width).max(0.0))
};
self.suggestions = None;
if self.allow_suggestions && self.auto_suggestions {
self.show_suggestions(atlas);
}
}
}
/// CommandSuggestions.showSuggestions.
fn show_suggestions(&mut self, atlas: &HudAtlas) {
if self.pending.is_empty() {
return;
}
let value = self.input.value.clone();
let width = self.pending.iter().map(|s| atlas.font.width(&s.text)).fold(0.0, f32::max);
let start_chars = char_len(&value[..self.pending_start.min(value.len())]);
let x = self.input.screen_x(atlas, start_chars).clamp(0.0, (self.input.screen_x(atlas, 0) + self.input.inner_width() - width).max(0.0));
// Sort: suggestions starting with the last word first.
let cursor = value.char_indices().nth(self.input.cursor).map_or(value.len(), |(i, _)| i);
let partial = &value[..cursor];
let last_word = partial.rfind(char::is_whitespace).map_or(0, |i| i + 1);
let word = partial[last_word..].to_lowercase();
let (mut first, partial_matches): (Vec<Suggestion>, Vec<Suggestion>) =
self.pending.iter().cloned().partition(|s| s.text.starts_with(&word) || s.text.starts_with(&format!("minecraft:{word}")));
first.extend(partial_matches);
let mut list = SuggestionList { x: x - 1.0, width: width + 1.0, list: first, offset: 0, current: 0, original: value, tab_cycles: false, last_mouse: (-1.0, -1.0) };
self.select(&mut list, 0);
self.suggestions = Some(list);
}
fn select(&mut self, list: &mut SuggestionList, index: isize) {
let n = list.list.len() as isize;
list.current = index.rem_euclid(n.max(1)) as usize;
let applied = list.list[list.current].apply(&list.original);
self.input.suggestion = applied.strip_prefix(self.input.value.as_str()).filter(|s| !s.is_empty()).map(str::to_owned);
}
fn cycle(&mut self, list: &mut SuggestionList, dir: isize) {
self.select(list, list.current as isize + dir);
let limit = 10;
let max_offset = list.list.len().saturating_sub(limit);
if list.current < list.offset {
list.offset = list.current.min(max_offset);
} else if list.current > list.offset + limit - 1 {
list.offset = (list.current + 1).saturating_sub(limit).min(max_offset);
}
}
fn use_suggestion(&mut self, list: &mut SuggestionList) {
let s = list.list[list.current].clone();
self.keep_suggestions = true;
let applied = s.apply(&list.original);
self.input.set_value(&applied);
let end = char_len(&list.original[..s.range.0.min(list.original.len())]) + char_len(&s.text);
self.input.set_cursor(end, false);
self.dirty = true;
self.select(list, list.current as isize);
self.keep_suggestions = false;
list.tab_cycles = true;
}
/// Suggestion-list keys (CommandSuggestions.keyPressed). Returns true if handled.
pub fn suggestion_key(&mut self, atlas: &HudAtlas, d: &Dispatcher, reg: &Registries, key: winit::keyboard::KeyCode, shift: bool) -> bool {
use winit::keyboard::KeyCode as K;
self.update(atlas, d, reg);
if let Some(mut list) = self.suggestions.take() {
let handled = match key {
K::ArrowUp => {
self.cycle(&mut list, -1);
list.tab_cycles = false;
true
}
K::ArrowDown => {
self.cycle(&mut list, 1);
list.tab_cycles = false;
true
}
K::Tab => {
if list.tab_cycles {
self.cycle(&mut list, if shift { -1 } else { 1 });
}
self.use_suggestion(&mut list);
// Keep the list across the re-parse triggered by the edit.
let keep = list.clone();
self.keep_suggestions = true;
self.update(atlas, d, reg);
self.keep_suggestions = false;
self.suggestions = Some(keep);
return true;
}
K::Escape => {
self.input.suggestion = None;
return true;
}
_ => false,
};
self.suggestions = Some(list);
return handled;
}
if key == K::Tab {
self.show_suggestions(atlas);
return true;
}
false
}
/// ChatScreen.moveInHistory.
pub fn move_in_history(&mut self, recent: &[String], dir: isize) {
let max = recent.len();
let new = (self.history_pos as isize + dir).clamp(0, max as isize) as usize;
if new == self.history_pos {
return;
}
if new == max {
self.history_pos = max;
let b = self.history_buffer.clone();
self.input.set_value(&b);
} else {
if self.history_pos == max {
self.history_buffer = self.input.value.clone();
}
self.input.set_value(&recent[new]);
self.suggestions = None;
self.allow_suggestions = false;
self.history_pos = new;
}
self.dirty = true;
}
/// Mouse wheel over the suggestion list.
pub fn scroll_suggestions(&mut self, cursor: (f32, f32), height: f32, amount: f32) -> bool {
let Some(list) = &mut self.suggestions else { return false };
let n = list.list.len().min(10);
let top = height - 12.0 - 3.0 - n as f32 * 12.0;
if crate::ui::hovered(cursor, list.x, top, list.width, n as f32 * 12.0) {
let max = list.list.len().saturating_sub(10) as isize;
list.offset = (list.offset as isize - amount.signum() as isize).clamp(0, max) as usize;
return true;
}
false
}
/// Click on a suggestion row.
pub fn click(&mut self, cursor: (f32, f32), height: f32) -> bool {
let Some(mut list) = self.suggestions.take() else { return false };
let n = list.list.len().min(10);
let top = height - 12.0 - 3.0 - n as f32 * 12.0;
if crate::ui::hovered(cursor, list.x, top, list.width, n as f32 * 12.0) {
let row = ((cursor.1 - top) / 12.0) as usize + list.offset;
if row < list.list.len() {
self.select(&mut list, row as isize);
self.use_suggestion(&mut list);
}
self.suggestions = Some(list);
return true;
}
self.suggestions = Some(list);
false
}
/// CommandSuggestions.formatText: argument colours over the input.
fn formatted(&self) -> Option<Text> {
let parse = self.parse.as_ref()?;
let value = &self.input.value;
let styles = [text::AQUA, text::YELLOW, text::GREEN, text::LIGHT_PURPLE, text::GOLD];
let mut colors = vec![text::GRAY; value.len()];
let ctx = parse.context.last_child();
for (i, arg) in ctx.args.iter().enumerate() {
let c = styles[i % styles.len()];
for b in arg.range.0.min(value.len())..arg.range.1.min(value.len()) {
colors[b] = c;
}
}
if parse.can_read() {
for c in colors.iter_mut().skip(parse.cursor) {
*c = text::RED;
}
}
let mut out = Text::empty();
for (i, ch) in value.char_indices() {
out.push(Text::styled(ch.to_string(), Style::color(colors[i])));
}
Some(out)
}
/// ChatScreen.extractRenderState minus the chat lines.
pub fn draw(&mut self, batch: &mut HudBatch, atlas: &HudAtlas, d: &Dispatcher, reg: &Registries, cursor: (f32, f32), background_opacity: f32) {
self.update(atlas, d, reg);
let (w, h) = (batch.width, batch.height);
batch.fill(atlas, 2.0, h - 14.0, w - 4.0, 12.0, rgba(0, 0, 0, (background_opacity * 255.0) as u8));
let formatted = self.formatted();
self.input.draw(batch, atlas, formatted.as_ref());
let fill = fill_color();
if let Some(mut list) = self.suggestions.take() {
let limit = list.list.len().min(10);
let top = h - 12.0 - 3.0 - limit as f32 * 12.0;
let has_prev = list.offset > 0;
let has_next = list.list.len() > list.offset + limit;
let moved = list.last_mouse != cursor;
list.last_mouse = cursor;
if has_prev || has_next {
batch.fill(atlas, list.x, top - 1.0, list.width, 1.0, fill);
batch.fill(atlas, list.x, top + limit as f32 * 12.0, list.width, 1.0, fill);
for x in (0..list.width as i32).step_by(2) {
if has_prev {
batch.fill(atlas, list.x + x as f32, top - 1.0, 1.0, 1.0, u32::MAX);
}
if has_next {
batch.fill(atlas, list.x + x as f32, top + limit as f32 * 12.0, 1.0, 1.0, u32::MAX);
}
}
}
let mut hovered_row = None;
for i in 0..limit {
let y = top + 12.0 * i as f32;
batch.fill(atlas, list.x, y, list.width, 12.0, fill);
if cursor.0 > list.x && cursor.0 < list.x + list.width && cursor.1 > y && cursor.1 < y + 12.0 {
hovered_row = Some(i + list.offset);
}
}
if moved && let Some(r) = hovered_row {
self.select(&mut list, r as isize);
}
for i in 0..limit {
let s = &list.list[i + list.offset];
let color = if i + list.offset == list.current { rgba(255, 255, 0, 255) } else { rgba(0xAA, 0xAA, 0xAA, 255) };
batch.text(atlas, &s.text, list.x + 1.0, top + 2.0 + 12.0 * i as f32, color, true);
}
if hovered_row.is_some()
&& let Some(tip) = &list.list[list.current].tooltip
{
crate::ui::tooltip(batch, atlas, &[Text::literal(tip.clone())], cursor);
}
self.suggestions = Some(list);
} else {
for (i, line) in self.usage.iter().enumerate() {
let y = h - 27.0 - 12.0 * i as f32;
let width = atlas.font.width_text(line);
batch.fill(atlas, self.usage_x - 1.0, y, width + 2.0, 12.0, fill);
batch.text_styled(atlas, line, self.usage_x, y + 2.0, u32::MAX, true);
}
}
}
/// ChatScreen.normalizeChatMessage.
pub fn normalized(&self) -> String {
let collapsed = self.input.value.split_whitespace().collect::<Vec<_>>().join(" ");
collapsed.chars().take(256).collect()
}
pub fn suggestions_visible(&self) -> bool {
self.suggestions.is_some()
}
}
+50 -4
View File
@@ -1,5 +1,7 @@
//! The playable game loop: streaming world, player simulation at 20 ticks/s,
//! block interaction, inventory and HUD.
mod chat;
mod commands;
mod control;
use horizon_client::{
Result,
@@ -166,6 +168,7 @@ enum Screen {
Playing,
Paused,
Options,
Chat,
Creative,
Inventory,
Dead,
@@ -196,8 +199,12 @@ struct GameLevel<'w> {
raining: bool,
thundering: bool,
player_box: Option<([f64; 3], [f64; 3])>,
rules: horizon_world::level::GameRules,
}
impl LevelAccess for GameLevel<'_> {
fn game_rules(&self) -> horizon_world::level::GameRules {
self.rules
}
fn block_state(&self, pos: BlockPos) -> BlockStateId {
self.world.block(pos.x, pos.y, pos.z)
}
@@ -387,6 +394,7 @@ struct Game<'a> {
/// Control replies waiting for a rendered frame or a benchmark deadline.
pending_screenshot: Option<std::sync::mpsc::Sender<String>>,
pending_bench: Option<(Instant, std::sync::mpsc::Sender<String>)>,
ui: chat::UiState,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Dim {
@@ -677,6 +685,7 @@ impl Game<'_> {
([p.position.x - w, p.position.y, p.position.z - w], [p.position.x + w, p.position.y + f64::from(p.dimensions.height), p.position.z + w])
});
let dimension = if self.dim == Dim::Nether { LevelDimension::Nether } else { LevelDimension::Overworld };
let rules = self.level_rules();
let mut level = GameLevel {
world: &mut self.world,
facts: &self.res.facts,
@@ -686,6 +695,7 @@ impl Game<'_> {
raining: rain > 0.2,
thundering: thunder > 0.9,
player_box,
rules,
};
f(&self.res.behaviours, &mut level, &mut self.block_ticks)
}
@@ -1286,12 +1296,14 @@ impl Game<'_> {
fn tick(&mut self) -> Result<()> {
self.ticks += 1;
self.world.game_time += 1;
self.world.weather.tick(&mut self.world.random);
if self.ui.rules.bool("advance_weather") {
self.world.weather.tick(&mut self.world.random);
}
self.tick_weather_effects();
if self.ticks % 6000 == 0 {
self.save_game()?;
}
self.world.day_time += 1;
self.advance_clock();
if self.use_delay > 0 {
self.use_delay -= 1;
}
@@ -1357,7 +1369,8 @@ impl Game<'_> {
if player.health.dead_or_dying() && self.screen != Screen::Dead {
// Inventory.dropAll: every stack thrown in a random direction.
let at = [player.position.x, player.position.y + 1.32, player.position.z];
if !self.creative {
self.death_message();
if !self.creative && !self.ui.rules.bool("keep_inventory") {
let stacks: Vec<ItemStack> = self.inventory.iter_mut().filter_map(Option::take).collect();
for stack in stacks {
let r = &mut self.world.random;
@@ -1676,6 +1689,8 @@ impl Game<'_> {
let tw = HudBatch::text_width(atlas, text);
batch.text(atlas, text, (w - tw) / 2.0, h - 59.0, u32::MAX, true);
}
self.draw_chat(&mut batch);
let atlas = &self.res.atlas;
if let Some((_, ticks)) = self.sleeping {
// Gui sleep overlay fading in over 100 ticks.
let a = ((ticks as f32 / 100.0).min(1.0) * 204.0) as u8;
@@ -1713,6 +1728,7 @@ impl Game<'_> {
Screen::Creative => {
self.draw_creative(&mut batch);
}
Screen::Chat => self.draw_chat_screen(&mut batch),
Screen::Playing | Screen::Options => {}
}
batch
@@ -2946,6 +2962,7 @@ impl Game<'_> {
if !save_root.join("level.dat").exists() {
self.level.write(&save_root)?;
}
self.load_world_state();
Ok(())
}
/// Streaming and region storage for one dimension of a world.
@@ -4110,6 +4127,7 @@ impl Game<'_> {
}
level.dimension = self.dim.id().to_owned();
level.write(&self.world_root)?;
self.save_world_state();
self.message = Some(("Saved the game".into(), Instant::now()));
Ok(())
}
@@ -4232,7 +4250,12 @@ impl Game<'_> {
self.capture(true);
}
Screen::Dead => {}
Screen::Chat => self.close_chat(),
},
KeyCode::KeyT if self.screen == Screen::Playing => self.open_chat(""),
KeyCode::Slash if self.screen == Screen::Playing => self.open_chat("/"),
KeyCode::F1 => self.toggle_hide_gui(),
KeyCode::F2 => self.take_screenshot(),
KeyCode::KeyE if self.screen == Screen::Creative && self.creative_screen.tab().search => {}
KeyCode::KeyE => match self.screen {
Screen::Playing => {
@@ -4418,6 +4441,9 @@ impl ApplicationHandler for Game<'_> {
MouseScrollDelta::LineDelta(_, y) => y,
MouseScrollDelta::PixelDelta(p) => p.y as f32,
};
if self.screen == Screen::Chat && d != 0.0 {
self.chat_scroll(d);
}
if self.screen == Screen::Creative && d != 0.0 {
let rows = self.creative_screen.rows(&self.res.names).saturating_sub(5).max(1) as f32;
self.creative_screen.scroll = (self.creative_screen.scroll - d.signum() / rows).clamp(0.0, 1.0);
@@ -4470,6 +4496,7 @@ impl ApplicationHandler for Game<'_> {
Screen::Inventory if pressed => {
self.click_inventory(button == MouseButton::Right);
}
Screen::Chat if pressed && button == MouseButton::Left => self.chat_click(),
Screen::Creative if pressed => {
self.click_creative(button == MouseButton::Right);
}
@@ -4500,6 +4527,16 @@ impl ApplicationHandler for Game<'_> {
_ => {}
}
}
WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::Chat && self.title.is_none() => {
if let PhysicalKey::Code(key) = event.physical_key {
if event.state == ElementState::Pressed {
self.keys.insert(key);
self.chat_key(&event);
} else {
self.keys.remove(&key);
}
}
}
WindowEvent::KeyboardInput { event, .. }
if self.screen == Screen::Creative && self.creative_screen.tab().search && event.state == ElementState::Pressed
&& !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) =>
@@ -4564,7 +4601,13 @@ impl ApplicationHandler for Game<'_> {
}
}
let rendered = self.render()?;
if let Some(result) = self.renderer.as_mut().and_then(|r| r.screenshot_result.take())
let finished = self.renderer.as_mut().and_then(|r| r.screenshot_result.take());
if let Some(result) = &finished
&& self.ui.screenshot_message.is_some()
{
self.finish_screenshot(result);
}
if let Some(result) = finished
&& let Some(reply) = self.pending_screenshot.take()
{
let _ = reply.send(match result {
@@ -4643,6 +4686,8 @@ pub fn run() -> Result<()> {
let light = Arc::new(LightTables::new(&facts));
eprintln!("load tables: {:.2}s", started.elapsed().as_secs_f32());
let atlas = HudAtlas::build(&root)?;
horizon_client::ui::load_metadata(&root);
horizon_client::lang::set(horizon_client::lang::Language::load(&[&root], horizon_client::lang::DEFAULT));
eprintln!("load atlas: {:.2}s", started.elapsed().as_secs_f32());
let layer_names = assets
.sprite_layers
@@ -4803,6 +4848,7 @@ pub fn run() -> Result<()> {
frame_stats: Default::default(),
pending_screenshot: None,
pending_bench: None,
ui: Default::default(),
};
if let Some(path) = &game.options.control {
let server = horizon_client::control::Server::start(path)
+494
View File
@@ -0,0 +1,494 @@
//! 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>,
}
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();
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()
}
});
self.system_message(Text::translate(&key, &[Text::literal(PLAYER_NAME)]));
}
/// 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(())
}
File diff suppressed because it is too large Load Diff
+35
View File
@@ -23,6 +23,9 @@ const HELP: &[&str] = &[
"time TICKS set the time of day",
"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)",
"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",
@@ -211,6 +214,25 @@ impl Game<'_> {
self.pending_screenshot = Some(reply.clone());
Ok(None)
}
"chat" => {
self.require_world()?;
let text = line.trim_start().strip_prefix("chat").unwrap_or("").trim();
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.screen != Screen::Chat {
return Err("type needs the chat screen (key t tap)".into());
}
self.chat_type(text);
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") {
@@ -264,6 +286,10 @@ impl Game<'_> {
}
fn control_key_down(&mut self, key: KeyCode) -> Result<()> {
if self.screen == Screen::Chat {
self.chat_key_code(key, None);
return Ok(());
}
if self.keys.insert(key) {
self.key_pressed(key)?;
}
@@ -281,6 +307,7 @@ impl Game<'_> {
Screen::Inventory => "inventory",
Screen::Creative => "creative",
Screen::Dead => "dead",
Screen::Chat => "chat",
}
}
@@ -390,7 +417,15 @@ fn key_code(name: &str) -> Option<KeyCode> {
"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,
+1 -2
View File
@@ -4,7 +4,6 @@
//! language used by every screen.
use std::{
collections::{BTreeMap, HashMap},
path::Path,
sync::{Arc, RwLock},
};
@@ -34,7 +33,7 @@ static CURRENT: RwLock<Option<Arc<Language>>> = RwLock::new(None);
pub trait ResourceSource {
fn read(&self, path: &str) -> Option<Vec<u8>>;
}
impl ResourceSource for Path {
impl ResourceSource for std::path::PathBuf {
fn read(&self, path: &str) -> Option<Vec<u8>> {
std::fs::read(self.join(path)).ok()
}
+2
View File
@@ -7,6 +7,7 @@ pub mod audio;
pub mod biome;
pub mod blocks;
pub mod chunk;
pub mod chat;
pub mod clock;
pub mod command;
pub mod containers;
@@ -41,6 +42,7 @@ pub mod streaming;
pub mod testgen;
pub mod text;
pub mod title;
pub mod ui;
pub mod vanillagen;
pub mod world;
pub mod zip;
+502
View File
@@ -0,0 +1,502 @@
//! Shared GUI widgets drawn as HUD quads: nine-slice sprites (gui.scaling
//! metadata), buttons, sliders, tiled menu backgrounds, separators and the
//! EditBox text field with vanilla cursor, selection and scrolling.
use crate::{
hud::{HudAtlas, HudBatch, Rect, rgba},
text::Text,
};
use std::{
collections::HashMap,
path::Path,
sync::RwLock,
time::Instant,
};
/// Nine-slice borders (left, top, right, bottom) from `.png.mcmeta` files.
static NINE_SLICE: RwLock<Option<HashMap<String, [u32; 4]>>> = RwLock::new(None);
/// Read `gui.scaling` metadata for every GUI sprite under `root`.
pub fn load_metadata(root: &Path) {
let mut map = HashMap::new();
let base = root.join("assets/minecraft/textures");
let mut stack = vec![base.join("gui/sprites")];
while let Some(dir) = stack.pop() {
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
for e in entries.flatten() {
let p = e.path();
if p.is_dir() {
stack.push(p);
continue;
}
let name = p.to_string_lossy().into_owned();
let Some(stripped) = name.strip_suffix(".png.mcmeta") else { continue };
let Ok(text) = std::fs::read_to_string(&p) else { continue };
let Ok(v) = serde_json::from_str::<serde_json::Value>(&text) else { continue };
let s = &v["gui"]["scaling"];
if s["type"] != "nine_slice" {
continue;
}
let border = &s["border"];
let b = if let Some(n) = border.as_u64() {
[n as u32; 4]
} else {
let g = |k: &str| border[k].as_u64().unwrap_or(0) as u32;
[g("left"), g("top"), g("right"), g("bottom")]
};
let key = Path::new(stripped).strip_prefix(&base).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default();
map.insert(key, b);
}
}
*NINE_SLICE.write().unwrap_or_else(|e| e.into_inner()) = Some(map);
}
fn border(sprite: &str) -> [u32; 4] {
NINE_SLICE.read().unwrap_or_else(|e| e.into_inner()).as_ref().and_then(|m| m.get(sprite).copied()).unwrap_or(match sprite {
"gui/sprites/widget/button" | "gui/sprites/widget/button_highlighted" | "gui/sprites/widget/button_disabled" => [3; 4],
"gui/sprites/widget/slider_handle" | "gui/sprites/widget/slider_handle_highlighted" => [2, 2, 2, 3],
_ => [1; 4],
})
}
fn sub(r: Rect, x: f32, y: f32, w: f32, h: f32) -> Rect {
let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32);
Rect { u0: r.u0 + x * du, v0: r.v0 + y * dv, u1: r.u0 + (x + w) * du, v1: r.v0 + (y + h) * dv, w: w as u32, h: h as u32 }
}
/// Tile `src` (a sub-rectangle of a sprite, in its pixels) over a target area.
fn tile(batch: &mut HudBatch, r: Rect, src: [f32; 4], dst: [f32; 4], color: u32) {
let [sx, sy, sw, sh] = src;
let [dx, dy, dw, dh] = dst;
if sw <= 0.0 || sh <= 0.0 || dw <= 0.0 || dh <= 0.0 {
return;
}
let mut y = 0.0;
while y < dh {
let h = sh.min(dh - y);
let mut x = 0.0;
while x < dw {
let w = sw.min(dw - x);
batch.rect_uv(dx + x, dy + y, w, h, sub(r, sx, sy, w, h), color);
x += sw;
}
y += sh;
}
}
/// GuiGraphics.blitSprite with nine-slice scaling (inner parts tiled).
pub fn nine_slice(batch: &mut HudBatch, atlas: &HudAtlas, sprite: &str, x: f32, y: f32, w: f32, h: f32, color: u32) {
let Some(r) = atlas.sprites.get(sprite).copied() else { return };
let [l, t, rr, b] = border(sprite).map(|v| v as f32);
let (sw, sh) = (r.w as f32, r.h as f32);
let l = l.min(w / 2.0);
let rr = rr.min(w / 2.0);
let t = t.min(h / 2.0);
let b = b.min(h / 2.0);
let (cw, ch) = (w - l - rr, h - t - b);
let (scw, sch) = (sw - l - rr, sh - t - b);
// Corners.
batch.rect_uv(x, y, l, t, sub(r, 0.0, 0.0, l, t), color);
batch.rect_uv(x + w - rr, y, rr, t, sub(r, sw - rr, 0.0, rr, t), color);
batch.rect_uv(x, y + h - b, l, b, sub(r, 0.0, sh - b, l, b), color);
batch.rect_uv(x + w - rr, y + h - b, rr, b, sub(r, sw - rr, sh - b, rr, b), color);
// Edges and centre.
tile(batch, r, [l, 0.0, scw, t], [x + l, y, cw, t], color);
tile(batch, r, [l, sh - b, scw, b], [x + l, y + h - b, cw, b], color);
tile(batch, r, [0.0, t, l, sch], [x, y + t, l, ch], color);
tile(batch, r, [sw - rr, t, rr, sch], [x + w - rr, y + t, rr, ch], color);
tile(batch, r, [l, t, scw, sch], [x + l, y + t, cw, ch], color);
}
/// Repeat a whole texture with each copy drawn `size` GUI pixels square.
pub fn tiled(batch: &mut HudBatch, atlas: &HudAtlas, sprite: &str, x: f32, y: f32, w: f32, h: f32, size: f32, color: u32) {
let Some(r) = atlas.sprites.get(sprite).copied() else { return };
let scale = r.w as f32 / size;
let mut yy = 0.0;
while yy < h {
let th = size.min(h - yy);
let mut xx = 0.0;
while xx < w {
let tw = size.min(w - xx);
batch.rect_uv(x + xx, y + yy, tw, th, sub(r, 0.0, 0.0, tw * scale, th * scale), color);
xx += size;
}
yy += size;
}
}
pub fn hovered(cursor: (f32, f32), x: f32, y: f32, w: f32, h: f32) -> bool {
cursor.0 >= x && cursor.0 < x + w && cursor.1 >= y && cursor.1 < y + h
}
/// Centered text with a shadow, scrolled when wider than `w` (AbstractWidget.renderScrollingString).
pub fn centered_text(batch: &mut HudBatch, atlas: &HudAtlas, text: &Text, x: f32, y: f32, w: f32, color: u32) {
let width = atlas.font.width_text(text);
if width <= w {
batch.text_styled(atlas, text, x + ((w - width) / 2.0).floor(), y, color, true);
} else {
// Clip by characters (vanilla scrolls; we show the part that fits).
let mut shown = Text::empty();
let mut used = 0.0;
for (i, (c, s)) in text.chars().enumerate() {
used += atlas.font.advance(c, s);
if used > w - 2.0 {
break;
}
shown.push(text.slice(i, i + 1));
}
batch.text_styled(atlas, &shown, x + 1.0, y, color, true);
}
}
/// Button (AbstractButton): nine-slice sprite plus the centred label.
pub fn button(batch: &mut HudBatch, atlas: &HudAtlas, x: f32, y: f32, w: f32, h: f32, label: &Text, active: bool, hover: bool) {
let sprite = if !active {
"gui/sprites/widget/button_disabled"
} else if hover {
"gui/sprites/widget/button_highlighted"
} else {
"gui/sprites/widget/button"
};
nine_slice(batch, atlas, sprite, x, y, w, h, u32::MAX);
let color = if active { rgba(255, 255, 255, 255) } else { rgba(160, 160, 160, 255) };
centered_text(batch, atlas, label, x + 2.0, y + ((h - 8.0) / 2.0).floor(), w - 4.0, color);
}
/// AbstractSliderButton: track, 8px handle at `value` (0..1) and the label.
pub fn slider(batch: &mut HudBatch, atlas: &HudAtlas, x: f32, y: f32, w: f32, label: &Text, value: f32, hover: bool, active: bool) {
let track = if hover && active { "gui/sprites/widget/slider_highlighted" } else { "gui/sprites/widget/slider" };
nine_slice(batch, atlas, track, x, y, w, 20.0, u32::MAX);
let handle = if hover && active { "gui/sprites/widget/slider_handle_highlighted" } else { "gui/sprites/widget/slider_handle" };
nine_slice(batch, atlas, handle, x + (value.clamp(0.0, 1.0) * (w - 8.0)).floor(), y, 8.0, 20.0, u32::MAX);
let color = if active { u32::MAX } else { rgba(160, 160, 160, 255) };
centered_text(batch, atlas, label, x + 2.0, y + 6.0, w - 4.0, color);
}
/// Slider value for a click at `cx` (AbstractSliderButton.setValueFromMouse).
pub fn slider_value(x: f32, w: f32, cx: f32) -> f32 {
((cx - (x + 4.0)) / (w - 8.0)).clamp(0.0, 1.0)
}
/// Screen.renderMenuBackground: in a world the translucent dark texture,
/// otherwise the dirt-like menu texture, tiled at 32 pixels.
pub fn menu_background(batch: &mut HudBatch, atlas: &HudAtlas, x: f32, y: f32, w: f32, h: f32, in_world: bool) {
let sprite = if in_world { "gui/inworld_menu_background" } else { "gui/menu_background" };
if atlas.sprites.contains_key(sprite) {
tiled(batch, atlas, sprite, x, y, w, h, 32.0, u32::MAX);
} else {
batch.fill(atlas, x, y, w, h, rgba(0, 0, 0, 160));
}
}
/// Header and footer separators of list screens.
pub fn separators(batch: &mut HudBatch, atlas: &HudAtlas, header_bottom: f32, footer_top: f32, in_world: bool) {
let (header, footer) = if in_world {
("gui/inworld_header_separator", "gui/inworld_footer_separator")
} else {
("gui/header_separator", "gui/footer_separator")
};
let w = batch.width;
tiled(batch, atlas, header, 0.0, header_bottom - 2.0, w, 2.0, 32.0, u32::MAX);
tiled(batch, atlas, footer, 0.0, footer_top, w, 2.0, 32.0, u32::MAX);
}
/// List background between the separators.
pub fn list_background(batch: &mut HudBatch, atlas: &HudAtlas, top: f32, bottom: f32, in_world: bool) {
let sprite = if in_world { "gui/inworld_menu_list_background" } else { "gui/menu_list_background" };
tiled(batch, atlas, sprite, 0.0, top, batch.width, bottom - top, 32.0, u32::MAX);
}
/// Vertical scroll bar (AbstractScrollArea): background and scroller sprites.
pub fn scrollbar(batch: &mut HudBatch, atlas: &HudAtlas, x: f32, top: f32, bottom: f32, content: f32, scroll: f32) {
let height = bottom - top;
if content <= height {
return;
}
let bar = (height * height / content).clamp(32.0, height - 8.0).floor();
let max = content - height;
let y = top + ((scroll / max) * (height - bar)).floor();
nine_slice(batch, atlas, "gui/sprites/widget/scroller_background", x, top, 6.0, height, u32::MAX);
nine_slice(batch, atlas, "gui/sprites/widget/scroller", x, y, 6.0, bar, u32::MAX);
}
/// Screen tooltip (DefaultTooltipPositioner + TooltipRenderUtil): the
/// background and frame sprites around the lines, beside the cursor.
pub fn tooltip(batch: &mut HudBatch, atlas: &HudAtlas, lines: &[Text], cursor: (f32, f32)) {
if lines.is_empty() {
return;
}
let w = lines.iter().map(|l| atlas.font.width_text(l)).fold(0.0, f32::max);
let h = if lines.len() == 1 { 8.0 } else { 10.0 * lines.len() as f32 };
let mut x = cursor.0 + 12.0;
let mut y = cursor.1 - 12.0;
if x + w > batch.width {
x = (cursor.0 - 24.0 - w).max(4.0);
}
if y + h + 3.0 > batch.height {
y = batch.height - h - 3.0;
}
y = y.max(4.0);
nine_slice(batch, atlas, "gui/sprites/tooltip/background", x - 12.0, y - 12.0, w + 24.0, h + 24.0, u32::MAX);
nine_slice(batch, atlas, "gui/sprites/tooltip/frame", x - 12.0, y - 12.0, w + 24.0, h + 24.0, u32::MAX);
let mut ly = y;
for (i, line) in lines.iter().enumerate() {
batch.text_styled(atlas, line, x, ly, u32::MAX, true);
ly += if i == 0 { 12.0 } else { 10.0 };
}
}
/// The EditBox text field.
#[derive(Clone, Debug)]
pub struct EditBox {
pub value: String,
/// Cursor and selection anchor, in characters.
pub cursor: usize,
pub highlight: usize,
display: usize,
pub max_length: usize,
pub bordered: bool,
pub x: f32,
pub y: f32,
pub width: f32,
pub height: f32,
pub focused: bool,
focused_at: Instant,
/// Grey completion shown after the text (EditBox.setSuggestion).
pub suggestion: Option<String>,
pub text_color: u32,
}
fn byte_index(s: &str, chars: usize) -> usize {
s.char_indices().nth(chars).map_or(s.len(), |(i, _)| i)
}
pub fn char_len(s: &str) -> usize {
s.chars().count()
}
impl EditBox {
pub fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
Self {
value: String::new(),
cursor: 0,
highlight: 0,
display: 0,
max_length: 32,
bordered: true,
x,
y,
width,
height,
focused: true,
focused_at: Instant::now(),
suggestion: None,
text_color: rgba(224, 224, 224, 255),
}
}
pub fn inner_width(&self) -> f32 {
if self.bordered { self.width - 8.0 } else { self.width }
}
pub fn text_x(&self) -> f32 {
if self.bordered { self.x + 4.0 } else { self.x }
}
pub fn text_y(&self) -> f32 {
if self.bordered { self.y + ((self.height - 8.0) / 2.0).floor() } else { self.y }
}
pub fn reset_blink(&mut self) {
self.focused_at = Instant::now();
}
pub fn set_value(&mut self, value: &str) {
self.value = value.chars().take(self.max_length).collect();
self.move_cursor_to_end(false);
}
fn selected(&self) -> (usize, usize) {
(self.cursor.min(self.highlight), self.cursor.max(self.highlight))
}
pub fn selected_text(&self) -> String {
let (a, b) = self.selected();
self.value.chars().skip(a).take(b - a).collect()
}
/// EditBox.insertText: replace the selection, respecting the maximum length.
pub fn insert_text(&mut self, text: &str) {
let (a, b) = self.selected();
let filtered: String = text.chars().filter(|c| !c.is_control() && *c != '§').collect();
let room = self.max_length.saturating_sub(char_len(&self.value) - (b - a));
let insert: String = filtered.chars().take(room).collect();
let (ba, bb) = (byte_index(&self.value, a), byte_index(&self.value, b));
self.value.replace_range(ba..bb, &insert);
let pos = a + char_len(&insert);
self.set_cursor(pos, false);
}
/// Delete `n` characters (negative: backwards) or the selection.
pub fn delete_chars(&mut self, n: isize) {
if self.cursor != self.highlight {
self.insert_text("");
return;
}
let target = (self.cursor as isize + n).clamp(0, char_len(&self.value) as isize) as usize;
let (a, b) = (self.cursor.min(target), self.cursor.max(target));
let (ba, bb) = (byte_index(&self.value, a), byte_index(&self.value, b));
self.value.replace_range(ba..bb, "");
self.set_cursor(a, false);
}
/// EditBox.getWordPosition.
pub fn word_position(&self, dir: isize) -> usize {
let chars: Vec<char> = self.value.chars().collect();
let mut pos = self.cursor;
if dir < 0 {
while pos > 0 && chars[pos - 1] == ' ' {
pos -= 1;
}
while pos > 0 && chars[pos - 1] != ' ' {
pos -= 1;
}
} else {
let len = chars.len();
while pos < len && chars[pos] != ' ' {
pos += 1;
}
while pos < len && chars[pos] == ' ' {
pos += 1;
}
}
pos
}
pub fn set_cursor(&mut self, pos: usize, select: bool) {
self.cursor = pos.min(char_len(&self.value));
if !select {
self.highlight = self.cursor;
}
self.scroll_to(self.cursor);
self.reset_blink();
}
pub fn move_cursor_to_end(&mut self, select: bool) {
self.set_cursor(char_len(&self.value), select);
}
fn scroll_to(&mut self, pos: usize) {
// EditBox.scrollTo without font access is completed in `layout`.
self.display = self.display.min(char_len(&self.value));
if pos < self.display {
self.display = pos;
}
}
fn layout(&mut self, atlas: &HudAtlas) {
let len = char_len(&self.value);
self.display = self.display.min(len);
let (value, inner) = (self.value.clone(), self.inner_width());
let visible = |d: usize| -> usize {
let rest: String = value.chars().skip(d).collect();
atlas.font.fit(&rest, inner)
};
while self.cursor > self.display + visible(self.display) && self.display < len {
self.display += 1;
}
if self.cursor < self.display {
self.display = self.cursor;
}
}
/// Keyboard editing shared by every text field. Returns true if handled.
pub fn key(&mut self, key: winit::keyboard::KeyCode, ctrl: bool, shift: bool) -> bool {
use winit::keyboard::KeyCode as K;
match key {
K::Backspace => {
let n = if ctrl { self.word_position(-1) as isize - self.cursor as isize } else { -1 };
self.delete_chars(n);
}
K::Delete => {
let n = if ctrl { self.word_position(1) as isize - self.cursor as isize } else { 1 };
self.delete_chars(n);
}
K::ArrowLeft => {
let p = if ctrl { self.word_position(-1) } else { self.cursor.saturating_sub(1) };
self.set_cursor(p, shift);
}
K::ArrowRight => {
let p = if ctrl { self.word_position(1) } else { self.cursor + 1 };
self.set_cursor(p, shift);
}
K::Home => self.set_cursor(0, shift),
K::End => self.move_cursor_to_end(shift),
K::KeyA if ctrl => {
self.move_cursor_to_end(false);
self.highlight = 0;
}
_ => return false,
}
true
}
/// Draw the field; `format` styles the visible text (command colouring).
pub fn draw(&mut self, batch: &mut HudBatch, atlas: &HudAtlas, format: Option<&Text>) {
self.layout(atlas);
if self.bordered {
let sprite = if self.focused { "gui/sprites/widget/text_field_highlighted" } else { "gui/sprites/widget/text_field" };
nine_slice(batch, atlas, sprite, self.x, self.y, self.width, self.height, u32::MAX);
}
let color = self.text_color;
let rest: String = self.value.chars().skip(self.display).collect();
let shown_len = atlas.font.fit(&rest, self.inner_width());
let displayed: String = rest.chars().take(shown_len).collect();
let rel_cursor = self.cursor as isize - self.display as isize;
let on_screen = rel_cursor >= 0 && rel_cursor as usize <= shown_len;
let show_cursor = self.focused && (self.focused_at.elapsed().as_millis() / 300) % 2 == 0 && on_screen;
let styled = |from: usize, to: usize| -> Text {
match format {
Some(t) => t.slice(self.display + from, self.display + to),
None => Text::literal(displayed.chars().skip(from).take(to - from).collect::<String>()),
}
};
let (tx, ty) = (self.text_x(), self.text_y());
let mut draw_x = tx;
if !displayed.is_empty() {
let half = if on_screen { rel_cursor as usize } else { shown_len };
let t = styled(0, half);
batch.text_styled(atlas, &t, draw_x, ty, color, true);
draw_x += atlas.font.width_text(&t) + 1.0;
}
let insert = self.cursor < char_len(&self.value) || char_len(&self.value) >= self.max_length;
let mut cursor_x = draw_x;
if !on_screen {
cursor_x = if rel_cursor > 0 { tx + self.width } else { tx };
} else if insert {
cursor_x -= 1.0;
draw_x -= 1.0;
}
if !displayed.is_empty() && on_screen && (rel_cursor as usize) < shown_len {
batch.text_styled(atlas, &styled(rel_cursor as usize, shown_len), draw_x, ty, color, true);
}
if !insert && let Some(s) = &self.suggestion {
batch.text(atlas, s, cursor_x - 1.0, ty, rgba(128, 128, 128, 255), true);
}
let rel_highlight = (self.highlight as isize - self.display as isize).clamp(0, shown_len as isize) as usize;
if rel_highlight as isize != rel_cursor {
let hx = tx + atlas.font.width(&displayed.chars().take(rel_highlight).collect::<String>());
let (a, b) = (cursor_x.min(hx - 1.0), cursor_x.max(hx - 1.0));
batch.fill(atlas, a, ty - 1.0, b - a, 11.0, rgba(0, 0, 255, 128));
}
if show_cursor {
if insert {
batch.fill(atlas, cursor_x, ty - 1.0, 1.0, 11.0, color);
} else {
batch.text(atlas, "_", cursor_x, ty, color, true);
}
}
}
/// Character index under GUI x (mouse click).
pub fn index_at(&self, atlas: &HudAtlas, x: f32) -> usize {
let rest: String = self.value.chars().skip(self.display).collect();
self.display + atlas.font.fit(&rest, (x - self.text_x()).max(0.0))
}
/// GUI x of a character index (EditBox.getScreenX).
pub fn screen_x(&self, atlas: &HudAtlas, index: usize) -> f32 {
if index > char_len(&self.value) {
return self.x;
}
let shown: String = self.value.chars().skip(self.display).take(index.saturating_sub(self.display)).collect();
self.text_x() + atlas.font.width(&shown)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn edit_box_editing() {
let mut e = EditBox::new(0.0, 0.0, 100.0, 20.0);
e.max_length = 10;
e.insert_text("hello world");
assert_eq!(e.value, "hello worl");
e.set_cursor(5, false);
assert_eq!(e.word_position(-1), 0);
assert_eq!(e.word_position(1), 6);
e.delete_chars(-2);
assert_eq!(e.value, "hel worl");
e.set_cursor(0, false);
e.set_cursor(3, true);
assert_eq!(e.selected_text(), "hel");
e.insert_text("é§x");
assert_eq!(e.value, "éx worl");
assert_eq!(e.cursor, 2);
}
}