Skip to content

Minecraft: Java Edition 26.3 rewritten from scratch in Rust, checked against vanilla with 281 differential harnesses. Get it with the Horizon launcher.

Fusion packs: cut connecting texture sheets into a sprite per tile

some-du6e64688576ee15
diff --git a/crates/horizon-client-render/src/sprites.rs b/crates/horizon-client-render/src/sprites.rs
index ca38f33f8..2ed854b09 100644
--- a/crates/horizon-client-render/src/sprites.rs
+++ b/crates/horizon-client-render/src/sprites.rs
@@ -405,6 +405,81 @@ impl Sprites {
};
self.register(root, resource, decoded)
}
+ /// The tiles of the texture `name` (`ns:path`) cut into a `columns` x `rows` grid, row by
+ /// row from the top left: a Fusion connecting texture's sheet. Each tile is its own layer
+ /// (named `fusion/<ns>/<path>#<tile>`); a fully transparent one is `None`, as Fusion skips empty
+ /// tiles. Tiles are square, as wide as a column. An animated sheet's frames are whole grids
+ /// one below the other, or with `per_tile` each cell is a column of its tile's frames.
+ pub fn insert_tiles(
+ &mut self,
+ root: &Path,
+ name: &str,
+ (columns, rows): (u32, u32),
+ per_tile: bool,
+ ) -> Result<Vec<Option<u32>>> {
+ let path = crate::atlas_sources::texture_path(root, name, "textures");
+ let animation = match fs::read_to_string(path.with_extension("png.mcmeta")) {
+ Ok(text) => {
+ serde_json::from_str::<BTreeMap<String, Box<serde_json::value::RawValue>>>(&text)?
+ .remove("animation")
+ .map(|v| v.get().to_owned())
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
+ Err(error) => return Err(error.into()),
+ };
+ let (width, height, pixels) = read_rgba(&path)?;
+ let side = width / columns.max(1);
+ // How far down the next frame of a tile is, and the next row of tiles.
+ let (frame_step, row_step) = match per_tile {
+ true => (side, height / rows.max(1)),
+ false => (rows * side, side),
+ };
+ let frames = match per_tile {
+ true => row_step / side.max(1),
+ false => height / frame_step.max(1),
+ };
+ let whole = match per_tile {
+ true => height % rows.max(1) == 0 && row_step % side.max(1) == 0,
+ false => height % frame_step.max(1) == 0,
+ };
+ if side == 0 || frames == 0 || width % columns.max(1) != 0 || !whole {
+ return Err(format!("{name} isn't a {columns} x {rows} grid of square tiles").into());
+ }
+ (0..columns * rows)
+ .map(|tile| {
+ let frames: Vec<Vec<u8>> = (0..frames)
+ .map(|f| {
+ let (x, y) = (
+ tile % columns * side,
+ tile / columns * row_step + f * frame_step,
+ );
+ (y..y + side)
+ .flat_map(|row| {
+ let start = ((row * width + x) * 4) as usize;
+ pixels[start..start + side as usize * 4].iter().copied()
+ })
+ .collect()
+ })
+ .collect();
+ let alphas = || frames.iter().flat_map(|f| f.iter().skip(3).step_by(4));
+ if alphas().all(|&a| a == 0) {
+ return Ok(None);
+ }
+ let decoded = crate::sprite_cache::Decoded {
+ side,
+ animation: animation.clone().filter(|_| frames.len() > 1),
+ strategy: Default::default(),
+ alpha_cutoff_bias: 0.0,
+ has_transparent: alphas().any(|&a| a == 0),
+ opaque: alphas().all(|&a| a == 255),
+ translucent: alphas().any(|&a| a != 0 && a != 255),
+ frames,
+ };
+ let tile_name = format!("fusion/{}#{tile}", name.replace(':', "/"));
+ self.register(root, &tile_name, decoded).map(Some)
+ })
+ .collect()
+ }
/// Read and decode one texture and its `.mcmeta`.
fn decode(root: &Path, name: &str) -> Result<crate::sprite_cache::Decoded> {
if !name.contains(':') {
@@ -754,6 +829,72 @@ mod tests {
fs::remove_dir_all(&root).unwrap();
}
#[test]
+ fn tile_sheets_cut_into_a_layer_per_tile() {
+ let root =
+ std::env::temp_dir().join(format!("horizon-sprite-tiles-{}", std::process::id()));
+ let file = root.join("assets/minecraft/textures/block/sheet.png");
+ fs::create_dir_all(file.parent().unwrap()).unwrap();
+ // 3 columns of 2 x 2 tiles over 4 rows of pixels: the pixel at (x, y) has red x, green
+ // y; the middle column is transparent, and the top-right tile half see-through.
+ let (w, h) = (6u32, 4u32);
+ let pixels: Vec<u8> = (0..w * h)
+ .flat_map(|i| {
+ let (x, y) = (i % w, i / w);
+ let alpha = match x / 2 {
+ 1 => 0,
+ 2 if y < 2 => 128,
+ _ => 255,
+ };
+ [x as u8, y as u8, 0, alpha]
+ })
+ .collect();
+ let mut encoder = png::Encoder::new(File::create(&file).unwrap(), w, h);
+ encoder.set_color(png::ColorType::Rgba);
+ encoder.set_depth(png::BitDepth::Eight);
+ encoder
+ .write_header()
+ .unwrap()
+ .write_image_data(&pixels)
+ .unwrap();
+ // Red and green of each pixel in a layer's frame.
+ let texels = |sprites: &Sprites, layer: u32, frame: usize| -> Vec<(u8, u8)> {
+ sprites.native[layer as usize].1[frame]
+ .chunks(4)
+ .map(|p| (p[0], p[1]))
+ .collect()
+ };
+ let mut sprites = Sprites::default();
+ let name = "minecraft:block/sheet";
+ // Still, as a 3 x 2 grid: the empty middle column draws nothing.
+ let tiles = sprites.insert_tiles(&root, name, (3, 2), false).unwrap();
+ assert_eq!(
+ tiles.iter().map(Option::is_some).collect::<Vec<_>>(),
+ [true, false, true, true, false, true]
+ );
+ let bottom_left = tiles[3].unwrap();
+ assert_eq!(
+ texels(&sprites, bottom_left, 0),
+ [(0, 2), (1, 2), (0, 3), (1, 3)]
+ );
+ assert!(sprites.translucent[tiles[2].unwrap() as usize]);
+ assert!(sprites.opaque[bottom_left as usize]);
+ // Animated, as one row of tiles: two frames, the grid's top and then its bottom half;
+ // per tile, each cell is the column of a tile's frames, which here is the same.
+ fs::write(file.with_extension("png.mcmeta"), r#"{"animation":{}}"#).unwrap();
+ for per_tile in [false, true] {
+ let mut sprites = Sprites::default();
+ let tiles = sprites.insert_tiles(&root, name, (3, 1), per_tile).unwrap();
+ let first = tiles[0].unwrap();
+ assert_eq!(texels(&sprites, first, 0), [(0, 0), (1, 0), (0, 1), (1, 1)]);
+ assert_eq!(texels(&sprites, first, 1), [(0, 2), (1, 2), (0, 3), (1, 3)]);
+ assert_eq!(sprites.animations.len(), 2, "two non-empty tiles");
+ }
+ // Not a grid of square tiles.
+ assert!(sprites.insert_tiles(&root, name, (4, 1), false).is_err());
+ assert!(sprites.insert_tiles(&root, name, (3, 3), false).is_err());
+ fs::remove_dir_all(&root).unwrap();
+ }
+ #[test]
fn custom_item_texture_ids_load_with_their_animation() {
let root = std::env::temp_dir().join(format!("horizon-sprite-cit-{}", std::process::id()));
let file = root.join("assets/minecraft/optifine/cit/a.png");