Merge pull request #1215 from ludovic111/feat/win-screen

🤖 Agent: merged after verify passed and the wave-3 integration on the desktop by integ-w3: main + 17 PRs, fmt, clippy 0, 1929 workspace tests, parity --changed (only known flakes failed, and those passed on rerun), lan_e2e in both modes, and the perf numbers back to back against main posted on each PR.
This commit is contained in:
Ludovic Marie
2026-10-23 06:20:28 +02:00
committed by GitHub
17 changed files with 997 additions and 22 deletions
+71
View File
@@ -52,6 +52,10 @@ struct Cache {
cursor: (u32, u32),
pending: Vec<Patch>,
hex: Option<Vec<HexProvider>>,
/// `FontSet.glyphsByWidth` for obfuscated text (built on first use).
by_width: Option<HashMap<u32, Vec<char>>>,
/// `Font.random`: picks obfuscated glyphs.
random: horizon_core::random::LegacyRandom,
}
pub struct Font {
bitmap: HashMap<char, Glyph>,
@@ -285,6 +289,12 @@ impl Font {
cursor: (0, 0),
pending: Vec::new(),
hex: None,
by_width: None,
random: horizon_core::random::LegacyRandom::new(
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos() as i64),
),
}),
uniform: false,
japanese: false,
@@ -353,6 +363,7 @@ impl Font {
cache.glyphs.clear();
cache.cursor = (0, 0);
cache.hex = None;
cache.by_width = None;
}
/// The glyph for a character (FontSet.getGlyph).
pub fn glyph(&self, c: char) -> Glyph {
@@ -427,6 +438,66 @@ impl Font {
offset: 0.5,
})
}
/// `FontSet.getRandomGlyph`: what an obfuscated character draws, a random
/// glyph as wide as `advance` (rounded up), else the missing glyph.
///
/// Vanilla picks among every glyph of the font set, Unifont's included.
/// Those are rasterized into a fixed atlas region on demand, which a
/// line of obfuscated text would fill in seconds, so the candidates are
/// the glyphs already in the atlas (the bitmap sheets and spaces), or with
/// "Force Unicode Font" the Unifont glyphs below U+0250.
pub fn random_glyph(&self, advance: f32) -> Glyph {
use horizon_core::random::RandomSource;
let width = advance.ceil() as u32;
let pick = {
let mut cache = self.cache.borrow_mut();
if cache.by_width.is_none() {
let by_width = self.glyphs_by_width(&mut cache);
cache.by_width = Some(by_width);
}
let Cache {
by_width, random, ..
} = &mut *cache;
by_width
.as_ref()
.and_then(|m| m.get(&width))
.and_then(|chars| {
let i = random.next_int_bound(chars.len() as i32).ok()?;
chars.get(i as usize).copied()
})
};
pick.map_or(self.missing, |c| self.glyph(c))
}
fn glyphs_by_width(&self, cache: &mut Cache) -> HashMap<u32, Vec<char>> {
let mut chars: Vec<(char, f32)> = self.space.iter().map(|(c, a)| (*c, *a)).collect();
if self.uniform {
if cache.hex.is_none() {
cache.hex = Some(self.load_hex());
}
for code in 0..0x250u32 {
let hex = cache.hex.iter().flatten().find_map(|p| p.glyphs.get(&code));
if let (Some(c), Some(h)) = (char::from_u32(code), hex)
&& !self.space.contains_key(&c)
{
let width = h.right.saturating_sub(h.left) + 1;
chars.push((c, (width / 2 + 1) as f32));
}
}
} else {
chars.extend(
self.bitmap
.iter()
.filter(|(c, _)| !self.space.contains_key(c))
.map(|(c, g)| (*c, g.advance)),
);
}
chars.sort_by_key(|(c, _)| *c);
let mut out: HashMap<u32, Vec<char>> = HashMap::new();
for (c, advance) in chars {
out.entry(advance.ceil() as u32).or_default().push(c);
}
out
}
/// Atlas pixels rasterized since the last call.
pub fn take_patches(&self) -> Vec<Patch> {
std::mem::take(&mut self.cache.borrow_mut().pending)
+28 -5
View File
@@ -162,6 +162,7 @@ mod ui_control;
mod vault;
mod villagers;
mod wandering_trader;
mod win;
mod wind;
mod wither;
mod world_loading;
@@ -464,6 +465,8 @@ enum Screen {
Friends,
/// CommandBlockEditScreen (game/command_blocks.rs).
CommandBlock,
/// WinScreen: the end poem and the credits (game/win.rs).
Win,
}
struct Mining {
pos: [i32; 3],
@@ -1357,6 +1360,8 @@ struct Game<'a> {
respawn_travel: Option<respawn_anchor::RespawnConfig>,
/// The next enter_dimension call comes from an End portal.
end_portal_travel: bool,
/// The open WinScreen (game/win.rs).
win: Option<win::Win>,
end: end::EndState,
block_ticks: Ticks,
tick_chunks: horizon_client::tick_chunk_membership::TickChunkMembership,
@@ -3798,6 +3803,9 @@ impl Game<'_> {
return Ok(());
}
if let Some((_, target)) = &self.travelling {
if self.win_screen_holds_arrival() {
return Ok(());
}
let (cx, cz) = (
(target.x.floor() as i32) >> 4,
(target.z.floor() as i32) >> 4,
@@ -4485,7 +4493,8 @@ impl Game<'_> {
| Screen::WorldOptions
| Screen::Friends
| Screen::CommandBlock
) || self.book.is_some())
) || self.book.is_some()
|| self.win_screen_pauses())
}
/// `MouseHandler.grabMouse` / `releaseMouse`. Both put the pointer at
/// the window's centre, so a screen opened from gameplay (inventory,
@@ -4700,6 +4709,10 @@ impl Game<'_> {
fn hud_layers(&mut self, size: [u32; 2]) -> HudBatch {
let mut batch = HudBatch::new(size);
let (w, h) = (batch.width, batch.height);
if self.screen == Screen::Win {
self.draw_win_screen(&mut batch);
return batch;
}
if self.screen == Screen::Options {
self.draw_options(&mut batch);
return batch;
@@ -4934,7 +4947,7 @@ impl Game<'_> {
self.draw_creative(&mut batch);
}
Screen::Chat => self.draw_chat_screen(&mut batch),
Screen::Playing | Screen::Options => {}
Screen::Playing | Screen::Options | Screen::Win => {}
}
self.draw_toasts(&mut batch);
self.remote_hud(&mut batch);
@@ -10098,12 +10111,13 @@ impl Game<'_> {
let loading = self.loading_reason() == Some(horizon_client::level_loading::Reason::Other);
let blurred = loading
|| self.title.as_ref().is_some_and(|t| {
self.screen == Screen::Options
matches!(self.screen, Screen::Options | Screen::Win)
|| !matches!(t.mode, horizon_client::title::Mode::Main)
})
|| (self.title.is_none()
&& self.player.is_some()
&& self.screen.blurs_background(self.pause_menu));
&& (self.screen.blurs_background(self.pause_menu)
|| (self.screen == Screen::Win && self.win_screen_pauses())));
let radius = self.settings.menu_blur as f32;
(blurred && radius >= 1.0).then_some(radius)
}
@@ -10187,6 +10201,7 @@ impl Game<'_> {
Screen::WorldOptions => self.world_options_escape(),
Screen::CommandBlock => self.close_command_block(),
Screen::Chat => self.close_chat(),
Screen::Win => self.close_win_screen()?,
},
KeyCode::Digit1
| KeyCode::Digit2
@@ -10786,7 +10801,9 @@ impl ApplicationHandler for Game<'_> {
}) * wheel_sensitivity
};
let d = scaled(raw_y) as f32;
if let Some(title) = &mut self.title {
if let Some(title) = &mut self.title
&& self.screen != Screen::Win
{
let size = self
.window
.as_ref()
@@ -10844,6 +10861,7 @@ impl ApplicationHandler for Game<'_> {
self.advancements_scroll(scaled(raw_x) as f32, d);
}
}
WindowEvent::MouseInput { .. } if self.screen == Screen::Win => {}
WindowEvent::MouseInput { state, button, .. } if self.screen == Screen::Options => {
if self.options_waiting_for_key() && state == ElementState::Pressed {
self.options_bind_mouse(button)?;
@@ -11100,6 +11118,9 @@ impl ApplicationHandler for Game<'_> {
{
self.world_options_key(&event)
}
WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::Win => {
self.win_key(&event)?
}
WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::CommandBlock => {
self.command_block_key(&event)
}
@@ -11233,6 +11254,7 @@ impl ApplicationHandler for Game<'_> {
self.tick_ambience();
self.tick_fov();
}
self.tick_win_screen()?;
self.tick_music();
self.tick_sound_engine();
self.clock.record(started.elapsed());
@@ -11660,6 +11682,7 @@ impl<'a> Game<'a> {
respawn_config: None,
respawn_travel: None,
end_portal_travel: false,
win: None,
end: Default::default(),
block_ticks: Ticks::new(0),
tick_chunks: Default::default(),
+1
View File
@@ -405,6 +405,7 @@ impl Game<'_> {
Screen::WorldOptions => "world-options",
Screen::Friends => "friends",
Screen::CommandBlock => "command-block",
Screen::Win => "win",
}
}
pub(super) fn inventory_counts(&self) -> BTreeMap<String, i64> {
+25
View File
@@ -42,6 +42,7 @@ const HELP: &[&str] = &[
"chat MESSAGE send chat or a /command to the server",
"disconnect leave the server for the server list",
"respawn respawn after death on a server",
"credits [poem] [SCROLL] roll the credits (with the end poem), or hold them SCROLL pixels in",
"quit save and exit",
];
@@ -574,6 +575,7 @@ impl Game<'_> {
"graphics" => Page::Graphics,
"graphics-advanced" => Page::GraphicsAdvanced,
"extras" => Page::Extras,
"credits" => Page::Credits,
"horizon" => Page::Horizon,
"agent" => Page::Agent,
"shader-packs" => Page::ShaderPacks,
@@ -652,6 +654,25 @@ impl Game<'_> {
self.connect_server(arg(1)?, &name)?;
ok()
}
"credits" => {
let poem = words.get(1) == Some(&"poem");
let hold = words
.get(1 + usize::from(poem))
.map(|s| s.parse::<f32>())
.transpose()?;
if self.screen != Screen::Win {
let finish = if self.screen == Screen::Options {
super::win::Finish::Options
} else {
super::win::Finish::Closed
};
self.open_win_screen(poem, finish);
}
if let Some(scroll) = hold {
self.hold_win_screen(scroll);
}
ok()
}
"respawn" => {
if self.remote.is_none() || self.screen != Screen::Dead {
return Err("respawn needs the death screen on a server".into());
@@ -734,6 +755,9 @@ impl Game<'_> {
}
fn screen_name(&self) -> &'static str {
if self.screen == Screen::Win {
return "win";
}
if self.title.is_some() {
return "title";
}
@@ -751,6 +775,7 @@ impl Game<'_> {
Screen::WorldOptions => "world-options",
Screen::Friends => "friends",
Screen::CommandBlock => "command-block",
Screen::Win => "win",
}
}
+4 -1
View File
@@ -342,7 +342,10 @@ impl Game<'_> {
f64::from(p.dimensions.width),
f64::from(p.dimensions.height),
);
if portal {
if portal && self.dim == Dim::End && !self.level.seen_credits {
// EndPortalBlock.entityInside: the first exit shows the credits.
self.show_end_credits()?;
} else if portal {
if self.portals.player.cooldown == 0 {
let target = if self.dim == Dim::End {
Dim::Overworld
+6 -2
View File
@@ -12,7 +12,7 @@ impl Game<'_> {
pub(super) fn tick_music(&mut self) {
let (music, volume) = self.situational_music();
// LevelLoadingScreen: no new track before the player is in the world.
let loading = self.title.is_none() && self.player.is_none();
let loading = self.title.is_none() && self.player.is_none() && self.win.is_none();
self.music
.tick(music.as_ref(), volume, loading, &mut self.audio);
}
@@ -59,7 +59,11 @@ impl Game<'_> {
None => (empty, 1.0),
};
let situation = Situation {
screen_music: None,
// WinScreen.getBackgroundMusic.
screen_music: self
.win
.is_some()
.then(horizon_client::music::Music::credits),
in_world: eye.is_some(),
in_end: self.dim == super::Dim::End,
boss_music: self.boss_music(),
@@ -242,6 +242,7 @@ impl Game<'_> {
let _ = std::fs::create_dir_all(&dir);
super::packs::open_folder(&dir);
}
Event::Credits => self.open_win_screen(false, super::win::Finish::Options),
}
}
Ok(())
+4
View File
@@ -2117,6 +2117,10 @@ impl Game<'_> {
);
}
}
// WIN_GAME: the poem and credits, then PERFORM_RESPAWN.
4 if self.screen != Screen::Win => {
self.open_win_screen(true, super::win::Finish::RemoteRespawn);
}
1 => {
self.world.weather.raining = true;
self.world.weather.rain_level = (0.0, 0.0);
@@ -25,6 +25,9 @@ impl Screen {
| Self::Inventory
| Self::Dead
| Self::CommandBlock => false,
// WinScreen.extractBackground: the poem fills the screen with the End portal, the
// credits alone blur. Game::menu_blur knows which one rolls.
Self::Win => false,
}
}
}
@@ -359,6 +362,7 @@ mod tests {
Screen::Inventory,
Screen::Dead,
Screen::CommandBlock,
Screen::Win,
] {
assert!(!screen.blurs_background(true));
assert!(!screen.blurs_background(false));
@@ -12,6 +12,8 @@ pub(super) struct StartupMenu {
title: Option<Title>,
options: OptionsUi,
options_open: bool,
/// The credits from Credits & Attribution, and their last frame.
win: Option<(horizon_client::win_screen::WinScreen, Instant)>,
root: PathBuf,
cursor: (f32, f32),
pointer: (f64, f64),
@@ -370,6 +372,21 @@ impl Loading {
let _ = std::fs::create_dir_all(&dir);
packs::open_folder(&dir);
}
Event::Credits => {
if let Some(gui) = &self.gui {
let name = self.options.as_ref().map_or_else(
|| horizon_client::offline_name::generate(0),
Options::player_name,
);
let screen = horizon_client::win_screen::WinScreen::new(
false,
&self.menu.root,
&name,
&gui.atlas.font,
);
self.menu.win = Some((screen, Instant::now()));
}
}
// The startup menu runs before the game opens a control socket.
Event::ButtonClick | Event::CopyAgentDetails => {}
}
@@ -457,6 +474,20 @@ impl Loading {
}
}
_ if self.gui.is_none() || self.menu.pending.is_some() => {}
WindowEvent::KeyboardInput { event, .. } if self.menu.win.is_some() => {
if let PhysicalKey::Code(code) = event.physical_key {
let pressed = event.state == ElementState::Pressed;
if code == KeyCode::Escape && pressed {
self.menu.win = None;
} else if let Some(key) = horizon_client::win_screen::Key::from_code(code)
&& let Some((win, _)) = &mut self.menu.win
{
win.key(key, pressed);
}
}
}
WindowEvent::MouseInput { .. } | WindowEvent::MouseWheel { .. }
if self.menu.win.is_some() => {}
WindowEvent::CursorMoved { position, .. } => {
self.menu.pointer = (position.x, position.y);
self.update_menu_cursor();
@@ -576,6 +607,15 @@ impl Loading {
self.progress.line(),
self.progress.fraction(),
);
} else if let Some((win, frame)) = &mut self.menu.win {
let now = Instant::now();
// 20 ticks a second: the startup menu runs no tick rate.
let delta_ticks = now.duration_since(*frame).as_secs_f32() * 20.0;
*frame = now;
win.draw(batch, &gui.atlas, delta_ticks, Default::default());
if win.finished(batch.height) {
self.menu.win = None;
}
} else if self.menu.options_open {
self.menu
.options
+150
View File
@@ -0,0 +1,150 @@
//! `WinScreen` in the game: the poem and credits after leaving the End for
//! the first time (`EndPortalBlock.entityInside` -> `ServerPlayer.showEndCredits`,
//! or a server's `WIN_GAME` event), and the credits from Credits &
//! Attribution.
use super::{Game, Screen};
use horizon_client::{
Result,
hud::{EndPortalFill, HudBatch},
win_screen::{Key, WinScreen},
};
use std::time::Instant;
use winit::{
event::{ElementState, KeyEvent},
keyboard::{KeyCode, PhysicalKey},
};
/// What closing the screen does (`WinScreen.onFinished`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Finish {
/// `PERFORM_RESPAWN` in single player: the player, out of the End since
/// the credits began, arrives in the Overworld.
Respawn,
/// `PERFORM_RESPAWN` sent to the server.
RemoteRespawn,
/// Back to Credits & Attribution.
Options,
/// Back to the game (`horizon-ctl credits`).
Closed,
}
pub(super) struct Win {
screen: WinScreen,
finish: Finish,
/// The last drawn frame, for the scroll's game-time delta.
frame: Instant,
}
impl Game<'_> {
pub(super) fn open_win_screen(&mut self, poem: bool, finish: Finish) {
let screen = WinScreen::new(
poem,
&self.options.resources,
&self.options.player_name(),
&self.gui.atlas.font,
);
self.win = Some(Win {
screen,
finish,
frame: Instant::now(),
});
self.keys.clear();
self.screen = Screen::Win;
self.capture(false);
}
/// `ServerPlayer.showEndCredits`: the player leaves the End now (no
/// longer in any level until the credits end) and has seen the credits.
pub(super) fn show_end_credits(&mut self) -> Result<()> {
self.level.seen_credits = true;
self.open_win_screen(true, Finish::Respawn);
self.end_portal_travel = true;
let result = self.enter_dimension(super::Dim::Overworld);
self.end_portal_travel = false;
result
}
/// Stop the scroll `scroll` pixels in (`horizon-ctl credits ... SCROLL`).
pub(super) fn hold_win_screen(&mut self, scroll: f32) {
if let Some(win) = self.win.as_mut() {
win.screen.hold(scroll);
}
}
/// `WinScreen.isPauseScreen`: only the credits without the poem pause.
pub(super) fn win_screen_pauses(&self) -> bool {
self.win.as_ref().is_some_and(|w| !w.screen.poem)
}
/// The player waits out of the world while the poem rolls.
pub(super) fn win_screen_holds_arrival(&self) -> bool {
self.win
.as_ref()
.is_some_and(|w| w.finish == Finish::Respawn)
}
pub(super) fn draw_win_screen(&mut self, batch: &mut HudBatch) {
let Some(win) = self.win.as_mut() else {
return;
};
let now = Instant::now();
// DeltaTracker.getGameTimeDeltaTicks: the frame's length in ticks.
let delta_ticks =
now.duration_since(win.frame).as_secs_f32() / self.clock.tick_duration().as_secs_f32();
win.frame = now;
let sprite = |n: &str| {
self.gui
.atlas
.sprites
.get(n)
.map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0])
};
let fill = EndPortalFill {
sprites: [
sprite("environment/end_sky"),
sprite("entity/end_portal/end_portal"),
],
game_time: (self.world.game_time % 24000) as f32 / 24000.0,
};
win.screen.draw(batch, &self.gui.atlas, delta_ticks, fill);
}
/// `WinScreen.keyPressed` / `keyReleased`; Escape closes it (`onClose`).
pub(super) fn win_key(&mut self, event: &KeyEvent) -> Result<()> {
let PhysicalKey::Code(code) = event.physical_key else {
return Ok(());
};
let pressed = event.state == ElementState::Pressed;
if code == KeyCode::Escape && pressed {
return self.close_win_screen();
}
let Some(key) = Key::from_code(code) else {
return Ok(());
};
if let Some(win) = self.win.as_mut() {
win.screen.key(key, pressed);
}
Ok(())
}
/// `WinScreen.tick`: done once everything has rolled past the top.
pub(super) fn tick_win_screen(&mut self) -> Result<()> {
let height = self.gui_size().1;
if self.win.as_ref().is_some_and(|w| w.screen.finished(height)) {
self.close_win_screen()?;
}
Ok(())
}
/// `WinScreen.respawn` (`onFinished`) and `removed`: the credits music stops.
pub(super) fn close_win_screen(&mut self) -> Result<()> {
let Some(win) = self.win.take() else {
return Ok(());
};
let credits = horizon_client::music::Music::credits();
self.music
.stop_playing_music(&credits, None, &mut self.audio);
match win.finish {
Finish::Options => self.screen = Screen::Options,
Finish::Closed if self.title.is_some() => self.screen = Screen::Playing,
Finish::Respawn | Finish::RemoteRespawn | Finish::Closed => {
if win.finish == Finish::RemoteRespawn {
self.remote_respawn();
}
self.screen = Screen::Playing;
self.capture(true);
}
}
Ok(())
}
}
+98 -10
View File
@@ -395,6 +395,8 @@ pub struct HudBatch {
pub patches: Vec<crate::font::Patch>,
/// Vertex ranges with another blend or depth/scissor state, in order.
pub blends: Vec<(std::ops::Range<u32>, Blend)>,
/// The textures and time of the `Blend::EndPortal` runs.
pub end_portal: EndPortalFill,
/// Screen's first vertex: the preceding HUD is part of its blurred background.
pub blur_at: u32,
}
@@ -409,6 +411,19 @@ pub enum Blend {
Additive,
/// Alpha blending with an isolated depth buffer and a pixel scissor.
Depth([u32; 4]),
/// `RenderPipelines.VIGNETTE`: the destination darkened by the texture
/// (`ZERO, ONE_MINUS_SRC_COLOR`).
Vignette,
/// `RenderPipelines.END_PORTAL` as a GUI fill: the End portal's layers
/// projected from the screen (`HudBatch::end_portal` sets the textures).
EndPortal,
}
/// What a `Blend::EndPortal` fill samples: the atlas rects (u0, v0, width,
/// height) of `end_sky.png` and `end_portal.png`, and the `GameTime` uniform.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct EndPortalFill {
pub sprites: [[f32; 4]; 2],
pub game_time: f32,
}
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)
@@ -432,6 +447,7 @@ impl HudBatch {
height: (window[1] as f32 / scale as f32).ceil(),
patches: Vec::new(),
blends: Vec::new(),
end_portal: EndPortalFill::default(),
blur_at: 0,
}
}
@@ -738,7 +754,12 @@ impl HudBatch {
let mut glyphs = Vec::new();
let mut cursor = x;
for (i, (ch, style)) in text.chars().enumerate() {
let g = font.glyph(ch);
let mut g = font.glyph(ch);
// Font.StringRenderOutput.accept: obfuscated characters draw a
// random glyph of the same width each frame.
if style.obfuscated == Some(true) && ch != ' ' {
g = font.random_glyph(g.advance);
}
let c = style.color.map_or(color, |rgb| {
rgba((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8, alpha)
});
@@ -832,6 +853,20 @@ impl HudBatch {
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct HudUniform {
size: [f32; 4],
/// `EndPortalFill`: the two sprites, then the game time in x.
end_portal: [[f32; 4]; 3],
}
impl HudUniform {
fn new(size: [f32; 4], fill: EndPortalFill) -> Self {
Self {
size,
end_portal: [
fill.sprites[0],
fill.sprites[1],
[fill.game_time, 0.0, 0.0, 0.0],
],
}
}
}
pub struct HudRenderer {
pub fire_animations: Vec<(Rect, crate::sprites::SpriteAnimation, usize)>,
@@ -842,6 +877,8 @@ pub struct HudRenderer {
invert_pipeline: wgpu::RenderPipeline,
additive_pipeline: wgpu::RenderPipeline,
depth_pipeline: wgpu::RenderPipeline,
vignette_pipeline: wgpu::RenderPipeline,
end_portal_pipeline: wgpu::RenderPipeline,
group: wgpu::BindGroup,
uniform: wgpu::Buffer,
buffer: wgpu::Buffer,
@@ -864,7 +901,7 @@ impl HudRenderer {
});
let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("HUD size"),
contents: bytemuck::bytes_of(&HudUniform { size: [1.0; 4] }),
contents: bytemuck::bytes_of(&HudUniform::new([1.0; 4], EndPortalFill::default())),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
});
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
@@ -872,7 +909,7 @@ impl HudRenderer {
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
@@ -1000,6 +1037,31 @@ impl HudRenderer {
"fs_main",
false,
);
// RenderPipelines.VIGNETTE: ZERO, ONE_MINUS_SRC_COLOR, ZERO, ONE.
let vignette_pipeline = create(
"HUD vignette",
wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Zero,
dst_factor: wgpu::BlendFactor::OneMinusSrc,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Zero,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
},
"fs_main",
false,
);
// RenderPipelines.END_PORTAL: opaque.
let end_portal_pipeline = create(
"HUD end portal",
wgpu::BlendState::REPLACE,
"fs_end_portal",
false,
);
let capacity = 1 << 16;
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("HUD vertices"),
@@ -1014,6 +1076,8 @@ impl HudRenderer {
invert_pipeline,
additive_pipeline,
depth_pipeline,
vignette_pipeline,
end_portal_pipeline,
group,
uniform,
buffer,
@@ -1107,9 +1171,10 @@ impl HudRenderer {
encoder,
&self.uniform,
0,
bytemuck::bytes_of(&HudUniform {
size: [size[0] as f32, size[1] as f32, batch.scale, 0.0],
}),
bytemuck::bytes_of(&HudUniform::new(
[size[0] as f32, size[1] as f32, batch.scale, 0.0],
batch.end_portal,
)),
);
}
/// Draw the batch `prepare` staged.
@@ -1197,6 +1262,8 @@ impl HudRenderer {
Blend::Invert => &self.invert_pipeline,
Blend::Additive => &self.additive_pipeline,
Blend::Depth(_) => &self.depth_pipeline,
Blend::Vignette => &self.vignette_pipeline,
Blend::EndPortal => &self.end_portal_pipeline,
});
pass.draw(range.clone(), 0..1);
}
@@ -1209,10 +1276,10 @@ impl HudRenderer {
mod tests {
use super::*;
#[test]
fn the_fonts_only_atlas_measures_text_like_the_full_one() {
// A synthetic default font: two 8x8 glyphs, 3 and 5 pixels wide.
let root = std::env::temp_dir().join(format!("horizon-fonts-atlas-{}", std::process::id()));
/// A synthetic default font: two 8x8 glyphs, 3 and 5 pixels wide.
fn two_glyph_font(name: &str) -> std::path::PathBuf {
let root =
std::env::temp_dir().join(format!("horizon-fonts-{name}-{}", std::process::id()));
let font = root.join("assets/minecraft/font");
let textures = root.join("assets/minecraft/textures/font");
fs::create_dir_all(&font).unwrap();
@@ -1237,6 +1304,11 @@ mod tests {
.unwrap()
.write_image_data(&pixels)
.unwrap();
root
}
#[test]
fn the_fonts_only_atlas_measures_text_like_the_full_one() {
let root = two_glyph_font("atlas");
let full = HudAtlas::build(&root).unwrap();
let fonts = HudAtlas::fonts(&root).unwrap();
let _ = fs::remove_dir_all(&root);
@@ -1245,6 +1317,21 @@ mod tests {
assert!(width > 0.0);
assert_eq!(fonts.font.width("abba"), width);
}
#[test]
fn obfuscated_glyphs_keep_the_width() {
let root = two_glyph_font("obfuscated");
let fonts = HudAtlas::fonts(&root).unwrap();
let _ = fs::remove_dir_all(&root);
let (a, b) = (fonts.font.glyph('a').advance, fonts.font.glyph('b').advance);
assert_ne!(a, b);
for _ in 0..20 {
assert_eq!(fonts.font.random_glyph(a).advance, a);
assert_eq!(fonts.font.random_glyph(b).advance, b);
}
// No glyph that wide: FontSet's missing glyph.
let missing = fonts.font.random_glyph(30.0);
assert!(missing.rect.is_none() && missing.right == 5.0);
}
#[test]
fn effect_icons_are_painted_from_the_mob_effect_directory() {
@@ -1429,6 +1516,7 @@ mod tests {
height: height as f32,
patches: Vec::new(),
blends: Vec::new(),
end_portal: EndPortalFill::default(),
blur_at: 0,
};
for (image_width, image_height) in [(195, 136), (176, 166), (176, 222)] {
+50 -1
View File
@@ -1,4 +1,9 @@
struct Hud { size: vec4<f32> }
struct Hud {
size: vec4<f32>,
// Blend::EndPortal: atlas rects (u0, v0, width, height) of end_sky.png and
// end_portal.png, then vanilla's GameTime in x.
end_portal: array<vec4<f32>, 3>,
}
@group(0) @binding(0) var<uniform> hud: Hud;
@group(0) @binding(1) var atlas: texture_2d<f32>;
@group(0) @binding(2) var atlas_sampler: sampler;
@@ -6,6 +11,8 @@ struct Out {
@builtin(position) clip: vec4<f32>,
@location(0) uv: vec2<f32>,
@location(1) color: vec4<f32>,
// projection_from_position(gl_Position): the End portal's texProj0.
@location(2) proj: vec4<f32>,
}
@vertex fn vs_main(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>, @location(2) color: vec4<f32>, @location(3) depth: f32) -> Out {
let pixels = pos * hud.size.z;
@@ -13,6 +20,7 @@ struct Out {
out.clip = vec4(pixels.x / hud.size.x * 2.0 - 1.0, 1.0 - pixels.y / hud.size.y * 2.0, depth, 1.0);
out.uv = uv;
out.color = color;
out.proj = vec4(out.clip.xy * 0.5 + 0.5, out.clip.zw);
return out;
}
@fragment fn fs_main(in: Out) -> @location(0) vec4<f32> {
@@ -31,3 +39,44 @@ struct Out {
if c.a == 0.0 { discard; }
return c;
}
// rendertype_end_portal.fsh (entity.wgsl has the same for portal blocks).
const PORTAL_COLORS = array<vec3<f32>, 16>(
vec3(0.022087, 0.098399, 0.110818),
vec3(0.011892, 0.095924, 0.089485),
vec3(0.027636, 0.101689, 0.100326),
vec3(0.046564, 0.109883, 0.114838),
vec3(0.064901, 0.117696, 0.097189),
vec3(0.063761, 0.086895, 0.123646),
vec3(0.084817, 0.111994, 0.166380),
vec3(0.097489, 0.154120, 0.091064),
vec3(0.106152, 0.131144, 0.195191),
vec3(0.097721, 0.110188, 0.187229),
vec3(0.133516, 0.138278, 0.148582),
vec3(0.070006, 0.243332, 0.235792),
vec3(0.196766, 0.142899, 0.214696),
vec3(0.047281, 0.315338, 0.321970),
vec3(0.204675, 0.390010, 0.302066),
vec3(0.080955, 0.314821, 0.661491),
);
fn portal_sample(rect: vec4<f32>, p: vec4<f32>) -> vec3<f32> {
let st = fract(p.xy / p.w);
return textureSampleLevel(atlas, atlas_sampler, rect.xy + st * rect.zw, 0.0).rgb;
}
fn portal_layer(p: vec4<f32>, layer: f32) -> vec4<f32> {
let a = radians((layer * layer * 4321.0 + layer * 9.0) * 2.0);
let c = cos(a);
let s = sin(a);
let k = (4.5 - layer / 4.0) * 2.0;
var v = vec4(k * (c * p.x - s * p.y), k * (s * p.x + c * p.y), p.z, p.w);
v = vec4(v.x + 17.0 / layer * v.w, v.y + (2.0 + layer / 1.5) * (hud.end_portal[2].x * 1.5) * v.w, v.z, v.w);
return vec4(0.5 * v.x + 0.25 * v.w, 0.5 * v.y + 0.25 * v.w, v.z, v.w);
}
// RenderPipelines.END_PORTAL (WinScreen's poem background): end_sky and 15
// layers of end_portal.png.
@fragment fn fs_end_portal(in: Out) -> @location(0) vec4<f32> {
var c = portal_sample(hud.end_portal[0], in.proj) * PORTAL_COLORS[0];
for (var i = 0; i < 15; i++) {
c += portal_sample(hud.end_portal[1], portal_layer(in.proj, f32(i + 1))) * PORTAL_COLORS[i];
}
return vec4(c, 1.0);
}
+1
View File
@@ -188,6 +188,7 @@ pub mod vanillagen;
pub mod vault;
pub mod weather;
pub mod widgets;
pub mod win_screen;
pub mod window;
pub mod world;
pub mod world_spawn;
+58 -3
View File
@@ -871,6 +871,8 @@ pub enum Page {
Controller,
PadBinds,
Extras,
/// CreditsAndAttributionScreen.
Credits,
/// Horizon Settings: every page Horizon adds, as a mod's settings
/// screen hangs off vanilla's Options.
Horizon,
@@ -896,6 +898,8 @@ enum Act {
/// Pick shader pack `i` of `OptionsUi::shader_packs` (again: off).
ToggleShaderPack(usize),
OpenShaderPackFolder,
/// Credits & Attribution's Credits button (WinScreen without the poem).
Credits,
CopyAgentDetails,
}
enum WKind {
@@ -946,6 +950,8 @@ pub enum Event {
OpenModFolder,
/// Create `shaderpacks/` if needed and open it.
OpenShaderPackFolder,
/// Roll the credits (`CreditsAndAttributionScreen.openCreditsScreen`).
Credits,
/// Copy how an agent connects (the AI Agent page).
CopyAgentDetails,
}
@@ -1213,6 +1219,7 @@ impl OptionsUi {
Page::Controller => "Controller Settings",
Page::PadBinds => "Controller Binds",
Page::Extras => "Horizon Extras",
Page::Credits => "credits_and_attribution.screen.title",
Page::Horizon => "Horizon Settings",
Page::Agent => "AI Agent",
}
@@ -1633,10 +1640,13 @@ impl OptionsUi {
("options.accessibility", Some(Page::Accessibility)),
// Vanilla's Telemetry Data and Credits slots: Horizon's
// settings and its mods, as a mod adds its button here.
// Credits & Attribution (WinScreen's credits) follows them.
("Horizon Settings...", Some(Page::Horizon)),
("Mods...", Some(Page::Mods)),
("options.credits_and_attribution", Some(Page::Credits)),
];
let gy = (61.0 + 30.0f32).min(h - 33.0 - 120.0);
let rows = entries.len().div_ceil(2) as f32;
let gy = (61.0 + 30.0f32).min(h - 33.0 - rows * 24.0);
for (i, (key, page)) in entries.iter().enumerate() {
let x = cx - 158.0 + 4.0 + (i % 2) as f32 * 158.0;
let y = gy + (i / 2) as f32 * 24.0;
@@ -1647,6 +1657,46 @@ impl OptionsUi {
top = 0.0;
bottom = 0.0;
}
Page::Credits => {
// CreditsAndAttributionScreen: the title header, three 210-wide
// buttons 8 apart (HeaderAndFooterLayout: 30 below the header
// unless the footer is closer), Done.
out.push(Widget {
x: 0.0,
y: 12.0,
w,
h: 9.0,
kind: WKind::Text {
text: tr(Self::title(page)),
color: u32::MAX,
centered: true,
},
list: false,
});
let y = (33.0 + 30.0f32).min(h - 33.0 - 76.0);
let x = cx - 105.0;
out.push(button(
x,
y,
210.0,
tr("credits_and_attribution.button.credits"),
Act::Credits,
));
// ConfirmLinkScreen to minecraft.net: Horizon opens no links.
for (i, key) in [
"credits_and_attribution.button.attribution",
"credits_and_attribution.button.licenses",
]
.into_iter()
.enumerate()
{
let y = y + 28.0 * (i + 1) as f32;
out.push(inactive(button(x, y, 210.0, tr(key), Act::None)));
}
out.push(done(h - 27.0));
top = 0.0;
bottom = 0.0;
}
Page::KeyBinds => {
top = 38.0;
out.push(Widget {
@@ -2537,6 +2587,7 @@ impl OptionsUi {
events.push(Event::Changed);
}
Act::OpenShaderPackFolder => events.push(Event::OpenShaderPackFolder),
Act::Credits => events.push(Event::Credits),
Act::CopyAgentDetails => events.push(Event::CopyAgentDetails),
Act::None => {}
}
@@ -4172,9 +4223,13 @@ mod tests {
})
.collect()
};
// Vanilla's ten Options buttons, the last two Horizon's.
// Vanilla's Options buttons, Horizon's two in the Telemetry and Credits slots, then
// Credits & Attribution (WinScreen's credits).
let main = pushes(&mut ui);
assert_eq!(&main[main.len() - 2..], [Page::Horizon, Page::Mods]);
assert_eq!(
&main[main.len() - 3..],
[Page::Horizon, Page::Mods, Page::Credits]
);
ui.push(Page::Horizon);
assert_eq!(
pushes(&mut ui),
+4
View File
@@ -2274,6 +2274,8 @@ pub struct Level {
pub inventory_components: HashMap<u8, Box<crate::item_data::StackData>>,
/// Player.XpSeed: the enchanting table seed.
pub xp_seed: i32,
/// ServerPlayer.seenCredits: the end poem has been shown.
pub seen_credits: bool,
/// Player.active_effects: (id, duration, amplifier, ambient, show_icon).
pub active_effects: Vec<(String, i32, i32, bool, bool)>,
/// Player.EnderItems: the ender chest inventory (27 slots).
@@ -2465,6 +2467,7 @@ impl Level {
self.selected_slot = n("SelectedItemSlot").unwrap_or(0) as i32;
self.fall_distance = f("fall_distance").unwrap_or(0.0);
self.on_ground = n("OnGround").unwrap_or(0) != 0;
self.seen_credits = n("seenCredits").unwrap_or(0) != 0;
if let Some(mode) = n("playerGameType") {
self.creative = mode == 1;
self.game_mode = mode as i32;
@@ -2686,6 +2689,7 @@ impl Level {
if let Some(pos) = self.position {
entries.push(("Pos", doubles(&pos)));
}
entries.push(("seenCredits", Tag::Byte(i8::from(self.seen_credits))));
// A respawn point other than the world spawn: an anchor elsewhere, or a bed.
if let Some((dimension, block, yaw, forced)) = &self.respawn_elsewhere {
let mut respawn = vec![
+452
View File
@@ -0,0 +1,452 @@
//! `WinScreen`: the end poem, the credits and the post-credits text rolling up
//! under the logo, after the player leaves the End for the first time (with
//! the poem) or from Credits & Attribution (the credits alone). The texts come
//! from the resource root, so resource packs can replace them.
use crate::{
font::Font,
hud::{Blend, EndPortalFill, HudAtlas, HudBatch},
text::{self, Style, Text},
};
use horizon_core::random::{LegacyRandom, RandomSource};
use std::{collections::HashSet, path::Path};
/// `WinScreen.OBFUSCATE_TOKEN`: `§f§k§a§b` marks where the poem hides a name.
const OBFUSCATE_TOKEN: &str = "\u{a7}f\u{a7}k\u{a7}a\u{a7}b";
/// `WinScreen.NAME_PREFIX`.
const NAME_PREFIX: &str = " ";
/// `WinScreen.SECTION_HEADING`.
const SECTION_HEADING: &str = "============";
/// A key the screen reacts to (`keyPressed` / `keyReleased`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Key {
/// `KeyEvent.isUp`: the up arrow scrolls back.
Up,
/// Space speeds the scroll up.
Space,
/// Each held Control key speeds it up more.
LeftControl,
RightControl,
}
impl Key {
pub fn from_code(code: winit::keyboard::KeyCode) -> Option<Self> {
use winit::keyboard::KeyCode;
match code {
KeyCode::ArrowUp => Some(Self::Up),
KeyCode::Space => Some(Self::Space),
KeyCode::ControlLeft => Some(Self::LeftControl),
KeyCode::ControlRight => Some(Self::RightControl),
_ => None,
}
}
}
pub struct WinScreen {
pub poem: bool,
lines: Vec<Text>,
centered: HashSet<usize>,
total_scroll_length: i32,
scroll: f32,
speedup_active: bool,
speedup_modifiers: HashSet<Key>,
unmodified_scroll_speed: f32,
scroll_speed: f32,
direction: i32,
}
impl WinScreen {
/// `WinScreen.<init>` and `init`: the poem (`texts/end.txt`) when `poem`,
/// the credits (`texts/credits.json`), then `texts/postcredits.txt`.
pub fn new(poem: bool, root: &Path, player: &str, font: &Font) -> Self {
let speed = if poem { 0.5 } else { 0.75 };
let mut screen = Self {
poem,
lines: Vec::new(),
centered: HashSet::new(),
total_scroll_length: 0,
scroll: 0.0,
speedup_active: false,
speedup_modifiers: HashSet::new(),
unmodified_scroll_speed: speed,
scroll_speed: speed,
direction: 1,
};
let texts = root.join("assets/minecraft/texts");
let read = |name: &str| match std::fs::read_to_string(texts.join(name)) {
Ok(s) => Some(s),
Err(e) => {
log::error!("Couldn't load credits from file minecraft:texts/{name}: {e}");
None
}
};
if poem && let Some(s) = read("end.txt") {
screen.add_poem_file(&s, player, font);
}
if let Some(s) = read("credits.json") {
match serde_json::from_str(&s) {
Ok(json) => screen.add_credits_file(&json),
Err(e) => {
log::error!("Couldn't load credits from file minecraft:texts/credits.json: {e}")
}
}
}
if poem && let Some(s) = read("postcredits.txt") {
screen.add_poem_file(&s, player, font);
}
screen.total_scroll_length = screen.lines.len() as i32 * 12;
screen
}
/// `addPoemFile`: each line with the player's name in, its obfuscated
/// spans turned into 3 to 6 scrambled characters, wrapped at 256 pixels
/// and followed by an empty line; 8 more empty lines at the end.
fn add_poem_file(&mut self, file: &str, player: &str, font: &Font) {
let mut random = LegacyRandom::new(8124371);
// BufferedReader.readLine: \n, \r or \r\n end a line; no empty last line.
let mut lines: Vec<&str> = file
.split('\n')
.map(|l| l.strip_suffix('\r').unwrap_or(l))
.collect();
if file.ends_with('\n') {
lines.pop();
}
for line in lines.iter().flat_map(|l| l.split('\r')) {
let mut line = line.replace("PLAYERNAME", player);
while let Some(pos) = line.find(OBFUSCATE_TOKEN) {
let n = random.next_int_bound(4).unwrap_or(0) as usize + 3;
line = format!(
"{}\u{a7}f\u{a7}k{}{}",
&line[..pos],
&"XXXXXXXX"[..n],
&line[pos + OBFUSCATE_TOKEN.len()..]
);
}
let text = Text::legacy(&line);
self.lines
.extend(font.split_lines(&text, 256.0).into_iter().map(|(t, _)| t));
self.add_empty_line();
}
for _ in 0..8 {
self.add_empty_line();
}
}
/// `addCreditsFile`: each section's heading, then each discipline's name
/// and its titles with the names under them.
fn add_credits_file(&mut self, json: &serde_json::Value) {
let colored = |s: &str, color: u32| Text::styled(s, Style::color(color));
let heading = || colored(SECTION_HEADING, text::WHITE);
for section in json.as_array().into_iter().flatten() {
let name = section["section"].as_str().unwrap_or_default();
self.add_credits_line(heading(), true);
self.add_credits_line(colored(name, text::YELLOW), true);
self.add_credits_line(heading(), true);
self.add_empty_line();
self.add_empty_line();
for discipline in section["disciplines"].as_array().into_iter().flatten() {
let name = discipline["discipline"].as_str().unwrap_or_default();
if !name.is_empty() {
self.add_credits_line(colored(name, text::YELLOW), true);
self.add_empty_line();
self.add_empty_line();
}
for title in discipline["titles"].as_array().into_iter().flatten() {
let name = title["title"].as_str().unwrap_or_default();
self.add_credits_line(colored(name, text::GRAY), false);
for name in title["names"].as_array().into_iter().flatten() {
let line = format!("{NAME_PREFIX}{}", name.as_str().unwrap_or_default());
self.add_credits_line(colored(&line, text::WHITE), false);
}
self.add_empty_line();
self.add_empty_line();
}
}
}
}
fn add_empty_line(&mut self) {
self.lines.push(Text::empty());
}
fn add_credits_line(&mut self, line: Text, centered: bool) {
if centered {
self.centered.insert(self.lines.len());
}
self.lines.push(line);
}
/// The lines in order and whether each is centred.
pub fn lines(&self) -> impl Iterator<Item = (&Text, bool)> {
self.lines
.iter()
.enumerate()
.map(|(i, l)| (l, self.centered.contains(&i)))
}
fn calculate_scroll_speed(&self) -> f32 {
let speed = if self.speedup_active {
self.unmodified_scroll_speed * (5.0 + self.speedup_modifiers.len() as f32 * 15.0)
} else {
self.unmodified_scroll_speed
};
speed * self.direction as f32
}
/// `keyPressed` / `keyReleased` (Escape closes the screen: `onClose`).
pub fn key(&mut self, key: Key, pressed: bool) {
match (key, pressed) {
(Key::Up, _) => self.direction = if pressed { -1 } else { 1 },
(Key::Space, _) => self.speedup_active = pressed,
(_, true) => {
self.speedup_modifiers.insert(key);
}
(_, false) => {
self.speedup_modifiers.remove(&key);
}
}
self.scroll_speed = self.calculate_scroll_speed();
}
/// `tick`: once the text has rolled past the top, the screen is done
/// (`respawn`, or back to the screen that opened it).
pub fn finished(&self, height: f32) -> bool {
let height = height as i32;
self.scroll > (self.total_scroll_length + height + height + 24) as f32
}
pub fn scroll(&self) -> f32 {
self.scroll
}
/// Stay `scroll` pixels in (until a key changes the speed), for
/// screenshots.
pub fn hold(&mut self, scroll: f32) {
self.scroll = scroll;
self.scroll_speed = 0.0;
}
/// `extractRenderState` after a frame of `delta_ticks` game ticks:
/// `extractBackground`, the vignette, then the logo and the lines
/// scrolled up. The poem's End portal background samples `end_portal`;
/// the credits draw the scrolling menu background (over the blurred
/// panorama on the title screen).
pub fn draw(
&mut self,
batch: &mut HudBatch,
atlas: &HudAtlas,
delta_ticks: f32,
end_portal: EndPortalFill,
) {
let (w, h) = (batch.width, batch.height);
if self.poem {
let start = batch.vertices.len();
batch.fill(atlas, 0.0, 0.0, w, h, u32::MAX);
batch.blend_since(start, Blend::EndPortal);
batch.end_portal = end_portal;
} else {
self.menu_background(batch, atlas, w, h);
}
// extractVignette: credits_vignette.png stretched over the screen.
if let Some(r) = atlas.sprites.get("misc/credits_vignette").copied() {
let start = batch.vertices.len();
batch.rect_uv(0.0, 0.0, w, h, r, u32::MAX);
batch.blend_since(start, Blend::Vignette);
}
self.scroll = (self.scroll + delta_ticks * self.scroll_speed).max(0.0);
let logo_x = (w / 2.0).floor() - 128.0;
let logo_y = h + 50.0;
// Everything below is drawn translated by `y_offs`.
let y_offs = -self.scroll;
// LogoRenderer(false) at full alpha.
let edition_x = (w / 2.0).floor() - 64.0;
batch.sprite_region(
atlas,
"gui/title/minecraft",
[logo_x, logo_y + y_offs, 256.0, 44.0],
256.0,
64.0,
);
batch.sprite_region(
atlas,
crate::title_edition::SPRITE,
[edition_x, logo_y + 44.0 - 7.0 + y_offs, 128.0, 14.0],
128.0,
16.0,
);
let mut y_pos = logo_y + 100.0;
let last = self.lines.len().saturating_sub(1);
for (i, line) in self.lines.iter().enumerate() {
let mut shift = y_offs;
if i == last {
// The last line stops in the middle of the screen.
let diff = y_pos + y_offs - ((h as i32 / 2) as f32 - 6.0);
if diff < 0.0 {
shift -= diff;
}
}
if y_pos + y_offs + 12.0 + 8.0 > 0.0 && y_pos + y_offs < h {
let x = if self.centered.contains(&i) {
// GuiGraphicsExtractor.centeredText: x - width / 2.
logo_x + 128.0 - (atlas.font.width_text(line) as i32 / 2) as f32
} else {
logo_x
};
batch.text_styled(atlas, line, x, y_pos + shift, u32::MAX, true);
}
y_pos += 12.0;
}
}
/// `extractMenuBackground`: `menu_background.png` tiled at 32 pixels,
/// scrolled by half the text's scroll.
fn menu_background(&self, batch: &mut HudBatch, atlas: &HudAtlas, w: f32, h: f32) {
let v = (self.scroll * 0.5).rem_euclid(32.0);
let start = batch.vertices.len();
crate::ui::tiled(
batch,
atlas,
"gui/menu_background",
0.0,
-v,
w,
h + 32.0,
32.0,
u32::MAX,
);
batch.clip_since(start, 0.0, 0.0, w, h);
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A resource root with only the credits texts: every glyph is the
/// missing one, 6 pixels wide.
fn screen(poem: bool, end: &str, credits: &str, post: &str) -> WinScreen {
let root = std::env::temp_dir().join(format!(
"horizon-win-screen-{}-{poem}-{}",
std::process::id(),
end.len()
));
let texts = root.join("assets/minecraft/texts");
std::fs::create_dir_all(&texts).unwrap();
std::fs::write(texts.join("end.txt"), end).unwrap();
std::fs::write(texts.join("credits.json"), credits).unwrap();
std::fs::write(texts.join("postcredits.txt"), post).unwrap();
let atlas = HudAtlas::fonts(&root).unwrap();
let screen = WinScreen::new(poem, &root, "Steve", &atlas.font);
let _ = std::fs::remove_dir_all(&root);
screen
}
const CREDITS: &str = r#"[{"section":"Studio","disciplines":[
{"discipline":"","titles":[{"title":"Head","names":["Ada","Bo"]}]},
{"discipline":"Art","titles":[{"title":"Artist","names":[]}]}]}]"#;
#[test]
fn the_poem_names_the_player_and_scrambles_its_hidden_names() {
let s = screen(
true,
"\u{a7}3Hello PLAYERNAME.\r\n\n\u{a7}2\u{a7}f\u{a7}k\u{a7}a\u{a7}bkey\n",
"[]",
"End.",
);
let lines: Vec<(String, bool)> = s.lines().map(|(t, c)| (t.plain(), c)).collect();
// Each line then an empty one; the empty line adds no text line; 8
// empty lines after each file.
let mut want = vec!["Hello Steve.", ""];
want.push("");
// LegacyRandom(8124371).nextInt(4) + 3 scrambled characters.
let n = LegacyRandom::new(8124371).next_int_bound(4).unwrap() as usize + 3;
let hidden = format!("{}key", &"XXXXXXXX"[..n]);
want.extend([hidden.as_str(), ""]);
want.extend([""; 8]);
want.extend(["End.", ""]);
want.extend([""; 8]);
assert_eq!(
lines,
want.iter()
.map(|l| (l.to_string(), false))
.collect::<Vec<_>>()
);
let hidden_line = s.lines().nth(3).unwrap().0;
let styles: Vec<_> = hidden_line.chars().map(|(_, s)| s.obfuscated).collect();
assert!(styles[..n].iter().all(|o| *o == Some(true)));
assert_eq!(s.total_scroll_length, lines.len() as i32 * 12);
}
#[test]
fn long_poem_lines_wrap_at_256_pixels() {
// 6-pixel glyphs: 42 fit a line, and the space at each break goes.
let line = vec!["a"; 50].join(" ");
let s = screen(true, &line, "[]", "");
let lines: Vec<String> = s.lines().take(4).map(|(t, _)| t.plain()).collect();
assert_eq!(
lines.iter().map(|l| l.chars().count()).collect::<Vec<_>>(),
[41, 41, 15, 0]
);
assert!(lines.iter().all(|l| !l.starts_with(' ')));
}
#[test]
fn credits_centre_the_headings_and_list_the_names() {
let s = screen(false, "ignored", CREDITS, "ignored");
let lines: Vec<(String, bool)> = s.lines().map(|(t, c)| (t.plain(), c)).collect();
let l = |s: &str, c| (s.to_string(), c);
let names = |n: &str| l(&format!("{NAME_PREFIX}{n}"), false);
assert_eq!(
lines,
vec![
l(SECTION_HEADING, true),
l("Studio", true),
l(SECTION_HEADING, true),
l("", false),
l("", false),
l("Head", false),
names("Ada"),
names("Bo"),
l("", false),
l("", false),
l("Art", true),
l("", false),
l("", false),
l("Artist", false),
l("", false),
l("", false),
]
);
let color = |i: usize| s.lines().nth(i).unwrap().0.chars().next().unwrap().1.color;
assert_eq!(
[color(0), color(1), color(5), color(6), color(10)],
[
Some(text::WHITE),
Some(text::YELLOW),
Some(text::GRAY),
Some(text::WHITE),
Some(text::YELLOW)
]
);
}
#[test]
fn keys_set_the_scroll_speed_and_direction() {
let mut s = screen(false, "", CREDITS, "");
assert_eq!(s.scroll_speed, 0.75);
s.key(Key::Space, true);
assert_eq!(s.scroll_speed, 0.75 * 5.0);
s.key(Key::LeftControl, true);
s.key(Key::RightControl, true);
assert_eq!(s.scroll_speed, 0.75 * 35.0);
s.key(Key::Up, true);
assert_eq!(s.scroll_speed, -0.75 * 35.0);
s.key(Key::Space, false);
assert_eq!(s.scroll_speed, -0.75);
s.key(Key::Up, false);
s.key(Key::LeftControl, false);
assert_eq!(s.scroll_speed, 0.75);
// The poem rolls at 0.5 pixels a tick.
assert_eq!(screen(true, "", CREDITS, "").scroll_speed, 0.5);
}
#[test]
fn the_screen_ends_once_everything_rolled_past() {
let mut s = screen(false, "", CREDITS, "");
let atlas = HudAtlas::fonts(Path::new("/nonexistent")).unwrap();
let mut batch = HudBatch::new([640, 480]);
let h = batch.height;
let end = (s.total_scroll_length as f32 + 2.0 * h + 24.0) / 0.75;
s.draw(&mut batch, &atlas, end - 1.0, EndPortalFill::default());
assert!(!s.finished(h));
// Scrolling back never goes above the start.
s.key(Key::Up, true);
s.draw(&mut batch, &atlas, end * 2.0, EndPortalFill::default());
assert_eq!(s.scroll(), 0.0);
s.key(Key::Up, false);
s.draw(&mut batch, &atlas, end + 1.0, EndPortalFill::default());
assert!(s.finished(h));
}
}