Merge remote-tracking branch 'origin/wip/parity-ui' into t3/minecraft-parity
# Conflicts: # crates/horizon-client/src/game.rs # crates/horizon-client/src/lib.rs
This commit is contained in:
Generated
+1
@@ -687,6 +687,7 @@ dependencies = [
|
||||
"horizon-core",
|
||||
"horizon-protocol",
|
||||
"horizon-world",
|
||||
"miniz_oxide 0.8.9",
|
||||
"png",
|
||||
"pollster",
|
||||
"serde_json",
|
||||
|
||||
@@ -21,3 +21,4 @@ png = "0.18"
|
||||
serde_json = { version = "1.0.151", features = ["raw_value"] }
|
||||
cpal = "0.16"
|
||||
symphonia = { version = "0.5", default-features = false, features = ["ogg", "vorbis"] }
|
||||
miniz_oxide = "0.8"
|
||||
|
||||
@@ -212,7 +212,7 @@ impl Audio {
|
||||
decode(&self.root.join(format!("assets/minecraft/sounds/{file}.ogg"))).map(|(s, r)| (Arc::new(s), r))
|
||||
});
|
||||
let Some((samples, rate)) = entry.clone() else { return };
|
||||
let volume = (volume * variant.volume).clamp(0.0, 1.0) * self.master;
|
||||
let volume = (volume * variant.volume).clamp(0.0, 1.0) * self.master * crate::settings::event_volume(event);
|
||||
let pitch = (pitch * variant.pitch).clamp(0.5, 2.0);
|
||||
let (mut left, mut right) = (volume, volume);
|
||||
if let Some(p) = at {
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,639 @@
|
||||
//! A port of Brigadier (the command library vanilla uses): a string reader,
|
||||
//! literal/argument node trees with redirects, parsing that tries every
|
||||
//! relevant child and keeps the best result, completion suggestions, smart
|
||||
//! usage text and the vanilla error messages. Argument types live in
|
||||
//! [`args`]; the vanilla command tree in [`vanilla`].
|
||||
pub mod args;
|
||||
pub mod vanilla;
|
||||
|
||||
use crate::text::Text;
|
||||
pub use args::{Arg, ArgType, Registries};
|
||||
|
||||
/// A command error (CommandSyntaxException): the message and, for parse
|
||||
/// errors, the input and cursor it occurred at.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct CommandError {
|
||||
pub message: Text,
|
||||
pub input: Option<String>,
|
||||
pub cursor: usize,
|
||||
/// BuiltInExceptions.literalIncorrect (summarised specially by the chat UI).
|
||||
pub literal_incorrect: bool,
|
||||
}
|
||||
impl CommandError {
|
||||
pub fn new(message: Text) -> Self {
|
||||
Self { message, input: None, cursor: 0, literal_incorrect: false }
|
||||
}
|
||||
pub fn tr(key: &str, args: &[&dyn std::fmt::Display]) -> Self {
|
||||
Self::new(Text::tr(key, args))
|
||||
}
|
||||
pub fn at(message: Text, reader: &Reader) -> Self {
|
||||
Self { message, input: Some(reader.string.to_owned()), cursor: reader.cursor, literal_incorrect: false }
|
||||
}
|
||||
pub fn tr_at(key: &str, args: &[&dyn std::fmt::Display], reader: &Reader) -> Self {
|
||||
Self::at(Text::tr(key, args), reader)
|
||||
}
|
||||
/// CommandSyntaxException.getContext: up to ten characters before the
|
||||
/// cursor followed by "<--[HERE]".
|
||||
pub fn context(&self) -> Option<String> {
|
||||
let input = self.input.as_ref()?;
|
||||
let cursor = self.cursor.min(input.len());
|
||||
let start = input.floor_char_boundary(cursor.saturating_sub(10));
|
||||
let mut out = String::new();
|
||||
if cursor > 10 {
|
||||
out.push_str("...");
|
||||
}
|
||||
out.push_str(&input[start..cursor]);
|
||||
out.push_str("<--[HERE]");
|
||||
Some(out)
|
||||
}
|
||||
/// The message as shown by command suggestions ("... at position N: ...").
|
||||
pub fn with_context(&self) -> Text {
|
||||
match self.context() {
|
||||
Some(context) => Text::translate("command.context.parse_error", &[self.message.clone(), Text::literal(self.cursor.to_string()), Text::literal(context)]),
|
||||
None => self.message.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub type CmdResult<T> = Result<T, CommandError>;
|
||||
|
||||
/// Brigadier StringReader over a command line (byte cursor on char boundaries).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Reader<'a> {
|
||||
pub string: &'a str,
|
||||
pub cursor: usize,
|
||||
}
|
||||
impl<'a> Reader<'a> {
|
||||
pub fn new(string: &'a str) -> Self {
|
||||
Self { string, cursor: 0 }
|
||||
}
|
||||
pub fn can_read(&self) -> bool {
|
||||
self.cursor < self.string.len()
|
||||
}
|
||||
pub fn can_read_n(&self, n: usize) -> bool {
|
||||
self.string[self.cursor..].chars().take(n).count() == n
|
||||
}
|
||||
pub fn peek(&self) -> char {
|
||||
self.string[self.cursor..].chars().next().unwrap_or('\0')
|
||||
}
|
||||
pub fn peek_at(&self, offset: usize) -> char {
|
||||
self.string[self.cursor..].chars().nth(offset).unwrap_or('\0')
|
||||
}
|
||||
pub fn skip(&mut self) {
|
||||
self.cursor += self.peek().len_utf8();
|
||||
}
|
||||
pub fn read(&mut self) -> char {
|
||||
let c = self.peek();
|
||||
self.skip();
|
||||
c
|
||||
}
|
||||
pub fn remaining(&self) -> &'a str {
|
||||
&self.string[self.cursor..]
|
||||
}
|
||||
pub fn skip_whitespace(&mut self) {
|
||||
while self.can_read() && self.peek().is_whitespace() {
|
||||
self.skip();
|
||||
}
|
||||
}
|
||||
pub fn is_allowed_number(c: char) -> bool {
|
||||
c.is_ascii_digit() || c == '.' || c == '-'
|
||||
}
|
||||
pub fn is_allowed_in_unquoted(c: char) -> bool {
|
||||
c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '+')
|
||||
}
|
||||
fn read_number_text(&mut self) -> &'a str {
|
||||
let start = self.cursor;
|
||||
while self.can_read() && Self::is_allowed_number(self.peek()) {
|
||||
self.skip();
|
||||
}
|
||||
&self.string[start..self.cursor]
|
||||
}
|
||||
fn number<T: std::str::FromStr>(&mut self, kind: &str) -> CmdResult<T> {
|
||||
let start = self.cursor;
|
||||
let text = self.read_number_text();
|
||||
if text.is_empty() {
|
||||
return Err(CommandError::tr_at(&format!("parsing.{kind}.expected"), &[], self));
|
||||
}
|
||||
// Java's parsers reject a trailing '.'-less exponent etc. the same way.
|
||||
match text.parse::<T>() {
|
||||
Ok(v) if !(kind == "int" || kind == "long") || !text.contains('.') => Ok(v),
|
||||
_ => {
|
||||
self.cursor = start;
|
||||
Err(CommandError::tr_at(&format!("parsing.{kind}.invalid"), &[&text], self))
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn read_int(&mut self) -> CmdResult<i32> {
|
||||
self.number("int")
|
||||
}
|
||||
pub fn read_long(&mut self) -> CmdResult<i64> {
|
||||
self.number("long")
|
||||
}
|
||||
pub fn read_double(&mut self) -> CmdResult<f64> {
|
||||
self.number("double")
|
||||
}
|
||||
pub fn read_float(&mut self) -> CmdResult<f32> {
|
||||
self.number("float")
|
||||
}
|
||||
pub fn read_unquoted_string(&mut self) -> &'a str {
|
||||
let start = self.cursor;
|
||||
while self.can_read() && Self::is_allowed_in_unquoted(self.peek()) {
|
||||
self.skip();
|
||||
}
|
||||
&self.string[start..self.cursor]
|
||||
}
|
||||
pub fn read_string_until(&mut self, terminator: char) -> CmdResult<String> {
|
||||
let mut out = String::new();
|
||||
let mut escaped = false;
|
||||
while self.can_read() {
|
||||
let c = self.read();
|
||||
if escaped {
|
||||
if c == terminator || c == '\\' {
|
||||
out.push(c);
|
||||
escaped = false;
|
||||
} else {
|
||||
self.cursor -= c.len_utf8();
|
||||
return Err(CommandError::tr_at("parsing.quote.escape", &[&c], self));
|
||||
}
|
||||
} else if c == '\\' {
|
||||
escaped = true;
|
||||
} else if c == terminator {
|
||||
return Ok(out);
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
Err(CommandError::tr_at("parsing.quote.expected.end", &[], self))
|
||||
}
|
||||
pub fn read_quoted_string(&mut self) -> CmdResult<String> {
|
||||
if !self.can_read() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let next = self.peek();
|
||||
if next != '"' && next != '\'' {
|
||||
return Err(CommandError::tr_at("parsing.quote.expected.start", &[], self));
|
||||
}
|
||||
self.skip();
|
||||
self.read_string_until(next)
|
||||
}
|
||||
pub fn read_string(&mut self) -> CmdResult<String> {
|
||||
if !self.can_read() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let next = self.peek();
|
||||
if next == '"' || next == '\'' {
|
||||
self.skip();
|
||||
return self.read_string_until(next);
|
||||
}
|
||||
Ok(self.read_unquoted_string().to_owned())
|
||||
}
|
||||
pub fn read_boolean(&mut self) -> CmdResult<bool> {
|
||||
let start = self.cursor;
|
||||
let value = self.read_string()?;
|
||||
if value.is_empty() {
|
||||
return Err(CommandError::tr_at("parsing.bool.expected", &[], self));
|
||||
}
|
||||
match value.as_str() {
|
||||
"true" => Ok(true),
|
||||
"false" => Ok(false),
|
||||
_ => {
|
||||
self.cursor = start;
|
||||
Err(CommandError::tr_at("parsing.bool.invalid", &[&value], self))
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn expect(&mut self, c: char) -> CmdResult<()> {
|
||||
if !self.can_read() || self.peek() != c {
|
||||
return Err(CommandError::tr_at("parsing.expected", &[&c], self));
|
||||
}
|
||||
self.skip();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub type Range = (usize, usize);
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum NodeKind {
|
||||
Root,
|
||||
Literal(String),
|
||||
Argument { name: String, ty: ArgType },
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Node {
|
||||
pub kind: NodeKind,
|
||||
pub children: Vec<usize>,
|
||||
/// The command id run when parsing ends here.
|
||||
pub command: Option<&'static str>,
|
||||
pub redirect: Option<usize>,
|
||||
/// Required permission level (0 everyone, 2 game masters, 4 owners).
|
||||
pub permission: u8,
|
||||
}
|
||||
impl Node {
|
||||
pub fn name(&self) -> &str {
|
||||
match &self.kind {
|
||||
NodeKind::Root => "",
|
||||
NodeKind::Literal(l) => l,
|
||||
NodeKind::Argument { name, .. } => name,
|
||||
}
|
||||
}
|
||||
/// CommandNode.getUsageText.
|
||||
pub fn usage_text(&self) -> String {
|
||||
match &self.kind {
|
||||
NodeKind::Root => String::new(),
|
||||
NodeKind::Literal(l) => l.clone(),
|
||||
NodeKind::Argument { name, .. } => format!("<{name}>"),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ParsedArg {
|
||||
pub name: String,
|
||||
pub value: Arg,
|
||||
pub range: Range,
|
||||
}
|
||||
/// CommandContextBuilder: the nodes and arguments parsed so far.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Context {
|
||||
pub root: usize,
|
||||
pub nodes: Vec<(usize, Range)>,
|
||||
pub args: Vec<ParsedArg>,
|
||||
pub command: Option<&'static str>,
|
||||
pub range: Range,
|
||||
pub child: Option<Box<Context>>,
|
||||
/// Literal words parsed so far (mode keywords such as `masked`).
|
||||
pub literals: Vec<String>,
|
||||
}
|
||||
impl Context {
|
||||
fn new(root: usize, start: usize) -> Self {
|
||||
Self { root, nodes: Vec::new(), args: Vec::new(), command: None, range: (start, start), child: None, literals: Vec::new() }
|
||||
}
|
||||
/// Whether the literal `word` was parsed (in this context).
|
||||
pub fn has(&self, word: &str) -> bool {
|
||||
self.literals.iter().any(|l| l == word)
|
||||
}
|
||||
fn with_node(&mut self, node: usize, range: Range) {
|
||||
self.nodes.push((node, range));
|
||||
self.range = (self.range.0.min(range.0), self.range.1.max(range.1));
|
||||
}
|
||||
pub fn last_child(&self) -> &Context {
|
||||
let mut c = self;
|
||||
while let Some(child) = &c.child {
|
||||
c = child;
|
||||
}
|
||||
c
|
||||
}
|
||||
pub fn get(&self, name: &str) -> Option<&Arg> {
|
||||
self.args.iter().rev().find(|a| a.name == name).map(|a| &a.value)
|
||||
}
|
||||
/// CommandContextBuilder.findSuggestionContext: the node whose children
|
||||
/// complete the text at `cursor`, and where that text starts.
|
||||
pub fn suggestion_context(&self, cursor: usize) -> (usize, usize, &Context) {
|
||||
if self.range.1 < cursor {
|
||||
if let Some(child) = &self.child {
|
||||
return child.suggestion_context(cursor);
|
||||
}
|
||||
if let Some((node, range)) = self.nodes.last() {
|
||||
return (*node, range.1 + 1, self);
|
||||
}
|
||||
return (self.root, self.range.0, self);
|
||||
}
|
||||
let mut prev = self.root;
|
||||
for (node, range) in &self.nodes {
|
||||
if range.0 <= cursor && cursor <= range.1 {
|
||||
return (prev, range.0, self);
|
||||
}
|
||||
prev = *node;
|
||||
}
|
||||
(prev, self.range.0, self)
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ParseResults {
|
||||
pub context: Context,
|
||||
pub input: String,
|
||||
pub cursor: usize,
|
||||
pub errors: Vec<(usize, CommandError)>,
|
||||
}
|
||||
impl ParseResults {
|
||||
pub fn can_read(&self) -> bool {
|
||||
self.cursor < self.input.len()
|
||||
}
|
||||
/// Commands.getParseException.
|
||||
pub fn error(&self) -> Option<CommandError> {
|
||||
if !self.can_read() {
|
||||
return None;
|
||||
}
|
||||
if self.errors.len() == 1 {
|
||||
return Some(self.errors[0].1.clone());
|
||||
}
|
||||
let reader = Reader { string: &self.input, cursor: self.cursor };
|
||||
Some(if self.context.range.0 == self.context.range.1 {
|
||||
CommandError::tr_at("command.unknown.command", &[], &reader)
|
||||
} else {
|
||||
CommandError::tr_at("command.unknown.argument", &[], &reader)
|
||||
})
|
||||
}
|
||||
/// The executable context and command id, or the vanilla error.
|
||||
pub fn executable(&self) -> CmdResult<(&Context, &'static str)> {
|
||||
if let Some(e) = self.error() {
|
||||
return Err(e);
|
||||
}
|
||||
let last = self.context.last_child();
|
||||
match last.command {
|
||||
Some(id) => Ok((last, id)),
|
||||
None => Err(CommandError::tr_at("command.unknown.command", &[], &Reader { string: &self.input, cursor: self.cursor })),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// A completion: replace `range` of the input with `text`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Suggestion {
|
||||
pub range: Range,
|
||||
pub text: String,
|
||||
pub tooltip: Option<String>,
|
||||
}
|
||||
impl Suggestion {
|
||||
/// Suggestion.apply.
|
||||
pub fn apply(&self, input: &str) -> String {
|
||||
let (s, e) = (self.range.0.min(input.len()), self.range.1.min(input.len()));
|
||||
format!("{}{}{}", &input[..s], self.text, &input[e..])
|
||||
}
|
||||
}
|
||||
/// SuggestionsBuilder: suggestions for the text from `start` to the cursor.
|
||||
pub struct SuggestionsBuilder<'a> {
|
||||
pub input: &'a str,
|
||||
pub start: usize,
|
||||
pub out: Vec<Suggestion>,
|
||||
}
|
||||
impl<'a> SuggestionsBuilder<'a> {
|
||||
pub fn new(input: &'a str, start: usize) -> Self {
|
||||
Self { input, start: start.min(input.len()), out: Vec::new() }
|
||||
}
|
||||
pub fn remaining(&self) -> &'a str {
|
||||
&self.input[self.start..]
|
||||
}
|
||||
pub fn remaining_lower(&self) -> String {
|
||||
self.remaining().to_lowercase()
|
||||
}
|
||||
pub fn suggest(&mut self, text: impl Into<String>) {
|
||||
let text = text.into();
|
||||
if text != self.remaining() {
|
||||
self.out.push(Suggestion { range: (self.start, self.input.len()), text, tooltip: None });
|
||||
}
|
||||
}
|
||||
pub fn suggest_tooltip(&mut self, text: impl Into<String>, tooltip: impl Into<String>) {
|
||||
let text = text.into();
|
||||
if text != self.remaining() {
|
||||
self.out.push(Suggestion { range: (self.start, self.input.len()), text, tooltip: Some(tooltip.into()) });
|
||||
}
|
||||
}
|
||||
pub fn offset(&self, start: usize) -> SuggestionsBuilder<'a> {
|
||||
SuggestionsBuilder::new(self.input, start)
|
||||
}
|
||||
/// SharedSuggestionProvider.suggest: candidates starting with the remaining text.
|
||||
pub fn suggest_matching<'b>(&mut self, candidates: impl IntoIterator<Item = &'b str>) {
|
||||
let lower = self.remaining_lower();
|
||||
for c in candidates {
|
||||
if c.to_lowercase().starts_with(&lower) {
|
||||
self.suggest(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Suggestions.create: merged, expanded to a common range and sorted case-insensitively.
|
||||
pub fn merge_suggestions(input: &str, list: Vec<Suggestion>) -> (Range, Vec<Suggestion>) {
|
||||
if list.is_empty() {
|
||||
return ((0, 0), Vec::new());
|
||||
}
|
||||
let start = list.iter().map(|s| s.range.0).min().unwrap_or(0);
|
||||
let end = list.iter().map(|s| s.range.1).max().unwrap_or(0);
|
||||
let mut out: Vec<Suggestion> = Vec::new();
|
||||
for s in list {
|
||||
// Suggestion.expand: pad the text with the input around it.
|
||||
let text = format!("{}{}{}", &input[start..s.range.0], s.text, &input[s.range.1..end]);
|
||||
let expanded = Suggestion { range: (start, end), text, tooltip: s.tooltip };
|
||||
if !out.iter().any(|o| o.text == expanded.text) {
|
||||
out.push(expanded);
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| a.text.to_lowercase().cmp(&b.text.to_lowercase()));
|
||||
((start, end), out)
|
||||
}
|
||||
|
||||
/// The command tree (CommandDispatcher). Node 0 is the root.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Dispatcher {
|
||||
pub nodes: Vec<Node>,
|
||||
}
|
||||
impl Default for Dispatcher {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
impl Dispatcher {
|
||||
pub fn new() -> Self {
|
||||
Self { nodes: vec![Node { kind: NodeKind::Root, children: Vec::new(), command: None, redirect: None, permission: 0 }] }
|
||||
}
|
||||
fn add(&mut self, parent: usize, kind: NodeKind) -> usize {
|
||||
let name = match &kind {
|
||||
NodeKind::Literal(l) => l.clone(),
|
||||
NodeKind::Argument { name, .. } => name.clone(),
|
||||
NodeKind::Root => String::new(),
|
||||
};
|
||||
// CommandNode.addChild merges same-named children.
|
||||
if let Some(&existing) = self.nodes[parent].children.iter().find(|&&c| self.nodes[c].name() == name) {
|
||||
return existing;
|
||||
}
|
||||
let permission = self.nodes[parent].permission;
|
||||
self.nodes.push(Node { kind, children: Vec::new(), command: None, redirect: None, permission });
|
||||
let id = self.nodes.len() - 1;
|
||||
self.nodes[parent].children.push(id);
|
||||
id
|
||||
}
|
||||
pub fn literal(&mut self, parent: usize, name: &str) -> usize {
|
||||
self.add(parent, NodeKind::Literal(name.to_owned()))
|
||||
}
|
||||
pub fn argument(&mut self, parent: usize, name: &str, ty: ArgType) -> usize {
|
||||
self.add(parent, NodeKind::Argument { name: name.to_owned(), ty })
|
||||
}
|
||||
pub fn executes(&mut self, node: usize, command: &'static str) -> usize {
|
||||
self.nodes[node].command = Some(command);
|
||||
node
|
||||
}
|
||||
pub fn redirect(&mut self, node: usize, target: usize) -> usize {
|
||||
self.nodes[node].redirect = Some(target);
|
||||
node
|
||||
}
|
||||
pub fn requires(&mut self, node: usize, level: u8) -> usize {
|
||||
self.nodes[node].permission = level;
|
||||
node
|
||||
}
|
||||
/// A root literal by name.
|
||||
pub fn find(&self, name: &str) -> Option<usize> {
|
||||
self.nodes[0].children.iter().copied().find(|&c| self.nodes[c].name() == name)
|
||||
}
|
||||
fn relevant(&self, node: usize, reader: &Reader) -> Vec<usize> {
|
||||
let children = &self.nodes[node].children;
|
||||
let literals: Vec<usize> = children.iter().copied().filter(|&c| matches!(self.nodes[c].kind, NodeKind::Literal(_))).collect();
|
||||
let arguments: Vec<usize> = children.iter().copied().filter(|&c| matches!(self.nodes[c].kind, NodeKind::Argument { .. })).collect();
|
||||
if literals.is_empty() {
|
||||
return arguments;
|
||||
}
|
||||
let rest = reader.remaining();
|
||||
let word = rest.split(' ').next().unwrap_or("");
|
||||
match literals.iter().find(|&&l| self.nodes[l].name() == word) {
|
||||
Some(&l) => vec![l],
|
||||
None => arguments,
|
||||
}
|
||||
}
|
||||
fn parse_node(&self, node: usize, reader: &mut Reader, context: &mut Context, reg: &Registries) -> CmdResult<()> {
|
||||
let start = reader.cursor;
|
||||
match &self.nodes[node].kind {
|
||||
NodeKind::Root => Ok(()),
|
||||
NodeKind::Literal(literal) => {
|
||||
if reader.remaining().starts_with(literal.as_str()) {
|
||||
let end = start + literal.len();
|
||||
reader.cursor = end;
|
||||
if !reader.can_read() || reader.peek() == ' ' {
|
||||
context.with_node(node, (start, end));
|
||||
context.literals.push(literal.clone());
|
||||
return Ok(());
|
||||
}
|
||||
reader.cursor = start;
|
||||
}
|
||||
let mut e = CommandError::tr_at("argument.literal.incorrect", &[literal], reader);
|
||||
e.literal_incorrect = true;
|
||||
Err(e)
|
||||
}
|
||||
NodeKind::Argument { name, ty } => {
|
||||
let value = ty.parse(reader, reg)?;
|
||||
let range = (start, reader.cursor);
|
||||
context.args.push(ParsedArg { name: name.clone(), value, range });
|
||||
context.with_node(node, range);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
fn parse_nodes(&self, node: usize, input: &str, cursor: usize, so_far: &Context, reg: &Registries, level: u8) -> ParseResults {
|
||||
let mut errors = Vec::new();
|
||||
let mut potentials: Vec<ParseResults> = Vec::new();
|
||||
let original = Reader { string: input, cursor };
|
||||
for child in self.relevant(node, &original) {
|
||||
if self.nodes[child].permission > level {
|
||||
continue;
|
||||
}
|
||||
let mut context = so_far.clone();
|
||||
let mut reader = original.clone();
|
||||
let parsed = self.parse_node(child, &mut reader, &mut context, reg).and_then(|()| {
|
||||
if reader.can_read() && reader.peek() != ' ' {
|
||||
Err(CommandError::tr_at("command.expected.separator", &[], &reader))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
});
|
||||
if let Err(e) = parsed {
|
||||
errors.push((child, e));
|
||||
continue;
|
||||
}
|
||||
context.command = self.nodes[child].command;
|
||||
let redirect = self.nodes[child].redirect;
|
||||
if reader.can_read_n(if redirect.is_none() { 2 } else { 1 }) {
|
||||
reader.skip();
|
||||
if let Some(target) = redirect {
|
||||
let child_context = Context::new(target, reader.cursor);
|
||||
let parse = self.parse_nodes(target, input, reader.cursor, &child_context, reg, level);
|
||||
context.child = Some(Box::new(parse.context));
|
||||
return ParseResults { context, input: input.to_owned(), cursor: parse.cursor, errors: parse.errors };
|
||||
}
|
||||
potentials.push(self.parse_nodes(child, input, reader.cursor, &context, reg, level));
|
||||
} else {
|
||||
potentials.push(ParseResults { context, input: input.to_owned(), cursor: reader.cursor, errors: Vec::new() });
|
||||
}
|
||||
}
|
||||
if !potentials.is_empty() {
|
||||
// Prefer fully read input, then results without errors (stable sort).
|
||||
potentials.sort_by_key(|p| (p.can_read(), !p.errors.is_empty()));
|
||||
return potentials.swap_remove(0);
|
||||
}
|
||||
ParseResults { context: so_far.clone(), input: input.to_owned(), cursor, errors }
|
||||
}
|
||||
/// CommandDispatcher.parse from the start of `input` (no leading slash).
|
||||
pub fn parse(&self, input: &str, reg: &Registries) -> ParseResults {
|
||||
self.parse_at(input, 0, reg)
|
||||
}
|
||||
/// Parse starting at byte `start` (after a leading '/').
|
||||
pub fn parse_at(&self, input: &str, start: usize, reg: &Registries) -> ParseResults {
|
||||
let context = Context::new(0, start);
|
||||
self.parse_nodes(0, input, start, &context, reg, reg.permission)
|
||||
}
|
||||
/// CommandDispatcher.getCompletionSuggestions at `cursor`.
|
||||
pub fn suggestions(&self, parse: &ParseResults, cursor: usize, reg: &Registries) -> (Range, Vec<Suggestion>) {
|
||||
let (parent, start, context) = parse.context.suggestion_context(cursor);
|
||||
let start = start.min(cursor);
|
||||
let truncated = &parse.input[..cursor.min(parse.input.len())];
|
||||
let mut all = Vec::new();
|
||||
for &child in &self.nodes[parent].children {
|
||||
if self.nodes[child].permission > reg.permission {
|
||||
continue;
|
||||
}
|
||||
let mut builder = SuggestionsBuilder::new(truncated, start);
|
||||
match &self.nodes[child].kind {
|
||||
NodeKind::Literal(l) => {
|
||||
if l.to_lowercase().starts_with(&builder.remaining_lower()) {
|
||||
builder.suggest(l.clone());
|
||||
}
|
||||
}
|
||||
NodeKind::Argument { ty, name } => ty.suggest(&mut builder, reg, context, name),
|
||||
NodeKind::Root => {}
|
||||
}
|
||||
all.extend(builder.out);
|
||||
}
|
||||
merge_suggestions(truncated, all)
|
||||
}
|
||||
fn smart_usage_of(&self, node: usize, optional: bool, deep: bool, level: u8) -> Option<String> {
|
||||
let n = &self.nodes[node];
|
||||
if n.permission > level {
|
||||
return None;
|
||||
}
|
||||
let this = if optional { format!("[{}]", n.usage_text()) } else { n.usage_text() };
|
||||
let child_optional = n.command.is_some();
|
||||
let (open, close) = if child_optional { ("[", "]") } else { ("(", ")") };
|
||||
if !deep {
|
||||
if let Some(r) = n.redirect {
|
||||
let target = if r == 0 { "...".to_owned() } else { format!("-> {}", self.nodes[r].usage_text()) };
|
||||
return Some(format!("{this} {target}"));
|
||||
}
|
||||
let children: Vec<usize> = n.children.iter().copied().filter(|&c| self.nodes[c].permission <= level).collect();
|
||||
if children.len() == 1 {
|
||||
if let Some(usage) = self.smart_usage_of(children[0], child_optional, child_optional, level) {
|
||||
return Some(format!("{this} {usage}"));
|
||||
}
|
||||
} else if children.len() > 1 {
|
||||
let mut child_usage: Vec<String> = Vec::new();
|
||||
for &c in &children {
|
||||
if let Some(u) = self.smart_usage_of(c, child_optional, true, level)
|
||||
&& !child_usage.contains(&u)
|
||||
{
|
||||
child_usage.push(u);
|
||||
}
|
||||
}
|
||||
if child_usage.len() == 1 {
|
||||
let usage = &child_usage[0];
|
||||
return Some(format!("{this} {}", if child_optional { format!("[{usage}]") } else { usage.clone() }));
|
||||
}
|
||||
if child_usage.len() > 1 {
|
||||
let alternatives: Vec<String> = children.iter().map(|&c| self.nodes[c].usage_text()).collect();
|
||||
return Some(format!("{this} {open}{}{close}", alternatives.join("|")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(this)
|
||||
}
|
||||
/// CommandDispatcher.getSmartUsage: one line per child of `node`.
|
||||
pub fn smart_usage(&self, node: usize, level: u8) -> Vec<(usize, String)> {
|
||||
let optional = self.nodes[node].command.is_some();
|
||||
self.nodes[node].children.iter().filter_map(|&c| self.smart_usage_of(c, optional, false, level).map(|u| (c, u))).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,139 @@
|
||||
use super::{args::*, vanilla, *};
|
||||
|
||||
fn reg() -> Registries {
|
||||
let mut r = Registries { permission: 4, ..Registries::default() };
|
||||
r.items = vec!["minecraft:diamond".into(), "minecraft:diamond_sword".into(), "minecraft:stone".into()];
|
||||
r.blocks.insert("minecraft:stone".into(), vec![]);
|
||||
r.blocks.insert(
|
||||
"minecraft:oak_stairs".into(),
|
||||
vec![("facing".into(), vec!["north".into(), "south".into()]), ("half".into(), vec!["top".into(), "bottom".into()])],
|
||||
);
|
||||
r.summonable = vec!["minecraft:pig".into(), "minecraft:zombie".into()];
|
||||
r.entity_types = vec!["minecraft:pig".into(), "minecraft:player".into(), "minecraft:zombie".into()];
|
||||
r.players = vec!["Player".into()];
|
||||
r.dimensions = vec!["minecraft:overworld".into()];
|
||||
r.time_markers = vec!["minecraft:day".into(), "minecraft:noon".into()];
|
||||
r
|
||||
}
|
||||
fn run(input: &str) -> CmdResult<(String, Vec<String>)> {
|
||||
let reg = reg();
|
||||
let parse = vanilla::dispatcher().parse(input, ®);
|
||||
let (ctx, id) = parse.executable()?;
|
||||
Ok((id.to_owned(), ctx.args.iter().map(|a| a.name.clone()).collect()))
|
||||
}
|
||||
fn suggestions(input: &str) -> Vec<String> {
|
||||
let reg = reg();
|
||||
let d = vanilla::dispatcher();
|
||||
let parse = d.parse(input, ®);
|
||||
d.suggestions(&parse, input.len(), ®).1.into_iter().map(|s| s.text).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reader_matches_brigadier() {
|
||||
let mut r = Reader::new("12 -3.5 abc \"q\\\"x\" true");
|
||||
assert_eq!(r.read_int().unwrap(), 12);
|
||||
r.skip();
|
||||
assert_eq!(r.read_double().unwrap(), -3.5);
|
||||
r.skip();
|
||||
assert_eq!(r.read_unquoted_string(), "abc");
|
||||
r.skip();
|
||||
assert_eq!(r.read_string().unwrap(), "q\"x");
|
||||
r.skip();
|
||||
assert!(r.read_boolean().unwrap());
|
||||
let e = Reader::new("1.5").read_int().unwrap_err();
|
||||
assert_eq!(e.message.plain(), "parsing.int.invalid");
|
||||
assert_eq!(e.context().unwrap(), "<--[HERE]");
|
||||
}
|
||||
#[test]
|
||||
fn parses_vanilla_commands() {
|
||||
assert_eq!(run("gamemode creative").unwrap().0, "gamemode");
|
||||
assert_eq!(run("gamemode creative @s").unwrap().1, ["gamemode", "target"]);
|
||||
assert_eq!(run("give @s minecraft:diamond 64").unwrap().1, ["targets", "item", "count"]);
|
||||
assert_eq!(run("tp 1 2 3").unwrap().0, "teleport.location");
|
||||
assert_eq!(run("tp Player").unwrap().0, "teleport.destination");
|
||||
assert_eq!(run("tp @s ~ ~10 ~").unwrap().0, "teleport.targets.location");
|
||||
assert_eq!(run("teleport @e[type=pig,limit=2] ^ ^ ^5 90 0").unwrap().0, "teleport.targets.location");
|
||||
assert_eq!(run("time set 1000").unwrap().0, "time.set");
|
||||
assert_eq!(run("time set 1d").unwrap().0, "time.set");
|
||||
assert_eq!(run("time set day").unwrap().0, "time.set.marker");
|
||||
assert_eq!(run("time query gametime").unwrap().0, "time.query.gametime");
|
||||
assert_eq!(run("weather rain 10s").unwrap().0, "weather");
|
||||
assert_eq!(run("xp add @s 5 levels").unwrap().0, "experience");
|
||||
assert_eq!(run("gamerule keep_inventory true").unwrap().0, "gamerule");
|
||||
assert_eq!(run("gamerule minecraft:random_tick_speed 10").unwrap().0, "gamerule");
|
||||
assert_eq!(run("fill ~ ~ ~ ~1 ~1 ~1 stone hollow").unwrap().0, "fill");
|
||||
assert_eq!(run("fill 0 0 0 1 1 1 minecraft:oak_stairs[facing=north] replace stone").unwrap().0, "fill");
|
||||
assert_eq!(run("clone 0 0 0 1 1 1 5 5 5 masked move").unwrap().0, "clone");
|
||||
assert_eq!(run("setblock ~ ~1 ~ oak_stairs[half=top] keep").unwrap().0, "setblock");
|
||||
assert_eq!(run("summon zombie ~ ~ ~ {NoAI:1b}").unwrap().0, "summon");
|
||||
assert_eq!(run("difficulty hard").unwrap().0, "difficulty");
|
||||
assert_eq!(run("say hello @p").unwrap().0, "say");
|
||||
let reg = reg();
|
||||
let parse = vanilla::dispatcher().parse("clone 0 0 0 1 1 1 5 5 5 strict filtered stone force", ®);
|
||||
let (ctx, _) = parse.executable().unwrap();
|
||||
assert!(ctx.has("strict") && ctx.has("filtered") && ctx.has("force") && !ctx.has("move"));
|
||||
}
|
||||
#[test]
|
||||
fn vanilla_error_messages() {
|
||||
let e = run("foo").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "command.unknown.command");
|
||||
assert_eq!(e.cursor, 0);
|
||||
let e = run("gamemode").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "command.unknown.command");
|
||||
let e = run("gamemode creatve").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "argument.gamemode.invalid");
|
||||
assert_eq!(e.cursor, 9);
|
||||
let e = run("give @s minecraft:dirt").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "argument.item.id.invalid");
|
||||
let e = run("give @s diamond 0").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "argument.integer.low");
|
||||
let e = run("gamemode creative @e").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "argument.player.entities");
|
||||
let e = run("setblock 1 2").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "argument.pos3d.incomplete");
|
||||
let e = run("setblock 1 2 3 oak_stairs[facing=up]").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "argument.block.property.invalid");
|
||||
}
|
||||
#[test]
|
||||
fn suggestions_like_vanilla() {
|
||||
let root = suggestions("");
|
||||
assert!(root.contains(&"gamemode".to_owned()) && root.contains(&"tp".to_owned()));
|
||||
assert_eq!(suggestions("game"), ["gamemode", "gamerule"]);
|
||||
assert_eq!(suggestions("gamemode "), ["adventure", "creative", "spectator", "survival"]);
|
||||
assert_eq!(suggestions("gamemode c"), ["creative"]);
|
||||
assert_eq!(suggestions("give @s dia"), ["minecraft:diamond", "minecraft:diamond_sword"]);
|
||||
// Underscore-separated parts match too (SharedSuggestionProvider.matchesSubStr).
|
||||
assert_eq!(suggestions("give @s sword"), ["minecraft:diamond_sword"]);
|
||||
assert_eq!(suggestions("kill @"), ["@a", "@e", "@n", "@p", "@r", "@s"]);
|
||||
assert_eq!(suggestions("kill @e"), ["["]);
|
||||
assert_eq!(suggestions("kill @e[ty"), ["type="]);
|
||||
assert!(suggestions("kill @e[type=").contains(&"minecraft:zombie".to_owned()));
|
||||
assert_eq!(suggestions("kill @e[type=pig"), [",", "]"]);
|
||||
assert_eq!(suggestions("setblock 0 0 0 oak_stairs[fa"), ["facing="]);
|
||||
assert_eq!(suggestions("setblock 0 0 0 oak_stairs[facing=n"), ["north"]);
|
||||
assert_eq!(suggestions("tp "), ["@a", "@e", "@n", "@p", "@r", "@s", "Player", "~", "~ ~", "~ ~ ~"]);
|
||||
assert_eq!(suggestions("time set 5"), ["d", "s", "t"]);
|
||||
assert!(suggestions("time set ").contains(&"minecraft:day".to_owned()));
|
||||
}
|
||||
#[test]
|
||||
fn smart_usage_matches_brigadier() {
|
||||
let d = vanilla::dispatcher();
|
||||
let usage = |name: &str| d.smart_usage(0, 4).into_iter().find(|(n, _)| d.nodes[*n].name() == name).unwrap().1;
|
||||
assert_eq!(usage("gamemode"), "gamemode <gamemode> [<target>]");
|
||||
assert_eq!(usage("give"), "give <targets> <item> [<count>]");
|
||||
assert_eq!(usage("kill"), "kill [<targets>]");
|
||||
assert_eq!(usage("weather"), "weather (clear|rain|thunder)");
|
||||
assert_eq!(usage("tp"), "tp -> teleport");
|
||||
assert_eq!(usage("difficulty"), "difficulty [peaceful|easy|normal|hard]");
|
||||
}
|
||||
#[test]
|
||||
fn local_coordinates_follow_view() {
|
||||
// Facing south (yaw 0) moves +Z.
|
||||
let p = Coordinates::Local([0.0, 0.0, 2.0]).position([0.0, 64.0, 0.0], [0.0, 0.0]);
|
||||
assert!((p[2] - 2.0).abs() < 1e-6 && p[0].abs() < 1e-6);
|
||||
// ^1 (left) while facing south is +X.
|
||||
let p = Coordinates::Local([1.0, 0.0, 0.0]).position([0.0, 64.0, 0.0], [0.0, 0.0]);
|
||||
assert!((p[0] - 1.0).abs() < 1e-6, "{p:?}");
|
||||
let w = Coordinates::World([Coord { relative: true, value: 1.0 }, Coord { relative: false, value: 5.0 }, Coord { relative: true, value: 0.0 }]);
|
||||
assert_eq!(w.position([10.0, 64.0, 3.0], [0.0, 0.0]), [11.0, 5.0, 3.0]);
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
//! The vanilla command tree (Commands.java registrations) for the commands
|
||||
//! Horizon implements. Leaves carry command ids that the game executes;
|
||||
//! mode keywords are read back from the parsed literals.
|
||||
use super::{
|
||||
Dispatcher,
|
||||
args::{ArgType, GameMode, Resource, integer},
|
||||
};
|
||||
use crate::gamerules::{RULES, Value};
|
||||
|
||||
/// Permission levels (Commands.LEVEL_*).
|
||||
pub const ALL: u8 = 0;
|
||||
pub const GAMEMASTERS: u8 = 2;
|
||||
|
||||
const PLAYERS: ArgType = ArgType::Entity { single: false, players: true };
|
||||
const PLAYER: ArgType = ArgType::Entity { single: true, players: true };
|
||||
const ENTITIES: ArgType = ArgType::Entity { single: false, players: false };
|
||||
const ENTITY: ArgType = ArgType::Entity { single: true, players: false };
|
||||
|
||||
pub const DIFFICULTIES: [&str; 4] = ["peaceful", "easy", "normal", "hard"];
|
||||
|
||||
pub fn build() -> Dispatcher {
|
||||
let mut d = Dispatcher::new();
|
||||
let root = 0;
|
||||
|
||||
// help [<command>]
|
||||
let help = d.literal(root, "help");
|
||||
d.executes(help, "help");
|
||||
let c = d.argument(help, "command", ArgType::Greedy);
|
||||
d.executes(c, "help");
|
||||
|
||||
// gamemode <gamemode> [<target>]
|
||||
let gm = d.literal(root, "gamemode");
|
||||
d.requires(gm, GAMEMASTERS);
|
||||
let mode = d.argument(gm, "gamemode", ArgType::GameMode);
|
||||
d.executes(mode, "gamemode");
|
||||
let t = d.argument(mode, "target", PLAYERS);
|
||||
d.executes(t, "gamemode");
|
||||
|
||||
let dgm = d.literal(root, "defaultgamemode");
|
||||
d.requires(dgm, GAMEMASTERS);
|
||||
let mode = d.argument(dgm, "gamemode", ArgType::GameMode);
|
||||
d.executes(mode, "defaultgamemode");
|
||||
|
||||
// give <targets> <item> [<count>]
|
||||
let give = d.literal(root, "give");
|
||||
d.requires(give, GAMEMASTERS);
|
||||
let targets = d.argument(give, "targets", PLAYERS);
|
||||
let item = d.argument(targets, "item", ArgType::Item);
|
||||
d.executes(item, "give");
|
||||
let count = d.argument(item, "count", integer(1));
|
||||
d.executes(count, "give");
|
||||
|
||||
// teleport / tp
|
||||
let tp = d.literal(root, "teleport");
|
||||
d.requires(tp, GAMEMASTERS);
|
||||
let loc = d.argument(tp, "location", ArgType::Vec3 { center: true });
|
||||
d.executes(loc, "teleport.location");
|
||||
let dest = d.argument(tp, "destination", ENTITY);
|
||||
d.executes(dest, "teleport.destination");
|
||||
let targets = d.argument(tp, "targets", ENTITIES);
|
||||
let loc = d.argument(targets, "location", ArgType::Vec3 { center: true });
|
||||
d.executes(loc, "teleport.targets.location");
|
||||
let rot = d.argument(loc, "rotation", ArgType::Rotation);
|
||||
d.executes(rot, "teleport.targets.location");
|
||||
let facing = d.literal(loc, "facing");
|
||||
let fe = d.literal(facing, "entity");
|
||||
let fent = d.argument(fe, "facingEntity", ENTITY);
|
||||
d.executes(fent, "teleport.targets.location");
|
||||
let anchor = d.argument(fent, "facingAnchor", ArgType::Anchor);
|
||||
d.executes(anchor, "teleport.targets.location");
|
||||
let floc = d.argument(facing, "facingLocation", ArgType::Vec3 { center: true });
|
||||
d.executes(floc, "teleport.targets.location");
|
||||
let dest = d.argument(targets, "destination", ENTITY);
|
||||
d.executes(dest, "teleport.targets.destination");
|
||||
let alias = d.literal(root, "tp");
|
||||
d.requires(alias, GAMEMASTERS);
|
||||
d.redirect(alias, tp);
|
||||
|
||||
// time: clock nodes for the dimension's default clock, plus `of <clock>`.
|
||||
let time = d.literal(root, "time");
|
||||
d.requires(time, GAMEMASTERS);
|
||||
clock_nodes(&mut d, time);
|
||||
let query = d.literal(time, "query");
|
||||
let gt = d.literal(query, "gametime");
|
||||
d.executes(gt, "time.query.gametime");
|
||||
let of = d.literal(time, "of");
|
||||
let clock = d.argument(of, "clock", ArgType::Resource(Resource::Clock));
|
||||
clock_nodes(&mut d, clock);
|
||||
|
||||
// weather (clear|rain|thunder) [<duration>]
|
||||
let weather = d.literal(root, "weather");
|
||||
d.requires(weather, GAMEMASTERS);
|
||||
for kind in ["clear", "rain", "thunder"] {
|
||||
let k = d.literal(weather, kind);
|
||||
d.executes(k, "weather");
|
||||
let dur = d.argument(k, "duration", ArgType::Time { min: 1 });
|
||||
d.executes(dur, "weather");
|
||||
}
|
||||
|
||||
// kill [<targets>]
|
||||
let kill = d.literal(root, "kill");
|
||||
d.requires(kill, GAMEMASTERS);
|
||||
d.executes(kill, "kill");
|
||||
let t = d.argument(kill, "targets", ENTITIES);
|
||||
d.executes(t, "kill");
|
||||
|
||||
// summon <entity> [<pos>] [<nbt>]
|
||||
let summon = d.literal(root, "summon");
|
||||
d.requires(summon, GAMEMASTERS);
|
||||
let e = d.argument(summon, "entity", ArgType::Resource(Resource::EntityType));
|
||||
d.executes(e, "summon");
|
||||
let pos = d.argument(e, "pos", ArgType::Vec3 { center: true });
|
||||
d.executes(pos, "summon");
|
||||
let nbt = d.argument(pos, "nbt", ArgType::Nbt);
|
||||
d.executes(nbt, "summon");
|
||||
|
||||
// setblock <pos> <block> [destroy|keep|replace|strict]
|
||||
let sb = d.literal(root, "setblock");
|
||||
d.requires(sb, GAMEMASTERS);
|
||||
let pos = d.argument(sb, "pos", ArgType::BlockPos);
|
||||
let block = d.argument(pos, "block", ArgType::BlockState);
|
||||
d.executes(block, "setblock");
|
||||
for m in ["destroy", "keep", "replace", "strict"] {
|
||||
let l = d.literal(block, m);
|
||||
d.executes(l, "setblock");
|
||||
}
|
||||
|
||||
// fill <from> <to> <block> [modes]
|
||||
let fill = d.literal(root, "fill");
|
||||
d.requires(fill, GAMEMASTERS);
|
||||
let from = d.argument(fill, "from", ArgType::BlockPos);
|
||||
let to = d.argument(from, "to", ArgType::BlockPos);
|
||||
let block = d.argument(to, "block", ArgType::BlockState);
|
||||
fill_modes(&mut d, block);
|
||||
let replace = d.literal(block, "replace");
|
||||
d.executes(replace, "fill");
|
||||
let filter = d.argument(replace, "filter", ArgType::BlockPredicate);
|
||||
fill_modes(&mut d, filter);
|
||||
let keep = d.literal(block, "keep");
|
||||
d.executes(keep, "fill");
|
||||
|
||||
// clone [from <dim>] <begin> <end> [to <dim>] <destination> [strict] [mask] [mode]
|
||||
let clone = d.literal(root, "clone");
|
||||
d.requires(clone, GAMEMASTERS);
|
||||
clone_begin(&mut d, clone);
|
||||
let from = d.literal(clone, "from");
|
||||
let dim = d.argument(from, "sourceDimension", ArgType::Dimension);
|
||||
clone_begin(&mut d, dim);
|
||||
|
||||
// experience / xp
|
||||
let xp = d.literal(root, "experience");
|
||||
d.requires(xp, GAMEMASTERS);
|
||||
for (op, min) in [("add", i32::MIN), ("set", 0)] {
|
||||
let o = d.literal(xp, op);
|
||||
let t = d.argument(o, "target", PLAYERS);
|
||||
let amount = d.argument(t, "amount", integer(min));
|
||||
d.executes(amount, "experience");
|
||||
for unit in ["points", "levels"] {
|
||||
let u = d.literal(amount, unit);
|
||||
d.executes(u, "experience");
|
||||
}
|
||||
}
|
||||
let q = d.literal(xp, "query");
|
||||
let t = d.argument(q, "target", PLAYER);
|
||||
for unit in ["points", "levels"] {
|
||||
let u = d.literal(t, unit);
|
||||
d.executes(u, "experience");
|
||||
}
|
||||
let alias = d.literal(root, "xp");
|
||||
d.requires(alias, GAMEMASTERS);
|
||||
d.redirect(alias, xp);
|
||||
|
||||
// gamerule <rule> [<value>] (short and namespaced names)
|
||||
let gr = d.literal(root, "gamerule");
|
||||
d.requires(gr, GAMEMASTERS);
|
||||
for rule in RULES {
|
||||
for name in [rule.name.to_owned(), format!("minecraft:{}", rule.name)] {
|
||||
let r = d.literal(gr, &name);
|
||||
d.executes(r, "gamerule");
|
||||
let ty = match rule.default {
|
||||
Value::Bool(_) => ArgType::Bool,
|
||||
Value::Int(_) => ArgType::Integer { min: rule.min, max: rule.max },
|
||||
};
|
||||
let v = d.argument(r, "value", ty);
|
||||
d.executes(v, "gamerule");
|
||||
}
|
||||
}
|
||||
|
||||
// difficulty [<difficulty>]
|
||||
let diff = d.literal(root, "difficulty");
|
||||
d.executes(diff, "difficulty");
|
||||
for name in DIFFICULTIES {
|
||||
let l = d.literal(diff, name);
|
||||
d.requires(l, GAMEMASTERS);
|
||||
d.executes(l, "difficulty");
|
||||
}
|
||||
|
||||
let seed = d.literal(root, "seed");
|
||||
d.executes(seed, "seed");
|
||||
|
||||
// spawnpoint [<targets>] [<pos>] [<rotation>]
|
||||
let sp = d.literal(root, "spawnpoint");
|
||||
d.requires(sp, GAMEMASTERS);
|
||||
d.executes(sp, "spawnpoint");
|
||||
let t = d.argument(sp, "targets", PLAYERS);
|
||||
d.executes(t, "spawnpoint");
|
||||
let pos = d.argument(t, "pos", ArgType::BlockPos);
|
||||
d.executes(pos, "spawnpoint");
|
||||
let rot = d.argument(pos, "rotation", ArgType::Rotation);
|
||||
d.executes(rot, "spawnpoint");
|
||||
|
||||
// setworldspawn [<pos>] [<rotation>]
|
||||
let ws = d.literal(root, "setworldspawn");
|
||||
d.requires(ws, GAMEMASTERS);
|
||||
d.executes(ws, "setworldspawn");
|
||||
let pos = d.argument(ws, "pos", ArgType::BlockPos);
|
||||
d.executes(pos, "setworldspawn");
|
||||
let rot = d.argument(pos, "rotation", ArgType::Rotation);
|
||||
d.executes(rot, "setworldspawn");
|
||||
|
||||
// clear [<targets>] [<item>] [<maxCount>]
|
||||
let clear = d.literal(root, "clear");
|
||||
d.requires(clear, GAMEMASTERS);
|
||||
d.executes(clear, "clear");
|
||||
let t = d.argument(clear, "targets", PLAYERS);
|
||||
d.executes(t, "clear");
|
||||
let item = d.argument(t, "item", ArgType::ItemPredicate);
|
||||
d.executes(item, "clear");
|
||||
let max = d.argument(item, "maxCount", integer(0));
|
||||
d.executes(max, "clear");
|
||||
|
||||
// locate (structure|biome) <...>
|
||||
let locate = d.literal(root, "locate");
|
||||
d.requires(locate, GAMEMASTERS);
|
||||
let s = d.literal(locate, "structure");
|
||||
let a = d.argument(s, "structure", ArgType::Resource(Resource::Structure));
|
||||
d.executes(a, "locate.structure");
|
||||
let b = d.literal(locate, "biome");
|
||||
let a = d.argument(b, "biome", ArgType::Resource(Resource::Biome));
|
||||
d.executes(a, "locate.biome");
|
||||
|
||||
// say / me / msg / list
|
||||
let say = d.literal(root, "say");
|
||||
d.requires(say, GAMEMASTERS);
|
||||
let m = d.argument(say, "message", ArgType::Message);
|
||||
d.executes(m, "say");
|
||||
let me = d.literal(root, "me");
|
||||
let m = d.argument(me, "action", ArgType::Message);
|
||||
d.executes(m, "me");
|
||||
let msg = d.literal(root, "msg");
|
||||
let t = d.argument(msg, "targets", PLAYERS);
|
||||
let m = d.argument(t, "message", ArgType::Message);
|
||||
d.executes(m, "msg");
|
||||
for alias in ["tell", "w"] {
|
||||
let a = d.literal(root, alias);
|
||||
d.redirect(a, msg);
|
||||
}
|
||||
let list = d.literal(root, "list");
|
||||
d.executes(list, "list");
|
||||
let uuids = d.literal(list, "uuids");
|
||||
d.executes(uuids, "list");
|
||||
|
||||
d
|
||||
}
|
||||
|
||||
/// TimeCommand.addClockNodes.
|
||||
fn clock_nodes(d: &mut Dispatcher, node: usize) {
|
||||
let set = d.literal(node, "set");
|
||||
let t = d.argument(set, "time", ArgType::Time { min: 0 });
|
||||
d.executes(t, "time.set");
|
||||
let marker = d.argument(set, "timemarker", ArgType::Id("time_markers"));
|
||||
d.executes(marker, "time.set.marker");
|
||||
let add = d.literal(node, "add");
|
||||
let t = d.argument(add, "time", ArgType::Time { min: i32::MIN });
|
||||
d.executes(t, "time.add");
|
||||
let pause = d.literal(node, "pause");
|
||||
d.executes(pause, "time.pause");
|
||||
let resume = d.literal(node, "resume");
|
||||
d.executes(resume, "time.resume");
|
||||
let rate = d.literal(node, "rate");
|
||||
let r = d.argument(rate, "rate", ArgType::Float { min: 1.0e-5, max: 1000.0 });
|
||||
d.executes(r, "time.rate");
|
||||
let query = d.literal(node, "query");
|
||||
let time = d.literal(query, "time");
|
||||
d.executes(time, "time.query.time");
|
||||
let tl = d.argument(query, "timeline", ArgType::Resource(Resource::Timeline));
|
||||
d.executes(tl, "time.query.timeline");
|
||||
let rep = d.literal(tl, "repetition");
|
||||
d.executes(rep, "time.query.repetition");
|
||||
}
|
||||
/// FillCommand.wrapWithMode.
|
||||
fn fill_modes(d: &mut Dispatcher, node: usize) {
|
||||
d.executes(node, "fill");
|
||||
for m in ["outline", "hollow", "destroy", "strict"] {
|
||||
let l = d.literal(node, m);
|
||||
d.executes(l, "fill");
|
||||
}
|
||||
}
|
||||
fn clone_begin(d: &mut Dispatcher, node: usize) {
|
||||
let begin = d.argument(node, "begin", ArgType::BlockPos);
|
||||
let end = d.argument(begin, "end", ArgType::BlockPos);
|
||||
clone_destination(d, end);
|
||||
let to = d.literal(end, "to");
|
||||
let dim = d.argument(to, "targetDimension", ArgType::Dimension);
|
||||
clone_destination(d, dim);
|
||||
}
|
||||
fn clone_destination(d: &mut Dispatcher, node: usize) {
|
||||
let dest = d.argument(node, "destination", ArgType::BlockPos);
|
||||
clone_mask(d, dest);
|
||||
let strict = d.literal(dest, "strict");
|
||||
clone_mask(d, strict);
|
||||
}
|
||||
fn clone_mask(d: &mut Dispatcher, node: usize) {
|
||||
d.executes(node, "clone");
|
||||
for m in ["replace", "masked"] {
|
||||
let l = d.literal(node, m);
|
||||
clone_mode(d, l);
|
||||
}
|
||||
let filtered = d.literal(node, "filtered");
|
||||
let filter = d.argument(filtered, "filter", ArgType::BlockPredicate);
|
||||
clone_mode(d, filter);
|
||||
}
|
||||
fn clone_mode(d: &mut Dispatcher, node: usize) {
|
||||
d.executes(node, "clone");
|
||||
for m in ["force", "move", "normal"] {
|
||||
let l = d.literal(node, m);
|
||||
d.executes(l, "clone");
|
||||
}
|
||||
}
|
||||
/// Game mode names for selector `gamemode=` and the argument.
|
||||
pub fn game_modes() -> [&'static str; 4] {
|
||||
GameMode::ALL.map(GameMode::name)
|
||||
}
|
||||
/// The shared vanilla tree.
|
||||
pub fn dispatcher() -> &'static Dispatcher {
|
||||
static TREE: std::sync::OnceLock<Dispatcher> = std::sync::OnceLock::new();
|
||||
TREE.get_or_init(build)
|
||||
}
|
||||
#[allow(unused)]
|
||||
const _: (u8, u8) = (ALL, GAMEMASTERS);
|
||||
@@ -0,0 +1,455 @@
|
||||
//! The default font (FontSet over `font/default.json`): space and bitmap
|
||||
//! providers from the shared atlas, the unihex (GNU Unifont) fallback whose
|
||||
//! glyphs are rasterized on demand into a reserved atlas region, vanilla
|
||||
//! glyph metrics (ascent, oversampling, advances, bold/shadow offsets),
|
||||
//! styled drawing and StringSplitter-style line wrapping.
|
||||
use crate::{
|
||||
hud::Rect,
|
||||
text::{Style, Text},
|
||||
zip::Zip,
|
||||
};
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
collections::HashMap,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
/// A glyph ready to draw: atlas UVs and its box relative to the pen
|
||||
/// position (GlyphBitmap left/top/right/bottom), in GUI pixels.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Glyph {
|
||||
pub rect: Option<Rect>,
|
||||
pub left: f32,
|
||||
pub top: f32,
|
||||
pub right: f32,
|
||||
pub bottom: f32,
|
||||
pub advance: f32,
|
||||
/// Shadow and bold offset (1 for bitmap glyphs, 0.5 for unihex).
|
||||
pub offset: f32,
|
||||
}
|
||||
/// Pixels to copy into the shared atlas before the next HUD draw.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Patch {
|
||||
pub x: u32,
|
||||
pub y: u32,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub rgba: Vec<u8>,
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
struct HexGlyph {
|
||||
/// Rows left-aligned in 32 bits.
|
||||
rows: [u32; 16],
|
||||
left: u32,
|
||||
right: u32,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct HexProvider {
|
||||
glyphs: HashMap<u32, HexGlyph>,
|
||||
}
|
||||
struct Cache {
|
||||
glyphs: HashMap<char, Glyph>,
|
||||
cursor: (u32, u32),
|
||||
pending: Vec<Patch>,
|
||||
hex: Option<Vec<HexProvider>>,
|
||||
}
|
||||
pub struct Font {
|
||||
bitmap: HashMap<char, Glyph>,
|
||||
space: HashMap<char, f32>,
|
||||
missing: Glyph,
|
||||
white: Rect,
|
||||
root: PathBuf,
|
||||
/// Atlas size and the reserved dynamic region (y, height).
|
||||
atlas: (u32, u32),
|
||||
region: (u32, u32),
|
||||
cache: RefCell<Cache>,
|
||||
/// "Force Unicode Font": skip the bitmap providers (font/uniform.json).
|
||||
pub uniform: bool,
|
||||
/// "Japanese Glyph Variants": enable providers filtered on `jp`.
|
||||
pub japanese: bool,
|
||||
}
|
||||
fn parse_hex_digit(b: u8) -> Option<u32> {
|
||||
(b as char).to_digit(16)
|
||||
}
|
||||
/// UnihexProvider.readFromStream over one `.hex` file.
|
||||
fn parse_hex(text: &[u8], out: &mut HashMap<u32, HexGlyph>) {
|
||||
for line in text.split(|b| *b == b'\n') {
|
||||
let line = line.strip_suffix(b"\r").unwrap_or(line);
|
||||
let Some(colon) = line.iter().position(|b| *b == b':') else { continue };
|
||||
let (code, data) = (&line[..colon], &line[colon + 1..]);
|
||||
if !(4..=6).contains(&code.len()) {
|
||||
continue;
|
||||
}
|
||||
let Some(codepoint) = code.iter().try_fold(0u32, |a, b| parse_hex_digit(*b).map(|d| a << 4 | d)) else { continue };
|
||||
let digits_per_row = match data.len() {
|
||||
32 => 2,
|
||||
64 => 4,
|
||||
96 => 6,
|
||||
128 => 8,
|
||||
_ => continue,
|
||||
};
|
||||
let bit_width = digits_per_row as u32 * 4;
|
||||
let mut rows = [0u32; 16];
|
||||
let mut mask = 0u32;
|
||||
let mut ok = true;
|
||||
for (r, row) in rows.iter_mut().enumerate() {
|
||||
let chunk = &data[r * digits_per_row..(r + 1) * digits_per_row];
|
||||
match chunk.iter().try_fold(0u32, |a, b| parse_hex_digit(*b).map(|d| a << 4 | d)) {
|
||||
Some(v) => {
|
||||
*row = v << (32 - bit_width);
|
||||
mask |= *row;
|
||||
}
|
||||
None => ok = false,
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
continue;
|
||||
}
|
||||
// LineData.calculateWidth.
|
||||
let (left, right) = if mask == 0 { (0, bit_width) } else { (mask.leading_zeros(), 31 - mask.trailing_zeros()) };
|
||||
out.insert(codepoint, HexGlyph { rows, left, right });
|
||||
}
|
||||
}
|
||||
fn read_json(root: &Path, path: &str) -> Option<serde_json::Value> {
|
||||
serde_json::from_slice(&std::fs::read(root.join(path)).ok()?).ok()
|
||||
}
|
||||
fn resource_path(id: &str, folder: &str, ext: &str) -> String {
|
||||
let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id));
|
||||
format!("assets/{ns}/{folder}/{}{ext}", path.trim_end_matches(ext))
|
||||
}
|
||||
/// Providers of a font definition with references expanded, in order, with
|
||||
/// their `filter` objects.
|
||||
fn providers(root: &Path, id: &str, depth: u32, out: &mut Vec<serde_json::Value>) {
|
||||
if depth > 8 {
|
||||
return;
|
||||
}
|
||||
let Some(def) = read_json(root, &resource_path(id, "font", ".json")) else { return };
|
||||
for p in def["providers"].as_array().into_iter().flatten() {
|
||||
if p["type"] == "reference" {
|
||||
let mut nested = Vec::new();
|
||||
providers(root, p["id"].as_str().unwrap_or(""), depth + 1, &mut nested);
|
||||
for mut n in nested {
|
||||
// A reference's filter applies to everything it includes.
|
||||
if let Some(f) = p["filter"].as_object() {
|
||||
let merged = n["filter"].as_object().cloned().unwrap_or_default().into_iter().chain(f.clone()).collect();
|
||||
n["filter"] = serde_json::Value::Object(merged);
|
||||
}
|
||||
out.push(n);
|
||||
}
|
||||
} else {
|
||||
out.push(p.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Font {
|
||||
/// Build from the atlas holding the bitmap font sheets. `pixels` is the
|
||||
/// RGBA atlas (for glyph widths) and `region` the reserved rows.
|
||||
pub fn load(root: &Path, sprites: &HashMap<String, Rect>, pixels: &[u8], atlas: (u32, u32), region: (u32, u32), white: Rect) -> Self {
|
||||
let mut bitmap = HashMap::new();
|
||||
let mut space = HashMap::new();
|
||||
let mut all = Vec::new();
|
||||
providers(root, "minecraft:default", 0, &mut all);
|
||||
for provider in &all {
|
||||
match provider["type"].as_str() {
|
||||
Some("space") => {
|
||||
for (k, v) in provider["advances"].as_object().into_iter().flatten() {
|
||||
if let (Some(c), Some(a)) = (k.chars().next(), v.as_f64()) {
|
||||
space.entry(c).or_insert(a as f32);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some("bitmap") => {
|
||||
// Only non-uniform bitmap sheets exist in the default font.
|
||||
let file = provider["file"].as_str().unwrap_or("");
|
||||
let name = file.trim_start_matches("minecraft:").trim_end_matches(".png");
|
||||
let name = format!("{}", name);
|
||||
let Some(rect) = sprites.get(&name).copied() else { continue };
|
||||
let rows: Vec<Vec<char>> = provider["chars"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|r| r.as_str().map(|s| s.chars().collect()))
|
||||
.collect();
|
||||
if rows.is_empty() || rows[0].is_empty() {
|
||||
continue;
|
||||
}
|
||||
let cell_w = rect.w / rows[0].len() as u32;
|
||||
let cell_h = rect.h / rows.len() as u32;
|
||||
let height = provider["height"].as_f64().unwrap_or(8.0) as f32;
|
||||
let ascent = provider["ascent"].as_f64().unwrap_or(7.0) as f32;
|
||||
let scale = height / cell_h as f32;
|
||||
let (ax, ay) = ((rect.u0 * atlas.0 as f32).round() as u32, (rect.v0 * atlas.1 as f32).round() as u32);
|
||||
for (r, row) in rows.iter().enumerate() {
|
||||
for (c, ch) in row.iter().enumerate() {
|
||||
if *ch == '\0' || bitmap.contains_key(ch) {
|
||||
continue;
|
||||
}
|
||||
let (cx, cy) = (ax + c as u32 * cell_w, ay + r as u32 * cell_h);
|
||||
// BitmapProvider.getActualGlyphWidth.
|
||||
let mut used = 0;
|
||||
for x in (0..cell_w).rev() {
|
||||
if (0..cell_h).any(|y| pixels.get((((cy + y) * atlas.0 + cx + x) * 4 + 3) as usize).is_some_and(|a| *a != 0)) {
|
||||
used = x + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
let top = 7.0 - ascent;
|
||||
bitmap.insert(
|
||||
*ch,
|
||||
Glyph {
|
||||
rect: Some(Rect {
|
||||
u0: cx as f32 / atlas.0 as f32,
|
||||
v0: cy as f32 / atlas.1 as f32,
|
||||
u1: (cx + cell_w) as f32 / atlas.0 as f32,
|
||||
v1: (cy + cell_h) as f32 / atlas.1 as f32,
|
||||
w: cell_w,
|
||||
h: cell_h,
|
||||
}),
|
||||
left: 0.0,
|
||||
top,
|
||||
right: cell_w as f32 * scale,
|
||||
bottom: top + cell_h as f32 * scale,
|
||||
advance: (0.5 + used as f32 * scale).floor() + 1.0,
|
||||
offset: 1.0,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let missing = Glyph { rect: None, left: 0.0, top: 0.0, right: 5.0, bottom: 8.0, advance: 6.0, offset: 1.0 };
|
||||
Self {
|
||||
bitmap,
|
||||
space,
|
||||
missing,
|
||||
white,
|
||||
root: root.to_owned(),
|
||||
atlas,
|
||||
region,
|
||||
cache: RefCell::new(Cache { glyphs: HashMap::new(), cursor: (0, 0), pending: Vec::new(), hex: None }),
|
||||
uniform: false,
|
||||
japanese: false,
|
||||
}
|
||||
}
|
||||
fn load_hex(&self) -> Vec<HexProvider> {
|
||||
let mut all = Vec::new();
|
||||
providers(&self.root, "minecraft:default", 0, &mut all);
|
||||
let mut out = Vec::new();
|
||||
for p in all.iter().filter(|p| p["type"] == "unihex") {
|
||||
if let Some(filter) = p["filter"].as_object() {
|
||||
let pass = filter.iter().all(|(k, v)| match k.as_str() {
|
||||
"jp" => v.as_bool() == Some(self.japanese),
|
||||
"uniform" => v.as_bool() == Some(self.uniform),
|
||||
_ => true,
|
||||
});
|
||||
if !pass {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let Some(file) = p["hex_file"].as_str() else { continue };
|
||||
let path = self.root.join(resource_path(file, "", "").replace("//", "/"));
|
||||
let Ok(zip) = Zip::open(&path) else { continue };
|
||||
let mut provider = HexProvider::default();
|
||||
let names: Vec<String> = zip.names().filter(|n| n.ends_with(".hex")).map(str::to_owned).collect();
|
||||
for name in names {
|
||||
if let Ok(bytes) = zip.read(&name) {
|
||||
parse_hex(&bytes, &mut provider.glyphs);
|
||||
}
|
||||
}
|
||||
for o in p["size_overrides"].as_array().into_iter().flatten() {
|
||||
let from = o["from"].as_str().and_then(|s| s.chars().next()).map_or(0, u32::from);
|
||||
let to = o["to"].as_str().and_then(|s| s.chars().next()).map_or(0, u32::from);
|
||||
let (left, right) = (o["left"].as_u64().unwrap_or(0) as u32, o["right"].as_u64().unwrap_or(15) as u32);
|
||||
for c in from..=to {
|
||||
if let Some(g) = provider.glyphs.get_mut(&c) {
|
||||
g.left = left;
|
||||
g.right = right;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(provider);
|
||||
}
|
||||
out
|
||||
}
|
||||
/// Forget rasterized fallback glyphs (after changing font options).
|
||||
pub fn reset_cache(&self) {
|
||||
let mut cache = self.cache.borrow_mut();
|
||||
cache.glyphs.clear();
|
||||
cache.cursor = (0, 0);
|
||||
cache.hex = None;
|
||||
}
|
||||
/// The glyph for a character (FontSet.getGlyph).
|
||||
pub fn glyph(&self, c: char) -> Glyph {
|
||||
if let Some(a) = self.space.get(&c) {
|
||||
return Glyph { rect: None, left: 0.0, top: 0.0, right: 0.0, bottom: 0.0, advance: *a, offset: 1.0 };
|
||||
}
|
||||
if !self.uniform
|
||||
&& let Some(g) = self.bitmap.get(&c)
|
||||
{
|
||||
return *g;
|
||||
}
|
||||
if let Some(g) = self.cache.borrow().glyphs.get(&c) {
|
||||
return *g;
|
||||
}
|
||||
let mut cache = self.cache.borrow_mut();
|
||||
if cache.hex.is_none() {
|
||||
cache.hex = Some(self.load_hex());
|
||||
}
|
||||
let hex = cache.hex.as_ref().and_then(|providers| providers.iter().find_map(|p| p.glyphs.get(&u32::from(c)).copied()));
|
||||
let glyph = match hex {
|
||||
Some(h) => self.rasterize(&mut cache, h).unwrap_or(self.missing),
|
||||
None => self.missing,
|
||||
};
|
||||
cache.glyphs.insert(c, glyph);
|
||||
glyph
|
||||
}
|
||||
fn rasterize(&self, cache: &mut Cache, h: HexGlyph) -> Option<Glyph> {
|
||||
let width = h.right.saturating_sub(h.left) + 1;
|
||||
let (mut x, mut y) = cache.cursor;
|
||||
if x + width + 1 > self.atlas.0 {
|
||||
x = 0;
|
||||
y += 17;
|
||||
}
|
||||
if y + 16 > self.region.1 {
|
||||
return None;
|
||||
}
|
||||
let mut rgba = Vec::with_capacity((width * 16 * 4) as usize);
|
||||
for row in h.rows {
|
||||
for bit in h.left..=h.right {
|
||||
let set = bit < 32 && (row >> (31 - bit)) & 1 != 0;
|
||||
rgba.extend(if set { [255; 4] } else { [0; 4] });
|
||||
}
|
||||
}
|
||||
let (ax, ay) = (x, self.region.0 + y);
|
||||
cache.pending.push(Patch { x: ax, y: ay, width, height: 16, rgba });
|
||||
cache.cursor = (x + width + 1, y);
|
||||
Some(Glyph {
|
||||
rect: Some(Rect {
|
||||
u0: ax as f32 / self.atlas.0 as f32,
|
||||
v0: ay as f32 / self.atlas.1 as f32,
|
||||
u1: (ax + width) as f32 / self.atlas.0 as f32,
|
||||
v1: (ay + 16) as f32 / self.atlas.1 as f32,
|
||||
w: width,
|
||||
h: 16,
|
||||
}),
|
||||
left: 0.0,
|
||||
top: 0.0,
|
||||
right: width as f32 / 2.0,
|
||||
bottom: 8.0,
|
||||
advance: (width / 2 + 1) as f32,
|
||||
offset: 0.5,
|
||||
})
|
||||
}
|
||||
/// Atlas pixels rasterized since the last call.
|
||||
pub fn take_patches(&self) -> Vec<Patch> {
|
||||
std::mem::take(&mut self.cache.borrow_mut().pending)
|
||||
}
|
||||
pub fn advance(&self, c: char, style: &Style) -> f32 {
|
||||
let g = self.glyph(c);
|
||||
g.advance + if style.is_bold() { g.offset } else { 0.0 }
|
||||
}
|
||||
/// Font.width of plain text (legacy codes are formatting, not glyphs).
|
||||
pub fn width(&self, s: &str) -> f32 {
|
||||
if s.contains('§') {
|
||||
return self.width_text(&Text::legacy(s));
|
||||
}
|
||||
s.chars().map(|c| self.glyph(c).advance).sum::<f32>().ceil()
|
||||
}
|
||||
pub fn width_text(&self, t: &Text) -> f32 {
|
||||
t.chars().map(|(c, s)| self.advance(c, s)).sum::<f32>().ceil()
|
||||
}
|
||||
/// StringSplitter.splitLines: wrap at the last space that fits (or
|
||||
/// mid-word when none does); `\n` always breaks. Styles are kept.
|
||||
pub fn split(&self, t: &Text, max_width: f32) -> Vec<Text> {
|
||||
let chars: Vec<(char, Style)> = t.chars().map(|(c, s)| (c, s.clone())).collect();
|
||||
let mut lines = Vec::new();
|
||||
let mut start = 0;
|
||||
while start < chars.len() {
|
||||
let mut width = 0.0;
|
||||
let mut end = chars.len();
|
||||
let mut next = chars.len();
|
||||
let mut last_space = None;
|
||||
for (i, (c, style)) in chars.iter().enumerate().skip(start) {
|
||||
if *c == '\n' {
|
||||
end = i;
|
||||
next = i + 1;
|
||||
break;
|
||||
}
|
||||
if *c == ' ' {
|
||||
last_space = Some(i);
|
||||
}
|
||||
width += self.advance(*c, style);
|
||||
if width > max_width {
|
||||
match last_space {
|
||||
Some(s) if s > start => {
|
||||
end = s;
|
||||
next = s + 1;
|
||||
}
|
||||
_ => {
|
||||
end = i.max(start + 1);
|
||||
next = end;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
lines.push(t.slice(start, end));
|
||||
start = next;
|
||||
if start == chars.len() && chars.last().is_some_and(|c| c.0 == '\n') {
|
||||
lines.push(Text::empty());
|
||||
}
|
||||
}
|
||||
if lines.is_empty() {
|
||||
lines.push(Text::empty());
|
||||
}
|
||||
lines
|
||||
}
|
||||
/// Characters of `s` that fit in `width` (Font.plainSubstrByWidth).
|
||||
pub fn fit(&self, s: &str, width: f32) -> usize {
|
||||
let mut w = 0.0;
|
||||
for (i, c) in s.chars().enumerate() {
|
||||
w += self.glyph(c).advance;
|
||||
if w > width {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
s.chars().count()
|
||||
}
|
||||
/// Characters of `s` that fit in `width`, measured from the end.
|
||||
pub fn fit_reverse(&self, s: &str, width: f32) -> usize {
|
||||
let mut w = 0.0;
|
||||
for (i, c) in s.chars().rev().enumerate() {
|
||||
w += self.glyph(c).advance;
|
||||
if w > width {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
s.chars().count()
|
||||
}
|
||||
pub fn white(&self) -> Rect {
|
||||
self.white
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn unihex_rows_and_widths() {
|
||||
let mut out = HashMap::new();
|
||||
// 'A' from unifont (8 wide) and a 16-wide glyph with an empty left column.
|
||||
let wide = format!("4E00:{}7FFE{}\n", "0000".repeat(4), "0000".repeat(11));
|
||||
parse_hex(b"0041:0000000018242442427E424242420000\n", &mut out);
|
||||
parse_hex(wide.as_bytes(), &mut out);
|
||||
let a = out[&0x41];
|
||||
assert_eq!((a.left, a.right), (1, 6));
|
||||
assert_eq!(a.rows[4], 0x18 << 24);
|
||||
let yi = out[&0x4E00];
|
||||
assert_eq!((yi.left, yi.right), (1, 14));
|
||||
// Unparseable lines are skipped.
|
||||
parse_hex(b"zz:00\n", &mut out);
|
||||
assert_eq!(out.len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,12 @@ mod growth;
|
||||
mod machines;
|
||||
mod tnt;
|
||||
mod remote;
|
||||
mod chat;
|
||||
mod commands;
|
||||
mod control;
|
||||
mod options;
|
||||
mod packs;
|
||||
mod screens;
|
||||
use horizon_client::{
|
||||
Result,
|
||||
assets::Assets,
|
||||
@@ -187,6 +193,7 @@ enum Screen {
|
||||
Playing,
|
||||
Paused,
|
||||
Options,
|
||||
Chat,
|
||||
Creative,
|
||||
Inventory,
|
||||
Dead,
|
||||
@@ -242,6 +249,11 @@ impl LevelAccess for GameLevel<'_> {
|
||||
}
|
||||
fn day_time(&self) -> i64 {
|
||||
self.world.day_time
|
||||
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)
|
||||
@@ -451,6 +463,7 @@ struct Game<'a> {
|
||||
persist: persist::EntityMemory,
|
||||
/// Connected to a server: the world comes from the network (game/remote.rs).
|
||||
remote: Option<remote::Remote>,
|
||||
ui: chat::UiState,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Dim {
|
||||
@@ -751,6 +764,8 @@ impl Game<'_> {
|
||||
Dim::Nether => LevelDimension::Nether,
|
||||
Dim::End => LevelDimension::End,
|
||||
};
|
||||
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,
|
||||
@@ -765,6 +780,7 @@ impl Game<'_> {
|
||||
behaviours: &self.res.behaviours,
|
||||
items: &self.res.items,
|
||||
registry: self.res.assets.registry,
|
||||
rules,
|
||||
};
|
||||
f(&self.res.behaviours, &mut level, &mut self.block_ticks)
|
||||
}
|
||||
@@ -1391,12 +1407,14 @@ impl Game<'_> {
|
||||
}
|
||||
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;
|
||||
}
|
||||
@@ -1469,7 +1487,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;
|
||||
@@ -1678,7 +1697,7 @@ impl Game<'_> {
|
||||
let mut batch = HudBatch::new(size);
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
if self.screen == Screen::Options {
|
||||
self.settings.draw(&self.res.atlas, &mut batch, self.cursor);
|
||||
self.draw_options(&mut batch);
|
||||
return batch;
|
||||
}
|
||||
if let Some(title) = &self.title {
|
||||
@@ -1801,43 +1820,23 @@ 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;
|
||||
batch.fill(atlas, 0.0, 0.0, w, h, rgba(16, 16, 32, a));
|
||||
}
|
||||
match self.screen {
|
||||
Screen::Paused => {
|
||||
batch.fill(atlas, 0.0, 0.0, w, h, rgba(16, 16, 16, 160));
|
||||
let title = "Game Menu";
|
||||
let tw = HudBatch::text_width(atlas, title);
|
||||
batch.text(atlas, title, (w - tw) / 2.0, 40.0, u32::MAX, true);
|
||||
for (i, label) in ["Back to Game", "Options...", "Save and Quit to Title"].iter().enumerate() {
|
||||
let (bx, by) = (w / 2.0 - 100.0, h / 4.0 + 24.0 + i as f32 * 24.0 + 16.0);
|
||||
let hover = self.cursor.0 >= bx && self.cursor.0 < bx + 200.0 && self.cursor.1 >= by && self.cursor.1 < by + 20.0;
|
||||
let sprite = if hover { "gui/sprites/widget/button_highlighted" } else { "gui/sprites/widget/button" };
|
||||
batch.sprite_scaled(atlas, sprite, bx, by, 200.0, 20.0, u32::MAX);
|
||||
let tw = HudBatch::text_width(atlas, label);
|
||||
batch.text(atlas, label, bx + (200.0 - tw) / 2.0, by + 6.0, u32::MAX, true);
|
||||
}
|
||||
}
|
||||
Screen::Dead => {
|
||||
batch.fill(atlas, 0.0, 0.0, w, h, rgba(80, 0, 0, 120));
|
||||
let title = "You Died!";
|
||||
let tw = HudBatch::text_width(atlas, title);
|
||||
batch.text(atlas, title, (w - tw) / 2.0, 60.0, u32::MAX, true);
|
||||
let (bx, by) = (w / 2.0 - 100.0, h / 4.0 + 72.0);
|
||||
batch.sprite_scaled(atlas, "gui/sprites/widget/button", bx, by, 200.0, 20.0, u32::MAX);
|
||||
let label = "Respawn";
|
||||
let tw = HudBatch::text_width(atlas, label);
|
||||
batch.text(atlas, label, bx + (200.0 - tw) / 2.0, by + 6.0, u32::MAX, true);
|
||||
}
|
||||
Screen::Paused => self.draw_pause_menu(&mut batch),
|
||||
Screen::Dead => self.draw_death_screen(&mut batch),
|
||||
Screen::Inventory => {
|
||||
self.draw_inventory(&mut batch);
|
||||
}
|
||||
Screen::Creative => {
|
||||
self.draw_creative(&mut batch);
|
||||
}
|
||||
Screen::Chat => self.draw_chat_screen(&mut batch),
|
||||
Screen::Playing | Screen::Options => {}
|
||||
}
|
||||
self.remote_hud(&mut batch);
|
||||
@@ -3045,6 +3044,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.
|
||||
@@ -3856,6 +3856,7 @@ impl Game<'_> {
|
||||
self.streaming.radius = self.settings.render_distance;
|
||||
self.audio.master = self.settings.master_volume;
|
||||
horizon_client::hud::GUI_SCALE.store(self.settings.gui_scale, std::sync::atomic::Ordering::Relaxed);
|
||||
self.apply_ui_settings();
|
||||
}
|
||||
/// Whether precipitation at a column is snow (Biome.coldEnoughToSnow:
|
||||
/// base temperature lowered above y 80) or none (no precipitation).
|
||||
@@ -4237,6 +4238,7 @@ impl Game<'_> {
|
||||
level.dimension = self.dim.id().to_owned();
|
||||
level.active_effects = self.potions.effects.list.iter().map(|e| (format!("minecraft:{}", e.id), e.duration, e.amplifier, e.ambient, e.visible)).collect();
|
||||
level.write(&self.world_root)?;
|
||||
self.save_world_state();
|
||||
self.message = Some(("Saved the game".into(), Instant::now()));
|
||||
Ok(())
|
||||
}
|
||||
@@ -4350,10 +4352,7 @@ impl Game<'_> {
|
||||
}
|
||||
match key {
|
||||
KeyCode::Escape => match self.screen {
|
||||
Screen::Options => {
|
||||
self.settings.save(&std::env::current_dir()?.join("options.txt"));
|
||||
self.screen = if self.options_from_title { Screen::Playing } else { Screen::Paused };
|
||||
}
|
||||
Screen::Options => self.options_key(KeyCode::Escape, None)?,
|
||||
Screen::Playing => {
|
||||
self.screen = Screen::Paused;
|
||||
self.capture(false);
|
||||
@@ -4369,7 +4368,13 @@ 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::F11 => self.toggle_fullscreen(),
|
||||
KeyCode::F2 => self.take_screenshot(),
|
||||
KeyCode::KeyE if self.screen == Screen::Creative && self.creative_screen.tab().search => {}
|
||||
KeyCode::KeyE => match self.screen {
|
||||
Screen::Playing => {
|
||||
@@ -4552,8 +4557,8 @@ impl ApplicationHandler for Game<'_> {
|
||||
let b = HudBatch::new([r.config.width, r.config.height]);
|
||||
self.cursor = (position.x as f32 / b.scale, position.y as f32 / b.scale);
|
||||
if self.dragging && self.screen == Screen::Options {
|
||||
self.settings.click(self.cursor.0, self.cursor.1, (b.width, b.height), true);
|
||||
self.apply_settings();
|
||||
let _ = b;
|
||||
self.options_drag()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4562,6 +4567,12 @@ 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::Options && d != 0.0 {
|
||||
self.options_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);
|
||||
@@ -4573,17 +4584,11 @@ impl ApplicationHandler for Game<'_> {
|
||||
self.selected = (self.selected as i32 - d.signum() as i32).rem_euclid(9) as usize;
|
||||
}
|
||||
}
|
||||
WindowEvent::MouseInput { state, button: MouseButton::Left, .. } if self.screen == Screen::Options => {
|
||||
self.dragging = state == ElementState::Pressed;
|
||||
if self.dragging {
|
||||
let size = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]).unwrap_or([1, 1]);
|
||||
let b = HudBatch::new(size);
|
||||
if self.settings.click(self.cursor.0, self.cursor.1, (b.width, b.height), false) {
|
||||
self.settings.save(&std::env::current_dir()?.join("options.txt"));
|
||||
self.screen = if self.options_from_title { Screen::Playing } else { Screen::Paused };
|
||||
self.dragging = false;
|
||||
}
|
||||
self.apply_settings();
|
||||
WindowEvent::MouseInput { state, button, .. } if self.screen == Screen::Options => {
|
||||
if self.options_waiting_for_key() && state == ElementState::Pressed {
|
||||
self.options_bind_mouse(button)?;
|
||||
} else if matches!(button, MouseButton::Left | MouseButton::Right) {
|
||||
self.options_mouse(state == ElementState::Pressed, button == MouseButton::Right)?;
|
||||
}
|
||||
}
|
||||
WindowEvent::MouseInput { state, button: MouseButton::Left, .. }
|
||||
@@ -4594,10 +4599,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
let action = self.title.as_mut().map_or(Action::None, |t| t.click(self.cursor.0, self.cursor.1, (b.width, b.height)));
|
||||
match action {
|
||||
Action::Quit => event_loop.exit(),
|
||||
Action::Options => {
|
||||
self.screen = Screen::Options;
|
||||
self.options_from_title = true;
|
||||
}
|
||||
Action::Options => self.open_options(true),
|
||||
Action::Play { folder } => self.open_world(&folder, None, None, false)?,
|
||||
Action::Create { folder, name, seed, creative } => self.open_world(&folder, Some(&name), seed, creative)?,
|
||||
Action::Connect { address } => self.connect_server(&address, &self.options.player_name.clone())?,
|
||||
@@ -4613,7 +4615,17 @@ impl ApplicationHandler for Game<'_> {
|
||||
self.capture(true);
|
||||
return Ok(());
|
||||
}
|
||||
self.play_mouse(button, pressed)?;
|
||||
match self.settings.keys.translate_mouse(button) {
|
||||
Some(Err(b)) => self.play_mouse(b, pressed)?,
|
||||
Some(Ok(k)) if pressed => {
|
||||
self.keys.insert(k);
|
||||
self.key_pressed(k)?;
|
||||
}
|
||||
Some(Ok(k)) => {
|
||||
self.keys.remove(&k);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
Screen::Inventory if pressed => {
|
||||
self.click_inventory(button == MouseButton::Right);
|
||||
@@ -4621,6 +4633,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
self.container_changed(key);
|
||||
}
|
||||
}
|
||||
Screen::Chat if pressed && button == MouseButton::Left => self.chat_click(),
|
||||
Screen::Creative if pressed => {
|
||||
self.click_creative(button == MouseButton::Right);
|
||||
}
|
||||
@@ -4650,9 +4663,21 @@ impl ApplicationHandler for Game<'_> {
|
||||
self.spawn_player()?;
|
||||
self.capture(true);
|
||||
}
|
||||
Screen::Paused if pressed => self.pause_click()?,
|
||||
Screen::Dead if pressed => self.death_click()?,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
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)) =>
|
||||
@@ -4678,6 +4703,13 @@ impl ApplicationHandler for Game<'_> {
|
||||
self.station_text(event.text.as_deref(), backspace);
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. } if self.remote_chat_open() => self.remote_chat_key(&event),
|
||||
WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::Options => {
|
||||
if event.state == ElementState::Pressed
|
||||
&& let PhysicalKey::Code(key) = event.physical_key
|
||||
{
|
||||
self.options_key(key, event.text.as_deref())?;
|
||||
}
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. } if self.title.is_some() => {
|
||||
if event.state == ElementState::Pressed
|
||||
&& let Some(title) = self.title.as_mut()
|
||||
@@ -4696,6 +4728,17 @@ impl ApplicationHandler for Game<'_> {
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. } => {
|
||||
let PhysicalKey::Code(key) = event.physical_key else { return Ok(()) };
|
||||
// Key binds: act as the default key of the bound mapping.
|
||||
let key = match self.settings.keys.translate(key) {
|
||||
Some(Ok(k)) => k,
|
||||
Some(Err(button)) => {
|
||||
if self.screen == Screen::Playing && !event.repeat {
|
||||
self.play_mouse(button, event.state == ElementState::Pressed)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
None => return Ok(()),
|
||||
};
|
||||
if event.state != ElementState::Pressed {
|
||||
self.keys.remove(&key);
|
||||
return Ok(());
|
||||
@@ -4726,7 +4769,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 {
|
||||
@@ -4777,6 +4826,10 @@ impl ApplicationHandler for Game<'_> {
|
||||
event_loop.exit();
|
||||
return;
|
||||
}
|
||||
if let Some(due) = self.next_frame_due() {
|
||||
event_loop.set_control_flow(ControlFlow::WaitUntil(due));
|
||||
return;
|
||||
}
|
||||
if let Some(w) = &self.window {
|
||||
w.request_redraw();
|
||||
}
|
||||
@@ -4784,8 +4837,11 @@ impl ApplicationHandler for Game<'_> {
|
||||
}
|
||||
}
|
||||
pub fn run() -> Result<()> {
|
||||
let Some(options) = Options::read()? else { return Ok(()) };
|
||||
let Some(mut options) = Options::read()? else { return Ok(()) };
|
||||
let started = Instant::now();
|
||||
let vanilla_root = options.resources.clone();
|
||||
let early_settings = Settings::load(&std::env::current_dir()?.join("options.txt"));
|
||||
options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs);
|
||||
let root = options.resources.clone();
|
||||
let assets = Arc::new(Assets::load(&root).map_err(|e| {
|
||||
format!("{e}\nPrepare resources with: python3 tools/prepare_native_client.py --prepare")
|
||||
@@ -4805,6 +4861,8 @@ pub fn run() -> Result<()> {
|
||||
let light = Arc::new(LightTables::load(&root, &assets.registry, &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], &early_settings.language));
|
||||
eprintln!("load atlas: {:.2}s", started.elapsed().as_secs_f32());
|
||||
let layer_names = assets
|
||||
.sprite_layers
|
||||
@@ -4977,7 +5035,12 @@ pub fn run() -> Result<()> {
|
||||
pending_bench: None,
|
||||
persist: Default::default(),
|
||||
remote: None,
|
||||
ui: Default::default(),
|
||||
};
|
||||
game.ui.vanilla_root = vanilla_root;
|
||||
game.res.atlas.font.uniform = game.settings.force_unicode;
|
||||
game.res.atlas.font.japanese = game.settings.japanese_glyphs;
|
||||
game.ui.chat.options = game.settings.chat_options();
|
||||
if let Some(path) = &game.options.control {
|
||||
let server = horizon_client::control::Server::start(path)
|
||||
.map_err(|e| format!("control socket {}: {e}", path.display()))?;
|
||||
|
||||
@@ -0,0 +1,505 @@
|
||||
//! 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(())
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -23,6 +23,10 @@ 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)",
|
||||
"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",
|
||||
@@ -78,6 +82,27 @@ impl Game<'_> {
|
||||
"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" => {
|
||||
@@ -220,6 +245,49 @@ 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("");
|
||||
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") {
|
||||
@@ -306,6 +374,13 @@ 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.screen == Screen::Options {
|
||||
return self.options_key(key, None);
|
||||
}
|
||||
if self.keys.insert(key) {
|
||||
self.key_pressed(key)?;
|
||||
}
|
||||
@@ -323,6 +398,7 @@ impl Game<'_> {
|
||||
Screen::Inventory => "inventory",
|
||||
Screen::Creative => "creative",
|
||||
Screen::Dead => "dead",
|
||||
Screen::Chat => "chat",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -433,7 +509,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,
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
//! The options screens bound to the game: drawing, input, applying settings
|
||||
//! (video, sound, chat, font, language) and the F11 fullscreen toggle.
|
||||
use super::{Game, Screen};
|
||||
use horizon_client::{
|
||||
Result,
|
||||
hud::HudBatch,
|
||||
lang,
|
||||
options_ui::{Event, Page},
|
||||
};
|
||||
use winit::{event::MouseButton, keyboard::KeyCode, window::Fullscreen};
|
||||
|
||||
impl Game<'_> {
|
||||
fn options_path() -> std::path::PathBuf {
|
||||
std::env::current_dir().unwrap_or_default().join("options.txt")
|
||||
}
|
||||
fn gui_size(&self) -> (f32, f32) {
|
||||
let size = self.renderer.as_ref().map_or([1280, 720], |r| [r.config.width, r.config.height]);
|
||||
let b = HudBatch::new(size);
|
||||
(b.width, b.height)
|
||||
}
|
||||
/// Open the options screens (OptionsScreen) from the title or pause menu.
|
||||
pub(super) fn open_options(&mut self, from_title: bool) {
|
||||
self.screen = Screen::Options;
|
||||
self.options_from_title = from_title;
|
||||
let ui = &mut self.ui.options;
|
||||
ui.open(!from_title && self.title.is_none());
|
||||
let root = self.options.resources.clone();
|
||||
ui.languages = lang::available(&[&root]);
|
||||
self.refresh_pack_lists();
|
||||
}
|
||||
pub(super) fn draw_options(&mut self, batch: &mut HudBatch) {
|
||||
let mut ui = std::mem::take(&mut self.ui.options);
|
||||
ui.draw(&self.settings, batch, &self.res.atlas, self.cursor);
|
||||
self.ui.options = ui;
|
||||
}
|
||||
pub(super) fn options_mouse(&mut self, pressed: bool, right: bool) -> Result<()> {
|
||||
if !pressed {
|
||||
self.ui.options.release();
|
||||
self.dragging = false;
|
||||
return Ok(());
|
||||
}
|
||||
self.dragging = true;
|
||||
let size = self.gui_size();
|
||||
let mut ui = std::mem::take(&mut self.ui.options);
|
||||
let events = ui.click(&mut self.settings, &self.res.atlas, self.cursor.0, self.cursor.1, size, false, right);
|
||||
self.ui.options = ui;
|
||||
self.handle_option_events(events)
|
||||
}
|
||||
pub(super) fn options_drag(&mut self) -> Result<()> {
|
||||
let size = self.gui_size();
|
||||
let mut ui = std::mem::take(&mut self.ui.options);
|
||||
let events = ui.click(&mut self.settings, &self.res.atlas, self.cursor.0, self.cursor.1, size, true, false);
|
||||
self.ui.options = ui;
|
||||
self.handle_option_events(events)
|
||||
}
|
||||
pub(super) fn options_key(&mut self, key: KeyCode, text: Option<&str>) -> Result<()> {
|
||||
let mut ui = std::mem::take(&mut self.ui.options);
|
||||
let events = ui.key(&mut self.settings, key, text);
|
||||
self.ui.options = ui;
|
||||
self.handle_option_events(events)
|
||||
}
|
||||
pub(super) fn options_scroll(&mut self, amount: f32) {
|
||||
self.ui.options.scroll(amount);
|
||||
}
|
||||
/// Mouse buttons pressed while a key is being bound.
|
||||
pub(super) fn options_waiting_for_key(&self) -> bool {
|
||||
self.ui.options.selected_key.is_some() && self.ui.options.page() == Page::KeyBinds
|
||||
}
|
||||
pub(super) fn options_bind_mouse(&mut self, button: MouseButton) -> Result<()> {
|
||||
if let Some(name) = self.ui.options.selected_key.take() {
|
||||
self.settings.keys.set(name, &horizon_client::keybinds::mouse_name(button));
|
||||
self.handle_option_events(vec![Event::Changed])?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn handle_option_events(&mut self, events: Vec<Event>) -> Result<()> {
|
||||
for e in events {
|
||||
match e {
|
||||
Event::Changed => {
|
||||
self.settings.save(&Self::options_path());
|
||||
self.apply_settings();
|
||||
}
|
||||
Event::Close => {
|
||||
self.settings.save(&Self::options_path());
|
||||
self.screen = if self.options_from_title { Screen::Playing } else { Screen::Paused };
|
||||
self.dragging = false;
|
||||
}
|
||||
Event::Language(code) => {
|
||||
self.load_language(&code);
|
||||
}
|
||||
Event::Packs(_) => {
|
||||
self.settings.save(&Self::options_path());
|
||||
self.reload_packs();
|
||||
}
|
||||
Event::OpenPackFolder => {
|
||||
let dir = std::env::current_dir().unwrap_or_default().join("resourcepacks");
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let _ = std::process::Command::new("xdg-open").arg(&dir).spawn();
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// LanguageManager.setSelected + reload: translations, then re-wrap chat.
|
||||
pub(super) fn load_language(&mut self, code: &str) {
|
||||
let root = self.options.resources.clone();
|
||||
lang::set(lang::Language::load(&[&root], code));
|
||||
self.ui.chat.rescale(&self.res.atlas);
|
||||
}
|
||||
/// Settings that Horizon applies beyond render distance, volume and GUI scale.
|
||||
pub(super) fn apply_ui_settings(&mut self) {
|
||||
let s = &self.settings;
|
||||
if let Some(r) = self.renderer.as_mut() {
|
||||
r.gamma = s.gamma;
|
||||
r.set_vsync(s.vsync);
|
||||
}
|
||||
if let Some(w) = &self.window {
|
||||
let want = s.fullscreen;
|
||||
if want != w.fullscreen().is_some() {
|
||||
w.set_fullscreen(want.then_some(Fullscreen::Borderless(None)));
|
||||
}
|
||||
}
|
||||
let mut volumes = s.volumes;
|
||||
volumes[0] = 1.0;
|
||||
horizon_client::settings::set_source_volumes(volumes);
|
||||
let chat = s.chat_options();
|
||||
let rescale = {
|
||||
let o = &self.ui.chat.options;
|
||||
o.width != chat.width || o.scale != chat.scale || o.line_spacing != chat.line_spacing
|
||||
};
|
||||
self.ui.chat.options = chat;
|
||||
if rescale {
|
||||
self.ui.chat.rescale(&self.res.atlas);
|
||||
}
|
||||
let font = &mut self.res.atlas.font;
|
||||
if font.uniform != s.force_unicode || font.japanese != s.japanese_glyphs {
|
||||
font.uniform = s.force_unicode;
|
||||
font.japanese = s.japanese_glyphs;
|
||||
font.reset_cache();
|
||||
self.ui.chat.rescale(&self.res.atlas);
|
||||
}
|
||||
}
|
||||
/// F11 (key.fullscreen): Window.toggleFullScreen, remembered in options.txt.
|
||||
pub(super) fn toggle_fullscreen(&mut self) {
|
||||
self.settings.fullscreen = !self.settings.fullscreen;
|
||||
self.settings.save(&Self::options_path());
|
||||
self.apply_ui_settings();
|
||||
}
|
||||
/// Frame limiter for the Max Framerate option: when the next frame is due.
|
||||
pub(super) fn next_frame_due(&self) -> Option<std::time::Instant> {
|
||||
let fps = self.settings.max_fps;
|
||||
if fps >= 260 || self.options.frames.is_some() {
|
||||
return None;
|
||||
}
|
||||
// Menus without a world run at 60 fps like vanilla's title screen.
|
||||
let fps = if self.title.is_some() { fps.min(60) } else { fps };
|
||||
let due = self.previous + std::time::Duration::from_secs_f64(1.0 / f64::from(fps));
|
||||
(due > std::time::Instant::now()).then_some(due)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
//! Resource pack selection bound to the game: the pack screen lists and
|
||||
//! reloading after a change (atlas, fonts, GUI metadata, languages and item
|
||||
//! icons live; block textures and models from the next start).
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
hud::HudAtlas,
|
||||
lang,
|
||||
options_ui::PackEntry,
|
||||
packs::{self, Pack},
|
||||
text::Text,
|
||||
};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Where overlay roots are built (beside options.txt).
|
||||
pub fn cache_dir() -> PathBuf {
|
||||
std::env::current_dir().unwrap_or_default().join(".horizon-cache/resourcepacks")
|
||||
}
|
||||
pub fn packs_dir() -> PathBuf {
|
||||
std::env::current_dir().unwrap_or_default().join("resourcepacks")
|
||||
}
|
||||
/// The resource root to load from, given the vanilla root and the selection.
|
||||
pub fn startup_root(vanilla: &Path, selected: &[String]) -> PathBuf {
|
||||
let all = packs::discover(vanilla, &packs_dir());
|
||||
let enabled = packs::enabled(&all, selected);
|
||||
packs::resource_root(vanilla, &enabled, &cache_dir())
|
||||
}
|
||||
fn entry(p: &Pack) -> PackEntry {
|
||||
PackEntry { id: p.id.clone(), title: p.title.clone(), description: p.description.clone(), compatible: p.compatible, required: false }
|
||||
}
|
||||
fn vanilla_entry() -> PackEntry {
|
||||
PackEntry {
|
||||
id: "vanilla".into(),
|
||||
title: Text::translate("resourcePack.vanilla.name", &[]),
|
||||
description: Text::translate("resourcePack.vanilla.description", &[]),
|
||||
compatible: true,
|
||||
required: true,
|
||||
}
|
||||
}
|
||||
impl Game<'_> {
|
||||
fn vanilla_root(&self) -> PathBuf {
|
||||
if self.ui.vanilla_root.as_os_str().is_empty() { self.options.resources.clone() } else { self.ui.vanilla_root.clone() }
|
||||
}
|
||||
/// PackSelectionModel: available (unselected) and selected (top first).
|
||||
pub(super) fn refresh_pack_lists(&mut self) {
|
||||
let all = packs::discover(&self.vanilla_root(), &packs_dir());
|
||||
let selected_ids = &self.settings.resource_packs;
|
||||
let mut selected: Vec<PackEntry> = selected_ids
|
||||
.iter()
|
||||
.rev()
|
||||
.filter_map(|id| if id == "vanilla" { Some(vanilla_entry()) } else { all.iter().find(|p| &p.id == id).map(entry) })
|
||||
.collect();
|
||||
if !selected.iter().any(|p| p.id == "vanilla") {
|
||||
selected.push(vanilla_entry());
|
||||
}
|
||||
let available = all.iter().filter(|p| !selected_ids.contains(&p.id)).map(entry).collect();
|
||||
self.ui.options.available = available;
|
||||
self.ui.options.selected = selected;
|
||||
}
|
||||
/// Rebuild the overlay and reload what can change while running.
|
||||
pub(super) fn reload_packs(&mut self) {
|
||||
let vanilla = self.vanilla_root();
|
||||
if self.ui.vanilla_root.as_os_str().is_empty() {
|
||||
self.ui.vanilla_root = vanilla.clone();
|
||||
}
|
||||
let root = startup_root(&vanilla, &self.settings.resource_packs);
|
||||
self.options.resources = root.clone();
|
||||
horizon_client::ui::load_metadata(&root);
|
||||
match HudAtlas::build(&root) {
|
||||
Ok(mut atlas) => {
|
||||
atlas.font.uniform = self.settings.force_unicode;
|
||||
atlas.font.japanese = self.settings.japanese_glyphs;
|
||||
let same_size = atlas.width == self.res.atlas.width && atlas.height == self.res.atlas.height;
|
||||
if same_size {
|
||||
if let Some(texture) = self.renderer.as_ref().and_then(|r| r.hud.atlas_texture.clone())
|
||||
&& let Some(r) = self.renderer.as_ref()
|
||||
{
|
||||
r.queue.write_texture(
|
||||
wgpu::TexelCopyTextureInfo { texture: &texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
|
||||
&atlas.pixels,
|
||||
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(atlas.width * 4), rows_per_image: None },
|
||||
wgpu::Extent3d { width: atlas.width, height: atlas.height, depth_or_array_layers: 1 },
|
||||
);
|
||||
}
|
||||
self.res.atlas = atlas;
|
||||
self.res.icons.clear();
|
||||
self.res.displays.clear();
|
||||
} else {
|
||||
eprintln!("Horizon: resource pack atlas size changed; restart to apply GUI textures");
|
||||
}
|
||||
}
|
||||
Err(e) => eprintln!("Horizon: resource pack reload failed: {e}"),
|
||||
}
|
||||
let code = lang::code();
|
||||
lang::set(lang::Language::load(&[&root], &code));
|
||||
self.ui.chat.rescale(&self.res.atlas);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//! The pause menu (PauseScreen) and death screen (DeathScreen) layouts.
|
||||
use super::{Game, Screen};
|
||||
use horizon_client::{
|
||||
Result,
|
||||
hud::{HudBatch, rgba},
|
||||
text::{self, Text},
|
||||
ui,
|
||||
};
|
||||
|
||||
/// PauseScreen buttons: (x, y, width, label key, action id, active).
|
||||
fn pause_buttons(w: f32, h: f32) -> Vec<(f32, f32, f32, &'static str, u8, bool)> {
|
||||
// GridLayout of two 98px columns (padding 4), aligned at (0.5, 0.25).
|
||||
let (grid_w, grid_h) = (212.0, 166.0);
|
||||
let x0 = ((w - grid_w) * 0.5).floor();
|
||||
let y0 = ((h - grid_h) * 0.25).floor();
|
||||
vec![
|
||||
(x0 + 4.0, y0 + 50.0, 204.0, "menu.returnToGame", 0, true),
|
||||
(x0 + 4.0, y0 + 74.0, 98.0, "gui.advancements", 9, false),
|
||||
(x0 + 110.0, y0 + 74.0, 98.0, "gui.stats", 9, false),
|
||||
(x0 + 4.0, y0 + 122.0, 98.0, "menu.options", 1, true),
|
||||
(x0 + 110.0, y0 + 122.0, 98.0, "options.worldOptions.button", 9, false),
|
||||
(x0 + 4.0, y0 + 146.0, 204.0, "menu.returnToMenu", 2, true),
|
||||
]
|
||||
}
|
||||
/// The icon row: report bugs, feedback, friends, player reporting.
|
||||
fn pause_icons(w: f32, h: f32) -> [(f32, f32, &'static str); 4] {
|
||||
let x0 = ((w - 212.0) * 0.5).floor() + 60.0;
|
||||
let y = ((h - 166.0) * 0.25).floor() + 98.0;
|
||||
[
|
||||
(x0, y, "gui/sprites/pause_menu/bug"),
|
||||
(x0 + 24.0, y, "gui/sprites/pause_menu/social_interactions"),
|
||||
(x0 + 48.0, y, "gui/sprites/icon/friends"),
|
||||
(x0 + 72.0, y, "gui/sprites/pause_menu/player_reporting"),
|
||||
]
|
||||
}
|
||||
fn death_buttons(w: f32, h: f32) -> [(f32, f32, &'static str, u8); 2] {
|
||||
[(w / 2.0 - 100.0, h / 4.0 + 72.0, "deathScreen.respawn", 0), (w / 2.0 - 100.0, h / 4.0 + 96.0, "deathScreen.titleScreen", 1)]
|
||||
}
|
||||
impl Game<'_> {
|
||||
pub(super) fn draw_pause_menu(&mut self, batch: &mut HudBatch) {
|
||||
let atlas = &self.res.atlas;
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
|
||||
let title = Text::translate("menu.game", &[]);
|
||||
let tw = atlas.font.width_text(&title);
|
||||
batch.text_styled(atlas, &title, ((w - tw) / 2.0).floor(), 40.0, u32::MAX, true);
|
||||
for (x, y, bw, key, _, active) in pause_buttons(w, h) {
|
||||
let hover = active && ui::hovered(self.cursor, x, y, bw, 20.0);
|
||||
ui::button(batch, atlas, x, y, bw, 20.0, &Text::translate(key, &[]), active, hover);
|
||||
}
|
||||
for (x, y, sprite) in pause_icons(w, h) {
|
||||
ui::button(batch, atlas, x, y, 20.0, 20.0, &Text::empty(), false, false);
|
||||
batch.sprite_scaled(atlas, sprite, x + 2.0, y + 2.0, 15.0, 15.0, rgba(160, 160, 160, 255));
|
||||
}
|
||||
}
|
||||
pub(super) fn pause_click(&mut self) -> Result<()> {
|
||||
let (w, h) = {
|
||||
let size = self.renderer.as_ref().map_or([1, 1], |r| [r.config.width, r.config.height]);
|
||||
let b = HudBatch::new(size);
|
||||
(b.width, b.height)
|
||||
};
|
||||
let hit = pause_buttons(w, h).into_iter().find(|b| b.5 && ui::hovered(self.cursor, b.0, b.1, b.2, 20.0)).map(|b| b.4);
|
||||
match hit {
|
||||
Some(0) => {
|
||||
self.screen = Screen::Playing;
|
||||
self.capture(true);
|
||||
}
|
||||
Some(1) => self.open_options(false),
|
||||
Some(2) => self.close_world()?,
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// DeathScreen: gradient, the title at double size, the cause and score.
|
||||
pub(super) fn draw_death_screen(&mut self, batch: &mut HudBatch) {
|
||||
let atlas = &self.res.atlas;
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
// fillGradient(0x60500000 -> 0xA0803030).
|
||||
let rows = h.ceil() as i32;
|
||||
for y in 0..rows {
|
||||
let t = y as f32 / h.max(1.0);
|
||||
let lerp = |a: f32, b: f32| (a + (b - a) * t) as u8;
|
||||
batch.fill(atlas, 0.0, y as f32, w, 1.0, rgba(lerp(80.0, 128.0), lerp(0.0, 48.0), lerp(0.0, 48.0), lerp(96.0, 160.0)));
|
||||
}
|
||||
let title = Text::translate("deathScreen.title", &[]);
|
||||
let tw = atlas.font.width_text(&title);
|
||||
ui::text_scaled(batch, atlas, &title, (w / 2.0 - tw).floor(), 60.0, 2.0, u32::MAX);
|
||||
if let Some(cause) = &self.ui.death_text {
|
||||
let cw = atlas.font.width_text(cause);
|
||||
batch.text_styled(atlas, cause, ((w - cw) / 2.0).floor(), 85.0, u32::MAX, true);
|
||||
}
|
||||
let score = Text::translate("deathScreen.score.value", &[Text::colored(self.experience.total.to_string(), text::YELLOW)]);
|
||||
let sw = atlas.font.width_text(&score);
|
||||
batch.text_styled(atlas, &score, ((w - sw) / 2.0).floor(), 100.0, u32::MAX, true);
|
||||
let active = self.ui.died_at.is_none_or(|t| t.elapsed().as_millis() >= 1000);
|
||||
for (x, y, key, _) in death_buttons(w, h) {
|
||||
let hover = active && ui::hovered(self.cursor, x, y, 200.0, 20.0);
|
||||
ui::button(batch, atlas, x, y, 200.0, 20.0, &Text::translate(key, &[]), active, hover);
|
||||
}
|
||||
}
|
||||
pub(super) fn death_click(&mut self) -> Result<()> {
|
||||
if self.ui.died_at.is_some_and(|t| t.elapsed().as_millis() < 1000) {
|
||||
return Ok(());
|
||||
}
|
||||
let size = self.renderer.as_ref().map_or([1, 1], |r| [r.config.width, r.config.height]);
|
||||
let b = HudBatch::new(size);
|
||||
let hit = death_buttons(b.width, b.height).into_iter().find(|d| ui::hovered(self.cursor, d.0, d.1, 200.0, 20.0)).map(|d| d.3);
|
||||
match hit {
|
||||
Some(0) => {
|
||||
self.player = None;
|
||||
self.screen = Screen::Playing;
|
||||
self.ui.death_text = None;
|
||||
self.spawn_player()?;
|
||||
self.capture(true);
|
||||
}
|
||||
Some(1) => self.close_world()?,
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
//! Game rules (26.3 `GameRules`): the registered rules with their category,
|
||||
//! type, default and bounds, a value map, and persistence in the world's
|
||||
//! `data/minecraft/game_rules.dat` saved-data file.
|
||||
use horizon_world::{
|
||||
DATA_VERSION,
|
||||
compression::Compression,
|
||||
nbt::{self, Limits, NamedTag, Tag},
|
||||
};
|
||||
use std::{collections::BTreeMap, fs, path::Path};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Value {
|
||||
Bool(bool),
|
||||
Int(i32),
|
||||
}
|
||||
impl std::fmt::Display for Value {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Value::Bool(b) => write!(f, "{b}"),
|
||||
Value::Int(i) => write!(f, "{i}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub struct Rule {
|
||||
pub name: &'static str,
|
||||
pub category: &'static str,
|
||||
pub default: Value,
|
||||
pub min: i32,
|
||||
pub max: i32,
|
||||
}
|
||||
const fn b(name: &'static str, category: &'static str, default: bool) -> Rule {
|
||||
Rule { name, category, default: Value::Bool(default), min: 0, max: 0 }
|
||||
}
|
||||
const fn i(name: &'static str, category: &'static str, default: i32, min: i32, max: i32) -> Rule {
|
||||
Rule { name, category, default: Value::Int(default), min, max }
|
||||
}
|
||||
/// Every rule available without experimental features, in registration order.
|
||||
pub const RULES: &[Rule] = &[
|
||||
b("advance_time", "updates", true),
|
||||
b("advance_weather", "updates", true),
|
||||
b("allow_entering_nether_using_portals", "misc", true),
|
||||
b("block_drops", "drops", true),
|
||||
b("block_explosion_drop_decay", "drops", true),
|
||||
b("command_blocks_work", "misc", true),
|
||||
b("command_block_output", "chat", true),
|
||||
b("drowning_damage", "player", true),
|
||||
b("elytra_movement_check", "player", true),
|
||||
b("ender_pearls_vanish_on_death", "player", true),
|
||||
b("entity_drops", "drops", true),
|
||||
b("fall_damage", "player", true),
|
||||
b("fire_damage", "player", true),
|
||||
i("fire_spread_radius_around_player", "updates", 128, -1, i32::MAX),
|
||||
b("forgive_dead_players", "mobs", true),
|
||||
b("freeze_damage", "player", true),
|
||||
b("global_sound_events", "misc", true),
|
||||
b("immediate_respawn", "player", false),
|
||||
b("keep_inventory", "player", false),
|
||||
b("lava_source_conversion", "updates", false),
|
||||
b("limited_crafting", "player", false),
|
||||
b("locator_bar", "player", true),
|
||||
b("log_admin_commands", "chat", true),
|
||||
i("max_block_modifications", "misc", 32768, 1, i32::MAX),
|
||||
i("max_command_forks", "misc", 65536, 0, i32::MAX),
|
||||
i("max_command_sequence_length", "misc", 65536, 0, i32::MAX),
|
||||
i("max_entity_cramming", "mobs", 24, 0, i32::MAX),
|
||||
i("max_snow_accumulation_height", "updates", 1, 0, 8),
|
||||
b("mob_drops", "drops", true),
|
||||
b("mob_explosion_drop_decay", "drops", true),
|
||||
b("mob_griefing", "mobs", true),
|
||||
b("natural_health_regeneration", "player", true),
|
||||
b("player_movement_check", "player", true),
|
||||
i("players_nether_portal_creative_delay", "player", 0, 0, i32::MAX),
|
||||
i("players_nether_portal_default_delay", "player", 80, 0, i32::MAX),
|
||||
i("players_sleeping_percentage", "player", 100, 0, i32::MAX),
|
||||
b("projectiles_can_break_blocks", "drops", true),
|
||||
b("pvp", "player", true),
|
||||
b("raids", "mobs", true),
|
||||
i("random_tick_speed", "updates", 3, 0, i32::MAX),
|
||||
b("reduced_debug_info", "misc", false),
|
||||
i("respawn_radius", "player", 10, 0, i32::MAX),
|
||||
b("send_command_feedback", "chat", true),
|
||||
b("show_advancement_messages", "chat", true),
|
||||
b("show_death_messages", "chat", true),
|
||||
b("spawner_blocks_work", "misc", true),
|
||||
b("spawn_mobs", "spawning", true),
|
||||
b("spawn_monsters", "spawning", true),
|
||||
b("spawn_patrols", "spawning", true),
|
||||
b("spawn_phantoms", "spawning", true),
|
||||
b("spawn_wandering_traders", "spawning", true),
|
||||
b("spawn_wardens", "spawning", true),
|
||||
b("spectators_generate_chunks", "player", true),
|
||||
b("spread_vines", "updates", true),
|
||||
b("tnt_explodes", "misc", true),
|
||||
b("tnt_explosion_drop_decay", "drops", false),
|
||||
b("universal_anger", "mobs", false),
|
||||
b("water_source_conversion", "updates", true),
|
||||
];
|
||||
pub fn rule(name: &str) -> Option<&'static Rule> {
|
||||
let name = name.strip_prefix("minecraft:").unwrap_or(name);
|
||||
RULES.iter().find(|r| r.name == name)
|
||||
}
|
||||
|
||||
/// Current values (defaults unless set).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct GameRules {
|
||||
values: BTreeMap<&'static str, Value>,
|
||||
}
|
||||
impl GameRules {
|
||||
pub fn get(&self, name: &str) -> Option<Value> {
|
||||
let r = rule(name)?;
|
||||
Some(self.values.get(r.name).copied().unwrap_or(r.default))
|
||||
}
|
||||
pub fn bool(&self, name: &str) -> bool {
|
||||
matches!(self.get(name), Some(Value::Bool(true)))
|
||||
}
|
||||
pub fn int(&self, name: &str) -> i32 {
|
||||
match self.get(name) {
|
||||
Some(Value::Int(v)) => v,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
/// Set a rule; false if the name or value type is wrong.
|
||||
pub fn set(&mut self, name: &str, value: Value) -> bool {
|
||||
let Some(r) = rule(name) else { return false };
|
||||
let ok = match (r.default, value) {
|
||||
(Value::Bool(_), Value::Bool(_)) => true,
|
||||
(Value::Int(_), Value::Int(v)) => (r.min..=r.max).contains(&v),
|
||||
_ => false,
|
||||
};
|
||||
if ok && value == r.default {
|
||||
self.values.remove(r.name);
|
||||
} else if ok {
|
||||
self.values.insert(r.name, value);
|
||||
}
|
||||
ok
|
||||
}
|
||||
/// GameRuleMap codec: `{data: {"minecraft:<rule>": value...}, DataVersion}`.
|
||||
pub fn to_nbt(&self) -> NamedTag {
|
||||
let data: Vec<(horizon_world::nbt::JavaString, Tag)> = RULES
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let v = self.values.get(r.name).copied().unwrap_or(r.default);
|
||||
let tag = match v {
|
||||
Value::Bool(b) => Tag::Byte(i8::from(b)),
|
||||
Value::Int(i) => Tag::Int(i),
|
||||
};
|
||||
(horizon_world::nbt::JavaString::from(format!("minecraft:{}", r.name).as_str()), tag)
|
||||
})
|
||||
.collect();
|
||||
NamedTag { name: "".into(), tag: Tag::compound([("data", Tag::compound(data)), ("DataVersion", Tag::Int(DATA_VERSION))]) }
|
||||
}
|
||||
pub fn from_nbt(root: &Tag) -> Self {
|
||||
let mut rules = Self::default();
|
||||
let Some(data) = root.get("data") else { return rules };
|
||||
for r in RULES {
|
||||
let key = format!("minecraft:{}", r.name);
|
||||
let value = data.get(&key).or_else(|| data.get(r.name));
|
||||
match (r.default, value) {
|
||||
(Value::Bool(_), Some(Tag::Byte(v))) => {
|
||||
rules.set(r.name, Value::Bool(*v != 0));
|
||||
}
|
||||
(Value::Int(_), Some(Tag::Int(v))) => {
|
||||
rules.set(r.name, Value::Int(*v));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
rules
|
||||
}
|
||||
pub fn load(world: &Path) -> Self {
|
||||
let Ok(bytes) = fs::read(world.join("data/minecraft/game_rules.dat")) else { return Self::default() };
|
||||
let Ok(raw) = Compression::Gzip.decode(&bytes, 16 << 20) else { return Self::default() };
|
||||
match nbt::read_named(&raw, Limits::default()) {
|
||||
Ok((root, _)) => Self::from_nbt(&root.tag),
|
||||
Err(_) => Self::default(),
|
||||
}
|
||||
}
|
||||
pub fn save(&self, world: &Path) -> crate::Result<()> {
|
||||
let dir = world.join("data/minecraft");
|
||||
fs::create_dir_all(&dir)?;
|
||||
let bytes = nbt::write_named(&self.to_nbt(), Limits::default()).map_err(|e| e.to_string())?;
|
||||
fs::write(dir.join("game_rules.dat"), Compression::Gzip.encode(&bytes)?)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn defaults_bounds_and_round_trip() {
|
||||
let mut rules = GameRules::default();
|
||||
assert!(rules.bool("advance_time"));
|
||||
assert_eq!(rules.int("random_tick_speed"), 3);
|
||||
assert!(!rules.set("random_tick_speed", Value::Bool(true)));
|
||||
assert!(!rules.set("max_snow_accumulation_height", Value::Int(9)));
|
||||
assert!(rules.set("keep_inventory", Value::Bool(true)));
|
||||
assert!(rules.set("minecraft:random_tick_speed", Value::Int(10)));
|
||||
let back = GameRules::from_nbt(&rules.to_nbt().tag);
|
||||
assert_eq!(back, rules);
|
||||
assert!(back.bool("keep_inventory"));
|
||||
let dir = std::env::temp_dir().join(format!("horizon-gamerules-{}", std::process::id()));
|
||||
rules.save(&dir).unwrap();
|
||||
assert_eq!(GameRules::load(&dir), rules);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
@@ -110,6 +110,9 @@ pub struct Renderer {
|
||||
pub screenshot: Option<PathBuf>,
|
||||
/// Outcome of the last screenshot: frame size, or the error.
|
||||
pub screenshot_result: Option<std::result::Result<[u32; 2], String>>,
|
||||
/// Brightness option (lightmap gamma), 0..1.
|
||||
pub gamma: f32,
|
||||
present_modes: Vec<wgpu::PresentMode>,
|
||||
}
|
||||
fn mip_chain(pixels: &[u8], size: u32, layers: u32) -> (Vec<u8>, u32) {
|
||||
let levels = size.trailing_zeros() + 1;
|
||||
@@ -206,6 +209,7 @@ impl Renderer {
|
||||
if caps.usages.contains(wgpu::TextureUsages::COPY_SRC) {
|
||||
config.usage |= wgpu::TextureUsages::COPY_SRC;
|
||||
}
|
||||
let present_modes = caps.present_modes.clone();
|
||||
config.present_mode = if caps.present_modes.contains(&wgpu::PresentMode::Mailbox) {
|
||||
wgpu::PresentMode::Mailbox
|
||||
} else {
|
||||
@@ -490,7 +494,8 @@ impl Renderer {
|
||||
atlas_pixels,
|
||||
);
|
||||
let atlas_view = atlas.create_view(&Default::default());
|
||||
let hud = HudRenderer::new(&device, config.format.remove_srgb_suffix(), &atlas_view)?;
|
||||
let mut hud = HudRenderer::new(&device, config.format.remove_srgb_suffix(), &atlas_view)?;
|
||||
hud.atlas_texture = Some(atlas.clone());
|
||||
let entity_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("Horizon entities"),
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("entity.wgsl").into()),
|
||||
@@ -700,6 +705,8 @@ impl Renderer {
|
||||
started: Instant::now(),
|
||||
screenshot: None,
|
||||
screenshot_result: None,
|
||||
gamma: 0.5,
|
||||
present_modes,
|
||||
})
|
||||
}
|
||||
fn quad_indices(device: &wgpu::Device, quads: u32) -> wgpu::Buffer {
|
||||
@@ -733,6 +740,21 @@ impl Renderer {
|
||||
})
|
||||
.create_view(&Default::default())
|
||||
}
|
||||
/// VSync on: tear-free presentation (Mailbox, else Fifo); off: Immediate when available.
|
||||
pub fn set_vsync(&mut self, vsync: bool) {
|
||||
let has = |m| self.present_modes.contains(&m);
|
||||
let mode = match (vsync, has(wgpu::PresentMode::Mailbox), has(wgpu::PresentMode::Immediate)) {
|
||||
(true, true, _) => wgpu::PresentMode::Mailbox,
|
||||
(true, false, _) => wgpu::PresentMode::Fifo,
|
||||
(false, _, true) => wgpu::PresentMode::Immediate,
|
||||
(false, true, false) => wgpu::PresentMode::Mailbox,
|
||||
_ => wgpu::PresentMode::Fifo,
|
||||
};
|
||||
if self.config.present_mode != mode {
|
||||
self.config.present_mode = mode;
|
||||
self.surface.configure(&self.device, &self.config);
|
||||
}
|
||||
}
|
||||
pub fn resize(&mut self, width: u32, height: u32) {
|
||||
self.suspended = width == 0 || height == 0;
|
||||
if self.suspended {
|
||||
@@ -954,7 +976,7 @@ impl Renderer {
|
||||
}
|
||||
};
|
||||
self.animate(frame.ticks);
|
||||
self.update_lightmap(&frame.sky, 0.0, 0.5);
|
||||
self.update_lightmap(&frame.sky, 0.0, self.gamma);
|
||||
let view_proj = self.view_projection(frame);
|
||||
let aspect = self.config.width as f32 / self.config.height.max(1) as f32;
|
||||
let (yaw, pitch) = (frame.yaw.to_radians(), frame.pitch.to_radians());
|
||||
|
||||
@@ -18,19 +18,17 @@ pub struct Rect {
|
||||
pub w: u32,
|
||||
pub h: u32,
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
struct Glyph {
|
||||
rect: Rect,
|
||||
advance: f32,
|
||||
}
|
||||
pub struct HudAtlas {
|
||||
pub pixels: Vec<u8>,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub sprites: HashMap<String, Rect>,
|
||||
glyphs: HashMap<char, Glyph>,
|
||||
/// The default font (bitmap sheets in this atlas, unifont rasterized on demand).
|
||||
pub font: crate::font::Font,
|
||||
white: Rect,
|
||||
}
|
||||
/// Atlas rows reserved for glyphs rasterized at run time.
|
||||
pub const GLYPH_ROWS: u32 = 512;
|
||||
pub fn decode(path: &Path) -> Result<(u32, u32, Vec<u8>)> {
|
||||
let mut decoder = png::Decoder::new(std::io::BufReader::new(fs::File::open(path)?));
|
||||
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
|
||||
@@ -104,7 +102,7 @@ impl HudAtlas {
|
||||
}
|
||||
return Some((name, 256, 256, small));
|
||||
}
|
||||
(w <= 1024 && h <= 512).then_some((name, w, h, pixels))
|
||||
(w <= 1024 && (h <= 512 || name.starts_with("font/"))).then_some((name, w, h, pixels))
|
||||
};
|
||||
let threads = std::thread::available_parallelism().map_or(2, |n| n.get());
|
||||
let chunk = files.len().div_ceil(threads).max(1);
|
||||
@@ -130,7 +128,8 @@ impl HudAtlas {
|
||||
x += w + 1;
|
||||
row = row.max(*h);
|
||||
}
|
||||
let height = (y + row + 1).next_power_of_two();
|
||||
let glyph_region = y + row + 1;
|
||||
let height = (glyph_region + GLYPH_ROWS).next_power_of_two();
|
||||
let mut pixels = vec![0u8; (width * height * 4) as usize];
|
||||
let mut sprites = HashMap::new();
|
||||
for ((name, w, h, data), (px, py)) in images.iter().zip(placements) {
|
||||
@@ -152,91 +151,15 @@ impl HudAtlas {
|
||||
);
|
||||
}
|
||||
let white = sprites["horizon/white"];
|
||||
let mut atlas = Self {
|
||||
let font = crate::font::Font::load(root, &sprites, &pixels, (width, height), (glyph_region, height - glyph_region), white);
|
||||
Ok(Self {
|
||||
pixels,
|
||||
width,
|
||||
height,
|
||||
sprites,
|
||||
glyphs: HashMap::new(),
|
||||
font,
|
||||
white,
|
||||
};
|
||||
atlas.load_font(root)?;
|
||||
Ok(atlas)
|
||||
}
|
||||
fn load_font(&mut self, root: &Path) -> Result<()> {
|
||||
let text = fs::read_to_string(root.join("assets/minecraft/font/include/default.json"))?;
|
||||
let value: serde_json::Value = serde_json::from_str(&text)?;
|
||||
for provider in value["providers"].as_array().into_iter().flatten() {
|
||||
if provider["type"] != "bitmap" {
|
||||
continue;
|
||||
}
|
||||
let file = provider["file"].as_str().unwrap_or("");
|
||||
let name = file
|
||||
.trim_start_matches("minecraft:")
|
||||
.trim_end_matches(".png")
|
||||
.to_owned();
|
||||
let Some(rect) = self.sprites.get(&name).copied() else {
|
||||
continue;
|
||||
};
|
||||
let rows: Vec<Vec<char>> = provider["chars"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|r| r.as_str().map(|s| s.chars().collect()))
|
||||
.collect();
|
||||
if rows.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let columns = rows[0].len() as u32;
|
||||
let cell_w = rect.w / columns;
|
||||
let cell_h = rect.h / rows.len() as u32;
|
||||
let height = provider["height"].as_f64().unwrap_or(8.0) as f32;
|
||||
let scale = height / cell_h as f32;
|
||||
let (ax, ay) = (
|
||||
(rect.u0 * self.width as f32) as u32,
|
||||
(rect.v0 * self.height as f32) as u32,
|
||||
);
|
||||
for (r, row) in rows.iter().enumerate() {
|
||||
for (c, ch) in row.iter().enumerate() {
|
||||
if *ch == '\0' || self.glyphs.contains_key(ch) {
|
||||
continue;
|
||||
}
|
||||
let (cx, cy) = (ax + c as u32 * cell_w, ay + r as u32 * cell_h);
|
||||
// Glyph width: rightmost column containing an opaque pixel.
|
||||
let mut used = 0;
|
||||
for x in (0..cell_w).rev() {
|
||||
if (0..cell_h).any(|y| {
|
||||
self.pixels[(((cy + y) * self.width + cx + x) * 4 + 3) as usize] != 0
|
||||
}) {
|
||||
used = x + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.glyphs.insert(
|
||||
*ch,
|
||||
Glyph {
|
||||
rect: Rect {
|
||||
u0: cx as f32 / self.width as f32,
|
||||
v0: cy as f32 / self.height as f32,
|
||||
u1: (cx + cell_w) as f32 / self.width as f32,
|
||||
v1: (cy + cell_h) as f32 / self.height as f32,
|
||||
w: cell_w,
|
||||
h: cell_h,
|
||||
},
|
||||
advance: (used as f32 * scale + 0.5).floor() + 1.0,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.glyphs.insert(
|
||||
' ',
|
||||
Glyph {
|
||||
rect: self.white,
|
||||
advance: 4.0,
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
#[repr(C)]
|
||||
@@ -254,6 +177,8 @@ pub struct HudBatch {
|
||||
pub scale: f32,
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
/// Glyph pixels to upload into the atlas before drawing.
|
||||
pub patches: Vec<crate::font::Patch>,
|
||||
}
|
||||
pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> u32 {
|
||||
u32::from(a) << 24 | u32::from(b) << 16 | u32::from(g) << 8 | u32::from(r)
|
||||
@@ -272,6 +197,7 @@ impl HudBatch {
|
||||
scale: scale as f32,
|
||||
width: (window[0] as f32 / scale as f32).ceil(),
|
||||
height: (window[1] as f32 / scale as f32).ceil(),
|
||||
patches: Vec::new(),
|
||||
}
|
||||
}
|
||||
pub fn quad(&mut self, p: [[f32; 2]; 4], uv: [[f32; 2]; 4], color: u32) {
|
||||
@@ -318,26 +244,77 @@ impl HudBatch {
|
||||
self.rect_uv(x, y, w, h, r, color);
|
||||
}
|
||||
pub fn text_width(atlas: &HudAtlas, text: &str) -> f32 {
|
||||
text.chars()
|
||||
.map(|c| atlas.glyphs.get(&c).map_or(6.0, |g| g.advance))
|
||||
.sum()
|
||||
atlas.font.width(text)
|
||||
}
|
||||
/// Draw plain text (legacy `§` codes are honoured); returns the advance.
|
||||
pub fn text(&mut self, atlas: &HudAtlas, text: &str, x: f32, y: f32, color: u32, shadow: bool) -> f32 {
|
||||
if shadow {
|
||||
let c = color.to_le_bytes();
|
||||
let dark = rgba(c[0] / 4, c[1] / 4, c[2] / 4, c[3]);
|
||||
self.text(atlas, text, x + 1.0, y + 1.0, dark, false);
|
||||
}
|
||||
let t = if text.contains('§') { crate::text::Text::legacy(text) } else { crate::text::Text::literal(text) };
|
||||
self.text_styled(atlas, &t, x, y, color, shadow)
|
||||
}
|
||||
/// Font.drawInternal: styled glyphs, shadows first, with bold, italic,
|
||||
/// underline and strikethrough. `color` is the default colour and alpha.
|
||||
pub fn text_styled(&mut self, atlas: &HudAtlas, text: &crate::text::Text, x: f32, y: f32, color: u32, shadow: bool) -> f32 {
|
||||
let font = &atlas.font;
|
||||
let alpha = (color >> 24) as u8;
|
||||
let mut glyphs = Vec::new();
|
||||
let mut cursor = x;
|
||||
for ch in text.chars() {
|
||||
let Some(g) = atlas.glyphs.get(&ch).copied() else {
|
||||
cursor += 6.0;
|
||||
continue;
|
||||
};
|
||||
if ch != ' ' {
|
||||
self.rect_uv(cursor, y, 8.0, 8.0, g.rect, color);
|
||||
for (i, (ch, style)) in text.chars().enumerate() {
|
||||
let g = font.glyph(ch);
|
||||
let c = style.color.map_or(color, |rgb| rgba((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8, alpha));
|
||||
let bold = style.is_bold();
|
||||
let advance = g.advance + if bold { g.offset } else { 0.0 };
|
||||
glyphs.push((cursor, g, c, bold, style.is_italic(), style.underlined == Some(true), style.strikethrough == Some(true), i == 0, advance));
|
||||
cursor += advance;
|
||||
}
|
||||
self.patches.extend(font.take_patches());
|
||||
let white = font.white();
|
||||
let passes: &[bool] = if shadow { &[true, false] } else { &[false] };
|
||||
for &is_shadow in passes {
|
||||
for &(gx, g, c, bold, italic, underline, strike, first, advance) in &glyphs {
|
||||
let (dx, col) = if is_shadow {
|
||||
let b = c.to_le_bytes();
|
||||
(g.offset, rgba((f32::from(b[0]) * 0.25) as u8, (f32::from(b[1]) * 0.25) as u8, (f32::from(b[2]) * 0.25) as u8, b[3]))
|
||||
} else {
|
||||
(0.0, c)
|
||||
};
|
||||
let (px, py) = (gx + dx, y + dx);
|
||||
let shear = |v: f32| if italic { 1.0 - 0.25 * v } else { 0.0 };
|
||||
let thick = if bold { 0.1 } else { 0.0 };
|
||||
let draw = |batch: &mut Self, ox: f32| match g.rect {
|
||||
Some(r) => {
|
||||
let (x0, x1, y0, y1) = (px + ox + g.left, px + ox + g.right, py + g.top, py + g.bottom);
|
||||
batch.quad(
|
||||
[
|
||||
[x0 + shear(g.top) - thick, y0 - thick],
|
||||
[x1 + shear(g.top) + thick, y0 - thick],
|
||||
[x1 + shear(g.bottom) + thick, y1 + thick],
|
||||
[x0 + shear(g.bottom) - thick, y1 + thick],
|
||||
],
|
||||
[[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]],
|
||||
col,
|
||||
);
|
||||
}
|
||||
None if g.right > 0.0 => {
|
||||
// SpecialGlyphs.MISSING: a 5x8 outline.
|
||||
let (bx, by) = (px + ox, py);
|
||||
for (fx, fy, fw, fh) in [(0.0, 0.0, 5.0, 1.0), (0.0, 7.0, 5.0, 1.0), (0.0, 1.0, 1.0, 6.0), (4.0, 1.0, 1.0, 6.0)] {
|
||||
batch.rect_uv(bx + fx, by + fy, fw, fh, white, col);
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
};
|
||||
draw(self, 0.0);
|
||||
if bold {
|
||||
draw(self, g.offset);
|
||||
}
|
||||
let x0 = if first { px - 1.0 } else { px };
|
||||
if strike {
|
||||
self.rect_uv(x0, py + 3.5, px + advance - x0, 1.0, white, col);
|
||||
}
|
||||
if underline {
|
||||
self.rect_uv(x0, py + 8.0, px + advance - x0, 1.0, white, col);
|
||||
}
|
||||
}
|
||||
cursor += g.advance;
|
||||
}
|
||||
cursor - x
|
||||
}
|
||||
@@ -348,6 +325,8 @@ struct HudUniform {
|
||||
size: [f32; 4],
|
||||
}
|
||||
pub struct HudRenderer {
|
||||
/// The shared atlas texture, for run-time glyph uploads.
|
||||
pub atlas_texture: Option<wgpu::Texture>,
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
group: wgpu::BindGroup,
|
||||
uniform: wgpu::Buffer,
|
||||
@@ -466,6 +445,7 @@ impl HudRenderer {
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
Ok(Self {
|
||||
atlas_texture: None,
|
||||
pipeline,
|
||||
group,
|
||||
uniform,
|
||||
@@ -482,6 +462,16 @@ impl HudRenderer {
|
||||
batch: &HudBatch,
|
||||
size: [u32; 2],
|
||||
) {
|
||||
if let Some(texture) = &self.atlas_texture {
|
||||
for p in &batch.patches {
|
||||
queue.write_texture(
|
||||
wgpu::TexelCopyTextureInfo { texture, mip_level: 0, origin: wgpu::Origin3d { x: p.x, y: p.y, z: 0 }, aspect: wgpu::TextureAspect::All },
|
||||
&p.rgba,
|
||||
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(p.width * 4), rows_per_image: None },
|
||||
wgpu::Extent3d { width: p.width, height: p.height, depth_or_array_layers: 1 },
|
||||
);
|
||||
}
|
||||
}
|
||||
if batch.vertices.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
//! Key mappings (Options.keyMappings): vanilla names, categories and
|
||||
//! defaults, `key_<name>:key.keyboard.x` persistence, display names, and the
|
||||
//! translation of rebound physical keys back to the default keys the game
|
||||
//! logic listens for.
|
||||
use crate::text::Text;
|
||||
use std::collections::BTreeMap;
|
||||
use winit::{event::MouseButton, keyboard::KeyCode};
|
||||
|
||||
/// (name, default key, category) in Options.keyMappings order.
|
||||
pub const MAPPINGS: &[(&str, &str, &str)] = &[
|
||||
("key.attack", "key.mouse.left", "gameplay"),
|
||||
("key.use", "key.mouse.right", "gameplay"),
|
||||
("key.forward", "key.keyboard.w", "movement"),
|
||||
("key.left", "key.keyboard.a", "movement"),
|
||||
("key.back", "key.keyboard.s", "movement"),
|
||||
("key.right", "key.keyboard.d", "movement"),
|
||||
("key.jump", "key.keyboard.space", "movement"),
|
||||
("key.sneak", "key.keyboard.left.shift", "movement"),
|
||||
("key.sprint", "key.keyboard.left.control", "movement"),
|
||||
("key.drop", "key.keyboard.q", "inventory"),
|
||||
("key.inventory", "key.keyboard.e", "inventory"),
|
||||
("key.chat", "key.keyboard.t", "multiplayer"),
|
||||
("key.playerlist", "key.keyboard.tab", "multiplayer"),
|
||||
("key.pickItem", "key.mouse.middle", "gameplay"),
|
||||
("key.command", "key.keyboard.slash", "multiplayer"),
|
||||
("key.friends", "key.keyboard.o", "multiplayer"),
|
||||
("key.socialInteractions", "key.keyboard.p", "multiplayer"),
|
||||
("key.toggleGui", "key.keyboard.f1", "misc"),
|
||||
("key.toggleSpectatorShaderEffects", "key.keyboard.f4", "misc"),
|
||||
("key.screenshot", "key.keyboard.f2", "misc"),
|
||||
("key.togglePerspective", "key.keyboard.f5", "misc"),
|
||||
("key.smoothCamera", "key.keyboard.unknown", "misc"),
|
||||
("key.fullscreen", "key.keyboard.f11", "misc"),
|
||||
("key.spectatorOutlines", "key.keyboard.unknown", "spectator"),
|
||||
("key.spectatorHotbar", "key.mouse.middle", "spectator"),
|
||||
("key.swapOffhand", "key.keyboard.f", "inventory"),
|
||||
("key.saveToolbarActivator", "key.keyboard.c", "creative"),
|
||||
("key.loadToolbarActivator", "key.keyboard.x", "creative"),
|
||||
("key.advancements", "key.keyboard.l", "misc"),
|
||||
("key.quickActions", "key.keyboard.g", "misc"),
|
||||
("key.debug.overlay", "key.keyboard.f3", "debug"),
|
||||
("key.hotbar.1", "key.keyboard.1", "inventory"),
|
||||
("key.hotbar.2", "key.keyboard.2", "inventory"),
|
||||
("key.hotbar.3", "key.keyboard.3", "inventory"),
|
||||
("key.hotbar.4", "key.keyboard.4", "inventory"),
|
||||
("key.hotbar.5", "key.keyboard.5", "inventory"),
|
||||
("key.hotbar.6", "key.keyboard.6", "inventory"),
|
||||
("key.hotbar.7", "key.keyboard.7", "inventory"),
|
||||
("key.hotbar.8", "key.keyboard.8", "inventory"),
|
||||
("key.hotbar.9", "key.keyboard.9", "inventory"),
|
||||
];
|
||||
/// KeyMapping.Category sort order.
|
||||
pub const CATEGORIES: [&str; 8] = ["movement", "misc", "multiplayer", "gameplay", "inventory", "creative", "spectator", "debug"];
|
||||
|
||||
/// InputConstants key names <-> winit physical keys.
|
||||
const KEYS: &[(&str, KeyCode)] = &[
|
||||
("key.keyboard.a", KeyCode::KeyA),
|
||||
("key.keyboard.b", KeyCode::KeyB),
|
||||
("key.keyboard.c", KeyCode::KeyC),
|
||||
("key.keyboard.d", KeyCode::KeyD),
|
||||
("key.keyboard.e", KeyCode::KeyE),
|
||||
("key.keyboard.f", KeyCode::KeyF),
|
||||
("key.keyboard.g", KeyCode::KeyG),
|
||||
("key.keyboard.h", KeyCode::KeyH),
|
||||
("key.keyboard.i", KeyCode::KeyI),
|
||||
("key.keyboard.j", KeyCode::KeyJ),
|
||||
("key.keyboard.k", KeyCode::KeyK),
|
||||
("key.keyboard.l", KeyCode::KeyL),
|
||||
("key.keyboard.m", KeyCode::KeyM),
|
||||
("key.keyboard.n", KeyCode::KeyN),
|
||||
("key.keyboard.o", KeyCode::KeyO),
|
||||
("key.keyboard.p", KeyCode::KeyP),
|
||||
("key.keyboard.q", KeyCode::KeyQ),
|
||||
("key.keyboard.r", KeyCode::KeyR),
|
||||
("key.keyboard.s", KeyCode::KeyS),
|
||||
("key.keyboard.t", KeyCode::KeyT),
|
||||
("key.keyboard.u", KeyCode::KeyU),
|
||||
("key.keyboard.v", KeyCode::KeyV),
|
||||
("key.keyboard.w", KeyCode::KeyW),
|
||||
("key.keyboard.x", KeyCode::KeyX),
|
||||
("key.keyboard.y", KeyCode::KeyY),
|
||||
("key.keyboard.z", KeyCode::KeyZ),
|
||||
("key.keyboard.1", KeyCode::Digit1),
|
||||
("key.keyboard.2", KeyCode::Digit2),
|
||||
("key.keyboard.3", KeyCode::Digit3),
|
||||
("key.keyboard.4", KeyCode::Digit4),
|
||||
("key.keyboard.5", KeyCode::Digit5),
|
||||
("key.keyboard.6", KeyCode::Digit6),
|
||||
("key.keyboard.7", KeyCode::Digit7),
|
||||
("key.keyboard.8", KeyCode::Digit8),
|
||||
("key.keyboard.9", KeyCode::Digit9),
|
||||
("key.keyboard.0", KeyCode::Digit0),
|
||||
("key.keyboard.enter", KeyCode::Enter),
|
||||
("key.keyboard.escape", KeyCode::Escape),
|
||||
("key.keyboard.backspace", KeyCode::Backspace),
|
||||
("key.keyboard.tab", KeyCode::Tab),
|
||||
("key.keyboard.space", KeyCode::Space),
|
||||
("key.keyboard.minus", KeyCode::Minus),
|
||||
("key.keyboard.equal", KeyCode::Equal),
|
||||
("key.keyboard.left.bracket", KeyCode::BracketLeft),
|
||||
("key.keyboard.right.bracket", KeyCode::BracketRight),
|
||||
("key.keyboard.backslash", KeyCode::Backslash),
|
||||
("key.keyboard.semicolon", KeyCode::Semicolon),
|
||||
("key.keyboard.apostrophe", KeyCode::Quote),
|
||||
("key.keyboard.grave.accent", KeyCode::Backquote),
|
||||
("key.keyboard.comma", KeyCode::Comma),
|
||||
("key.keyboard.period", KeyCode::Period),
|
||||
("key.keyboard.slash", KeyCode::Slash),
|
||||
("key.keyboard.caps.lock", KeyCode::CapsLock),
|
||||
("key.keyboard.f1", KeyCode::F1),
|
||||
("key.keyboard.f2", KeyCode::F2),
|
||||
("key.keyboard.f3", KeyCode::F3),
|
||||
("key.keyboard.f4", KeyCode::F4),
|
||||
("key.keyboard.f5", KeyCode::F5),
|
||||
("key.keyboard.f6", KeyCode::F6),
|
||||
("key.keyboard.f7", KeyCode::F7),
|
||||
("key.keyboard.f8", KeyCode::F8),
|
||||
("key.keyboard.f9", KeyCode::F9),
|
||||
("key.keyboard.f10", KeyCode::F10),
|
||||
("key.keyboard.f11", KeyCode::F11),
|
||||
("key.keyboard.f12", KeyCode::F12),
|
||||
("key.keyboard.print.screen", KeyCode::PrintScreen),
|
||||
("key.keyboard.scroll.lock", KeyCode::ScrollLock),
|
||||
("key.keyboard.pause", KeyCode::Pause),
|
||||
("key.keyboard.insert", KeyCode::Insert),
|
||||
("key.keyboard.home", KeyCode::Home),
|
||||
("key.keyboard.page.up", KeyCode::PageUp),
|
||||
("key.keyboard.delete", KeyCode::Delete),
|
||||
("key.keyboard.end", KeyCode::End),
|
||||
("key.keyboard.page.down", KeyCode::PageDown),
|
||||
("key.keyboard.right", KeyCode::ArrowRight),
|
||||
("key.keyboard.left", KeyCode::ArrowLeft),
|
||||
("key.keyboard.down", KeyCode::ArrowDown),
|
||||
("key.keyboard.up", KeyCode::ArrowUp),
|
||||
("key.keyboard.num.lock", KeyCode::NumLock),
|
||||
("key.keyboard.keypad.divide", KeyCode::NumpadDivide),
|
||||
("key.keyboard.keypad.multiply", KeyCode::NumpadMultiply),
|
||||
("key.keyboard.keypad.subtract", KeyCode::NumpadSubtract),
|
||||
("key.keyboard.keypad.add", KeyCode::NumpadAdd),
|
||||
("key.keyboard.keypad.enter", KeyCode::NumpadEnter),
|
||||
("key.keyboard.keypad.1", KeyCode::Numpad1),
|
||||
("key.keyboard.keypad.2", KeyCode::Numpad2),
|
||||
("key.keyboard.keypad.3", KeyCode::Numpad3),
|
||||
("key.keyboard.keypad.4", KeyCode::Numpad4),
|
||||
("key.keyboard.keypad.5", KeyCode::Numpad5),
|
||||
("key.keyboard.keypad.6", KeyCode::Numpad6),
|
||||
("key.keyboard.keypad.7", KeyCode::Numpad7),
|
||||
("key.keyboard.keypad.8", KeyCode::Numpad8),
|
||||
("key.keyboard.keypad.9", KeyCode::Numpad9),
|
||||
("key.keyboard.keypad.0", KeyCode::Numpad0),
|
||||
("key.keyboard.keypad.period", KeyCode::NumpadDecimal),
|
||||
("key.keyboard.keypad.equal", KeyCode::NumpadEqual),
|
||||
("key.keyboard.menu", KeyCode::ContextMenu),
|
||||
("key.keyboard.left.control", KeyCode::ControlLeft),
|
||||
("key.keyboard.left.shift", KeyCode::ShiftLeft),
|
||||
("key.keyboard.left.alt", KeyCode::AltLeft),
|
||||
("key.keyboard.left.win", KeyCode::SuperLeft),
|
||||
("key.keyboard.right.control", KeyCode::ControlRight),
|
||||
("key.keyboard.right.shift", KeyCode::ShiftRight),
|
||||
("key.keyboard.right.alt", KeyCode::AltRight),
|
||||
("key.keyboard.right.win", KeyCode::SuperRight),
|
||||
];
|
||||
pub fn key_code(name: &str) -> Option<KeyCode> {
|
||||
KEYS.iter().find(|(n, _)| *n == name).map(|(_, k)| *k)
|
||||
}
|
||||
pub fn key_name(code: KeyCode) -> Option<&'static str> {
|
||||
KEYS.iter().find(|(_, k)| *k == code).map(|(n, _)| *n)
|
||||
}
|
||||
pub fn mouse_name(button: MouseButton) -> String {
|
||||
match button {
|
||||
MouseButton::Left => "key.mouse.left".into(),
|
||||
MouseButton::Right => "key.mouse.right".into(),
|
||||
MouseButton::Middle => "key.mouse.middle".into(),
|
||||
MouseButton::Back => "key.mouse.4".into(),
|
||||
MouseButton::Forward => "key.mouse.5".into(),
|
||||
MouseButton::Other(n) => format!("key.mouse.{}", n + 1),
|
||||
}
|
||||
}
|
||||
pub fn mouse_button(name: &str) -> Option<MouseButton> {
|
||||
Some(match name {
|
||||
"key.mouse.left" => MouseButton::Left,
|
||||
"key.mouse.right" => MouseButton::Right,
|
||||
"key.mouse.middle" => MouseButton::Middle,
|
||||
"key.mouse.4" => MouseButton::Back,
|
||||
"key.mouse.5" => MouseButton::Forward,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
/// InputConstants.Key.getDisplayName: one-character keys as the upper-case
|
||||
/// character, others by translation.
|
||||
pub fn display_name(key: &str) -> Text {
|
||||
if let Some(rest) = key.strip_prefix("key.keyboard.")
|
||||
&& rest.chars().count() == 1
|
||||
{
|
||||
let c = rest.to_uppercase();
|
||||
return Text::literal(c);
|
||||
}
|
||||
let symbol = match key {
|
||||
"key.keyboard.minus" => Some("-"),
|
||||
"key.keyboard.equal" => Some("="),
|
||||
"key.keyboard.left.bracket" => Some("["),
|
||||
"key.keyboard.right.bracket" => Some("]"),
|
||||
"key.keyboard.backslash" => Some("\\"),
|
||||
"key.keyboard.semicolon" => Some(";"),
|
||||
"key.keyboard.apostrophe" => Some("'"),
|
||||
"key.keyboard.grave.accent" => Some("`"),
|
||||
"key.keyboard.comma" => Some(","),
|
||||
"key.keyboard.period" => Some("."),
|
||||
"key.keyboard.slash" => Some("/"),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(s) = symbol {
|
||||
return Text::literal(s);
|
||||
}
|
||||
if let Some(n) = key.strip_prefix("key.mouse.")
|
||||
&& n.parse::<u32>().is_ok()
|
||||
&& !crate::lang::has(key)
|
||||
{
|
||||
return Text::translate("key.mouse", &[Text::literal(n)]);
|
||||
}
|
||||
Text::translate(key, &[])
|
||||
}
|
||||
|
||||
/// Current bindings by mapping name.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct KeyBinds {
|
||||
keys: BTreeMap<&'static str, String>,
|
||||
}
|
||||
impl Default for KeyBinds {
|
||||
fn default() -> Self {
|
||||
Self { keys: MAPPINGS.iter().map(|(n, d, _)| (*n, (*d).to_owned())).collect() }
|
||||
}
|
||||
}
|
||||
impl KeyBinds {
|
||||
pub fn get(&self, name: &str) -> &str {
|
||||
self.keys.get(name).map_or("key.keyboard.unknown", String::as_str)
|
||||
}
|
||||
pub fn default_of(name: &str) -> &'static str {
|
||||
MAPPINGS.iter().find(|m| m.0 == name).map_or("key.keyboard.unknown", |m| m.1)
|
||||
}
|
||||
pub fn is_default(&self, name: &str) -> bool {
|
||||
self.get(name) == Self::default_of(name)
|
||||
}
|
||||
pub fn set(&mut self, name: &str, key: &str) {
|
||||
if let Some((n, _, _)) = MAPPINGS.iter().find(|m| m.0 == name) {
|
||||
self.keys.insert(n, key.to_owned());
|
||||
}
|
||||
}
|
||||
/// Load `key_<name>` from options.txt; false for unknown mappings.
|
||||
pub fn set_saved(&mut self, name: &str, key: &str) -> bool {
|
||||
if MAPPINGS.iter().any(|m| m.0 == name) {
|
||||
self.set(name, key);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
pub fn saved(&self) -> Vec<(&'static str, String)> {
|
||||
MAPPINGS.iter().map(|(n, _, _)| (*n, self.get(n).to_owned())).collect()
|
||||
}
|
||||
pub fn reset_all(&mut self) {
|
||||
*self = Self::default();
|
||||
}
|
||||
/// Mappings sharing `name`'s key (KeyMapping.same), for conflict marks.
|
||||
pub fn conflicts(&self, name: &str) -> Vec<&'static str> {
|
||||
let key = self.get(name);
|
||||
if key == "key.keyboard.unknown" {
|
||||
return Vec::new();
|
||||
}
|
||||
MAPPINGS
|
||||
.iter()
|
||||
.filter(|(n, _, _)| *n != name && self.get(n) == key && (!self.is_default(n) || !self.is_default(name)))
|
||||
.map(|(n, _, _)| *n)
|
||||
.collect()
|
||||
}
|
||||
/// The mapping a physical input triggers (first in list order).
|
||||
pub fn mapping_for(&self, key: &str) -> Option<&'static str> {
|
||||
MAPPINGS.iter().map(|m| m.0).find(|n| self.get(n) == key)
|
||||
}
|
||||
/// Translate a physical key into the default key of the mapping it is
|
||||
/// bound to, so game code written against vanilla defaults follows the
|
||||
/// player's bindings. `None` means the key now does nothing; mouse
|
||||
/// mappings bound to keys come back as `Err(button)`.
|
||||
pub fn translate(&self, key: KeyCode) -> Option<Result<KeyCode, MouseButton>> {
|
||||
let Some(name) = key_name(key) else { return Some(Ok(key)) };
|
||||
if let Some(mapping) = self.mapping_for(name) {
|
||||
let default = Self::default_of(mapping);
|
||||
if let Some(code) = key_code(default) {
|
||||
return Some(Ok(code));
|
||||
}
|
||||
return mouse_button(default).map(Err);
|
||||
}
|
||||
// An unbound key whose default meaning was moved elsewhere is inert.
|
||||
if MAPPINGS.iter().any(|(n, d, _)| *d == name && !self.is_default(n)) {
|
||||
return None;
|
||||
}
|
||||
Some(Ok(key))
|
||||
}
|
||||
/// Translate a mouse button the same way (keys bound to mouse buttons).
|
||||
pub fn translate_mouse(&self, button: MouseButton) -> Option<Result<KeyCode, MouseButton>> {
|
||||
let name = mouse_name(button);
|
||||
if let Some(mapping) = self.mapping_for(&name) {
|
||||
let default = Self::default_of(mapping);
|
||||
if let Some(b) = mouse_button(default) {
|
||||
return Some(Err(b));
|
||||
}
|
||||
return key_code(default).map(Ok);
|
||||
}
|
||||
if MAPPINGS.iter().any(|(n, d, _)| *d == name && !self.is_default(n)) {
|
||||
return None;
|
||||
}
|
||||
Some(Err(button))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn rebinding_translates_to_defaults() {
|
||||
let mut k = KeyBinds::default();
|
||||
assert_eq!(k.translate(KeyCode::KeyW), Some(Ok(KeyCode::KeyW)));
|
||||
// Forward on the up arrow, inventory on W.
|
||||
k.set("key.forward", "key.keyboard.up");
|
||||
k.set("key.inventory", "key.keyboard.w");
|
||||
assert_eq!(k.translate(KeyCode::ArrowUp), Some(Ok(KeyCode::KeyW)));
|
||||
assert_eq!(k.translate(KeyCode::KeyW), Some(Ok(KeyCode::KeyE)));
|
||||
// E's default meaning moved and nothing else uses it.
|
||||
assert_eq!(k.translate(KeyCode::KeyE), None);
|
||||
// Attack on a key.
|
||||
k.set("key.attack", "key.keyboard.r");
|
||||
assert_eq!(k.translate(KeyCode::KeyR), Some(Err(MouseButton::Left)));
|
||||
assert_eq!(k.translate_mouse(MouseButton::Left), None);
|
||||
assert_eq!(k.translate(KeyCode::Escape), Some(Ok(KeyCode::Escape)));
|
||||
assert!(k.conflicts("key.forward").is_empty());
|
||||
k.set("key.jump", "key.keyboard.up");
|
||||
assert_eq!(k.conflicts("key.forward"), ["key.jump"]);
|
||||
}
|
||||
#[test]
|
||||
fn display_names() {
|
||||
assert_eq!(display_name("key.keyboard.w").plain(), "W");
|
||||
assert_eq!(display_name("key.keyboard.slash").plain(), "/");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
//! Languages (ClientLanguage / LanguageManager): `lang/<code>.json` from the
|
||||
//! resource root and enabled packs layered over `en_us`, the language list
|
||||
//! from `pack.mcmeta` `language` sections, and a process-wide current
|
||||
//! language used by every screen.
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
sync::{Arc, RwLock},
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct LanguageInfo {
|
||||
pub code: String,
|
||||
pub name: String,
|
||||
pub region: String,
|
||||
pub bidirectional: bool,
|
||||
}
|
||||
impl LanguageInfo {
|
||||
/// LanguageInfo.toComponent: "Name (Region)".
|
||||
pub fn label(&self) -> String {
|
||||
format!("{} ({})", self.name, self.region)
|
||||
}
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct Language {
|
||||
pub code: String,
|
||||
map: HashMap<String, String>,
|
||||
}
|
||||
pub const DEFAULT: &str = "en_us";
|
||||
|
||||
static CURRENT: RwLock<Option<Arc<Language>>> = RwLock::new(None);
|
||||
|
||||
/// A source of resource files: the prepared root plus packs, highest priority last.
|
||||
pub trait ResourceSource {
|
||||
fn read(&self, path: &str) -> Option<Vec<u8>>;
|
||||
}
|
||||
impl ResourceSource for std::path::PathBuf {
|
||||
fn read(&self, path: &str) -> Option<Vec<u8>> {
|
||||
std::fs::read(self.join(path)).ok()
|
||||
}
|
||||
}
|
||||
|
||||
impl Language {
|
||||
pub fn from_map(code: &str, map: HashMap<String, String>) -> Self {
|
||||
Self { code: code.to_owned(), map }
|
||||
}
|
||||
/// ClientLanguage.loadFrom: en_us first, then the selected language, each
|
||||
/// from every source in priority order (later sources override).
|
||||
pub fn load(sources: &[&dyn ResourceSource], code: &str) -> Self {
|
||||
let mut map = HashMap::new();
|
||||
let mut codes = vec![DEFAULT];
|
||||
if code != DEFAULT {
|
||||
codes.push(code);
|
||||
}
|
||||
for c in codes {
|
||||
for source in sources {
|
||||
let Some(bytes) = source.read(&format!("assets/minecraft/lang/{c}.json")) else { continue };
|
||||
if let Ok(entries) = serde_json::from_slice::<HashMap<String, String>>(&bytes) {
|
||||
map.extend(entries);
|
||||
}
|
||||
}
|
||||
}
|
||||
Self { code: code.to_owned(), map }
|
||||
}
|
||||
pub fn get(&self, key: &str) -> Option<&str> {
|
||||
self.map.get(key).map(String::as_str)
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
self.map.len()
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.map.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Languages declared by `pack.mcmeta` files (the vanilla asset root first).
|
||||
pub fn available(sources: &[&dyn ResourceSource]) -> Vec<LanguageInfo> {
|
||||
let mut found: BTreeMap<String, LanguageInfo> = BTreeMap::new();
|
||||
found.insert(
|
||||
DEFAULT.into(),
|
||||
LanguageInfo { code: DEFAULT.into(), name: "English".into(), region: "US".into(), bidirectional: false },
|
||||
);
|
||||
for source in sources {
|
||||
for path in ["assets/pack.mcmeta", "pack.mcmeta"] {
|
||||
let Some(bytes) = source.read(path) else { continue };
|
||||
let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes) else { continue };
|
||||
for (code, info) in value["language"].as_object().into_iter().flatten() {
|
||||
// Only languages whose file exists somewhere are selectable.
|
||||
let file = format!("assets/minecraft/lang/{code}.json");
|
||||
if code != DEFAULT && !sources.iter().any(|s| s.read(&file).is_some()) {
|
||||
continue;
|
||||
}
|
||||
found.insert(
|
||||
code.clone(),
|
||||
LanguageInfo {
|
||||
code: code.clone(),
|
||||
name: info["name"].as_str().unwrap_or(code).to_owned(),
|
||||
region: info["region"].as_str().unwrap_or("").to_owned(),
|
||||
bidirectional: info["bidirectional"].as_bool().unwrap_or(false),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
found.into_values().collect()
|
||||
}
|
||||
|
||||
pub fn set(language: Language) {
|
||||
*CURRENT.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(language));
|
||||
}
|
||||
pub fn current() -> Option<Arc<Language>> {
|
||||
CURRENT.read().unwrap_or_else(|e| e.into_inner()).clone()
|
||||
}
|
||||
pub fn code() -> String {
|
||||
current().map_or_else(|| DEFAULT.to_owned(), |l| l.code.clone())
|
||||
}
|
||||
/// Language.getOrDefault: the translation, or the key itself.
|
||||
pub fn get(key: &str) -> String {
|
||||
current().and_then(|l| l.get(key).map(str::to_owned)).unwrap_or_else(|| key.to_owned())
|
||||
}
|
||||
/// The translation, or `fallback` when the key is missing.
|
||||
pub fn get_or(key: &str, fallback: &str) -> String {
|
||||
current().and_then(|l| l.get(key).map(str::to_owned)).unwrap_or_else(|| fallback.to_owned())
|
||||
}
|
||||
pub fn has(key: &str) -> bool {
|
||||
current().is_some_and(|l| l.get(key).is_some())
|
||||
}
|
||||
/// I18n.get with plain string arguments.
|
||||
pub fn tr(key: &str, args: &[&dyn std::fmt::Display]) -> String {
|
||||
crate::text::Text::tr(key, args).plain()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
struct Mem(HashMap<String, Vec<u8>>);
|
||||
impl ResourceSource for Mem {
|
||||
fn read(&self, path: &str) -> Option<Vec<u8>> {
|
||||
self.0.get(path).cloned()
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn layers_selected_language_over_english() {
|
||||
let base = Mem(HashMap::from([
|
||||
("assets/minecraft/lang/en_us.json".into(), br#"{"a":"Apple","b":"Banana"}"#.to_vec()),
|
||||
("assets/minecraft/lang/fr_fr.json".into(), br#"{"a":"Pomme"}"#.to_vec()),
|
||||
("assets/pack.mcmeta".into(), r#"{"language":{"fr_fr":{"name":"Français","region":"France"},"de_de":{"name":"Deutsch","region":"Deutschland"}}}"#.as_bytes().to_vec()),
|
||||
]));
|
||||
let pack = Mem(HashMap::from([("assets/minecraft/lang/fr_fr.json".into(), br#"{"b":"Banane"}"#.to_vec())]));
|
||||
let sources: [&dyn ResourceSource; 2] = [&base, &pack];
|
||||
let fr = Language::load(&sources, "fr_fr");
|
||||
assert_eq!(fr.get("a"), Some("Pomme"));
|
||||
assert_eq!(fr.get("b"), Some("Banane"));
|
||||
let langs = available(&sources);
|
||||
// de_de has no file, so only English and French are offered.
|
||||
assert_eq!(langs.iter().map(|l| l.code.as_str()).collect::<Vec<_>>(), ["en_us", "fr_fr"]);
|
||||
assert_eq!(langs[1].label(), "Français (France)");
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,9 @@ pub mod biome;
|
||||
pub mod blocks;
|
||||
pub mod brewing;
|
||||
pub mod chunk;
|
||||
pub mod chat;
|
||||
pub mod clock;
|
||||
pub mod command;
|
||||
pub mod containers;
|
||||
pub mod control;
|
||||
pub mod crafting;
|
||||
@@ -19,6 +21,8 @@ pub mod effects;
|
||||
pub mod entities;
|
||||
pub mod entity_nbt;
|
||||
pub mod environment;
|
||||
pub mod font;
|
||||
pub mod gamerules;
|
||||
pub mod gfx;
|
||||
pub mod health;
|
||||
pub mod hud;
|
||||
@@ -26,6 +30,8 @@ pub mod hunger;
|
||||
pub mod input;
|
||||
pub mod item_data;
|
||||
pub mod items;
|
||||
pub mod keybinds;
|
||||
pub mod lang;
|
||||
pub mod landing;
|
||||
pub mod light;
|
||||
pub mod merchant;
|
||||
@@ -35,6 +41,8 @@ pub mod models;
|
||||
pub mod motion;
|
||||
pub mod multiplayer;
|
||||
pub mod net;
|
||||
pub mod options_ui;
|
||||
pub mod packs;
|
||||
pub mod particles;
|
||||
pub mod pose;
|
||||
pub mod save;
|
||||
@@ -45,7 +53,10 @@ pub mod stations;
|
||||
pub mod streaming;
|
||||
pub mod structure_blocks;
|
||||
pub mod testgen;
|
||||
pub mod text;
|
||||
pub mod title;
|
||||
pub mod ui;
|
||||
pub mod vanillagen;
|
||||
pub mod world;
|
||||
pub mod zip;
|
||||
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,284 @@
|
||||
//! Resource packs (PackRepository / FolderRepositorySource): discovery of
|
||||
//! folder and zip packs in `resourcepacks/` plus the built-in Programmer Art
|
||||
//! and High Contrast packs, `pack.mcmeta` metadata and format compatibility,
|
||||
//! and an overlay resource root that layers the enabled packs over the
|
||||
//! vanilla resources (later packs win), so every loader sees one tree.
|
||||
use crate::{text::Text, zip::Zip};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
fs, io,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
/// SharedConstants resource pack format of 26.3 (major, minor).
|
||||
pub const RESOURCE_FORMAT: (i64, i64) = (97, 1);
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Source {
|
||||
Dir(PathBuf),
|
||||
Zip(PathBuf),
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Pack {
|
||||
/// `file/<name>` for user packs, the bare name for built-in ones.
|
||||
pub id: String,
|
||||
pub source: Source,
|
||||
pub title: Text,
|
||||
pub description: Text,
|
||||
pub compatible: bool,
|
||||
}
|
||||
/// A minimal text component from JSON (strings, `text`, `translate`, arrays).
|
||||
pub fn component(v: &serde_json::Value) -> Text {
|
||||
match v {
|
||||
serde_json::Value::String(s) => Text::legacy(s),
|
||||
serde_json::Value::Array(a) => {
|
||||
let mut t = Text::empty();
|
||||
for e in a {
|
||||
t.push(component(e));
|
||||
}
|
||||
t
|
||||
}
|
||||
serde_json::Value::Object(o) => {
|
||||
let mut t = if let Some(s) = o.get("text").and_then(|s| s.as_str()) {
|
||||
Text::legacy(s)
|
||||
} else if let Some(k) = o.get("translate").and_then(|s| s.as_str()) {
|
||||
let args: Vec<Text> = o.get("with").and_then(|w| w.as_array()).map(|a| a.iter().map(component).collect()).unwrap_or_default();
|
||||
Text::translate(k, &args)
|
||||
} else {
|
||||
Text::empty()
|
||||
};
|
||||
if let Some(extra) = o.get("extra") {
|
||||
t.push(component(extra));
|
||||
}
|
||||
if let Some(c) = o.get("color").and_then(|c| c.as_str()) {
|
||||
let rgb = crate::text::named_color(c).or_else(|| c.strip_prefix('#').and_then(|h| u32::from_str_radix(h, 16).ok()));
|
||||
if let Some(rgb) = rgb {
|
||||
t = t.with_color(rgb);
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
serde_json::Value::Number(n) => Text::literal(n.to_string()),
|
||||
serde_json::Value::Bool(b) => Text::literal(b.to_string()),
|
||||
serde_json::Value::Null => Text::empty(),
|
||||
}
|
||||
}
|
||||
fn format_of(v: &serde_json::Value) -> Option<(i64, i64)> {
|
||||
match v {
|
||||
serde_json::Value::Number(n) => Some((n.as_i64()?, 0)),
|
||||
serde_json::Value::Array(a) => Some((a.first()?.as_i64()?, a.get(1).and_then(|m| m.as_i64()).unwrap_or(0))),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// PackCompatibility: inside [min_format, max_format] (or the legacy
|
||||
/// `pack_format`/`supported_formats`).
|
||||
pub fn compatible(meta: &serde_json::Value) -> bool {
|
||||
let pack = &meta["pack"];
|
||||
let current = RESOURCE_FORMAT;
|
||||
if let (Some(min), Some(max)) = (format_of(&pack["min_format"]), format_of(&pack["max_format"])) {
|
||||
return min <= current && current <= (max.0, max.1.max(if max.1 == 0 { i64::MAX } else { max.1 }));
|
||||
}
|
||||
if let Some(range) = pack["supported_formats"].as_array()
|
||||
&& let (Some(lo), Some(hi)) = (range.first().and_then(|v| v.as_i64()), range.get(1).and_then(|v| v.as_i64()))
|
||||
{
|
||||
return lo <= current.0 && current.0 <= hi;
|
||||
}
|
||||
format_of(&pack["pack_format"]).is_some_and(|f| f.0 == current.0)
|
||||
}
|
||||
fn read_meta(source: &Source) -> Option<serde_json::Value> {
|
||||
let bytes = match source {
|
||||
Source::Dir(d) => fs::read(d.join("pack.mcmeta")).ok()?,
|
||||
Source::Zip(z) => Zip::open(z).ok()?.read("pack.mcmeta").ok()?,
|
||||
};
|
||||
serde_json::from_slice(&bytes).ok()
|
||||
}
|
||||
fn pack(id: String, title: Text, source: Source) -> Option<Pack> {
|
||||
let meta = read_meta(&source)?;
|
||||
Some(Pack { id, title, description: component(&meta["pack"]["description"]), compatible: compatible(&meta), source })
|
||||
}
|
||||
/// Built-in and `resourcepacks/` packs (vanilla itself excluded), sorted like
|
||||
/// the pack screen (built-ins first, then by name).
|
||||
pub fn discover(resources: &Path, packs_dir: &Path) -> Vec<Pack> {
|
||||
let mut out = Vec::new();
|
||||
for (id, key) in [("programmer_art", "resourcePack.programmer_art.name"), ("high_contrast", "resourcePack.high_contrast.name")] {
|
||||
let z = resources.join(format!("assets/minecraft/resourcepacks/{id}.zip"));
|
||||
if z.exists()
|
||||
&& let Some(p) = pack(id.into(), Text::translate(key, &[]), Source::Zip(z))
|
||||
{
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
let mut user: Vec<Pack> = fs::read_dir(packs_dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.filter_map(|e| {
|
||||
let path = e.path();
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
let source = if path.is_dir() {
|
||||
Source::Dir(path)
|
||||
} else if name.ends_with(".zip") {
|
||||
Source::Zip(path)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
pack(format!("file/{name}"), Text::literal(name), source)
|
||||
})
|
||||
.collect();
|
||||
user.sort_by(|a, b| a.id.cmp(&b.id));
|
||||
out.extend(user);
|
||||
out
|
||||
}
|
||||
/// Files a pack provides under `assets/`.
|
||||
fn pack_files(source: &Source) -> io::Result<BTreeMap<String, Option<PathBuf>>> {
|
||||
let mut out = BTreeMap::new();
|
||||
match source {
|
||||
Source::Dir(d) => {
|
||||
let mut stack = vec![d.join("assets")];
|
||||
while let Some(dir) = stack.pop() {
|
||||
let Ok(entries) = fs::read_dir(&dir) else { continue };
|
||||
for e in entries.flatten() {
|
||||
let p = e.path();
|
||||
if p.is_dir() {
|
||||
stack.push(p);
|
||||
} else if let Ok(rel) = p.strip_prefix(d) {
|
||||
out.insert(rel.to_string_lossy().replace('\\', "/"), Some(p.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Source::Zip(z) => {
|
||||
for name in Zip::open(z)?.names() {
|
||||
if name.starts_with("assets/") {
|
||||
out.insert(name.to_owned(), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
#[cfg(unix)]
|
||||
fn link(target: &Path, at: &Path) -> io::Result<()> {
|
||||
std::os::unix::fs::symlink(target, at)
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
fn link(target: &Path, at: &Path) -> io::Result<()> {
|
||||
if target.is_dir() { Ok(()) } else { fs::copy(target, at).map(|_| ()) }
|
||||
}
|
||||
/// Build `out` as `vanilla` with the packs' files layered on top (packs in
|
||||
/// load order, last wins). Untouched directories are symlinks into vanilla.
|
||||
pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<()> {
|
||||
if out.exists() {
|
||||
fs::remove_dir_all(out)?;
|
||||
}
|
||||
fs::create_dir_all(out)?;
|
||||
// Final owner of every overridden file.
|
||||
let mut files: BTreeMap<String, (usize, Option<PathBuf>)> = BTreeMap::new();
|
||||
for (i, p) in packs.iter().enumerate() {
|
||||
for (name, path) in pack_files(&p.source)? {
|
||||
files.insert(name, (i, path));
|
||||
}
|
||||
}
|
||||
let touched_dirs: BTreeSet<String> = files
|
||||
.keys()
|
||||
.flat_map(|f| {
|
||||
let parts: Vec<&str> = f.split('/').collect();
|
||||
(1..parts.len()).map(move |n| parts[..n].join("/"))
|
||||
})
|
||||
.collect();
|
||||
let zips: Vec<Option<Zip>> = packs.iter().map(|p| if let Source::Zip(z) = &p.source { Zip::open(z).ok() } else { None }).collect();
|
||||
fn mirror(rel: &str, vanilla: &Path, out: &Path, touched: &BTreeSet<String>, files: &BTreeMap<String, (usize, Option<PathBuf>)>, zips: &[Option<Zip>]) -> io::Result<()> {
|
||||
let src = if rel.is_empty() { vanilla.to_path_buf() } else { vanilla.join(rel) };
|
||||
let dst = if rel.is_empty() { out.to_path_buf() } else { out.join(rel) };
|
||||
fs::create_dir_all(&dst)?;
|
||||
let mut names: BTreeSet<String> = BTreeSet::new();
|
||||
if let Ok(entries) = fs::read_dir(&src) {
|
||||
names.extend(entries.flatten().map(|e| e.file_name().to_string_lossy().into_owned()));
|
||||
}
|
||||
let prefix = if rel.is_empty() { String::new() } else { format!("{rel}/") };
|
||||
for f in files.keys().filter_map(|f| f.strip_prefix(&prefix)) {
|
||||
names.insert(f.split('/').next().unwrap_or("").to_owned());
|
||||
}
|
||||
for name in names {
|
||||
let child = format!("{prefix}{name}");
|
||||
if let Some((owner, path)) = files.get(&child) {
|
||||
let target = out.join(&child);
|
||||
match path {
|
||||
Some(p) => link(p, &target)?,
|
||||
None => {
|
||||
if let Some(Some(z)) = zips.get(*owner) {
|
||||
fs::write(&target, z.read(&child)?)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if touched.contains(&child) {
|
||||
mirror(&child, vanilla, out, touched, files, zips)?;
|
||||
} else {
|
||||
link(&vanilla.join(&child), &out.join(&child))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
mirror("", vanilla, out, &touched_dirs, &files, &zips)
|
||||
}
|
||||
/// The packs to apply for an options.txt `resourcePacks` list (bottom first).
|
||||
pub fn enabled(all: &[Pack], ids: &[String]) -> Vec<Pack> {
|
||||
ids.iter().filter(|id| *id != "vanilla").filter_map(|id| all.iter().find(|p| &p.id == id).cloned()).collect()
|
||||
}
|
||||
/// Resource root for a pack selection: vanilla itself when no pack is on.
|
||||
pub fn resource_root(vanilla: &Path, packs: &[Pack], cache: &Path) -> PathBuf {
|
||||
if packs.is_empty() {
|
||||
return vanilla.to_path_buf();
|
||||
}
|
||||
let key: String = packs.iter().map(|p| p.id.as_str()).collect::<Vec<_>>().join("|");
|
||||
let hash = key.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3));
|
||||
let out = cache.join(format!("{hash:016x}"));
|
||||
match build_overlay(vanilla, packs, &out) {
|
||||
Ok(()) => out,
|
||||
Err(e) => {
|
||||
eprintln!("Horizon: resource packs not applied: {e}");
|
||||
vanilla.to_path_buf()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn compatibility_ranges() {
|
||||
let v = |s: &str| serde_json::from_str::<serde_json::Value>(s).unwrap();
|
||||
assert!(compatible(&v(r#"{"pack":{"min_format":97,"max_format":98}}"#)));
|
||||
assert!(compatible(&v(r#"{"pack":{"min_format":[97,0],"max_format":[97,1]}}"#)));
|
||||
assert!(!compatible(&v(r#"{"pack":{"min_format":[97,2],"max_format":99}}"#)));
|
||||
assert!(compatible(&v(r#"{"pack":{"pack_format":97}}"#)));
|
||||
assert!(!compatible(&v(r#"{"pack":{"pack_format":34}}"#)));
|
||||
assert_eq!(component(&v(r#"["a",{"text":"b","color":"red"}]"#)).plain(), "ab");
|
||||
}
|
||||
#[test]
|
||||
fn overlay_layers_packs_over_vanilla() {
|
||||
let base = std::env::temp_dir().join(format!("horizon-packs-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&base);
|
||||
let vanilla = base.join("vanilla");
|
||||
fs::create_dir_all(vanilla.join("assets/minecraft/textures/block")).unwrap();
|
||||
fs::create_dir_all(vanilla.join("assets/minecraft/lang")).unwrap();
|
||||
fs::write(vanilla.join("assets/minecraft/textures/block/stone.png"), b"vanilla").unwrap();
|
||||
fs::write(vanilla.join("assets/minecraft/textures/block/dirt.png"), b"vanilla dirt").unwrap();
|
||||
fs::write(vanilla.join("assets/minecraft/lang/en_us.json"), b"{}").unwrap();
|
||||
fs::write(vanilla.join("facts.json"), b"[]").unwrap();
|
||||
let pack_dir = base.join("packs/Mine");
|
||||
fs::create_dir_all(pack_dir.join("assets/minecraft/textures/block")).unwrap();
|
||||
fs::write(pack_dir.join("pack.mcmeta"), br#"{"pack":{"description":"mine","pack_format":97}}"#).unwrap();
|
||||
fs::write(pack_dir.join("assets/minecraft/textures/block/stone.png"), b"pack").unwrap();
|
||||
let packs = discover(&vanilla, &base.join("packs"));
|
||||
assert_eq!(packs.len(), 1);
|
||||
assert_eq!(packs[0].id, "file/Mine");
|
||||
let out = base.join("overlay");
|
||||
build_overlay(&vanilla, &packs, &out).unwrap();
|
||||
assert_eq!(fs::read(out.join("assets/minecraft/textures/block/stone.png")).unwrap(), b"pack");
|
||||
assert_eq!(fs::read(out.join("assets/minecraft/textures/block/dirt.png")).unwrap(), b"vanilla dirt");
|
||||
assert_eq!(fs::read(out.join("assets/minecraft/lang/en_us.json")).unwrap(), b"{}");
|
||||
assert_eq!(fs::read(out.join("facts.json")).unwrap(), b"[]");
|
||||
let _ = fs::remove_dir_all(base);
|
||||
}
|
||||
}
|
||||
@@ -1,128 +1,410 @@
|
||||
//! Player settings persisted in `options.txt` with vanilla's keys, and the
|
||||
//! options screen (sliders and toggles in OptionsScreen's two-column layout).
|
||||
use crate::hud::{HudAtlas, HudBatch, rgba};
|
||||
use std::{fs, path::Path};
|
||||
//! Player settings persisted in `options.txt` with vanilla's keys and value
|
||||
//! encodings (Options.processOptions); lines Horizon does not know are kept.
|
||||
//! The option screens live in `options_ui`.
|
||||
use crate::keybinds::KeyBinds;
|
||||
use std::{collections::BTreeMap, fs, path::Path};
|
||||
|
||||
/// SoundSource names in vanilla order.
|
||||
pub const SOUND_SOURCES: [&str; 11] = ["master", "music", "record", "weather", "block", "hostile", "neutral", "player", "ambient", "voice", "ui"];
|
||||
|
||||
/// Per-source volumes for the mixer (soundCategory_* except master).
|
||||
static SOURCE_VOLUMES: std::sync::RwLock<[f32; 11]> = std::sync::RwLock::new([1.0; 11]);
|
||||
pub fn set_source_volumes(volumes: [f32; 11]) {
|
||||
*SOURCE_VOLUMES.write().unwrap_or_else(|e| e.into_inner()) = volumes;
|
||||
}
|
||||
/// The SoundSource an event plays on. Vanilla callers pick the source; this
|
||||
/// follows their conventions by event family.
|
||||
pub fn sound_source(event: &str) -> usize {
|
||||
let e = event.trim_start_matches("minecraft:");
|
||||
let index = |name: &str| SOUND_SOURCES.iter().position(|n| *n == name).unwrap_or(0);
|
||||
const HOSTILE: [&str; 24] = [
|
||||
"zombie", "skeleton", "creeper", "spider", "cave_spider", "enderman", "witch", "slime", "magma_cube", "blaze", "ghast", "drowned", "husk", "stray",
|
||||
"phantom", "pillager", "vindicator", "evoker", "ravager", "guardian", "elder_guardian", "silverfish", "zombified_piglin", "wither_skeleton",
|
||||
];
|
||||
if e.starts_with("music_disc.") {
|
||||
index("record")
|
||||
} else if e.starts_with("music.") {
|
||||
index("music")
|
||||
} else if e.starts_with("weather.") || e.starts_with("entity.lightning_bolt") {
|
||||
index("weather")
|
||||
} else if e.starts_with("block.") {
|
||||
index("block")
|
||||
} else if e.starts_with("ambient.") {
|
||||
index("ambient")
|
||||
} else if e.starts_with("ui.") {
|
||||
index("ui")
|
||||
} else if e.starts_with("entity.player.") || e.starts_with("item.") || e.starts_with("entity.item.") || e.starts_with("entity.experience_orb") || e.starts_with("entity.arrow") {
|
||||
index("player")
|
||||
} else if let Some(rest) = e.strip_prefix("entity.") {
|
||||
let mob = rest.split('.').next().unwrap_or("");
|
||||
if HOSTILE.contains(&mob) { index("hostile") } else { index("neutral") }
|
||||
} else {
|
||||
index("master")
|
||||
}
|
||||
}
|
||||
/// Volume multiplier of an event's source (master applied separately).
|
||||
pub fn event_volume(event: &str) -> f32 {
|
||||
let i = sound_source(event);
|
||||
if i == 0 { 1.0 } else { SOURCE_VOLUMES.read().unwrap_or_else(|e| e.into_inner())[i] }
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Settings {
|
||||
/// Degrees, 30..=110 (vanilla stores the slider value).
|
||||
/// Degrees, 30..=110 (options.txt stores (fov - 70) / 40).
|
||||
pub fov: f32,
|
||||
/// Chunks, 2..=32.
|
||||
pub render_distance: i32,
|
||||
/// Chunks, 5..=32.
|
||||
pub simulation_distance: i32,
|
||||
/// 0..1, vanilla default 0.5.
|
||||
pub sensitivity: f32,
|
||||
/// 0..1.
|
||||
/// 0..1 (soundCategory_master).
|
||||
pub master_volume: f32,
|
||||
/// Volumes of every other sound source, indexed like SOUND_SOURCES.
|
||||
pub volumes: [f32; 11],
|
||||
/// 0 = auto.
|
||||
pub gui_scale: u32,
|
||||
pub view_bobbing: bool,
|
||||
/// Brightness 0..1 (gamma).
|
||||
pub gamma: f32,
|
||||
/// 10..=260 (260 = unlimited).
|
||||
pub max_fps: u32,
|
||||
pub vsync: bool,
|
||||
pub fullscreen: bool,
|
||||
/// Smooth lighting (ao).
|
||||
pub smooth_lighting: bool,
|
||||
/// "false", "fast" or "true" (renderClouds).
|
||||
pub clouds: String,
|
||||
pub cloud_range: i32,
|
||||
/// 0 all, 1 decreased, 2 minimal.
|
||||
pub particles: u8,
|
||||
pub entity_distance: f32,
|
||||
pub entity_shadows: bool,
|
||||
pub biome_blend: i32,
|
||||
/// "fast", "fancy", "fabulous" or "custom".
|
||||
pub graphics_preset: String,
|
||||
pub mipmap_levels: i32,
|
||||
pub weather_radius: i32,
|
||||
pub chunk_fade: f32,
|
||||
pub vignette: bool,
|
||||
pub autosave_indicator: bool,
|
||||
pub cutout_leaves: bool,
|
||||
pub improved_transparency: bool,
|
||||
/// 0 off, 1 crosshair, 2 hotbar.
|
||||
pub attack_indicator: u8,
|
||||
pub inactivity_fps_limit: String,
|
||||
pub prioritize_chunk_updates: u8,
|
||||
pub menu_blur: i32,
|
||||
pub invert_y: bool,
|
||||
pub mouse_wheel_sensitivity: f32,
|
||||
pub discrete_scroll: bool,
|
||||
pub toggle_crouch: bool,
|
||||
pub toggle_sprint: bool,
|
||||
pub auto_jump: bool,
|
||||
pub language: String,
|
||||
pub force_unicode: bool,
|
||||
pub japanese_glyphs: bool,
|
||||
pub chat_visibility: u8,
|
||||
pub chat_colors: bool,
|
||||
pub chat_links: bool,
|
||||
pub chat_opacity: f32,
|
||||
pub text_background_opacity: f32,
|
||||
pub chat_scale: f32,
|
||||
pub chat_width: f32,
|
||||
pub chat_height_focused: f32,
|
||||
pub chat_height_unfocused: f32,
|
||||
pub chat_line_spacing: f32,
|
||||
pub auto_suggestions: bool,
|
||||
pub reduced_debug_info: bool,
|
||||
pub high_contrast: bool,
|
||||
pub main_hand_left: bool,
|
||||
/// Enabled resource packs, bottom first (resourcePacks).
|
||||
pub resource_packs: Vec<String>,
|
||||
pub keys: KeyBinds,
|
||||
/// Lines Horizon does not interpret, kept verbatim.
|
||||
pub extra: BTreeMap<String, String>,
|
||||
}
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Self { fov: 70.0, render_distance: 12, sensitivity: 0.5, master_volume: 1.0, gui_scale: 0, view_bobbing: true }
|
||||
Self {
|
||||
fov: 70.0,
|
||||
render_distance: 12,
|
||||
simulation_distance: 12,
|
||||
sensitivity: 0.5,
|
||||
master_volume: 1.0,
|
||||
volumes: [1.0; 11],
|
||||
gui_scale: 0,
|
||||
view_bobbing: true,
|
||||
gamma: 0.5,
|
||||
// Vanilla defaults to 120; Horizon runs unlimited unless capped.
|
||||
max_fps: 260,
|
||||
vsync: true,
|
||||
fullscreen: false,
|
||||
smooth_lighting: true,
|
||||
clouds: "true".into(),
|
||||
cloud_range: 128,
|
||||
particles: 0,
|
||||
entity_distance: 1.0,
|
||||
entity_shadows: true,
|
||||
biome_blend: 2,
|
||||
graphics_preset: "fancy".into(),
|
||||
mipmap_levels: 4,
|
||||
weather_radius: 10,
|
||||
chunk_fade: 0.75,
|
||||
vignette: true,
|
||||
autosave_indicator: true,
|
||||
cutout_leaves: true,
|
||||
improved_transparency: false,
|
||||
attack_indicator: 1,
|
||||
inactivity_fps_limit: "afk".into(),
|
||||
prioritize_chunk_updates: 0,
|
||||
menu_blur: 5,
|
||||
invert_y: false,
|
||||
mouse_wheel_sensitivity: 1.0,
|
||||
discrete_scroll: false,
|
||||
toggle_crouch: false,
|
||||
toggle_sprint: false,
|
||||
auto_jump: false,
|
||||
language: "en_us".into(),
|
||||
force_unicode: false,
|
||||
japanese_glyphs: false,
|
||||
chat_visibility: 0,
|
||||
chat_colors: true,
|
||||
chat_links: true,
|
||||
chat_opacity: 1.0,
|
||||
text_background_opacity: 0.5,
|
||||
chat_scale: 1.0,
|
||||
chat_width: 1.0,
|
||||
chat_height_focused: 1.0,
|
||||
chat_height_unfocused: 70.0 / 160.0,
|
||||
chat_line_spacing: 0.0,
|
||||
auto_suggestions: true,
|
||||
reduced_debug_info: false,
|
||||
high_contrast: false,
|
||||
main_hand_left: false,
|
||||
resource_packs: vec!["vanilla".into()],
|
||||
keys: KeyBinds::default(),
|
||||
extra: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn unquote(v: &str) -> &str {
|
||||
v.strip_prefix('"').and_then(|v| v.strip_suffix('"')).unwrap_or(v)
|
||||
}
|
||||
fn parse_list(v: &str) -> Vec<String> {
|
||||
serde_json::from_str::<Vec<String>>(v).unwrap_or_default()
|
||||
}
|
||||
impl Settings {
|
||||
pub fn load(path: &Path) -> Self {
|
||||
let Ok(text) = fs::read_to_string(path) else { return Self::default() };
|
||||
Self::parse(&text)
|
||||
}
|
||||
pub fn parse(text: &str) -> Self {
|
||||
let mut s = Self::default();
|
||||
let Ok(text) = fs::read_to_string(path) else { return s };
|
||||
for line in text.lines() {
|
||||
let Some((k, v)) = line.split_once(':') else { continue };
|
||||
let f = |d: f32| v.parse::<f32>().unwrap_or(d);
|
||||
let b = |d: bool| match v {
|
||||
"true" => true,
|
||||
"false" => false,
|
||||
_ => d,
|
||||
};
|
||||
let i = |d: i32| v.parse::<i32>().unwrap_or(d);
|
||||
match k {
|
||||
// Options.fov is stored as (fov - 70) / 40.
|
||||
"fov" => s.fov = v.parse::<f32>().map_or(70.0, |f| (70.0 + f * 40.0).clamp(30.0, 110.0)),
|
||||
"renderDistance" => s.render_distance = v.parse().unwrap_or(12).clamp(2, 32),
|
||||
"mouseSensitivity" => s.sensitivity = v.parse().unwrap_or(0.5f32).clamp(0.0, 1.0),
|
||||
"soundCategory_master" => s.master_volume = v.parse().unwrap_or(1.0f32).clamp(0.0, 1.0),
|
||||
"version" => {}
|
||||
"fov" => s.fov = v.parse::<f32>().map_or(70.0, |f| (f * 40.0 + 70.0).round().clamp(30.0, 110.0)),
|
||||
"renderDistance" => s.render_distance = i(12).clamp(2, 32),
|
||||
"simulationDistance" => s.simulation_distance = i(12).clamp(5, 32),
|
||||
"mouseSensitivity" => s.sensitivity = f(0.5).clamp(0.0, 1.0),
|
||||
"guiScale" => s.gui_scale = v.parse().unwrap_or(0),
|
||||
"bobView" => s.view_bobbing = v == "true",
|
||||
_ => {}
|
||||
"bobView" => s.view_bobbing = b(true),
|
||||
"gamma" => s.gamma = f(0.5).clamp(0.0, 1.0),
|
||||
"maxFps" => s.max_fps = v.parse::<u32>().unwrap_or(260).clamp(10, 260),
|
||||
"enableVsync" => s.vsync = b(true),
|
||||
"fullscreen" => s.fullscreen = b(false),
|
||||
"ao" => s.smooth_lighting = b(true),
|
||||
"renderClouds" => s.clouds = unquote(v).to_owned(),
|
||||
"cloudRange" => s.cloud_range = i(128).clamp(2, 128),
|
||||
"particles" => s.particles = v.parse::<u8>().unwrap_or(0).min(2),
|
||||
"entityDistanceScaling" => s.entity_distance = f(1.0).clamp(0.5, 5.0),
|
||||
"entityShadows" => s.entity_shadows = b(true),
|
||||
"biomeBlendRadius" => s.biome_blend = i(2).clamp(0, 7),
|
||||
"graphicsPreset" => s.graphics_preset = unquote(v).to_owned(),
|
||||
"mipmapLevels" => s.mipmap_levels = i(4).clamp(0, 4),
|
||||
"weatherRadius" => s.weather_radius = i(10).clamp(3, 10),
|
||||
"chunkSectionFadeInTime" => s.chunk_fade = f(0.75).clamp(0.0, 2.0),
|
||||
"vignette" => s.vignette = b(true),
|
||||
"showAutosaveIndicator" => s.autosave_indicator = b(true),
|
||||
"cutoutLeaves" => s.cutout_leaves = b(true),
|
||||
"improvedTransparency" => s.improved_transparency = b(false),
|
||||
"attackIndicator" => s.attack_indicator = v.parse::<u8>().unwrap_or(1).min(2),
|
||||
"inactivityFpsLimit" => s.inactivity_fps_limit = unquote(v).to_owned(),
|
||||
"prioritizeChunkUpdates" => s.prioritize_chunk_updates = v.parse::<u8>().unwrap_or(0).min(2),
|
||||
"menuBackgroundBlurriness" => s.menu_blur = i(5).clamp(0, 10),
|
||||
"invertYMouse" => s.invert_y = b(false),
|
||||
"mouseWheelSensitivity" => s.mouse_wheel_sensitivity = f(1.0).clamp(0.01, 10.0),
|
||||
"discrete_mouse_scroll" => s.discrete_scroll = b(false),
|
||||
"toggleCrouch" => s.toggle_crouch = b(false),
|
||||
"toggleSprint" => s.toggle_sprint = b(false),
|
||||
"autoJump" => s.auto_jump = b(false),
|
||||
"lang" => s.language = v.to_owned(),
|
||||
"forceUnicodeFont" => s.force_unicode = b(false),
|
||||
"japaneseGlyphVariants" => s.japanese_glyphs = b(false),
|
||||
"chatVisibility" => s.chat_visibility = v.parse::<u8>().unwrap_or(0).min(2),
|
||||
"chatColors" => s.chat_colors = b(true),
|
||||
"chatLinks" => s.chat_links = b(true),
|
||||
"chatOpacity" => s.chat_opacity = f(1.0).clamp(0.0, 1.0),
|
||||
"textBackgroundOpacity" => s.text_background_opacity = f(0.5).clamp(0.0, 1.0),
|
||||
"chatScale" => s.chat_scale = f(1.0).clamp(0.0, 1.0),
|
||||
"chatWidth" => s.chat_width = f(1.0).clamp(0.0, 1.0),
|
||||
"chatHeightFocused" => s.chat_height_focused = f(1.0).clamp(0.0, 1.0),
|
||||
"chatHeightUnfocused" => s.chat_height_unfocused = f(0.4375).clamp(0.0, 1.0),
|
||||
"chatLineSpacing" => s.chat_line_spacing = f(0.0).clamp(0.0, 1.0),
|
||||
"autoSuggestions" => s.auto_suggestions = b(true),
|
||||
"reducedDebugInfo" => s.reduced_debug_info = b(false),
|
||||
"highContrast" => s.high_contrast = b(false),
|
||||
"mainHand" => s.main_hand_left = unquote(v) == "left",
|
||||
"resourcePacks" => s.resource_packs = parse_list(v),
|
||||
_ if k.starts_with("key_") => {
|
||||
if !s.keys.set_saved(&k[4..], v) {
|
||||
s.extra.insert(k.to_owned(), v.to_owned());
|
||||
}
|
||||
}
|
||||
_ if k.starts_with("soundCategory_") => {
|
||||
let name = &k["soundCategory_".len()..];
|
||||
match SOUND_SOURCES.iter().position(|n| *n == name) {
|
||||
Some(0) => s.master_volume = f(1.0).clamp(0.0, 1.0),
|
||||
Some(i) => s.volumes[i] = f(1.0).clamp(0.0, 1.0),
|
||||
None => {
|
||||
s.extra.insert(k.to_owned(), v.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
s.extra.insert(k.to_owned(), v.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
/// The `options.txt` text (Options.save: `version` first, then key:value).
|
||||
pub fn serialize(&self) -> String {
|
||||
let mut lines: Vec<(String, String)> = vec![
|
||||
("ao".into(), self.smooth_lighting.to_string()),
|
||||
("biomeBlendRadius".into(), self.biome_blend.to_string()),
|
||||
("chunkSectionFadeInTime".into(), self.chunk_fade.to_string()),
|
||||
("cutoutLeaves".into(), self.cutout_leaves.to_string()),
|
||||
("enableVsync".into(), self.vsync.to_string()),
|
||||
("entityDistanceScaling".into(), self.entity_distance.to_string()),
|
||||
("entityShadows".into(), self.entity_shadows.to_string()),
|
||||
("forceUnicodeFont".into(), self.force_unicode.to_string()),
|
||||
("japaneseGlyphVariants".into(), self.japanese_glyphs.to_string()),
|
||||
("fov".into(), ((self.fov - 70.0) / 40.0).to_string()),
|
||||
("graphicsPreset".into(), format!("\"{}\"", self.graphics_preset)),
|
||||
("prioritizeChunkUpdates".into(), self.prioritize_chunk_updates.to_string()),
|
||||
("fullscreen".into(), self.fullscreen.to_string()),
|
||||
("gamma".into(), self.gamma.to_string()),
|
||||
("guiScale".into(), self.gui_scale.to_string()),
|
||||
("maxFps".into(), self.max_fps.to_string()),
|
||||
("improvedTransparency".into(), self.improved_transparency.to_string()),
|
||||
("inactivityFpsLimit".into(), format!("\"{}\"", self.inactivity_fps_limit)),
|
||||
("mipmapLevels".into(), self.mipmap_levels.to_string()),
|
||||
("particles".into(), self.particles.to_string()),
|
||||
("reducedDebugInfo".into(), self.reduced_debug_info.to_string()),
|
||||
("renderClouds".into(), format!("\"{}\"", self.clouds)),
|
||||
("cloudRange".into(), self.cloud_range.to_string()),
|
||||
("renderDistance".into(), self.render_distance.to_string()),
|
||||
("simulationDistance".into(), self.simulation_distance.to_string()),
|
||||
("vignette".into(), self.vignette.to_string()),
|
||||
("weatherRadius".into(), self.weather_radius.to_string()),
|
||||
("autoJump".into(), self.auto_jump.to_string()),
|
||||
("autoSuggestions".into(), self.auto_suggestions.to_string()),
|
||||
("chatColors".into(), self.chat_colors.to_string()),
|
||||
("chatLinks".into(), self.chat_links.to_string()),
|
||||
("discrete_mouse_scroll".into(), self.discrete_scroll.to_string()),
|
||||
("invertYMouse".into(), self.invert_y.to_string()),
|
||||
("bobView".into(), self.view_bobbing.to_string()),
|
||||
("toggleCrouch".into(), self.toggle_crouch.to_string()),
|
||||
("toggleSprint".into(), self.toggle_sprint.to_string()),
|
||||
("mouseSensitivity".into(), self.sensitivity.to_string()),
|
||||
("highContrast".into(), self.high_contrast.to_string()),
|
||||
("resourcePacks".into(), serde_json::to_string(&self.resource_packs).unwrap_or_else(|_| "[]".into())),
|
||||
("lang".into(), self.language.clone()),
|
||||
("chatVisibility".into(), self.chat_visibility.to_string()),
|
||||
("chatOpacity".into(), self.chat_opacity.to_string()),
|
||||
("chatLineSpacing".into(), self.chat_line_spacing.to_string()),
|
||||
("textBackgroundOpacity".into(), self.text_background_opacity.to_string()),
|
||||
("chatHeightFocused".into(), self.chat_height_focused.to_string()),
|
||||
("chatHeightUnfocused".into(), self.chat_height_unfocused.to_string()),
|
||||
("chatScale".into(), self.chat_scale.to_string()),
|
||||
("chatWidth".into(), self.chat_width.to_string()),
|
||||
("mainHand".into(), if self.main_hand_left { "\"left\"".into() } else { "\"right\"".into() }),
|
||||
("attackIndicator".into(), self.attack_indicator.to_string()),
|
||||
("mouseWheelSensitivity".into(), self.mouse_wheel_sensitivity.to_string()),
|
||||
("showAutosaveIndicator".into(), self.autosave_indicator.to_string()),
|
||||
("menuBackgroundBlurriness".into(), self.menu_blur.to_string()),
|
||||
];
|
||||
for (name, key) in self.keys.saved() {
|
||||
lines.push((format!("key_{name}"), key));
|
||||
}
|
||||
for (i, source) in SOUND_SOURCES.iter().enumerate() {
|
||||
let v = if i == 0 { self.master_volume } else { self.volumes[i] };
|
||||
lines.push((format!("soundCategory_{source}"), v.to_string()));
|
||||
}
|
||||
let known: std::collections::BTreeSet<String> = lines.iter().map(|(k, _)| k.clone()).collect();
|
||||
for (k, v) in &self.extra {
|
||||
if !known.contains(k) {
|
||||
lines.push((k.clone(), v.clone()));
|
||||
}
|
||||
}
|
||||
let mut out = format!("version:{}\n", horizon_world::DATA_VERSION);
|
||||
for (k, v) in lines {
|
||||
out.push_str(&format!("{k}:{v}\n"));
|
||||
}
|
||||
out
|
||||
}
|
||||
pub fn save(&self, path: &Path) {
|
||||
let text = format!(
|
||||
"version:4793\nfov:{}\nrenderDistance:{}\nmouseSensitivity:{}\nsoundCategory_master:{}\nguiScale:{}\nbobView:{}\n",
|
||||
(self.fov - 70.0) / 40.0,
|
||||
self.render_distance,
|
||||
self.sensitivity,
|
||||
self.master_volume,
|
||||
self.gui_scale,
|
||||
self.view_bobbing
|
||||
);
|
||||
let _ = fs::write(path, text);
|
||||
let _ = fs::write(path, self.serialize());
|
||||
}
|
||||
fn rows(&self) -> Vec<(String, Option<f32>)> {
|
||||
vec![
|
||||
(format!("FOV: {}", if self.fov.round() == 70.0 { "Normal".into() } else if self.fov >= 110.0 { "Quake Pro".into() } else { format!("{:.0}", self.fov) }), Some((self.fov - 30.0) / 80.0)),
|
||||
(format!("Render Distance: {} chunks", self.render_distance), Some((self.render_distance - 2) as f32 / 30.0)),
|
||||
(format!("Sensitivity: {}", if self.sensitivity == 0.0 { "*yawn*".into() } else if self.sensitivity >= 1.0 { "HYPERSPEED!!!".into() } else { format!("{:.0}%", self.sensitivity * 200.0) }), Some(self.sensitivity)),
|
||||
(format!("Master Volume: {}", if self.master_volume == 0.0 { "OFF".into() } else { format!("{:.0}%", self.master_volume * 100.0) }), Some(self.master_volume)),
|
||||
(format!("GUI Scale: {}", if self.gui_scale == 0 { "Auto".into() } else { self.gui_scale.to_string() }), None),
|
||||
(format!("View Bobbing: {}", if self.view_bobbing { "ON" } else { "OFF" }), None),
|
||||
]
|
||||
/// Volume of a sound source (master excluded).
|
||||
pub fn volume(&self, source: &str) -> f32 {
|
||||
SOUND_SOURCES.iter().position(|n| *n == source).map_or(1.0, |i| if i == 0 { self.master_volume } else { self.volumes[i] })
|
||||
}
|
||||
fn layout(w: f32, i: usize) -> (f32, f32) {
|
||||
(w / 2.0 - 155.0 + (i % 2) as f32 * 160.0, 48.0 + (i / 2) as f32 * 24.0)
|
||||
}
|
||||
pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, cursor: (f32, f32)) {
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
batch.fill(atlas, 0.0, 0.0, w, h, rgba(0, 0, 0, 150));
|
||||
let title = "Options";
|
||||
let tw = HudBatch::text_width(atlas, title);
|
||||
batch.text(atlas, title, (w - tw) / 2.0, 15.0, u32::MAX, true);
|
||||
let mut rows = self.rows();
|
||||
rows.push(("Done".into(), None));
|
||||
for (i, (label, slider)) in rows.iter().enumerate() {
|
||||
let (x, y) = if i == rows.len() - 1 { (w / 2.0 - 100.0, h / 6.0 + 168.0) } else { Self::layout(w, i) };
|
||||
let width = if i == rows.len() - 1 { 200.0 } else { 150.0 };
|
||||
let hover = cursor.0 >= x && cursor.0 < x + width && cursor.1 >= y && cursor.1 < y + 20.0;
|
||||
let sprite = match (slider, hover) {
|
||||
(Some(_), _) => "gui/sprites/widget/slider",
|
||||
(None, true) => "gui/sprites/widget/button_highlighted",
|
||||
(None, false) => "gui/sprites/widget/button",
|
||||
};
|
||||
if let Some(r) = atlas.sprites.get(sprite).copied() {
|
||||
let half = width / 2.0;
|
||||
let mut left = r;
|
||||
left.u1 = r.u0 + (r.u1 - r.u0) * (half / r.w as f32);
|
||||
batch.rect_uv(x, y, half, 20.0, left, u32::MAX);
|
||||
let mut right = r;
|
||||
right.u0 = r.u1 - (r.u1 - r.u0) * (half / r.w as f32);
|
||||
batch.rect_uv(x + half, y, half, 20.0, right, u32::MAX);
|
||||
}
|
||||
if let Some(v) = slider {
|
||||
let handle = if hover { "gui/sprites/widget/slider_handle_highlighted" } else { "gui/sprites/widget/slider_handle" };
|
||||
batch.sprite_scaled(atlas, handle, x + v.clamp(0.0, 1.0) * (width - 8.0), y, 8.0, 20.0, u32::MAX);
|
||||
}
|
||||
let tw = HudBatch::text_width(atlas, label);
|
||||
batch.text(atlas, label, x + (width - tw) / 2.0, y + 6.0, u32::MAX, true);
|
||||
pub fn chat_options(&self) -> crate::chat::ChatOptions {
|
||||
crate::chat::ChatOptions {
|
||||
opacity: self.chat_opacity,
|
||||
background_opacity: self.text_background_opacity,
|
||||
scale: self.chat_scale,
|
||||
width: self.chat_width,
|
||||
height_focused: self.chat_height_focused,
|
||||
height_unfocused: self.chat_height_unfocused,
|
||||
line_spacing: self.chat_line_spacing,
|
||||
}
|
||||
}
|
||||
/// Handle a click or drag; returns true when Done was pressed.
|
||||
pub fn click(&mut self, x: f32, y: f32, size: (f32, f32), drag: bool) -> bool {
|
||||
let (w, h) = size;
|
||||
let rows = self.rows().len();
|
||||
if !drag && x >= w / 2.0 - 100.0 && x < w / 2.0 + 100.0 && y >= h / 6.0 + 168.0 && y < h / 6.0 + 188.0 {
|
||||
return true;
|
||||
}
|
||||
for i in 0..rows {
|
||||
let (bx, by) = Self::layout(w, i);
|
||||
if !(x >= bx && x < bx + 150.0 && y >= by && y < by + 20.0) {
|
||||
continue;
|
||||
}
|
||||
let v = ((x - bx - 4.0) / 142.0).clamp(0.0, 1.0);
|
||||
match i {
|
||||
0 => self.fov = (30.0 + v * 80.0).round(),
|
||||
1 => self.render_distance = 2 + (v * 30.0).round() as i32,
|
||||
2 => self.sensitivity = (v * 100.0).round() / 100.0,
|
||||
3 => self.master_volume = (v * 100.0).round() / 100.0,
|
||||
4 if !drag => self.gui_scale = (self.gui_scale + 1) % 5,
|
||||
5 if !drag => self.view_bobbing = !self.view_bobbing,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn round_trips_vanilla_options_txt() {
|
||||
let text = "version:4000\nfov:0.5\nrenderDistance:16\nmaxFps:260\nrenderClouds:\"fast\"\nkey_key.jump:key.keyboard.j\nsoundCategory_music:0.25\nresourcePacks:[\"vanilla\",\"file/x.zip\"]\nlang:fr_fr\nsomeFutureOption:42\n";
|
||||
let s = Settings::parse(text);
|
||||
assert_eq!(s.fov, 90.0);
|
||||
assert_eq!(s.render_distance, 16);
|
||||
assert_eq!(s.max_fps, 260);
|
||||
assert_eq!(s.clouds, "fast");
|
||||
assert_eq!(s.keys.get("key.jump"), "key.keyboard.j");
|
||||
assert_eq!(s.volume("music"), 0.25);
|
||||
assert_eq!(s.resource_packs, ["vanilla", "file/x.zip"]);
|
||||
assert_eq!(s.language, "fr_fr");
|
||||
let out = s.serialize();
|
||||
assert!(out.starts_with("version:"));
|
||||
assert!(out.contains("\nkey_key.jump:key.keyboard.j\n"));
|
||||
assert!(out.contains("\nsomeFutureOption:42\n"));
|
||||
assert!(out.contains("\nrenderClouds:\"fast\"\n"));
|
||||
let again = Settings::parse(&out);
|
||||
assert_eq!(again.fov, 90.0);
|
||||
assert_eq!(again.keys.get("key.jump"), "key.keyboard.j");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
//! Styled text (a flattened `Component`): spans with ChatFormatting colours
|
||||
//! and decorations, translatable messages formatted like
|
||||
//! `TranslatableContents` (`%s`, `%1$s`, `%%`), and legacy `§` codes.
|
||||
use crate::lang;
|
||||
|
||||
/// ChatFormatting colours by legacy code index 0..=15.
|
||||
pub const COLORS: [(char, &str, u32); 16] = [
|
||||
('0', "black", 0x000000),
|
||||
('1', "dark_blue", 0x0000AA),
|
||||
('2', "dark_green", 0x00AA00),
|
||||
('3', "dark_aqua", 0x00AAAA),
|
||||
('4', "dark_red", 0xAA0000),
|
||||
('5', "dark_purple", 0xAA00AA),
|
||||
('6', "gold", 0xFFAA00),
|
||||
('7', "gray", 0xAAAAAA),
|
||||
('8', "dark_gray", 0x555555),
|
||||
('9', "blue", 0x5555FF),
|
||||
('a', "green", 0x55FF55),
|
||||
('b', "aqua", 0x55FFFF),
|
||||
('c', "red", 0xFF5555),
|
||||
('d', "light_purple", 0xFF55FF),
|
||||
('e', "yellow", 0xFFFF55),
|
||||
('f', "white", 0xFFFFFF),
|
||||
];
|
||||
pub const BLACK: u32 = 0x000000;
|
||||
pub const GRAY: u32 = 0xAAAAAA;
|
||||
pub const DARK_GRAY: u32 = 0x555555;
|
||||
pub const GREEN: u32 = 0x55FF55;
|
||||
pub const AQUA: u32 = 0x55FFFF;
|
||||
pub const RED: u32 = 0xFF5555;
|
||||
pub const YELLOW: u32 = 0xFFFF55;
|
||||
pub const GOLD: u32 = 0xFFAA00;
|
||||
pub const WHITE: u32 = 0xFFFFFF;
|
||||
pub const LIGHT_PURPLE: u32 = 0xFF55FF;
|
||||
|
||||
pub fn named_color(name: &str) -> Option<u32> {
|
||||
COLORS.iter().find(|c| c.1 == name).map(|c| c.2)
|
||||
}
|
||||
|
||||
/// Text style; `None` fields inherit from the enclosing style.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Style {
|
||||
pub color: Option<u32>,
|
||||
pub bold: Option<bool>,
|
||||
pub italic: Option<bool>,
|
||||
pub underlined: Option<bool>,
|
||||
pub strikethrough: Option<bool>,
|
||||
pub obfuscated: Option<bool>,
|
||||
/// ClickEvent.SuggestCommand: clicking puts this into the chat box.
|
||||
pub suggest: Option<String>,
|
||||
/// Hover text.
|
||||
pub hover: Option<Box<Text>>,
|
||||
}
|
||||
impl Style {
|
||||
pub fn color(c: u32) -> Self {
|
||||
Self { color: Some(c), ..Self::default() }
|
||||
}
|
||||
/// Fill unset fields from `base` (Style.applyTo).
|
||||
pub fn inherit(&mut self, base: &Style) {
|
||||
self.color = self.color.or(base.color);
|
||||
self.bold = self.bold.or(base.bold);
|
||||
self.italic = self.italic.or(base.italic);
|
||||
self.underlined = self.underlined.or(base.underlined);
|
||||
self.strikethrough = self.strikethrough.or(base.strikethrough);
|
||||
self.obfuscated = self.obfuscated.or(base.obfuscated);
|
||||
if self.suggest.is_none() {
|
||||
self.suggest.clone_from(&base.suggest);
|
||||
}
|
||||
if self.hover.is_none() {
|
||||
self.hover.clone_from(&base.hover);
|
||||
}
|
||||
}
|
||||
pub fn is_bold(&self) -> bool {
|
||||
self.bold == Some(true)
|
||||
}
|
||||
pub fn is_italic(&self) -> bool {
|
||||
self.italic == Some(true)
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Span {
|
||||
pub text: String,
|
||||
pub style: Style,
|
||||
}
|
||||
/// A run of styled spans.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Text {
|
||||
pub spans: Vec<Span>,
|
||||
}
|
||||
impl From<&str> for Text {
|
||||
fn from(s: &str) -> Self {
|
||||
Text::literal(s)
|
||||
}
|
||||
}
|
||||
impl From<String> for Text {
|
||||
fn from(s: String) -> Self {
|
||||
Text::literal(s)
|
||||
}
|
||||
}
|
||||
impl Text {
|
||||
pub fn empty() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
pub fn literal(s: impl Into<String>) -> Self {
|
||||
let text = s.into();
|
||||
if text.is_empty() {
|
||||
return Self::default();
|
||||
}
|
||||
Self { spans: vec![Span { text, style: Style::default() }] }
|
||||
}
|
||||
pub fn styled(s: impl Into<String>, style: Style) -> Self {
|
||||
let mut t = Self::literal(s);
|
||||
for span in &mut t.spans {
|
||||
span.style = style.clone();
|
||||
}
|
||||
t
|
||||
}
|
||||
pub fn colored(s: impl Into<String>, color: u32) -> Self {
|
||||
Self::styled(s, Style::color(color))
|
||||
}
|
||||
/// Component.translatable(key, args) in the current language.
|
||||
pub fn translate(key: &str, args: &[Text]) -> Self {
|
||||
format_translation(&lang::get(key), args)
|
||||
}
|
||||
/// A translatable message whose arguments are plain strings.
|
||||
pub fn tr(key: &str, args: &[&dyn std::fmt::Display]) -> Self {
|
||||
let args: Vec<Text> = args.iter().map(|a| Text::literal(a.to_string())).collect();
|
||||
Self::translate(key, &args)
|
||||
}
|
||||
pub fn append(mut self, other: impl Into<Text>) -> Self {
|
||||
self.spans.extend(other.into().spans);
|
||||
self
|
||||
}
|
||||
pub fn push(&mut self, other: impl Into<Text>) {
|
||||
self.spans.extend(other.into().spans);
|
||||
}
|
||||
/// Apply `style` underneath every span (MutableComponent.withStyle on a parent).
|
||||
pub fn with_style(mut self, style: &Style) -> Self {
|
||||
for span in &mut self.spans {
|
||||
span.style.inherit(style);
|
||||
}
|
||||
self
|
||||
}
|
||||
pub fn with_color(self, color: u32) -> Self {
|
||||
self.with_style(&Style::color(color))
|
||||
}
|
||||
pub fn italic(self) -> Self {
|
||||
self.with_style(&Style { italic: Some(true), ..Style::default() })
|
||||
}
|
||||
pub fn underlined(self) -> Self {
|
||||
self.with_style(&Style { underlined: Some(true), ..Style::default() })
|
||||
}
|
||||
pub fn bold(self) -> Self {
|
||||
self.with_style(&Style { bold: Some(true), ..Style::default() })
|
||||
}
|
||||
/// Component.getString: the plain characters.
|
||||
pub fn plain(&self) -> String {
|
||||
self.spans.iter().map(|s| s.text.as_str()).collect()
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.spans.iter().all(|s| s.text.is_empty())
|
||||
}
|
||||
/// Parse legacy formatting codes (`§a`, `§l`, `§r`...) as the font does.
|
||||
pub fn legacy(s: &str) -> Self {
|
||||
let mut out = Text::default();
|
||||
let mut style = Style::default();
|
||||
let mut current = String::new();
|
||||
let mut chars = s.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
if c != '§' {
|
||||
current.push(c);
|
||||
continue;
|
||||
}
|
||||
let Some(code) = chars.next() else { break };
|
||||
if !current.is_empty() {
|
||||
out.spans.push(Span { text: std::mem::take(&mut current), style: style.clone() });
|
||||
}
|
||||
let code = code.to_ascii_lowercase();
|
||||
if let Some(c) = COLORS.iter().find(|c| c.0 == code) {
|
||||
// Colour codes reset decorations (Style.applyLegacyFormat).
|
||||
style = Style::color(c.2);
|
||||
} else {
|
||||
match code {
|
||||
'k' => style.obfuscated = Some(true),
|
||||
'l' => style.bold = Some(true),
|
||||
'm' => style.strikethrough = Some(true),
|
||||
'n' => style.underlined = Some(true),
|
||||
'o' => style.italic = Some(true),
|
||||
'r' => style = Style::default(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !current.is_empty() {
|
||||
out.spans.push(Span { text: current, style });
|
||||
}
|
||||
out
|
||||
}
|
||||
/// Characters with their effective styles.
|
||||
pub fn chars(&self) -> impl Iterator<Item = (char, &Style)> {
|
||||
self.spans.iter().flat_map(|s| s.text.chars().map(move |c| (c, &s.style)))
|
||||
}
|
||||
/// Sub-range of characters [from, to) keeping styles.
|
||||
pub fn slice(&self, from: usize, to: usize) -> Text {
|
||||
let mut out = Text::default();
|
||||
let mut index = 0;
|
||||
for span in &self.spans {
|
||||
let mut part = String::new();
|
||||
for c in span.text.chars() {
|
||||
if index >= from && index < to {
|
||||
part.push(c);
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
if !part.is_empty() {
|
||||
out.spans.push(Span { text: part, style: span.style.clone() });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
pub fn char_count(&self) -> usize {
|
||||
self.spans.iter().map(|s| s.text.chars().count()).sum()
|
||||
}
|
||||
}
|
||||
|
||||
/// TranslatableContents.decomposeTemplate: `%s` takes the next argument,
|
||||
/// `%n$s` a numbered one and `%%` is a percent sign. Malformed templates are
|
||||
/// shown verbatim.
|
||||
pub fn format_translation(template: &str, args: &[Text]) -> Text {
|
||||
let mut out = Text::default();
|
||||
let mut literal = String::new();
|
||||
let mut next = 0usize;
|
||||
let chars: Vec<char> = template.chars().collect();
|
||||
let mut i = 0;
|
||||
while i < chars.len() {
|
||||
if chars[i] != '%' {
|
||||
literal.push(chars[i]);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
// %(?:(\d+)\$)?([A-Za-z%]|$)
|
||||
let mut j = i + 1;
|
||||
let mut number = None;
|
||||
let digits_start = j;
|
||||
while j < chars.len() && chars[j].is_ascii_digit() {
|
||||
j += 1;
|
||||
}
|
||||
if j > digits_start && j < chars.len() && chars[j] == '$' {
|
||||
number = chars[digits_start..j].iter().collect::<String>().parse::<usize>().ok();
|
||||
j += 1;
|
||||
} else {
|
||||
j = digits_start;
|
||||
}
|
||||
let conversion = chars.get(j).copied();
|
||||
match conversion {
|
||||
Some('%') if number.is_none() => {
|
||||
literal.push('%');
|
||||
i = j + 1;
|
||||
}
|
||||
// Not a format specifier at all: the percent sign is literal.
|
||||
Some(c) if !c.is_ascii_alphabetic() && c != '%' => {
|
||||
literal.push('%');
|
||||
i += 1;
|
||||
}
|
||||
Some('s') => {
|
||||
let index = match number {
|
||||
Some(n) => n.wrapping_sub(1),
|
||||
None => {
|
||||
next += 1;
|
||||
next - 1
|
||||
}
|
||||
};
|
||||
let Some(arg) = args.get(index) else {
|
||||
return Text::literal(template);
|
||||
};
|
||||
if !literal.is_empty() {
|
||||
out.spans.push(Span { text: std::mem::take(&mut literal), style: Style::default() });
|
||||
}
|
||||
out.spans.extend(arg.spans.iter().cloned());
|
||||
i = j + 1;
|
||||
}
|
||||
_ => return Text::literal(template),
|
||||
}
|
||||
}
|
||||
if !literal.is_empty() {
|
||||
out.spans.push(Span { text: literal, style: Style::default() });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn formats_like_translatable_contents() {
|
||||
let a = [Text::literal("Steve"), Text::colored("Zombie", RED)];
|
||||
assert_eq!(format_translation("%s was slain by %s", &a).plain(), "Steve was slain by Zombie");
|
||||
assert_eq!(format_translation("%2$s then %1$s", &a).plain(), "Zombie then Steve");
|
||||
assert_eq!(format_translation("100%% sure %s", &a).plain(), "100% sure Steve");
|
||||
// Missing arguments or unknown conversions show the template.
|
||||
assert_eq!(format_translation("%s %s %s", &a).plain(), "%s %s %s");
|
||||
assert_eq!(format_translation("%d", &a).plain(), "%d");
|
||||
assert_eq!(format_translation("50% off %s", &a).plain(), "50% off Steve");
|
||||
assert_eq!(format_translation("end %", &a).plain(), "end %");
|
||||
let t = format_translation("%s was slain by %s", &a);
|
||||
assert_eq!(t.spans.last().unwrap().style.color, Some(RED));
|
||||
}
|
||||
#[test]
|
||||
fn legacy_codes_and_inheritance() {
|
||||
let t = Text::legacy("§aGreen §lbold§r plain");
|
||||
assert_eq!(t.plain(), "Green bold plain");
|
||||
assert_eq!(t.spans[0].style.color, Some(GREEN));
|
||||
assert!(t.spans[1].style.is_bold());
|
||||
assert_eq!(t.spans[2].style, Style::default());
|
||||
let t = Text::literal("x").append(Text::colored("y", GOLD)).with_color(RED);
|
||||
assert_eq!(t.spans[0].style.color, Some(RED));
|
||||
assert_eq!(t.spans[1].style.color, Some(GOLD));
|
||||
assert_eq!(t.slice(1, 2).plain(), "y");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,510 @@
|
||||
//! 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;
|
||||
}
|
||||
}
|
||||
/// Text drawn at `scale` times its size (a scaled pose).
|
||||
pub fn text_scaled(batch: &mut HudBatch, atlas: &HudAtlas, text: &Text, x: f32, y: f32, scale: f32, color: u32) {
|
||||
let start = batch.vertices.len();
|
||||
batch.text_styled(atlas, text, 0.0, 0.0, color, true);
|
||||
for v in &mut batch.vertices[start..] {
|
||||
v.pos = [x + v.pos[0] * scale, y + v.pos[1] * scale];
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
//! Minimal read-only ZIP archive support (stored and deflated entries), used
|
||||
//! for resource packs and the unifont glyph archive.
|
||||
use std::{collections::BTreeMap, fs, io, path::Path};
|
||||
|
||||
/// One archive held in memory with its central directory indexed by name.
|
||||
pub struct Zip {
|
||||
data: Vec<u8>,
|
||||
entries: BTreeMap<String, Entry>,
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
struct Entry {
|
||||
method: u16,
|
||||
compressed: usize,
|
||||
size: usize,
|
||||
header: usize,
|
||||
}
|
||||
fn invalid(message: &str) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidData, message)
|
||||
}
|
||||
fn u16_at(d: &[u8], at: usize) -> io::Result<u16> {
|
||||
d.get(at..at + 2).map(|b| u16::from_le_bytes([b[0], b[1]])).ok_or_else(|| invalid("truncated zip"))
|
||||
}
|
||||
fn u32_at(d: &[u8], at: usize) -> io::Result<u32> {
|
||||
d.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).ok_or_else(|| invalid("truncated zip"))
|
||||
}
|
||||
impl Zip {
|
||||
pub fn open(path: &Path) -> io::Result<Self> {
|
||||
Self::from_bytes(fs::read(path)?)
|
||||
}
|
||||
pub fn from_bytes(data: Vec<u8>) -> io::Result<Self> {
|
||||
// End of central directory: the last "PK\x05\x06" within 64 KiB of the end.
|
||||
let min = data.len().saturating_sub(22 + 65_535);
|
||||
let eocd = (min..=data.len().saturating_sub(22))
|
||||
.rev()
|
||||
.find(|&i| data[i..i + 4] == [0x50, 0x4b, 0x05, 0x06])
|
||||
.ok_or_else(|| invalid("not a zip archive"))?;
|
||||
let count = usize::from(u16_at(&data, eocd + 10)?);
|
||||
let mut at = u32_at(&data, eocd + 16)? as usize;
|
||||
let mut entries = BTreeMap::new();
|
||||
for _ in 0..count {
|
||||
if u32_at(&data, at)? != 0x0201_4b50 {
|
||||
return Err(invalid("bad central directory entry"));
|
||||
}
|
||||
let method = u16_at(&data, at + 10)?;
|
||||
let compressed = u32_at(&data, at + 20)? as usize;
|
||||
let size = u32_at(&data, at + 24)? as usize;
|
||||
let name_len = usize::from(u16_at(&data, at + 28)?);
|
||||
let extra_len = usize::from(u16_at(&data, at + 30)?);
|
||||
let comment_len = usize::from(u16_at(&data, at + 32)?);
|
||||
let header = u32_at(&data, at + 42)? as usize;
|
||||
let name = data.get(at + 46..at + 46 + name_len).ok_or_else(|| invalid("truncated zip name"))?;
|
||||
let name = String::from_utf8_lossy(name).replace('\\', "/");
|
||||
if !name.ends_with('/') {
|
||||
entries.insert(name, Entry { method, compressed, size, header });
|
||||
}
|
||||
at += 46 + name_len + extra_len + comment_len;
|
||||
}
|
||||
Ok(Self { data, entries })
|
||||
}
|
||||
pub fn names(&self) -> impl Iterator<Item = &str> {
|
||||
self.entries.keys().map(String::as_str)
|
||||
}
|
||||
pub fn contains(&self, name: &str) -> bool {
|
||||
self.entries.contains_key(name)
|
||||
}
|
||||
pub fn read(&self, name: &str) -> io::Result<Vec<u8>> {
|
||||
let e = *self.entries.get(name).ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, name.to_owned()))?;
|
||||
if u32_at(&self.data, e.header)? != 0x0403_4b50 {
|
||||
return Err(invalid("bad local file header"));
|
||||
}
|
||||
let start = e.header + 30 + usize::from(u16_at(&self.data, e.header + 26)?) + usize::from(u16_at(&self.data, e.header + 28)?);
|
||||
let raw = self.data.get(start..start + e.compressed).ok_or_else(|| invalid("truncated zip entry"))?;
|
||||
match e.method {
|
||||
0 => Ok(raw.to_vec()),
|
||||
8 => {
|
||||
let out = miniz_oxide::inflate::decompress_to_vec_with_limit(raw, e.size.max(1) * 2 + 1024)
|
||||
.map_err(|_| invalid("corrupt deflate stream"))?;
|
||||
Ok(out)
|
||||
}
|
||||
_ => Err(invalid("unsupported zip compression")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
/// A hand-built archive with one stored and one deflated entry.
|
||||
fn archive() -> Vec<u8> {
|
||||
let files: [(&str, &[u8], bool); 2] = [("pack.mcmeta", b"{\"pack\":{}}", false), ("a/b.txt", b"hello hello hello hello", true)];
|
||||
let mut out = Vec::new();
|
||||
let mut central = Vec::new();
|
||||
for (name, body, deflate) in files {
|
||||
let data = if deflate { miniz_oxide::deflate::compress_to_vec(body, 6) } else { body.to_vec() };
|
||||
let offset = out.len() as u32;
|
||||
let local = |v: &mut Vec<u8>, sig: u32| {
|
||||
v.extend(sig.to_le_bytes());
|
||||
};
|
||||
local(&mut out, 0x0403_4b50);
|
||||
out.extend([20, 0, 0, 0]);
|
||||
out.extend((if deflate { 8u16 } else { 0 }).to_le_bytes());
|
||||
out.extend([0; 8]);
|
||||
out.extend((data.len() as u32).to_le_bytes());
|
||||
out.extend((body.len() as u32).to_le_bytes());
|
||||
out.extend((name.len() as u16).to_le_bytes());
|
||||
out.extend(0u16.to_le_bytes());
|
||||
out.extend(name.as_bytes());
|
||||
out.extend(&data);
|
||||
local(&mut central, 0x0201_4b50);
|
||||
central.extend([20, 0, 20, 0, 0, 0]);
|
||||
central.extend((if deflate { 8u16 } else { 0 }).to_le_bytes());
|
||||
central.extend([0; 8]);
|
||||
central.extend((data.len() as u32).to_le_bytes());
|
||||
central.extend((body.len() as u32).to_le_bytes());
|
||||
central.extend((name.len() as u16).to_le_bytes());
|
||||
central.extend([0; 12]);
|
||||
central.extend(offset.to_le_bytes());
|
||||
central.extend(name.as_bytes());
|
||||
}
|
||||
let start = out.len() as u32;
|
||||
out.extend(¢ral);
|
||||
out.extend(0x0605_4b50u32.to_le_bytes());
|
||||
out.extend([0; 4]);
|
||||
out.extend(2u16.to_le_bytes());
|
||||
out.extend(2u16.to_le_bytes());
|
||||
out.extend((central.len() as u32).to_le_bytes());
|
||||
out.extend(start.to_le_bytes());
|
||||
out.extend([0; 2]);
|
||||
out
|
||||
}
|
||||
#[test]
|
||||
fn reads_stored_and_deflated_entries() {
|
||||
let zip = Zip::from_bytes(archive()).unwrap();
|
||||
assert_eq!(zip.names().collect::<Vec<_>>(), ["a/b.txt", "pack.mcmeta"]);
|
||||
assert_eq!(zip.read("pack.mcmeta").unwrap(), b"{\"pack\":{}}");
|
||||
assert_eq!(zip.read("a/b.txt").unwrap(), b"hello hello hello hello");
|
||||
assert!(zip.read("missing").is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fetch the pinned version's indexed client assets that are not in the game
|
||||
jar: language files and the language list (pack.mcmeta), the unifont glyph
|
||||
archives and their font definitions, and the built-in Programmer Art and High
|
||||
Contrast resource packs. Every object's SHA-1 is verified. Files go to the
|
||||
private client resource directory (or --target) and are never committed."""
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
LOCAL = ROOT / '.local'
|
||||
|
||||
|
||||
def fetch(url):
|
||||
with urllib.request.urlopen(url, timeout=120) as response:
|
||||
return response.read()
|
||||
|
||||
|
||||
def wanted(name):
|
||||
return (name == 'pack.mcmeta'
|
||||
or name.startswith('minecraft/lang/')
|
||||
or name.startswith('minecraft/font/')
|
||||
or name.startswith('minecraft/resourcepacks/'))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--target', type=Path, default=LOCAL / 'horizon-client/26.3',
|
||||
help='prepared resource directory (default: .local/horizon-client/26.3)')
|
||||
args = parser.parse_args()
|
||||
manifest = json.loads((LOCAL / 'minecraft/26.3/manifest.json').read_text())
|
||||
index_info = manifest['assetIndex']
|
||||
target = args.target
|
||||
index_path = target / 'asset-index.json'
|
||||
if not index_path.exists() or hashlib.sha1(index_path.read_bytes()).hexdigest() != index_info['sha1']:
|
||||
data = fetch(index_info['url'])
|
||||
if hashlib.sha1(data).hexdigest() != index_info['sha1']:
|
||||
raise ValueError('asset index checksum mismatch')
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
index_path.write_bytes(data)
|
||||
objects = json.loads(index_path.read_text())['objects']
|
||||
selected = {name: info for name, info in objects.items() if wanted(name)}
|
||||
|
||||
def download(item):
|
||||
name, info = item
|
||||
path = target / 'assets' / name
|
||||
if path.exists() and hashlib.sha1(path.read_bytes()).hexdigest() == info['hash']:
|
||||
return 0
|
||||
h = info['hash']
|
||||
data = fetch(f'https://resources.download.minecraft.net/{h[:2]}/{h}')
|
||||
if hashlib.sha1(data).hexdigest() != h:
|
||||
raise ValueError(f'checksum mismatch for {name}')
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(data)
|
||||
return len(data)
|
||||
|
||||
total = 0
|
||||
with concurrent.futures.ThreadPoolExecutor(16) as pool:
|
||||
for size in pool.map(download, selected.items()):
|
||||
total += size
|
||||
print(f'Client assets ready: {len(selected)} files, {total / 1e6:.1f} MB downloaded')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user