From 9f2bcd2bd85228ffbe4a9087d3ddfaa70233778a Mon Sep 17 00:00:00 2001 From: endercodezz Date: Thu, 5 Nov 2026 20:42:26 +0200 Subject: [PATCH] feat(tools): texpack build writes the New 3DS texture pack `p3p-texpack build ` converts a PPSSPP pack into the P3P3DS 3DS pack: index.bin (entries sorted by PPSSPP key: offset, size, power-of-two size, citro3d format) and textures.bin (PICA200 data, rows bottom-up like the 3DS renderer's uploads). Images are box- downscaled with premultiplied alpha to at most --max-size texels per side; the format follows the alpha channel (RGB565, RGBA5551, RGBA4). Verified: the Community Expansion 3x pack converts in 52 s (4,580 textures, 10 missing from the pack itself; 872 MB at max 512, 302 MB at 256); replacements on the battle route are uniform 2x/3x/4.5x multiples of the PSP texture; the ATLUS entry decodes back correctly; cargo test 14/14, clippy clean. --- README.md | 2 +- docs/CURRENT_STATE.md | 7 + tools/texpack/src/build.rs | 238 ++++++++++++++++++++++++++++++++++ tools/texpack/src/main.rs | 41 +++++- tools/texpack/src/resample.rs | 88 +++++++++++++ 5 files changed, 372 insertions(+), 4 deletions(-) create mode 100644 tools/texpack/src/build.rs create mode 100644 tools/texpack/src/resample.rs diff --git a/README.md b/README.md index a03018c6..5027309b 100644 --- a/README.md +++ b/README.md @@ -242,7 +242,7 @@ Modding support and fan translations are first-class architectural requirements: disc0:/PSP_GAME/USRDIR/umd0.cpk, umd1.cpk (original game archives) ``` On PC, `--mods ` maps `ms0:/PSP/P3P` to a host directory. -- **Texture packs (work in progress, [#23](https://github.com/endercodezz/P3P3DS/issues/23), [#56](https://github.com/endercodezz/P3P3DS/issues/56)):** existing P3P packs are PPSSPP packs (`textures.ini` + PNG). `tools/texpack` (Rust, host only) checks a pack and encodes PNG into New 3DS texture data; the runtime does not load packs yet. From `tools/texpack`: `cargo run --release -- inspect ` and `cargo run --release -- encode --format rgba8|rgb8|rgb565|rgba5551|rgba4 --out ` (the same bytes as devkitPro `tex3ds -r -z none`). The runtime computes PPSSPP-compatible texture keys (`core/include/p3p3ds/ge/texture_replacement.hpp`); to see how much of a pack a PC run would find: `cargo run --release -- keys > keys.txt`, then `p3p_pc_bootstrap ... --texture-keys keys.txt --texture-keys-report keys.csv` (prints `[TEXKEYS]`, the CSV lists every texture key and whether the pack has it). +- **Texture packs (work in progress, [#23](https://github.com/endercodezz/P3P3DS/issues/23), [#56](https://github.com/endercodezz/P3P3DS/issues/56)):** existing P3P packs are PPSSPP packs (`textures.ini` + PNG). `tools/texpack` (Rust, host only) checks a pack and encodes PNG into New 3DS texture data; the runtime does not load packs yet. From `tools/texpack`: `cargo run --release -- inspect ` and `cargo run --release -- encode --format rgba8|rgb8|rgb565|rgba5551|rgba4 --out ` (the same bytes as devkitPro `tex3ds -r -z none`). The runtime computes PPSSPP-compatible texture keys (`core/include/p3p3ds/ge/texture_replacement.hpp`); to see how much of a pack a PC run would find: `cargo run --release -- keys > keys.txt`, then `p3p_pc_bootstrap ... --texture-keys keys.txt --texture-keys-report keys.csv` (prints `[TEXKEYS]`, the CSV lists every texture key and whether the pack has it). `cargo run --release -- build [--max-size 512] [--format auto|rgba8|...]` converts a pack into the New 3DS pack format (`index.bin` + `textures.bin`, documented in `tools/texpack/src/build.rs`): images downscaled to at most `--max-size` texels per side, RGB565 / RGBA5551 / RGBA4 chosen from the alpha channel. - **Translation & Mod Support (Future Goal):** The architecture aims to support community translations (such as Russian, Spanish, German, French) and mods via VFS redirection. Note that translations are not guaranteed to be drop-in asset-only packages: individual localizations may require custom font sheets, character encoding tables, `.bmd`/`.bf` script handling, or runtime executable hooks (such as glyph-spacing/kerning adjustments). --- diff --git a/docs/CURRENT_STATE.md b/docs/CURRENT_STATE.md index 754b7c03..f8733098 100644 --- a/docs/CURRENT_STATE.md +++ b/docs/CURRENT_STATE.md @@ -2,6 +2,13 @@ This is the current source of truth, newest entries first. Evidence concerns ULUS-10512; each section says whether it was measured on the PC runner, in Azahar or on a real New 3DS. +## New 3DS texture pack format: `p3p-texpack build` (#56, 2026-11-05) + +- [VERIFIED] In the Community Expansion 3x pack every replacement matched on the battle route is a uniform multiple of the full PSP texture (192 checked: 166 at 3x, 23 at 2x, 3 at 4.5x; same aspect ratio, not cropped to maxSeenV). So a replacement can be stored at any power-of-two size with that aspect ratio and sampled with the PSP texture's normalised coordinates. +- `build` (`tools/texpack/src/build.rs`, format documented there): `index.bin` (magic `P3TXPACK`, version 1, ignoreAddress flag, 32-byte entries sorted by key: data offset/size, width, height, citro3d texture format) + `textures.bin` (PICA200 data, 128-byte aligned, rows bottom-up like the 3DS renderer's uploads, `tiled_row` in `platform/3ds/gpu_renderer.cpp`). Box downscale with premultiplied alpha to at most `--max-size` per side (default 512); RGB565 if opaque, RGBA5551 if alpha is only 0/255, else RGBA4. +- [VERIFIED] The 3x pack converts in 52 s (max 512, 12 threads): 4,580 textures (10 skipped: files missing from the pack), 871,815,168 bytes; RGBA4 2,813, RGB565 1,673, RGBA5551 94. With `--max-size 256`: 301,750,272 bytes, 27 s. The ATLUS logo entry decodes back to the expected image (512x256 RGB565). `cargo test` 14/14 (sizes, box filter, alpha formats, index layout, alignment, row order). +- Next: read the pack in the runtime and replace textures, first in the PC renderer (frame dumps), then on the 3DS (#23). + ## PPSSPP-compatible texture keys find a real P3P pack (#23, 2026-11-05) - `core/src/ge/xxhash.cpp` (XXH32/XXH64 from the specification) and `core/src/ge/texture_replacement.cpp`: the texture key PPSSPP packs use, reproduced from PPSSPP's behaviour (`references/ppsspp/GPU/Common/TextureCacheCommon.cpp`, `TextureReplacer.cpp`; behavioural reference only). cachekey = (address << 32 | TEXSIZE & 0xF0F) ^ CLUT hash; CLUT hash = XXH32 of min(last load + start index bytes, largest load) palette bytes, seed 0xC0108888, xored with the CLUTFORMAT command word including its 0xC5 byte; data hash = low 32 bits of XXH64, seed 0xBACD7814, row-wise when the buffer is wider, maxSeenV rows for 512-tall textures; lookup order with zeroed-part fallbacks. PC runner: `--texture-keys ` (keys from `p3p-texpack keys`) and `--texture-keys-report ` wrap the renderer and report matches; nothing is replaced yet. diff --git a/tools/texpack/src/build.rs b/tools/texpack/src/build.rs new file mode 100644 index 00000000..7d506cf4 --- /dev/null +++ b/tools/texpack/src/build.rs @@ -0,0 +1,238 @@ +//! `build`: PPSSPP pack -> New 3DS pack (two files in the output directory). +//! +//! index.bin (little endian): +//! 0 "P3TXPACK" magic +//! 8 u32 version = 1 +//! 12 u32 flags bit 0: ignoreAddress (keys carry no address) +//! 16 u32 entry count +//! 20 u32 reserved = 0 +//! 24 entries, 32 bytes each, sorted by (cachekey, hash): +//! u64 cachekey, u32 hash, u32 data offset in textures.bin, +//! u32 data size, u16 width, u16 height (power of two, 8..1024), +//! u8 format (citro3d GPU_TEXCOLOR: 0 RGBA8, 2 RGBA5551, 3 RGB565, 4 RGBA4), +//! u8 reserved, u16 reserved, u32 reserved +//! An entry with width 0 means "keep the original texture" (an empty or `|` +//! file in textures.ini). +//! textures.bin: PICA200 texture data (pica.rs), each entry 128-byte aligned, +//! rows bottom-up as the P3P3DS 3DS renderer uploads textures: image row y +//! is memory row h - 1 - y (platform/3ds/gpu_renderer.cpp, tiled_row). +//! +//! The replacement covers the whole PSP texture: the renderer samples it with +//! the PSP texture's normalised coordinates, so any power-of-two size with the +//! same aspect ratio works. + +use crate::pack::{Key, Pack}; +use crate::pica::{self, Format, Image}; +use crate::resample; +use std::fs::File; +use std::io::{BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; + +pub const MAGIC: &[u8; 8] = b"P3TXPACK"; +pub const VERSION: u32 = 1; +pub const ENTRY_SIZE: usize = 32; +const ALIGN: usize = 128; + +pub struct Options { + pub max_size: usize, + /// None: pick per texture from its alpha channel. + pub format: Option, +} + +/// citro3d GPU_TEXCOLOR value of a format. +pub fn gpu_format(format: Format) -> u8 { + match format { + Format::Rgba8 => 0, + Format::Rgb8 => 1, + Format::Rgba5551 => 2, + Format::Rgb565 => 3, + Format::Rgba4 => 4, + } +} + +/// Opaque -> RGB565, alpha only 0/255 -> RGBA5551, otherwise RGBA4. +pub fn auto_format(image: &Image) -> Format { + let (mut partial, mut transparent) = (false, false); + for a in image.rgba.iter().skip(3).step_by(4) { + match a { + 255 => {} + 0 => transparent = true, + _ => { + partial = true; + break; + } + } + } + if partial { + Format::Rgba4 + } else if transparent { + Format::Rgba5551 + } else { + Format::Rgb565 + } +} + +/// Image row y becomes row h - 1 - y. +pub fn flip_vertical(image: Image) -> Image { + let row = image.width * 4; + let rgba = image.rgba.chunks_exact(row).rev().flatten().copied().collect(); + Image { rgba, ..image } +} + +struct Built { + key: Key, + width: u16, + height: u16, + format: u8, + data: Vec, +} + +pub struct Summary { + pub entries: usize, + pub keep_original: usize, + pub skipped: Vec, + pub data_bytes: u64, + pub by_format: [usize; 5], +} + +fn build_one(dir: &Path, key: Key, file: &str, options: &Options, load: &dyn Fn(&Path) -> Result) -> Result { + let image = load(&dir.join(file))?; + let (w, h) = resample::target_size(image.width, image.height, options.max_size); + let (w, h) = (w.max(pica::MIN_SIZE), h.max(pica::MIN_SIZE)); + let scaled = flip_vertical(resample::resize(&image, w, h)); + let format = options.format.unwrap_or_else(|| auto_format(&scaled)); + let data = pica::encode(&scaled, format).map_err(|e| format!("{file}: {e}"))?; + Ok(Built { key, width: w as u16, height: h as u16, format: gpu_format(format), data }) +} + +/// Converts level 0 of every entry. `load` decodes a PNG (main.rs). +pub fn build(dir: &Path, pack: &Pack, out: &Path, options: &Options, load: &(dyn Fn(&Path) -> Result + Sync)) -> Result { + std::fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?; + let jobs: Vec<(Key, Option)> = pack.entries.iter().filter_map(|(k, e)| e.levels.get(&0).map(|f| (*k, f.clone()))).collect(); + let next = AtomicUsize::new(0); + let results: Mutex>>> = Mutex::new((0..jobs.len()).map(|_| None).collect()); + let threads = std::thread::available_parallelism().map_or(4, |n| n.get()); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| loop { + let i = next.fetch_add(1, Ordering::Relaxed); + if i >= jobs.len() { + break; + } + let (key, file) = &jobs[i]; + let r = match file { + Some(f) => build_one(dir, *key, f, options, load), + None => Ok(Built { key: *key, width: 0, height: 0, format: 0, data: Vec::new() }), + }; + results.lock().unwrap()[i] = Some(r); + }); + } + }); + let mut built = Vec::new(); + let mut summary = Summary { entries: 0, keep_original: 0, skipped: Vec::new(), data_bytes: 0, by_format: [0; 5] }; + for r in results.into_inner().unwrap().into_iter().flatten() { + match r { + Ok(b) => built.push(b), + Err(e) => summary.skipped.push(e), + } + } + built.sort_by_key(|b| (b.key.cachekey, b.key.hash)); + + let data_path: PathBuf = out.join("textures.bin"); + let mut data = BufWriter::new(File::create(&data_path).map_err(|e| format!("{}: {e}", data_path.display()))?); + let mut index = Vec::with_capacity(24 + built.len() * ENTRY_SIZE); + index.extend_from_slice(MAGIC); + index.extend_from_slice(&VERSION.to_le_bytes()); + index.extend_from_slice(&(pack.options.ignore_address as u32).to_le_bytes()); + index.extend_from_slice(&(built.len() as u32).to_le_bytes()); + index.extend_from_slice(&0u32.to_le_bytes()); + let mut offset: u64 = 0; + for b in &built { + if offset > u32::MAX as u64 { + return Err("textures.bin would exceed 4 GiB; lower --max-size".into()); + } + index.extend_from_slice(&b.key.cachekey.to_le_bytes()); + index.extend_from_slice(&b.key.hash.to_le_bytes()); + index.extend_from_slice(&(offset as u32).to_le_bytes()); + index.extend_from_slice(&(b.data.len() as u32).to_le_bytes()); + index.extend_from_slice(&b.width.to_le_bytes()); + index.extend_from_slice(&b.height.to_le_bytes()); + index.extend_from_slice(&[b.format, 0, 0, 0]); + index.extend_from_slice(&0u32.to_le_bytes()); + if b.width == 0 { + summary.keep_original += 1; + continue; + } + data.write_all(&b.data).map_err(|e| e.to_string())?; + let pad = (ALIGN - b.data.len() % ALIGN) % ALIGN; + data.write_all(&vec![0; pad]).map_err(|e| e.to_string())?; + offset += (b.data.len() + pad) as u64; + summary.by_format[b.format.min(4) as usize] += 1; + } + data.flush().map_err(|e| e.to_string())?; + std::fs::write(out.join("index.bin"), &index).map_err(|e| format!("{}: {e}", out.display()))?; + summary.entries = built.len(); + summary.data_bytes = offset; + Ok(summary) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn flips_rows() { + let img = Image { width: 1, height: 3, rgba: vec![1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3] }; + assert_eq!(flip_vertical(img).rgba, vec![3, 3, 3, 3, 2, 2, 2, 2, 1, 1, 1, 1]); + } + + #[test] + fn auto_format_by_alpha() { + let img = |a: [u8; 2]| Image { width: 2, height: 1, rgba: vec![1, 2, 3, a[0], 4, 5, 6, a[1]] }; + assert_eq!(auto_format(&img([255, 255])), Format::Rgb565); + assert_eq!(auto_format(&img([255, 0])), Format::Rgba5551); + assert_eq!(auto_format(&img([255, 128])), Format::Rgba4); + } + + #[test] + fn writes_sorted_index_and_aligned_data() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../build/texpack/test-build"); + let _ = std::fs::remove_dir_all(&root); + let src = root.join("pack"); + std::fs::create_dir_all(&src).unwrap(); + let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures"); + std::fs::copy(fixtures.join("all_values_16x16.png"), src.join("b.png")).unwrap(); + std::fs::copy(fixtures.join("pattern_16x8.png"), src.join("a.png")).unwrap(); + let ini = "[options]\nhash = xxh64\nignoreAddress = true\n[hashes]\n\ + 00000000000000ff00000002 = b.png\n0000000000000001aaaaaaaa = a.png\n000000000000000500000000 = |\n"; + let pack = crate::pack::parse_ini(ini, &[]).unwrap(); + let out = root.join("out"); + let options = Options { max_size: 8, format: Some(Format::Rgba8) }; + let summary = build(&src, &pack, &out, &options, &crate::load_png).unwrap(); + assert_eq!((summary.entries, summary.keep_original), (3, 1)); + let index = std::fs::read(out.join("index.bin")).unwrap(); + assert_eq!(&index[..8], MAGIC); + assert_eq!(u32::from_le_bytes(index[12..16].try_into().unwrap()), 1); + assert_eq!(u32::from_le_bytes(index[16..20].try_into().unwrap()), 3); + assert_eq!(index.len(), 24 + 3 * ENTRY_SIZE); + let entry = |i: usize| &index[24 + i * ENTRY_SIZE..24 + (i + 1) * ENTRY_SIZE]; + let ck = |i: usize| u64::from_le_bytes(entry(i)[..8].try_into().unwrap()); + assert_eq!((ck(0), ck(1), ck(2)), (1, 5, 0xff)); + // a.png 16x8 -> 8x8 at max 8 (aspect 2:1 -> 8x4, raised to the 8 minimum). + let e0 = entry(0); + assert_eq!(u16::from_le_bytes([e0[20], e0[21]]), 8); + assert_eq!(u32::from_le_bytes(e0[16..20].try_into().unwrap()), 8 * 8 * 4); + let e1 = entry(1); + assert_eq!(u16::from_le_bytes([e1[20], e1[21]]), 0, "keep-original entry has no size"); + let e2 = entry(2); + assert_eq!(u32::from_le_bytes(e2[12..16].try_into().unwrap()), 256, "second texture starts on the next 128-byte boundary"); + let data = std::fs::read(out.join("textures.bin")).unwrap(); + assert_eq!(data.len(), 512); + // Stored bottom-up: the first entry equals encode() of the flipped, resized image. + let a = crate::load_png(&src.join("a.png")).unwrap(); + let expect = pica::encode(&flip_vertical(resample::resize(&a, 8, 8)), Format::Rgba8).unwrap(); + assert_eq!(&data[..256], &expect[..]); + } +} diff --git a/tools/texpack/src/main.rs b/tools/texpack/src/main.rs index 951b1ee8..fbc991ec 100644 --- a/tools/texpack/src/main.rs +++ b/tools/texpack/src/main.rs @@ -2,21 +2,25 @@ //! //! p3p-texpack inspect //! p3p-texpack keys +//! p3p-texpack build [--max-size ] [--format auto|] //! p3p-texpack encode --format --out //! //! `encode` writes PICA200 texture data (no header), the same bytes as -//! `tex3ds -r -z none -f ` after its 4-byte header. Exit codes: 0 ok, +//! `tex3ds -r -z none -f ` after its 4-byte header. `build` writes the +//! New 3DS pack (build.rs: index.bin + textures.bin). Exit codes: 0 ok, //! 1 error, 2 usage. +mod build; mod pack; mod pica; +mod resample; use std::fs::File; use std::io::BufReader; use std::path::{Path, PathBuf}; use std::process::ExitCode; -const USAGE: &str = "usage: p3p-texpack inspect \n p3p-texpack keys \n p3p-texpack encode --format --out \n\ +const USAGE: &str = "usage: p3p-texpack inspect \n p3p-texpack keys \n p3p-texpack build [--max-size ] [--format auto|]\n p3p-texpack encode --format --out \n\ formats: rgba8 rgb8 rgb565 rgba5551 rgba4"; /// Largest source image accepted (packs ship upscales; the 3DS limit applies at encode). @@ -37,7 +41,7 @@ fn png_info(path: &Path) -> Result { Ok(PngInfo { width: info.width, height: info.height, color: info.color_type, depth: info.bit_depth }) } -fn load_png(path: &Path) -> Result { +pub(crate) fn load_png(path: &Path) -> Result { let file = File::open(path).map_err(|e| format!("{}: {e}", path.display()))?; let mut decoder = png::Decoder::new_with_limits(BufReader::new(file), png::Limits { bytes: MAX_SOURCE_BYTES }); decoder.set_transformations(png::Transformations::normalize_to_color8()); @@ -120,6 +124,19 @@ fn keys(dir: &Path) -> Result<(), String> { Ok(()) } +fn build_pack(dir: &Path, out: &Path, options: &build::Options) -> Result<(), String> { + let pack = pack::load(dir).map_err(|e| e.to_string())?; + let start = std::time::Instant::now(); + let s = build::build(dir, &pack, out, options, &load_png)?; + for e in &s.skipped { + println!("skipped {e}"); + } + println!("entries={} keep_original={} skipped={} data_bytes={} rgba8={} rgba5551={} rgb565={} rgba4={} seconds={:.1}", + s.entries, s.keep_original, s.skipped.len(), s.data_bytes, s.by_format[0], s.by_format[2], s.by_format[3], + s.by_format[4], start.elapsed().as_secs_f64()); + Ok(()) +} + fn encode(input: &Path, format: pica::Format, out: &Path) -> Result<(), String> { let image = load_png(input)?; let data = pica::encode(&image, format).map_err(|e| format!("{}: {e}", input.display()))?; @@ -133,6 +150,24 @@ fn run(args: &[String]) -> Result, ()> { match args { [cmd, dir] if cmd == "inspect" => Ok(inspect(Path::new(dir))), [cmd, dir] if cmd == "keys" => Ok(keys(Path::new(dir))), + [cmd, dir, out, rest @ ..] if cmd == "build" => { + let mut options = build::Options { max_size: 512, format: None }; + let mut it = rest.iter(); + while let Some(a) = it.next() { + match (a.as_str(), it.next()) { + ("--max-size", Some(n)) => { + options.max_size = n.parse().map_err(|_| ())?; + if !(pica::MIN_SIZE..=pica::MAX_SIZE).contains(&options.max_size) { + return Err(()); + } + } + ("--format", Some(f)) if f == "auto" => options.format = None, + ("--format", Some(f)) => options.format = Some(pica::Format::parse(f).ok_or(())?), + _ => return Err(()), + } + } + Ok(build_pack(Path::new(dir), Path::new(out), &options)) + } [cmd, input, rest @ ..] if cmd == "encode" => { let (mut format, mut out) = (None, None); let mut it = rest.iter(); diff --git a/tools/texpack/src/resample.rs b/tools/texpack/src/resample.rs new file mode 100644 index 00000000..76fba5ac --- /dev/null +++ b/tools/texpack/src/resample.rs @@ -0,0 +1,88 @@ +//! Downscaling for replacement art (packs ship 2x-6x upscales; the New 3DS +//! needs power-of-two textures of at most 1024 texels and a small budget). + +use crate::pica::Image; + +/// Largest power-of-two size with the image's aspect ratio that fits in the +/// image and in `max` on both axes. Pack images are k x (power-of-two texture), +/// so their aspect ratio is a power of two; others get the nearest fit. +pub fn target_size(width: usize, height: usize, max: usize) -> (usize, usize) { + let floor_pow2 = |n: usize| if n <= 1 { 1 } else { 1usize << (usize::BITS - 1 - n.leading_zeros()) }; + // Aspect ratio as a power of two: width = height << shift (negative: taller). + let shift = (width.max(1) as f64 / height.max(1) as f64).log2().round() as i32; + let max = floor_pow2(max); + let w_limit = floor_pow2(width).min(max); + let h_limit = floor_pow2(height).min(max); + let h_from_w = |w: usize| if shift >= 0 { w >> shift } else { w << -shift }; + let w_from_h = |h: usize| if shift >= 0 { h << shift } else { h >> -shift }; + let (w, h) = if h_from_w(w_limit) <= h_limit { (w_limit, h_from_w(w_limit)) } else { (w_from_h(h_limit), h_limit) }; + (w.max(1), h.max(1)) +} + +/// Area-average (box) resample with premultiplied alpha, so transparent texels +/// don't darken the edges of opaque ones. +pub fn resize(src: &Image, width: usize, height: usize) -> Image { + if src.width == width && src.height == height { + return Image { width, height, rgba: src.rgba.clone() }; + } + let sx = src.width as f64 / width as f64; + let sy = src.height as f64 / height as f64; + let mut rgba = Vec::with_capacity(width * height * 4); + for y in 0..height { + let (y0, y1) = (y as f64 * sy, (y + 1) as f64 * sy); + for x in 0..width { + let (x0, x1) = (x as f64 * sx, (x + 1) as f64 * sx); + let mut acc = [0f64; 4]; + let mut area = 0f64; + let mut py = y0.floor() as usize; + while (py as f64) < y1 && py < src.height { + let wy = (y1.min(py as f64 + 1.0) - y0.max(py as f64)).max(0.0); + let mut px = x0.floor() as usize; + while (px as f64) < x1 && px < src.width { + let wx = (x1.min(px as f64 + 1.0) - x0.max(px as f64)).max(0.0); + let wgt = wx * wy; + let o = (py * src.width + px) * 4; + let a = src.rgba[o + 3] as f64; + acc[0] += src.rgba[o] as f64 * a * wgt; + acc[1] += src.rgba[o + 1] as f64 * a * wgt; + acc[2] += src.rgba[o + 2] as f64 * a * wgt; + acc[3] += a * wgt; + area += wgt; + px += 1; + } + py += 1; + } + let alpha = if area > 0.0 { acc[3] / area } else { 0.0 }; + let color = |c: f64| if acc[3] > 0.0 { (c / acc[3]).round().clamp(0.0, 255.0) as u8 } else { 0 }; + rgba.extend_from_slice(&[color(acc[0]), color(acc[1]), color(acc[2]), alpha.round().clamp(0.0, 255.0) as u8]); + } + } + Image { width, height, rgba } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn target_sizes_of_pack_images() { + assert_eq!(target_size(1536, 768, 512), (512, 256)); // 3x 512x256 backdrop + assert_eq!(target_size(144, 144, 512), (128, 128)); // 4.5x 32x32 font glyph + assert_eq!(target_size(768, 192, 1024), (512, 128)); // 3x 256x64 + assert_eq!(target_size(192, 768, 128), (32, 128)); + assert_eq!(target_size(64, 64, 512), (64, 64)); + assert_eq!(target_size(3, 3, 512), (2, 2)); + } + + #[test] + fn box_filter_averages_and_keeps_alpha_edges_clean() { + // 2x2 -> 1x1: red opaque, transparent black x3 -> red at quarter alpha. + let src = Image { width: 2, height: 2, rgba: vec![255, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }; + let out = resize(&src, 1, 1); + assert_eq!(out.rgba, vec![255, 0, 0, 64]); + // 3x1 -> 2x1 with fractional coverage: 10,20,30 -> 13.3, 26.7. + let src = Image { width: 3, height: 1, rgba: vec![10, 10, 10, 255, 20, 20, 20, 255, 30, 30, 30, 255] }; + let out = resize(&src, 2, 1); + assert_eq!(out.rgba, vec![13, 13, 13, 255, 27, 27, 27, 255]); + } +}