Sprite mips from MipmapGenerator: cutout edges keep their coverage
Horizon averaged each mip level's alpha plainly, so a cutout texture's transparent edges grew past the alpha test with every level: the cactus side's transparent border columns opened see-through slits along its corners from about 40 blocks, more than vanilla shows. The sprite array's mips now come from a port of MipmapGenerator.generateMipLevels: the texture's .mcmeta mipmap_strategy (auto: cutout when a pixel is fully transparent) and alpha_cutoff_bias, solidify or the dark fill on the base, meanLinear or darkenedAlphaBlend, and scaleAlphaToCoverage keeping every cutout level's alpha-test coverage at the base level's. tools/test_mipmap_parity.py runs vanilla's MipmapGenerator and the port on every static 16x16 block texture and a sample of item textures. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
//! Horizon's sprite mip levels for tools/test_mipmap_parity.py: each sprite
|
||||
//! loads through `sprites::Sprites` (its .mcmeta settings and transparency)
|
||||
//! and `mipmap::generate` makes its levels down to 1x1, printed as RGBA hex
|
||||
//! rows like VanillaMipmapOracle.
|
||||
use std::{fmt::Write as _, fs, path::Path};
|
||||
|
||||
fn main() -> horizon_client::Result<()> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let input = fs::read_to_string(&args[0])?;
|
||||
let mut lines = input.lines();
|
||||
let root = Path::new(lines.next().ok_or("no resources root")?);
|
||||
let names: Vec<&str> = lines.collect();
|
||||
let mut sprites = horizon_client::sprites::Sprites::default();
|
||||
let layers = names
|
||||
.iter()
|
||||
.map(|name| sprites.insert(root, name))
|
||||
.collect::<horizon_client::Result<Vec<u32>>>()?;
|
||||
sprites.finish();
|
||||
let size = sprites.size;
|
||||
let bytes = (size * size * 4) as usize;
|
||||
let mut out = String::new();
|
||||
for (name, layer) in names.iter().zip(layers) {
|
||||
let start = layer as usize * bytes;
|
||||
let base = horizon_client::mipmap::Image {
|
||||
width: size,
|
||||
height: size,
|
||||
pixels: sprites.pixels[start..start + bytes]
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.to_vec(),
|
||||
};
|
||||
let s = sprites.mips[layer as usize];
|
||||
writeln!(out, "== {name}")?;
|
||||
for mip in horizon_client::mipmap::generate(
|
||||
base,
|
||||
size.trailing_zeros(),
|
||||
s.strategy,
|
||||
s.alpha_cutoff_bias,
|
||||
s.has_transparent,
|
||||
s.item,
|
||||
) {
|
||||
write!(out, "{}x{}", mip.width, mip.height)?;
|
||||
for row in mip.pixels.chunks(mip.width as usize) {
|
||||
out.push(' ');
|
||||
for p in row {
|
||||
write!(out, "{:02x}{:02x}{:02x}{:02x}", p[0], p[1], p[2], p[3])?;
|
||||
}
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
fs::write(&args[1], out)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -63,6 +63,8 @@ pub struct Assets {
|
||||
pub animations: Vec<crate::sprites::SpriteAnimation>,
|
||||
pub sprite_layers: std::collections::BTreeMap<String, u32>,
|
||||
pub translucent_layers: Vec<bool>,
|
||||
/// Each layer's `MipmapGenerator` settings.
|
||||
pub sprite_mips: Vec<crate::mipmap::Settings>,
|
||||
/// Block names in `#minecraft:blocks_fluid_flow` (fluid flow vectors).
|
||||
pub blocks_fluid_flow: BTreeSet<String>,
|
||||
}
|
||||
@@ -246,6 +248,7 @@ impl Assets {
|
||||
animations: sprites.animations,
|
||||
sprite_layers: sprites.layers,
|
||||
translucent_layers: sprites.translucent,
|
||||
sprite_mips: sprites.mips,
|
||||
blocks_fluid_flow,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -6946,6 +6946,7 @@ impl Game<'_> {
|
||||
&assets.pixels,
|
||||
assets.sprite_size,
|
||||
assets.texture_layers,
|
||||
&assets.sprite_mips,
|
||||
&assets.animations,
|
||||
(
|
||||
&self.res.atlas.pixels,
|
||||
|
||||
@@ -273,6 +273,8 @@ pub struct Renderer {
|
||||
lightmap_view: wgpu::TextureView,
|
||||
lightmap_sampler: wgpu::Sampler,
|
||||
animations: Vec<(SpriteAnimation, usize)>,
|
||||
/// Each sprite layer's MipmapGenerator settings, for animation frames.
|
||||
sprite_mips: Vec<crate::mipmap::Settings>,
|
||||
/// Edge length of the block sprite array's layers.
|
||||
sprite_size: u32,
|
||||
indices: wgpu::Buffer,
|
||||
@@ -320,41 +322,41 @@ pub struct Renderer {
|
||||
pub animated_textures: bool,
|
||||
present_modes: Vec<wgpu::PresentMode>,
|
||||
}
|
||||
fn mip_chain(pixels: &[u8], size: u32, layers: u32) -> (Vec<u8>, u32) {
|
||||
/// Every layer's mip levels, layer major (`first` is the first layer's
|
||||
/// index into `settings`), made by `MipmapGenerator`.
|
||||
fn mip_chain(
|
||||
pixels: &[u8],
|
||||
size: u32,
|
||||
settings: &[crate::mipmap::Settings],
|
||||
first: u32,
|
||||
layers: u32,
|
||||
) -> (Vec<u8>, u32) {
|
||||
let levels = size.trailing_zeros() + 1;
|
||||
let layer_bytes = (size * size * 4) as usize;
|
||||
let mut out = Vec::new();
|
||||
for layer in 0..layers as usize {
|
||||
let base =
|
||||
&pixels[layer * (size * size * 4) as usize..(layer + 1) * (size * size * 4) as usize];
|
||||
let mut level = base.to_vec();
|
||||
let mut s = size as usize;
|
||||
out.extend_from_slice(&level);
|
||||
for _ in 1..levels {
|
||||
let n = s / 2;
|
||||
let mut next = vec![0u8; n * n * 4];
|
||||
for y in 0..n {
|
||||
for x in 0..n {
|
||||
let mut acc = [0u32; 4];
|
||||
let mut weight = 0u32;
|
||||
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
|
||||
let p = &level[((y * 2 + dy) * s + x * 2 + dx) * 4..][..4];
|
||||
let a = u32::from(p[3]);
|
||||
for c in 0..3 {
|
||||
acc[c] += u32::from(p[c]) * a;
|
||||
}
|
||||
acc[3] += a;
|
||||
weight += a;
|
||||
}
|
||||
let o = &mut next[(y * n + x) * 4..][..4];
|
||||
for c in 0..3 {
|
||||
o[c] = acc[c].checked_div(weight).unwrap_or(0) as u8;
|
||||
}
|
||||
o[3] = (acc[3] / 4) as u8;
|
||||
}
|
||||
}
|
||||
out.extend_from_slice(&next);
|
||||
level = next;
|
||||
s = n;
|
||||
let base = crate::mipmap::Image {
|
||||
width: size,
|
||||
height: size,
|
||||
pixels: pixels[layer * layer_bytes..(layer + 1) * layer_bytes]
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.to_vec(),
|
||||
};
|
||||
let s = settings
|
||||
.get(first as usize + layer)
|
||||
.copied()
|
||||
.unwrap_or_default();
|
||||
let has_transparent = s.has_transparent || base.pixels.iter().any(|p| p[3] == 0);
|
||||
for image in crate::mipmap::generate(
|
||||
base,
|
||||
levels - 1,
|
||||
s.strategy,
|
||||
s.alpha_cutoff_bias,
|
||||
has_transparent,
|
||||
s.item,
|
||||
) {
|
||||
out.extend(image.pixels.iter().flatten());
|
||||
}
|
||||
}
|
||||
(out, levels)
|
||||
@@ -395,6 +397,7 @@ impl Renderer {
|
||||
sprite_pixels: &[u8],
|
||||
sprite_size: u32,
|
||||
layers: u32,
|
||||
sprite_mips: &[crate::mipmap::Settings],
|
||||
animations: &[SpriteAnimation],
|
||||
hud_atlas: (&[u8], u32, u32),
|
||||
forcefield: (&[u8], u32),
|
||||
@@ -716,7 +719,7 @@ impl Renderer {
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let (mips, mip_levels) = mip_chain(sprite_pixels, sprite_size, layers);
|
||||
let (mips, mip_levels) = mip_chain(sprite_pixels, sprite_size, sprite_mips, 0, layers);
|
||||
let sprite_texture = device.create_texture_with_data(
|
||||
&queue,
|
||||
&wgpu::TextureDescriptor {
|
||||
@@ -1101,7 +1104,8 @@ impl Renderer {
|
||||
// WorldBorderRenderer: misc/forcefield.png as a MipmappedTexture
|
||||
// (repeat, linear minification with mipmaps, nearest magnification).
|
||||
let (forcefield_pixels, forcefield_size) = forcefield;
|
||||
let (forcefield_mips, forcefield_levels) = mip_chain(forcefield_pixels, forcefield_size, 1);
|
||||
let (forcefield_mips, forcefield_levels) =
|
||||
mip_chain(forcefield_pixels, forcefield_size, &[], 0, 1);
|
||||
let forcefield_texture = device.create_texture_with_data(
|
||||
&queue,
|
||||
&wgpu::TextureDescriptor {
|
||||
@@ -1408,6 +1412,7 @@ impl Renderer {
|
||||
lightmap_view,
|
||||
lightmap_sampler,
|
||||
animations: animations.iter().map(|a| (a.clone(), usize::MAX)).collect(),
|
||||
sprite_mips: sprite_mips.to_vec(),
|
||||
sprite_size,
|
||||
indices,
|
||||
index_quads,
|
||||
@@ -1786,7 +1791,13 @@ impl Renderer {
|
||||
continue;
|
||||
}
|
||||
*previous = frame;
|
||||
let (mips, levels) = mip_chain(animation.pixels(frame), self.sprite_size, 1);
|
||||
let (mips, levels) = mip_chain(
|
||||
animation.pixels(frame),
|
||||
self.sprite_size,
|
||||
&self.sprite_mips,
|
||||
animation.layer,
|
||||
1,
|
||||
);
|
||||
let mut offset = 0;
|
||||
for level in 0..levels.min(self.mip_levels) {
|
||||
let size = self.sprite_size >> level;
|
||||
|
||||
@@ -89,6 +89,7 @@ pub mod menu;
|
||||
pub mod merchant;
|
||||
pub mod mesher;
|
||||
pub mod minimap;
|
||||
pub mod mipmap;
|
||||
pub mod mobs;
|
||||
pub mod models;
|
||||
pub mod motion;
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
//! `MipmapGenerator`: the mip levels of a sprite. Cutout textures keep the
|
||||
//! alpha-test coverage of their base level at every level
|
||||
//! (`scaleAlphaToCoverage`), so thin cutout edges (cactus sides, leaves,
|
||||
//! flowers) don't erode into gaps with distance; colours average in linear
|
||||
//! light (`ARGB.meanLinear`).
|
||||
|
||||
/// `MipmapStrategy`, from the texture's `.mcmeta` `texture` section.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Strategy {
|
||||
#[default]
|
||||
Auto,
|
||||
Mean,
|
||||
Cutout,
|
||||
StrictCutout,
|
||||
DarkCutout,
|
||||
}
|
||||
impl Strategy {
|
||||
pub fn parse(name: &str) -> Option<Self> {
|
||||
Some(match name {
|
||||
"auto" => Self::Auto,
|
||||
"mean" => Self::Mean,
|
||||
"cutout" => Self::Cutout,
|
||||
"strict_cutout" => Self::StrictCutout,
|
||||
"dark_cutout" => Self::DarkCutout,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// How a sprite's mips are made: its `.mcmeta` `texture` section, whether
|
||||
/// it has a fully transparent pixel and whether it is an `item/` sprite.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct Settings {
|
||||
pub strategy: Strategy,
|
||||
pub alpha_cutoff_bias: f32,
|
||||
pub has_transparent: bool,
|
||||
pub item: bool,
|
||||
}
|
||||
|
||||
/// A square or rectangular RGBA8 image, rows top to bottom.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Image {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub pixels: Vec<[u8; 4]>,
|
||||
}
|
||||
impl Image {
|
||||
fn get(&self, x: u32, y: u32) -> [u8; 4] {
|
||||
self.pixels[(x + y * self.width) as usize]
|
||||
}
|
||||
fn set(&mut self, x: u32, y: u32, p: [u8; 4]) {
|
||||
self.pixels[(x + y * self.width) as usize] = p;
|
||||
}
|
||||
}
|
||||
|
||||
/// `ARGB.SRGB_TO_LINEAR`: an sRGB channel in linear light, 0 to 1023.
|
||||
fn srgb_to_linear() -> &'static [u16; 256] {
|
||||
static TABLE: std::sync::OnceLock<[u16; 256]> = std::sync::OnceLock::new();
|
||||
TABLE.get_or_init(|| {
|
||||
std::array::from_fn(|i| {
|
||||
let x = i as f32 / 255.0;
|
||||
let linear = if x >= 0.04045 {
|
||||
((f64::from(x) + 0.055) / 1.055).powf(2.4) as f32
|
||||
} else {
|
||||
x / 12.92
|
||||
};
|
||||
java_round(linear * 1023.0) as u16
|
||||
})
|
||||
})
|
||||
}
|
||||
/// `ARGB.LINEAR_TO_SRGB`: 1024 linear steps back to sRGB.
|
||||
fn linear_to_srgb() -> &'static [u8; 1024] {
|
||||
static TABLE: std::sync::OnceLock<[u8; 1024]> = std::sync::OnceLock::new();
|
||||
TABLE.get_or_init(|| {
|
||||
std::array::from_fn(|i| {
|
||||
let x = i as f32 / 1023.0;
|
||||
let srgb = if x >= 0.003_130_8 {
|
||||
(1.055 * f64::from(x).powf(0.416_666_666_666_666_7) - 0.055) as f32
|
||||
} else {
|
||||
12.92 * x
|
||||
};
|
||||
java_round(srgb * 255.0) as u8
|
||||
})
|
||||
})
|
||||
}
|
||||
/// `Math.round(float)`, bit for bit.
|
||||
fn java_round(a: f32) -> i32 {
|
||||
let bits = a.to_bits() as i32;
|
||||
let biased_exp = (bits & 0x7F80_0000) >> 23;
|
||||
let shift = (22 + 127) - biased_exp;
|
||||
if shift & -32 == 0 {
|
||||
let mut r = bits & 0x007F_FFFF | 0x0080_0000;
|
||||
if bits < 0 {
|
||||
r = -r;
|
||||
}
|
||||
((r >> shift) + 1) >> 1
|
||||
} else {
|
||||
a as i32
|
||||
}
|
||||
}
|
||||
/// `ARGB.alphaFloat`.
|
||||
fn alpha_float(p: [u8; 4]) -> f32 {
|
||||
f32::from(p[3]) / 255.0
|
||||
}
|
||||
|
||||
/// `MipmapGenerator.alphaTestCoverage`: the share of the image (bilinearly
|
||||
/// subsampled 4x4 per texel) whose scaled alpha passes `alpha_ref`.
|
||||
fn alpha_test_coverage(image: &Image, alpha_ref: f32, alpha_scale: f32) -> f32 {
|
||||
let (width, height) = (image.width as i32, image.height as i32);
|
||||
let mut coverage = 0.0f32;
|
||||
let a =
|
||||
|x: i32, y: i32| (alpha_float(image.get(x as u32, y as u32)) * alpha_scale).clamp(0.0, 1.0);
|
||||
for y in 0..height - 1 {
|
||||
for x in 0..width - 1 {
|
||||
let (a00, a10, a01, a11) = (a(x, y), a(x + 1, y), a(x, y + 1), a(x + 1, y + 1));
|
||||
let mut texel = 0.0f32;
|
||||
for sy in 0..4 {
|
||||
let fy = (sy as f32 + 0.5) / 4.0;
|
||||
for sx in 0..4 {
|
||||
let fx = (sx as f32 + 0.5) / 4.0;
|
||||
let alpha = a00 * (1.0 - fx) * (1.0 - fy)
|
||||
+ a10 * fx * (1.0 - fy)
|
||||
+ a01 * (1.0 - fx) * fy
|
||||
+ a11 * fx * fy;
|
||||
if alpha > alpha_ref {
|
||||
texel += 1.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
coverage += texel / 16.0;
|
||||
}
|
||||
}
|
||||
coverage / ((width - 1) * (height - 1)) as f32
|
||||
}
|
||||
|
||||
/// `MipmapGenerator.scaleAlphaToCoverage`: five bisection steps for the
|
||||
/// alpha scale whose coverage is nearest `desired`, then every alpha scaled
|
||||
/// and biased.
|
||||
fn scale_alpha_to_coverage(image: &mut Image, desired: f32, alpha_ref: f32, bias: f32) {
|
||||
let (mut min_scale, mut max_scale) = (0.0f32, 4.0f32);
|
||||
let mut scale = 1.0f32;
|
||||
let mut best_scale = 1.0f32;
|
||||
let mut best_error = f32::MAX;
|
||||
for _ in 0..5 {
|
||||
let current = alpha_test_coverage(image, alpha_ref, scale);
|
||||
let error = (current - desired).abs();
|
||||
if error < best_error {
|
||||
best_error = error;
|
||||
best_scale = scale;
|
||||
}
|
||||
if current < desired {
|
||||
min_scale = scale;
|
||||
} else if current > desired {
|
||||
max_scale = scale;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
scale = (min_scale + max_scale) * 0.5;
|
||||
}
|
||||
for p in &mut image.pixels {
|
||||
let alpha = (alpha_float(*p) * best_scale + bias + 0.025).clamp(0.0, 1.0);
|
||||
p[3] = (alpha * 255.0).floor() as u8;
|
||||
}
|
||||
}
|
||||
|
||||
/// `TextureUtil.solidify`: every transparent pixel takes the colour of the
|
||||
/// nearest opaque one (breadth first, keeping its zero alpha).
|
||||
fn solidify(image: &mut Image) {
|
||||
let (width, height) = (image.width as i32, image.height as i32);
|
||||
let n = image.pixels.len();
|
||||
let mut nearest = vec![[0u8; 4]; n];
|
||||
let mut distance = vec![i32::MAX; n];
|
||||
let mut queue = std::collections::VecDeque::new();
|
||||
for x in 0..width {
|
||||
for y in 0..height {
|
||||
let i = (x + y * width) as usize;
|
||||
let p = image.pixels[i];
|
||||
if p[3] != 0 {
|
||||
distance[i] = 0;
|
||||
nearest[i] = p;
|
||||
queue.push_back(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
while let Some(i) = queue.pop_front() {
|
||||
let (x, y) = (i as i32 % width, i as i32 / width);
|
||||
for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)] {
|
||||
let (nx, ny) = (x + dx, y + dy);
|
||||
if nx >= 0 && ny >= 0 && nx < width && ny < height {
|
||||
let j = (nx + ny * width) as usize;
|
||||
if distance[j] > distance[i] + 1 {
|
||||
distance[j] = distance[i] + 1;
|
||||
nearest[j] = nearest[i];
|
||||
queue.push_back(j);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i, p) in image.pixels.iter_mut().enumerate() {
|
||||
if p[3] == 0 {
|
||||
let c = nearest[i];
|
||||
*p = [c[0], c[1], c[2], 0];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `TextureUtil.fillEmptyAreasWithDarkColor`: transparent pixels take three
|
||||
/// quarters of the darkest visible colour.
|
||||
fn fill_empty_dark(image: &mut Image) {
|
||||
let mut darkest = [255u8; 4];
|
||||
let mut min = i32::MAX;
|
||||
for x in 0..image.width {
|
||||
for y in 0..image.height {
|
||||
let p = image.get(x, y);
|
||||
if p[3] != 0 {
|
||||
let brightness = i32::from(p[0]) + i32::from(p[1]) + i32::from(p[2]);
|
||||
if brightness < min {
|
||||
min = brightness;
|
||||
darkest = p;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let dark = |c: u8| (3 * i32::from(c) / 4) as u8;
|
||||
let fill = [dark(darkest[0]), dark(darkest[1]), dark(darkest[2]), 0];
|
||||
for p in &mut image.pixels {
|
||||
if p[3] == 0 {
|
||||
*p = fill;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `ARGB.meanLinear`.
|
||||
fn mean_linear(c: [[u8; 4]; 4]) -> [u8; 4] {
|
||||
let (to_linear, to_srgb) = (srgb_to_linear(), linear_to_srgb());
|
||||
let channel = |k: usize| {
|
||||
let sum: u32 = c.iter().map(|p| u32::from(to_linear[p[k] as usize])).sum();
|
||||
to_srgb[(sum / 4) as usize]
|
||||
};
|
||||
let alpha = c.iter().map(|p| u32::from(p[3])).sum::<u32>() / 4;
|
||||
[channel(0), channel(1), channel(2), alpha as u8]
|
||||
}
|
||||
|
||||
/// `MipmapGenerator.darkenedAlphaBlend`: the visible pixels' mean in linear
|
||||
/// light, transparent ones counting as black.
|
||||
fn darkened_alpha_blend(c: [[u8; 4]; 4]) -> [u8; 4] {
|
||||
let to_linear = srgb_to_linear();
|
||||
let linear = |v: u8| f32::from(to_linear[v as usize]) / 1023.0;
|
||||
let mut total = [0.0f32; 4];
|
||||
for p in c.iter().filter(|p| p[3] != 0) {
|
||||
total[3] += linear(p[3]);
|
||||
for k in 0..3 {
|
||||
total[k] += linear(p[k]);
|
||||
}
|
||||
}
|
||||
let to_srgb = |v: f32| linear_to_srgb()[(v / 4.0 * 1023.0).floor() as usize];
|
||||
[
|
||||
to_srgb(total[0]),
|
||||
to_srgb(total[1]),
|
||||
to_srgb(total[2]),
|
||||
to_srgb(total[3]),
|
||||
]
|
||||
}
|
||||
|
||||
/// `MipmapGenerator.generateMipLevels` from the base image (`levels` mips
|
||||
/// below it): `has_transparent` is `Transparency.hasTransparent` (a pixel
|
||||
/// with zero alpha), `item` whether the sprite is under `item/` (its base
|
||||
/// is left as is).
|
||||
pub fn generate(
|
||||
mut base: Image,
|
||||
levels: u32,
|
||||
strategy: Strategy,
|
||||
alpha_cutoff_bias: f32,
|
||||
has_transparent: bool,
|
||||
item: bool,
|
||||
) -> Vec<Image> {
|
||||
let strategy = match strategy {
|
||||
Strategy::Auto if has_transparent => Strategy::Cutout,
|
||||
Strategy::Auto => Strategy::Mean,
|
||||
s => s,
|
||||
};
|
||||
if !item {
|
||||
match strategy {
|
||||
Strategy::Cutout | Strategy::StrictCutout => solidify(&mut base),
|
||||
Strategy::DarkCutout => fill_empty_dark(&mut base),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let cutout = matches!(
|
||||
strategy,
|
||||
Strategy::Cutout | Strategy::StrictCutout | Strategy::DarkCutout
|
||||
);
|
||||
let alpha_ref = if strategy == Strategy::StrictCutout {
|
||||
0.3
|
||||
} else {
|
||||
0.5
|
||||
};
|
||||
let coverage = if cutout {
|
||||
alpha_test_coverage(&base, alpha_ref, 1.0)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let mut out = vec![base];
|
||||
for _ in 1..=levels {
|
||||
let last = out.last().expect("the base level");
|
||||
let (width, height) = (last.width >> 1, last.height >> 1);
|
||||
let mut data = Image {
|
||||
width,
|
||||
height,
|
||||
pixels: vec![[0; 4]; (width * height) as usize],
|
||||
};
|
||||
for x in 0..width {
|
||||
for y in 0..height {
|
||||
let c = [
|
||||
last.get(x * 2, y * 2),
|
||||
last.get(x * 2 + 1, y * 2),
|
||||
last.get(x * 2, y * 2 + 1),
|
||||
last.get(x * 2 + 1, y * 2 + 1),
|
||||
];
|
||||
let p = if strategy == Strategy::DarkCutout {
|
||||
darkened_alpha_blend(c)
|
||||
} else {
|
||||
mean_linear(c)
|
||||
};
|
||||
data.set(x, y, p);
|
||||
}
|
||||
}
|
||||
if cutout {
|
||||
scale_alpha_to_coverage(&mut data, coverage, alpha_ref, alpha_cutoff_bias);
|
||||
}
|
||||
out.push(data);
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -34,6 +34,8 @@ pub struct Sprites {
|
||||
pub animations: Vec<SpriteAnimation>,
|
||||
pub opaque: Vec<bool>,
|
||||
pub translucent: Vec<bool>,
|
||||
/// Each layer's `MipmapGenerator` settings.
|
||||
pub mips: Vec<crate::mipmap::Settings>,
|
||||
/// Each layer's frames at the texture's own resolution (square), and the
|
||||
/// frame shown first.
|
||||
native: Vec<(u32, Arc<Vec<Vec<u8>>>, usize)>,
|
||||
@@ -109,6 +111,7 @@ impl Sprites {
|
||||
let layer = u32::try_from(self.layers.len())?;
|
||||
self.opaque.push(true);
|
||||
self.translucent.push(false);
|
||||
self.mips.push(crate::mipmap::Settings::default());
|
||||
self.layers.insert(name.to_owned(), layer);
|
||||
self.native.push((SPRITE_SIZE, Arc::new(vec![frame]), 0));
|
||||
Ok(layer)
|
||||
@@ -198,6 +201,27 @@ impl Sprites {
|
||||
clip: Arc::new(clip),
|
||||
});
|
||||
}
|
||||
// SpriteContents: TextureMetadataSection's mipmap strategy and alpha
|
||||
// cutoff bias, and the whole image's NativeImage.computeTransparency.
|
||||
let texture = metadata
|
||||
.as_ref()
|
||||
.and_then(|v| v.get("texture"))
|
||||
.and_then(|v| serde_json::from_str::<serde_json::Value>(v.get()).ok());
|
||||
self.mips.push(crate::mipmap::Settings {
|
||||
strategy: texture
|
||||
.as_ref()
|
||||
.and_then(|t| t["mipmap_strategy"].as_str())
|
||||
.and_then(crate::mipmap::Strategy::parse)
|
||||
.unwrap_or_default(),
|
||||
alpha_cutoff_bias: texture
|
||||
.as_ref()
|
||||
.and_then(|t| t["alpha_cutoff_bias"].as_f64())
|
||||
.unwrap_or(0.0) as f32,
|
||||
has_transparent: pixels.as_chunks::<4>().0.iter().any(|p| p[3] == 0),
|
||||
item: name
|
||||
.split_once(':')
|
||||
.is_some_and(|(_, p)| p.starts_with("item/")),
|
||||
});
|
||||
self.opaque
|
||||
.push(pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255));
|
||||
self.translucent.push(
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import com.mojang.blaze3d.platform.NativeImage;
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import net.minecraft.client.renderer.texture.MipmapGenerator;
|
||||
import net.minecraft.client.renderer.texture.MipmapStrategy;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
/**
|
||||
* Vanilla's sprite mip levels for tools/test_mipmap_parity.py. The first
|
||||
* input line is the resources root; each further line is a sprite
|
||||
* (`minecraft:block/cactus_side`). The oracle reads its PNG and the `texture`
|
||||
* section of its .mcmeta (mipmap_strategy, alpha_cutoff_bias), as
|
||||
* SpriteContents does, and prints every level MipmapGenerator.generateMipLevels
|
||||
* makes (down to 1x1) as RGBA hex rows.
|
||||
*/
|
||||
public final class VanillaMipmapOracle {
|
||||
public static void main(String[] args) throws Exception {
|
||||
List<String> lines = Files.readAllLines(Path.of(args[0]), StandardCharsets.UTF_8);
|
||||
Path root = Path.of(lines.get(0));
|
||||
try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
for (String name : lines.subList(1, lines.size())) {
|
||||
Identifier id = Identifier.parse(name);
|
||||
Path png = root.resolve("assets/" + id.getNamespace() + "/textures/" + id.getPath() + ".png");
|
||||
Path meta = png.resolveSibling(png.getFileName() + ".mcmeta");
|
||||
MipmapStrategy strategy = MipmapStrategy.AUTO;
|
||||
float bias = 0.0F;
|
||||
if (Files.isRegularFile(meta)) {
|
||||
JsonObject json = JsonParser.parseString(Files.readString(meta)).getAsJsonObject();
|
||||
if (json.has("texture")) {
|
||||
JsonObject texture = json.getAsJsonObject("texture");
|
||||
if (texture.has("mipmap_strategy"))
|
||||
strategy = MipmapStrategy.valueOf(texture.get("mipmap_strategy").getAsString().toUpperCase(Locale.ROOT));
|
||||
if (texture.has("alpha_cutoff_bias")) bias = texture.get("alpha_cutoff_bias").getAsFloat();
|
||||
}
|
||||
}
|
||||
NativeImage image;
|
||||
try (var in = Files.newInputStream(png)) {
|
||||
image = NativeImage.read(in);
|
||||
}
|
||||
int levels = Integer.numberOfTrailingZeros(Math.min(image.getWidth(), image.getHeight()));
|
||||
NativeImage[] mips = MipmapGenerator.generateMipLevels(id, new NativeImage[] {image}, levels, strategy, bias, image.computeTransparency());
|
||||
out.println("== " + name);
|
||||
for (NativeImage mip : mips) {
|
||||
StringBuilder line = new StringBuilder(mip.getWidth() + "x" + mip.getHeight());
|
||||
for (int y = 0; y < mip.getHeight(); y++) {
|
||||
line.append(' ');
|
||||
for (int x = 0; x < mip.getWidth(); x++) {
|
||||
int c = mip.getPixel(x, y);
|
||||
line.append(String.format(Locale.ROOT, "%02x%02x%02x%02x", c >> 16 & 255, c >> 8 & 255, c & 255, c >>> 24));
|
||||
}
|
||||
}
|
||||
out.println(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sprite mip levels against the pinned client's MipmapGenerator.
|
||||
|
||||
Every static square block texture and a sample of item textures, with their
|
||||
.mcmeta `texture` settings (mipmap_strategy, alpha_cutoff_bias):
|
||||
VanillaMipmapOracle runs MipmapGenerator.generateMipLevels (solidify or the
|
||||
dark fill, meanLinear or darkenedAlphaBlend, scaleAlphaToCoverage for cutout
|
||||
sprites) and the `mipmap_probe` example loads the same sprites through
|
||||
`sprites::Sprites` and runs `mipmap::generate`; every level's pixels must be
|
||||
identical."""
|
||||
import json
|
||||
import struct
|
||||
|
||||
try:
|
||||
from . import oracle_harness as oh
|
||||
except ImportError:
|
||||
import oracle_harness as oh
|
||||
|
||||
NAME = 'mipmap-parity'
|
||||
|
||||
|
||||
def size(png):
|
||||
with open(png, 'rb') as f:
|
||||
head = f.read(24)
|
||||
return struct.unpack('>II', head[16:24])
|
||||
|
||||
|
||||
def make_input(build):
|
||||
root = oh.lab.LOCAL / 'horizon-client' / '26.3'
|
||||
textures = root / 'assets/minecraft/textures'
|
||||
names = []
|
||||
for folder, every in (('block', 1), ('item', 7)):
|
||||
for i, png in enumerate(sorted((textures / folder).glob('*.png'))):
|
||||
if i % every:
|
||||
continue
|
||||
meta = png.with_name(png.name + '.mcmeta')
|
||||
if meta.is_file() and 'animation' in json.loads(meta.read_text(encoding='utf-8')):
|
||||
continue
|
||||
w, h = size(png)
|
||||
if w != h or w & (w - 1) or w != 16:
|
||||
continue
|
||||
names.append(f'minecraft:{folder}/{png.stem}')
|
||||
path = build / 'sprites.txt'
|
||||
path.write_text('\n'.join([str(root)] + names) + '\n', encoding='utf-8')
|
||||
return path, len(names)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
oh.differential(NAME, 'VanillaMipmapOracle', 'mipmap_probe', make_input,
|
||||
'MipmapGenerator.generateMipLevels (solidify, fillEmptyAreasWithDarkColor, meanLinear, '
|
||||
'darkenedAlphaBlend, alphaTestCoverage, scaleAlphaToCoverage) on static 16x16 block and item sprites '
|
||||
'with their .mcmeta texture settings',
|
||||
sources=[oh.lab.ROOT / 'crates/horizon-client/src/mipmap.rs',
|
||||
oh.lab.ROOT / 'crates/horizon-client/src/sprites.rs'])
|
||||
Reference in New Issue
Block a user