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.

OptiFine emissive textures: cutout block overlays, native mods kept to 32, safer pairing

some-du6efacacb213834
diff --git a/crates/horizon-client-render/src/native_emissive.rs b/crates/horizon-client-render/src/native_emissive.rs
index 220206c64..23ac4ba7e 100644
--- a/crates/horizon-client-render/src/native_emissive.rs
+++ b/crates/horizon-client-render/src/native_emissive.rs
@@ -34,31 +34,72 @@ pub fn load(root: &Path, sprites: &mut Sprites) {
/// paired with it, first by name, at most [`MAX`]. A pack without such files adds nothing.
pub fn load_optifine(root: &Path, sprites: &mut Sprites) -> Vec<(String, String)> {
let suffix = horizon_optifine::emissive::suffix(root);
+ // Blocks with identical pixels share a layer (and the shader pairs by layer): a shared
+ // base would glow on every block that shares it, so it gets no overlay.
+ let mut sharing: BTreeMap<u32, usize> = BTreeMap::new();
+ for layer in sprites.layers.values() {
+ *sharing.entry(*layer).or_default() += 1;
+ }
let bases: Vec<String> = sprites
.layers
- .keys()
- .filter(|name| {
- name.split_once(':')
- .is_some_and(|(_, p)| p.starts_with("block/") && !p.ends_with(&suffix))
+ .iter()
+ .filter(|(name, layer)| {
+ sharing[layer] == 1
+ && name
+ .split_once(':')
+ .is_some_and(|(_, p)| p.starts_with("block/") && !p.ends_with(&suffix))
})
- .cloned()
+ .map(|(name, _)| name.clone())
.collect();
let mut pairs = Vec::new();
for base in bases {
+ let overlay = format!("{base}{suffix}");
+ let file = crate::atlas_sources::texture_path(root, &overlay, "textures");
+ if !std::fs::metadata(&file).is_ok_and(|m| m.is_file()) {
+ continue;
+ }
if pairs.len() == MAX {
+ log::warn!(
+ "Horizon: more than {MAX} emissive block overlays: {overlay} and later skipped"
+ );
break;
}
- let overlay = format!("{base}{suffix}");
- let file = crate::atlas_sources::texture_path(root, &overlay, "textures");
- if std::fs::metadata(file).is_ok_and(|m| m.is_file() && m.len() <= 1 << 20)
- && sprites.insert(root, &overlay).is_ok()
- {
- pairs.push((base, overlay));
+ if std::fs::metadata(&file).is_ok_and(|m| m.len() > 1 << 20) {
+ log::warn!("Horizon: emissive overlay {overlay} is over 1 MiB, skipped");
+ continue;
+ }
+ // A file that doesn't load would glow as the missing texture: no pair instead.
+ match sprites.try_insert(root, &overlay) {
+ Ok(_) => pairs.push((base, overlay)),
+ Err(e) => log::warn!("Horizon: emissive overlay {overlay} skipped: {e}"),
}
}
pairs
}
+/// The overlay layer's flag (its high bit) for an OptiFine overlay, which draws cutout: opaque
+/// where its alpha is at least 0.1 (OptiFine renders SOLID textures' overlays as CUTOUT).
+pub const CUTOUT: u32 = 1 << 31;
+
+/// The frame's overlay table: native mods' pairs (at most [`NATIVE`] requested), then the packs'
+/// OptiFine pairs flagged [`CUTOUT`], one per base layer (native first), sorted by base layer
+/// for the shader's early exit, at most [`MAX`].
+pub fn table<'a>(
+ layers: &BTreeMap<String, u32>,
+ native: impl IntoIterator<Item = (&'a str, &'a str)>,
+ optifine: &'a [(String, String)],
+) -> Vec<[u32; 4]> {
+ let mut by_base: BTreeMap<u32, [u32; 4]> = BTreeMap::new();
+ for pair in mappings(layers, native.into_iter().take(NATIVE)) {
+ by_base.insert(pair[0], pair);
+ }
+ let optifine = optifine.iter().map(|(b, o)| (b.as_str(), o.as_str()));
+ for [b, o, z, w] in mappings(layers, optifine) {
+ by_base.entry(b).or_insert([b, o | CUTOUT, z, w]);
+ }
+ by_base.into_values().take(MAX).collect()
+}
+
/// Only loaded base/overlay pairs are sent to the GPU; sorted for vertex lookup.
pub fn mappings<'a>(
layers: &BTreeMap<String, u32>,
@@ -77,14 +118,17 @@ pub fn mappings<'a>(
mod tests {
use super::*;
- fn png(path: &Path) {
+ /// A 16x16 image of one colour, `shade` its red (images of different shades never share a
+ /// sprite layer).
+ fn png(path: &Path, shade: u8) {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let file = std::io::BufWriter::new(std::fs::File::create(path).unwrap());
let mut encoder = png::Encoder::new(file, 16, 16);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
let mut writer = encoder.write_header().unwrap();
- writer.write_image_data(&[255; 16 * 16 * 4]).unwrap();
+ let pixels: Vec<u8> = (0..16 * 16).flat_map(|_| [shade, 9, 9, 255]).collect();
+ writer.write_image_data(&pixels).unwrap();
}
#[test]
@@ -93,20 +137,38 @@ mod tests {
std::env::temp_dir().join(format!("horizon-block-emissive-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let block = root.join("assets/minecraft/textures/block");
- for name in [
+ let names = [
"stone",
"stone_e",
"dirt",
"glowstone_e",
"deepslate",
"deepslate_glow",
- ] {
- png(&block.join(format!("{name}.png")));
+ "andesite",
+ "granite",
+ ];
+ for (i, name) in names.iter().enumerate() {
+ png(&block.join(format!("{name}.png")), i as u8 * 20);
}
- png(&root.join("assets/minecraft/textures/item/stick.png"));
- png(&root.join("assets/minecraft/textures/item/stick_e.png"));
+ // Same pixels as andesite: the two share a layer, so neither gets an overlay.
+ png(&block.join("diorite.png"), 6 * 20);
+ png(&block.join("diorite_e.png"), 200);
+ // A broken overlay: skipped, not drawn as the missing texture.
+ std::fs::write(block.join("granite_e.png"), b"not a png").unwrap();
+ png(&root.join("assets/minecraft/textures/item/stick.png"), 210);
+ png(
+ &root.join("assets/minecraft/textures/item/stick_e.png"),
+ 220,
+ );
let mut sprites = Sprites::default();
- for name in ["stone", "dirt", "deepslate"] {
+ for name in [
+ "stone",
+ "dirt",
+ "deepslate",
+ "andesite",
+ "diorite",
+ "granite",
+ ] {
sprites
.insert(&root, &format!("minecraft:block/{name}"))
.unwrap();
@@ -120,9 +182,10 @@ mod tests {
[(
"minecraft:block/stone".into(),
"minecraft:block/stone_e".into()
- ),]
+ )]
);
assert!(sprites.layers.contains_key("minecraft:block/stone_e"));
+ assert!(!sprites.layers.contains_key("minecraft:block/granite_e"));
// The pack's own suffix.
let props = root.join("assets/minecraft/optifine/emissive.properties");
std::fs::create_dir_all(props.parent().unwrap()).unwrap();
@@ -137,6 +200,28 @@ mod tests {
);
std::fs::remove_dir_all(&root).unwrap();
}
+
+ #[test]
+ fn the_table_keeps_native_pairs_first_and_flags_optifine_cutout() {
+ let layers: BTreeMap<String, u32> =
+ [("a", 5), ("a_e", 6), ("b", 2), ("b_e", 3), ("native", 9)]
+ .map(|(n, l)| (n.to_owned(), l))
+ .into();
+ let optifine = [
+ ("a".to_owned(), "a_e".to_owned()),
+ ("b".to_owned(), "b_e".to_owned()),
+ ];
+ // A native mod pairs `a` too: its pair wins; `b` stays the pack's, flagged.
+ let t = table(&layers, [("a", "native")], &optifine);
+ assert_eq!(
+ t,
+ [[2, 3 | CUTOUT, 0, 0], [5, 9, 0, 0]],
+ "sorted by base layer"
+ );
+ // Native mods keep their 32.
+ let many: Vec<(&str, &str)> = (0..40).map(|_| ("b", "native")).collect();
+ assert_eq!(table(&layers, many, &[]), [[2, 9, 0, 0]]);
+ }
#[test]
fn only_existing_pairs_are_mapped() {
let layers = [
diff --git a/crates/horizon-client-render/src/sprites.rs b/crates/horizon-client-render/src/sprites.rs
index ca38f33f8..de55cb985 100644
--- a/crates/horizon-client-render/src/sprites.rs
+++ b/crates/horizon-client-render/src/sprites.rs
@@ -305,6 +305,14 @@ impl Sprites {
/// The layer of a texture, added on first use. A texture that is missing
/// or does not load (a resource pack's filter or a broken file) becomes
/// vanilla's missing texture, as in a stitched atlas.
+ /// [`Sprites::insert`] without the missing-texture fallback: a file that doesn't load is an
+ /// error, and nothing is added.
+ pub fn try_insert(&mut self, root: &Path, name: &str) -> Result<u32> {
+ match self.layers.get(name) {
+ Some(layer) => Ok(*layer),
+ None => self.load(root, name),
+ }
+ }
pub fn insert(&mut self, root: &Path, name: &str) -> Result<u32> {
if let Some(layer) = self.layers.get(name) {
return Ok(*layer);
diff --git a/crates/horizon-client-render/src/terrain.wgsl b/crates/horizon-client-render/src/terrain.wgsl
index 7abf46c30..cc95930cc 100644
--- a/crates/horizon-client-render/src/terrain.wgsl
+++ b/crates/horizon-client-render/src/terrain.wgsl
@@ -370,9 +370,15 @@ fn terrain_vertex(position: vec3<f32>, uv: vec2<f32>, layer: u32, color: vec4<f3
out.uv = uv;
out.layer = layer;
out.emissive_layer = 0xffffffffu;
+ // The pairs are sorted by base layer: stop at the first past this one.
+ let sprite_layer = layer & 0x7fffu;
for (var i = 0u; i < min(globals.emissive_count.x, 128u); i++) {
- if globals.emissive_layers[i].x == (layer & 0x7fffu) {
- out.emissive_layer = globals.emissive_layers[i].y;
+ let pair = globals.emissive_layers[i];
+ if pair.x == sprite_layer {
+ out.emissive_layer = pair.y;
+ break;
+ }
+ if pair.x > sprite_layer {
break;
}
}
@@ -462,7 +468,11 @@ fn solid_finish(in: TerrainOut, texel: vec4<f32>, color: vec4<f32>) -> vec4<f32>
}
}
if in.emissive_layer != 0xffffffffu {
- let mask = sprite(in.uv, in.emissive_layer);
+ // The high bit: an OptiFine overlay, drawn cutout (opaque where alpha >= 0.1).
+ var mask = sprite(in.uv, in.emissive_layer & 0x7fffffffu);
+ if (in.emissive_layer & 0x80000000u) != 0u {
+ mask.a = select(0.0, 1.0, mask.a >= 0.1);
+ }
return apply_fog(vec4(mix(color.rgb, mask.rgb, mask.a), mix(emissive, hdr_mark(3u, 1.0), mask.a)), in.spherical, in.cylindrical);
}
return apply_fog(vec4(color.rgb, emissive), in.spherical, in.cylindrical);
diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs
index 9e05d3c0d..15a4aaa5c 100644
--- a/crates/horizon-client/src/game.rs
+++ b/crates/horizon-client/src/game.rs
@@ -15108,13 +15108,10 @@ impl Game<'_> {
let mut requests = Vec::new();
self.native_emissive(&mut requests);
// Native mods' overlays first, then the packs' OptiFine emissive blocks.
- let optifine = self.pack.render.emissive.iter();
- horizon_client::native_emissive::mappings(
+ horizon_client::native_emissive::table(
&self.pack.render.sprite_layers,
- requests
- .into_iter()
- .chain(optifine.map(|(base, overlay)| (base.as_str(), overlay.as_str())))
- .take(horizon_client::native_emissive::MAX),
+ requests,
+ &self.pack.render.emissive,
)
} else {
Vec::new()