From 79ee670d7915a1ea4e7cdd4355053aa1a1ff513f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:59:07 +0200 Subject: [PATCH] High-resolution resource packs draw the GUI at its size With Faithful 32x the inventory showed the top-left quarter of its background stretched over the screen, tooltips lost their background and toasts doubled in size (#1442): the GUI code drew every atlas sprite in texels, where vanilla draws in GUI units whatever the pack's resolution. - Atlas sprites carry their GUI size: the size of the default resources' texture of that name (what vanilla's `blit(..., 256, 256)` calls and sprite sizes assume), their texels only for what copies pixels (font sheets, fire frames). Textures only a pack has keep their own size. The texture size filter reads the GUI size too, so Faithful 64x's 1024x1024 container backgrounds are no longer dropped. - Nine-slice sprites follow `GuiGraphicsExtractor.blitNineSlicedSprite`: their `gui.scaling` width, height and borders (Faithful's tooltip background is 50x50 with a 10-pixel border), `stretch_inner`, the single-quad and three-part cases, and borders capped at half the drawn size by integer division. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/font.rs | 5 +- crates/horizon-client/src/game.rs | 10 +- crates/horizon-client/src/game/packs.rs | 2 +- crates/horizon-client/src/hud.rs | 128 +++++++-- crates/horizon-client/src/ui.rs | 329 ++++++++++++++++++------ 5 files changed, 378 insertions(+), 96 deletions(-) diff --git a/crates/horizon-client/src/font.rs b/crates/horizon-client/src/font.rs index c5e5760f3..a25568df5 100644 --- a/crates/horizon-client/src/font.rs +++ b/crates/horizon-client/src/font.rs @@ -271,7 +271,10 @@ fn load_bitmap( .flatten(); // The sheet: its size, and its pixels when they are not in the atlas. let (sw, sh, sheet) = match in_atlas { - Some(rect) => (rect.w, rect.h, None), + Some(rect) => { + let (w, h) = rect.texels(atlas); + (w, h, None) + } None => match crate::hud::decode(&root.join(resource_path(file, "textures", ""))) { Ok((w, h, rgba)) => (w, h, Some(Arc::new((w, rgba)))), Err(_) => { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index df9400e4b..8d2d45a9e 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1021,9 +1021,11 @@ pub struct UiResources { pub panorama: Arc, } impl UiResources { - pub fn load(root: &std::path::Path) -> Result { + /// From a resource root layering packs over `defaults`, the game's own + /// resources (`root` itself when no pack is on). + pub fn load(root: &std::path::Path, defaults: &std::path::Path) -> Result { Ok(Self { - atlas: HudAtlas::build(root)?, + atlas: HudAtlas::build_over(root, defaults)?, panorama: Arc::new(horizon_client::gfx::panorama::Faces::load(root)), }) } @@ -12109,7 +12111,7 @@ fn load_resources( let mut loaded_gui = None; let mut ui_ready = false; let mut pack_error = None; - let ui = match UiResources::load(&root) { + let ui = match UiResources::load(&root, vanilla_root) { Ok(ui) => Some(ui), // Minecraft.rollbackResourcePacks: the packs' textures don't fit, start // with the game's own resources. @@ -12161,7 +12163,7 @@ fn load_resources( let render = Arc::new(render); // The menu bundle must come from the same root as the world bundle. if !ui_ready || root != requested_root { - let ui = UiResources::load(&root)?; + let ui = UiResources::load(&root, vanilla_root)?; if menu { horizon_client::telemetry::mark_ui_ready(); log::info!( diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index 94e61d948..ae2de00e6 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -133,7 +133,7 @@ impl Game<'_> { } fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> { let render = std::sync::Arc::new(self.pack.assets.reload(root)?); - let mut atlas = HudAtlas::build(root)?; + let mut atlas = HudAtlas::build_over(root, &self.vanilla_root())?; atlas.font.uniform = self.settings.force_unicode; atlas.font.japanese = self.settings.japanese_glyphs; let gui = super::UiResources { diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 1d0ab91b9..9d30ae0e6 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -9,6 +9,11 @@ use std::{ }; use wgpu::util::DeviceExt; +/// A sprite's atlas region, and its size in GUI pixels: the size of the +/// default resources' texture of that name, whatever the resolution of the +/// pack that replaced it (vanilla's GUI code draws in those units: `blit` +/// divides by the texture size it is given, sprites by their `gui.scaling` +/// size). Textures the default resources lack keep their own size. #[derive(Clone, Copy, Debug)] pub struct Rect { pub u0: f32, @@ -18,6 +23,15 @@ pub struct Rect { pub w: u32, pub h: u32, } +impl Rect { + /// The region's size in texels of an atlas this large. + pub fn texels(&self, (width, height): (u32, u32)) -> (u32, u32) { + ( + ((self.u1 - self.u0) * width as f32).round() as u32, + ((self.v1 - self.v0) * height as f32).round() as u32, + ) + } +} /// `TextureMetadataSection`'s `blur` and `clamp`: how vanilla samples a /// standalone texture (`ReloadableTexture.setSampler`: linear rather than /// nearest filtering, clamp-to-edge rather than repeat addressing). @@ -92,6 +106,15 @@ pub fn decode_bytes(data: &[u8]) -> Result<(u32, u32, Vec)> { } Ok((info.width, info.height, rgba)) } +/// A PNG's width and height, from its header alone. +fn png_size(path: &Path) -> Option<(u32, u32)> { + use std::io::Read; + let mut header = [0u8; 24]; + fs::File::open(path).ok()?.read_exact(&mut header).ok()?; + let field = |at: usize| u32::from_be_bytes(header[at..at + 4].try_into().unwrap_or_default()); + (header[..8] == *b"\x89PNG\r\n\x1a\n" && header[12..16] == *b"IHDR") + .then(|| (field(16), field(20))) +} fn walk(dir: &Path, out: &mut Vec) { let Ok(entries) = fs::read_dir(dir) else { return; @@ -204,8 +227,14 @@ impl HudAtlas { (g.rect, g.advance) } pub fn build(root: &Path) -> Result { + Self::build_over(root, root) + } + /// The atlas of a resource root that layers packs over `defaults` (the + /// game's own resources), whose textures give the sprites' GUI sizes. + pub fn build_over(root: &Path, defaults: &Path) -> Result { Self::pack( root, + defaults, &[ "gui", "item", @@ -268,7 +297,7 @@ impl HudAtlas { /// holding its textures. The pixels are dropped once the glyph widths are /// read, since nothing uploads them. pub fn fonts(root: &Path) -> Result { - let mut atlas = Self::pack(root, &["font"], false)?; + let mut atlas = Self::pack(root, root, &["font"], false)?; atlas.pixels = Vec::new(); Ok(atlas) } @@ -311,8 +340,10 @@ impl HudAtlas { } /// Pack the textures under these folders of `textures/`, and for the /// `full` atlas the generated sprites and the run-time slots too. - fn pack(root: &Path, folders: &[&str], full: bool) -> Result { + fn pack(root: &Path, defaults: &Path, folders: &[&str], full: bool) -> Result { let textures = root.join("assets/minecraft/textures"); + let default_textures = + (defaults != root).then(|| defaults.join("assets/minecraft/textures")); let mut files = Vec::new(); for folder in folders { walk(&textures.join(folder), &mut files); @@ -321,7 +352,8 @@ impl HudAtlas { let s = p.to_string_lossy(); !s.contains("title/background") && !s.contains("realms") && !s.contains("presets") }); - let decode_one = |path: &PathBuf| -> Option<(PackedImage, Option)> { + type Decoded = (PackedImage, Option, Option<(u32, u32)>); + let decode_one = |path: &PathBuf| -> Option { let name = path .strip_prefix(&textures) .ok()? @@ -329,18 +361,29 @@ impl HudAtlas { .to_string_lossy() .replace('\\', "/"); let (w, mut h, pixels) = decode(path).ok()?; - let is_frame_strip = (name.starts_with("block/") || name.starts_with("item/")) && h > w; - let pixels = if is_frame_strip { + // Animated strips keep their first frame. + let frames = name.starts_with("block/") || name.starts_with("item/"); + let pixels = if frames && h > w { h = w; pixels[..(w * w * 4) as usize].to_vec() } else { pixels }; + // The default texture's size, when a pack's differs from it. + let gui_size = default_textures + .as_ref() + .and_then(|d| png_size(&d.join(format!("{name}.png")))) + .map(|(dw, dh)| (dw, if frames { dh.min(dw) } else { dh })) + .filter(|&size| size != (w, h)); let flags = fs::read_to_string(path.with_extension("png.mcmeta")) .ok() .and_then(|json| TextureFlags::from_mcmeta(&json)); - (w <= 1024 && (h <= 512 || name.starts_with("font/"))) - .then_some(((name, w, h, pixels), flags)) + let (gw, gh) = gui_size.unwrap_or((w, h)); + (gw <= 1024 && (gh <= 512 || name.starts_with("font/"))).then_some(( + (name, w, h, pixels), + flags, + gui_size, + )) }; let threads = std::thread::available_parallelism().map_or(2, |n| n.get()); let chunk = files.len().div_ceil(threads).max(1); @@ -357,11 +400,15 @@ impl HudAtlas { .collect() }); let mut flags = HashMap::new(); + let mut gui_sizes = HashMap::new(); let mut images: Vec = Vec::with_capacity(decoded.len()); - for (image, image_flags) in decoded { + for (image, image_flags, gui_size) in decoded { if let Some(f) = image_flags { flags.insert(image.0.clone(), f); } + if let Some(size) = gui_size { + gui_sizes.insert(image.0.clone(), size); + } images.push(image); } if full { @@ -405,6 +452,7 @@ impl HudAtlas { } let b = u32::from(bordered.contains(name)); let (px, py, w, h) = (px + b, py + b, w - 2 * b, h - 2 * b); + let (gw, gh) = gui_sizes.get(name).copied().unwrap_or((w, h)); sprites.insert( name.clone(), Rect { @@ -412,8 +460,8 @@ impl HudAtlas { v0: py as f32 / height as f32, u1: (px + w) as f32 / width as f32, v1: (py + h) as f32 / height as f32, - w, - h, + w: gw, + h: gh, }, ); } @@ -433,14 +481,15 @@ impl HudAtlas { .find(|a| a.layer == layer) .cloned() { - let image = animation.resized_pixels(animation.frame(0), rect.w, rect.h); + let (tw, th) = rect.texels((width, height)); + let image = animation.resized_pixels(animation.frame(0), tw, th); let x = (rect.u0 * width as f32).round() as usize; let y = (rect.v0 * height as f32).round() as usize; - for row in 0..rect.h as usize { + let row_bytes = tw as usize * 4; + for row in 0..th as usize { let dst = ((y + row) * width as usize + x) * 4; - let src = row * rect.w as usize * 4; - pixels[dst..dst + rect.w as usize * 4] - .copy_from_slice(&image[src..src + rect.w as usize * 4]); + let src = row * row_bytes; + pixels[dst..dst + row_bytes].copy_from_slice(&image[src..src + row_bytes]); } fire_animations.push((rect, animation)); } @@ -1191,7 +1240,8 @@ impl HudRenderer { if frame == *previous { continue; } - let pixels = animation.resized_pixels(frame, rect.w, rect.h); + let (w, h) = rect.texels((texture.width(), texture.height())); + let pixels = animation.resized_pixels(frame, w, h); uploads.texture( encoder, wgpu::TexelCopyTextureInfo { @@ -1204,8 +1254,8 @@ impl HudRenderer { }, aspect: wgpu::TextureAspect::All, }, - rect.w, - rect.h, + w, + h, &pixels, ); *previous = frame; @@ -1383,6 +1433,48 @@ mod tests { ); } } + fn write_png(root: &Path, name: &str, w: u32, h: u32) { + let path = root.join(format!("assets/minecraft/textures/{name}.png")); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + let mut encoder = png::Encoder::new(fs::File::create(path).unwrap(), w, h); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + let pixels = vec![255; (w * h * 4) as usize]; + encoder + .write_header() + .unwrap() + .write_image_data(&pixels) + .unwrap(); + } + #[test] + fn a_pack_texture_keeps_the_default_textures_gui_size() { + let temp = std::env::temp_dir().join(format!("horizon-gui-size-{}", std::process::id())); + let (defaults, pack) = (temp.join("defaults"), temp.join("pack")); + write_png(&defaults, "gui/container/inventory", 256, 256); + write_png(&defaults, "gui/sprites/widget/button", 200, 20); + write_png(&defaults, "block/stone", 16, 16); + write_png(&defaults, "item/compass", 16, 512); + // Faithful 64x's inventory (past the 512 rows a texture may have), + // 32x's button and stone, an animated strip, and a texture of its own. + write_png(&pack, "gui/container/inventory", 1024, 1024); + write_png(&pack, "gui/sprites/widget/button", 400, 40); + write_png(&pack, "block/stone", 32, 32); + write_png(&pack, "item/compass", 32, 1024); + write_png(&pack, "gui/sprites/pack_only", 30, 10); + let atlas = HudAtlas::build_over(&pack, &defaults).unwrap(); + let _ = fs::remove_dir_all(&temp); + let size = (atlas.width, atlas.height); + for (name, gui, texels) in [ + ("gui/container/inventory", (256, 256), (1024, 1024)), + ("gui/sprites/widget/button", (200, 20), (400, 40)), + ("block/stone", (16, 16), (32, 32)), + ("item/compass", (16, 16), (32, 32)), + ("gui/sprites/pack_only", (30, 10), (30, 10)), + ] { + let r = atlas.sprites[name]; + assert_eq!(((r.w, r.h), r.texels(size)), (gui, texels), "{name}"); + } + } #[test] fn the_default_textures_keep_a_4096_wide_atlas() { let images = sized(400, 64, 64); diff --git a/crates/horizon-client/src/ui.rs b/crates/horizon-client/src/ui.rs index b1ffab866..8ddfa91ff 100644 --- a/crates/horizon-client/src/ui.rs +++ b/crates/horizon-client/src/ui.rs @@ -7,9 +7,40 @@ use crate::{ }; 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>> = RwLock::new(None); +/// `GuiSpriteScaling.NineSlice`: the sprite's size in GUI pixels, whatever +/// its texture's resolution, its borders (left, top, right, bottom) in the +/// same units, and whether the edges and centre stretch rather than tile. +#[derive(Clone, Copy, Debug, PartialEq)] +struct NineSlice { + width: u32, + height: u32, + border: [u32; 4], + stretch_inner: bool, +} +/// Nine-slice scaling from `.png.mcmeta` files. +static NINE_SLICE: RwLock>> = RwLock::new(None); +/// A `gui.scaling` section of type `nine_slice`. +fn parse_nine_slice(v: &serde_json::Value) -> Option { + let s = &v["gui"]["scaling"]; + if s["type"] != "nine_slice" { + return None; + } + let size = |k: &str| s[k].as_u64().map(|n| n as u32); + let border = &s["border"]; + let border = 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")] + }; + Some(NineSlice { + width: size("width")?, + height: size("height")?, + border, + stretch_inner: s["stretch_inner"].as_bool().unwrap_or(false), + }) +} /// Read `gui.scaling` metadata for every GUI sprite under `root`. pub fn load_metadata(root: &Path) { let mut map = HashMap::new(); @@ -32,47 +63,48 @@ pub fn load_metadata(root: &Path) { let Ok(text) = std::fs::read_to_string(&p) else { continue; }; - let Ok(v) = serde_json::from_str::(&text) else { + let Some(nine_slice) = serde_json::from_str(&text) + .ok() + .as_ref() + .and_then(parse_nine_slice) + 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); + map.insert(key, nine_slice); } } *NINE_SLICE.write().unwrap_or_else(|e| e.into_inner()) = Some(map); } -fn border(sprite: &str) -> [u32; 4] { +/// The sprite's nine-slice metadata; without any (no resources loaded), its +/// GUI size and the widgets' usual borders. +fn scaling(sprite: &str, r: &Rect) -> NineSlice { 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], + .unwrap_or(NineSlice { + width: r.w, + height: r.h, + border: 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], + }, + stretch_inner: false, }) } -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); +/// The region `[x, y, w, h]` of a sprite `size` GUI pixels large, in its +/// own units (`TextureAtlasSprite.getU(x / width)`). +fn sub(r: Rect, size: [f32; 2], [x, y, w, h]: [f32; 4]) -> Rect { + let (du, dv) = ((r.u1 - r.u0) / size[0], (r.v1 - r.v0) / size[1]); Rect { u0: r.u0 + x * du, v0: r.v0 + y * dv, @@ -82,8 +114,9 @@ fn sub(r: Rect, x: f32, y: f32, w: f32, h: f32) -> Rect { 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) { +/// `blitTiledSprite`: `src` (a region of a sprite `size` large, in its +/// units) repeated over `dst` from its top left, the last row and column cut. +fn tile(batch: &mut HudBatch, r: Rect, size: [f32; 2], 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 { @@ -95,13 +128,16 @@ fn tile(batch: &mut HudBatch, r: Rect, src: [f32; 4], dst: [f32; 4], color: u32) 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); + batch.rect_uv(dx + x, dy + y, w, h, sub(r, size, [sx, sy, w, h]), color); x += sw; } y += sh; } } -/// GuiGraphics.blitSprite with nine-slice scaling (inner parts tiled). +/// `GuiGraphicsExtractor.blitNineSlicedSprite`: the corners at their size, +/// the edges and centre tiled (or stretched with `stretch_inner`), all in +/// the sprite's `gui.scaling` units, so a high-resolution pack's sprite draws +/// as the default one does. pub fn nine_slice( batch: &mut HudBatch, atlas: &HudAtlas, @@ -112,47 +148,73 @@ pub fn nine_slice( h: f32, color: u32, ) { - let Some(r) = atlas.sprites.get(sprite).copied() else { - return; + if let Some(r) = atlas.sprites.get(sprite) { + draw_nine_slice(batch, *r, scaling(sprite, r), [x, y, w, h], color); + } +} +fn draw_nine_slice( + batch: &mut HudBatch, + r: Rect, + n: NineSlice, + [x, y, w, h]: [f32; 4], + color: u32, +) { + let size = [n.width as f32, n.height as f32]; + let [sw, sh] = size; + let [l, t, rr, b] = n.border.map(|v| v as f32); + let (half_w, half_h) = ((w / 2.0).floor(), (h / 2.0).floor()); + let (l, rr, t, b) = (l.min(half_w), rr.min(half_w), t.min(half_h), b.min(half_h)); + // blitSprite(sprite, width, height, textureX, textureY, x, y, w, h). + let part = |batch: &mut HudBatch, tx: f32, ty: f32, dst: [f32; 4]| { + if dst[2] != 0.0 && dst[3] != 0.0 { + batch.rect_uv( + dst[0], + dst[1], + dst[2], + dst[3], + sub(r, size, [tx, ty, dst[2], dst[3]]), + color, + ); + } }; - 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); + // blitNineSliceInnerSegment. + let inner = |batch: &mut HudBatch, dst: [f32; 4], src: [f32; 4]| { + if dst[2] <= 0.0 || dst[3] <= 0.0 { + return; + } + if n.stretch_inner { + batch.rect_uv(dst[0], dst[1], dst[2], dst[3], sub(r, size, src), color); + } else { + tile(batch, r, size, src, dst, color); + } + }; + if w == sw && h == sh { + part(batch, 0.0, 0.0, [x, y, w, h]); + return; + } + if h == sh { + part(batch, 0.0, 0.0, [x, y, l, h]); + inner(batch, [x + l, y, w - rr - l, h], [l, 0.0, sw - rr - l, sh]); + part(batch, sw - rr, 0.0, [x + w - rr, y, rr, h]); + return; + } + if w == sw { + part(batch, 0.0, 0.0, [x, y, w, t]); + inner(batch, [x, y + t, w, h - b - t], [0.0, t, sw, sh - b - t]); + part(batch, 0.0, sh - b, [x, y + h - b, w, b]); + return; + } + let (cw, ch) = (w - rr - l, h - b - t); + let (scw, sch) = (sw - rr - l, sh - b - t); + part(batch, 0.0, 0.0, [x, y, l, t]); + inner(batch, [x + l, y, cw, t], [l, 0.0, scw, t]); + part(batch, sw - rr, 0.0, [x + w - rr, y, rr, t]); + part(batch, 0.0, sh - b, [x, y + h - b, l, b]); + inner(batch, [x + l, y + h - b, cw, b], [l, sh - b, scw, b]); + part(batch, sw - rr, sh - b, [x + w - rr, y + h - b, rr, b]); + inner(batch, [x, y + t, l, ch], [0.0, t, l, sch]); + inner(batch, [x + l, y + t, cw, ch], [l, t, scw, sch]); + inner(batch, [x + w - rr, y + t, rr, ch], [sw - rr, t, rr, sch]); } /// Repeat a whole texture with each copy drawn `size` GUI pixels square. pub fn tiled( @@ -169,7 +231,6 @@ pub fn tiled( 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); @@ -181,7 +242,7 @@ pub fn tiled( y + yy, tw, th, - sub(r, 0.0, 0.0, tw * scale, th * scale), + sub(r, [size, size], [0.0, 0.0, tw, th]), color, ); xx += size; @@ -1128,6 +1189,130 @@ impl EditBox { #[cfg(test)] mod tests { use super::*; + + /// The quads' destination rectangles and their UVs. + fn quads(batch: &HudBatch) -> Vec<([f32; 4], [f32; 4])> { + batch + .vertices + .chunks(6) + .map(|q| { + let (a, c) = (q[0], q[2]); + ( + [a.pos[0], a.pos[1], c.pos[0], c.pos[1]], + [a.uv[0], a.uv[1], c.uv[0], c.uv[1]], + ) + }) + .collect() + } + /// Destination and UV rectangles equal to within f32 rounding. + fn assert_quad(actual: ([f32; 4], [f32; 4]), expected: ([f32; 4], [f32; 4])) { + let close = |a: [f32; 4], b: [f32; 4]| a.iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-5); + assert!( + close(actual.0, expected.0) && close(actual.1, expected.1), + "{actual:?} != {expected:?}" + ); + } + /// A sprite filling the atlas, `w x h` texels as a 32x pack draws it. + fn sprite(w: u32, h: u32) -> Rect { + Rect { + u0: 0.0, + v0: 0.0, + u1: 1.0, + v1: 1.0, + w, + h, + } + } + fn faithful(json: &str) -> NineSlice { + parse_nine_slice(&serde_json::from_str(json).unwrap()).unwrap() + } + #[test] + fn a_high_resolution_button_slices_in_its_gui_units() { + // Faithful 32x's widget/button: 400x40 texels, gui.scaling 200x20. + let n = faithful( + r#"{"gui":{"scaling":{"type":"nine_slice","width":200,"height":20, + "border":{"left":20,"top":4,"right":20,"bottom":4}}}}"#, + ); + let mut batch = HudBatch::new([640, 480]); + draw_nine_slice( + &mut batch, + sprite(400, 40), + n, + [10.0, 5.0, 150.0, 20.0], + u32::MAX, + ); + let q = quads(&batch); + // Full height: left border, the centre tiled, right border + // (blitNineSlicedSprite's height == nineSlice.height case). + assert_quad(q[0], ([10.0, 5.0, 30.0, 25.0], [0.0, 0.0, 0.1, 1.0])); + assert_quad(q[1], ([30.0, 5.0, 140.0, 25.0], [0.1, 0.0, 0.65, 1.0])); + assert_quad(q[2], ([140.0, 5.0, 160.0, 25.0], [0.9, 0.0, 1.0, 1.0])); + assert_eq!(q.len(), 3); + } + #[test] + fn nine_slice_corners_and_a_stretched_centre() { + // Faithful 32x's tooltip/frame: 200x200 texels, 100x100, border 12, stretched. + let n = faithful( + r#"{"gui":{"scaling":{"type":"nine_slice","width":100,"height":100,"border":12,"stretch_inner":true}}}"#, + ); + let mut batch = HudBatch::new([640, 480]); + draw_nine_slice( + &mut batch, + sprite(200, 200), + n, + [0.0, 0.0, 300.0, 40.0], + u32::MAX, + ); + let q = quads(&batch); + assert_eq!(q.len(), 9); + // Top left corner: 12 GUI pixels, 12/100 of the sprite. + assert_quad(q[0], ([0.0, 0.0, 12.0, 12.0], [0.0, 0.0, 0.12, 0.12])); + // The centre is one stretched quad (blitNineSliceInnerSegment, stretch_inner). + assert_quad(q[7], ([12.0, 12.0, 288.0, 28.0], [0.12, 0.12, 0.88, 0.88])); + // Bottom right corner. + assert_quad(q[5], ([288.0, 28.0, 300.0, 40.0], [0.88, 0.88, 1.0, 1.0])); + } + #[test] + fn a_sprite_drawn_at_its_own_size_is_one_quad() { + let n = NineSlice { + width: 50, + height: 50, + border: [10; 4], + stretch_inner: false, + }; + let mut batch = HudBatch::new([640, 480]); + draw_nine_slice( + &mut batch, + sprite(100, 100), + n, + [4.0, 4.0, 50.0, 50.0], + u32::MAX, + ); + let q = quads(&batch); + assert_eq!(q.len(), 1); + assert_quad(q[0], ([4.0, 4.0, 54.0, 54.0], [0.0, 0.0, 1.0, 1.0])); + } + #[test] + fn borders_shrink_to_half_the_drawn_size() { + let n = NineSlice { + width: 20, + height: 20, + border: [8; 4], + stretch_inner: true, + }; + let mut batch = HudBatch::new([640, 480]); + // 9 wide: borders of floor(9 / 2) = 4, as vanilla's integer division. + draw_nine_slice( + &mut batch, + sprite(20, 20), + n, + [0.0, 0.0, 9.0, 30.0], + u32::MAX, + ); + let q = quads(&batch); + assert_quad(q[0], ([0.0, 0.0, 4.0, 8.0], [0.0, 0.0, 0.2, 0.4])); + assert_quad(q[2], ([5.0, 0.0, 9.0, 8.0], [0.8, 0.0, 1.0, 0.4])); + } #[test] fn append_fields_highlight_the_whole_value_and_blink_their_cursor() { use crate::hud::Blend;