Merge pull request #1157 from ludovic111/fix/shaderpack-compat

🤖 Agent: merged after integration wave 1 on the desktop (main e730dc14 + #1108 #1114 #1131 #1157 #1158 #1162 = ae482a72): fmt, clippy -D warnings, workspace tests (one port-race flake in horizon-server panel, passes on rerun), release build, tools/parity.py --changed origin/main 299/302 then the 3 rerun: save_roundtrip pass, world_reopen pass x2 (one early-count flake), dedicated_server = known flake also failing on main (fixed by #1183/#1184).
This commit is contained in:
Ludovic Marie
2026-10-22 12:51:27 +02:00
committed by GitHub
7 changed files with 761 additions and 17 deletions
+39
View File
@@ -179,4 +179,43 @@ mod tests {
);
assert_eq!(vendor_name(0, "Apple M4 Pro"), "Apple");
}
/// The packs in `HORIZON_TEST_SHADERPACKS` (folders or zips) load as the
/// game loads them, with their default options: the compatibility table
/// of docs/shader-packs.md. Skipped when the variable isn't set.
#[test]
fn real_packs_load() {
let Some(dir) = std::env::var_os("HORIZON_TEST_SHADERPACKS") else {
return;
};
let mut entries: Vec<_> = std::fs::read_dir(dir)
.unwrap()
.flatten()
.map(|e| e.path())
.filter(|p| is_java_pack(p))
.collect();
entries.sort();
let mut failures = Vec::new();
for path in entries {
let name = path.file_name().unwrap().to_string_lossy().into_owned();
match load(&path, &BTreeMap::new(), "Apple", "Apple M4 Pro") {
Ok(pack) => {
let folders: Vec<String> = pack
.folders
.iter()
.map(|f| {
let n = f.passes.len() + usize::from(f.final_pass.is_some());
format!("{} {n} passes", f.folder)
})
.collect();
println!("{name}: loads ({})", folders.join(", "));
}
Err(e) => {
println!("{name}: {e}");
failures.push(name);
}
}
}
assert!(failures.is_empty(), "{failures:?}");
}
}
+175 -5
View File
@@ -6,8 +6,9 @@
use crate::include::Inlined;
use pp_rs::{
pp::Preprocessor,
token::{Punct, TokenValue},
token::{PreprocessorError, Punct, TokenValue},
};
use std::collections::HashMap;
/// The version of Minecraft packs are told they run on (`MC_VERSION`,
/// Iris's `formatVersionString("26.3")`).
@@ -286,14 +287,176 @@ fn mark_comments(text: &str) -> (String, Vec<String>) {
(out, comments)
}
/// Whether trimmed `line` is an `#if` or `#elif` directive.
pub(crate) fn is_condition(line: &str) -> bool {
line.strip_prefix('#')
.map(str::trim_start)
.and_then(|d| d.strip_prefix("elif").or_else(|| d.strip_prefix("if")))
.is_some_and(|r| !r.starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_'))
}
/// Whether `word` is a float literal.
pub(crate) fn is_float(word: &str) -> bool {
word.starts_with(|c: char| c.is_ascii_digit() || c == '.')
&& !word.starts_with("0x")
&& !word.starts_with("0X")
&& word.contains(['.', 'e', 'E'])
}
/// What JCPP's `#if` makes of a number (`Preprocessor.expr` takes
/// `NumericValue.longValue`): a float counts as its integer part, so
/// `0.75` is 0 and `1.5e1` is 10. `None` for a non-number.
pub(crate) fn jcpp_integer(number: &str) -> Option<i64> {
let number = number.trim_end_matches(['f', 'F', 'l', 'L', 'u', 'U']);
let (mantissa, exponent) = match number.find(['e', 'E']) {
Some(i) => (&number[..i], number[i + 1..].parse::<i32>().ok()?),
None => (number, 0),
};
let integer = mantissa.split('.').next()?;
let value = if integer.is_empty() {
0
} else {
integer.parse::<i64>().ok()?
};
Some((value as f64 * 10f64.powi(exponent)) as i64)
}
/// `line` with each word (identifier or number, with an exponent's sign:
/// `1e-3`) replaced by what `f` returns for it, if anything. The directive's
/// name and the names after `defined` are kept.
pub(crate) fn rewrite_condition(line: &str, f: impl Fn(&str) -> Option<String>) -> String {
let mut out = String::with_capacity(line.len());
let (mut rest, mut first, mut after_defined) = (line, true, false);
while let Some(c) = rest.chars().next() {
if !(c.is_ascii_alphanumeric() || c == '_' || c == '.') {
if !c.is_whitespace() && c != '(' && c != '#' {
after_defined = false;
}
out.push(c);
rest = &rest[c.len_utf8()..];
continue;
}
let bytes = rest.as_bytes();
let mut len = 0;
while let Some(&b) = bytes.get(len) {
let sign = (b == b'+' || b == b'-')
&& bytes[0].is_ascii_digit()
&& matches!(bytes[len - 1], b'e' | b'E');
if !(b.is_ascii_alphanumeric() || b == b'_' || b == b'.' || sign) {
break;
}
len += 1;
}
let word = &rest[..len];
let kept = first || after_defined;
match (!kept).then(|| f(word)).flatten() {
Some(replacement) => out.push_str(&replacement),
None => out.push_str(word),
}
after_defined = word == "defined";
first = false;
rest = &rest[len..];
}
out
}
/// Make pp-rs read `text` as JCPP, Iris's preprocessor, does:
/// - a `#define` replaces an earlier macro (`Preprocessor.addMacro`; Bloop
/// and Steadfast redefine theirs), where pp-rs refuses a different
/// redefinition: an `#undef` line goes before every `#define`;
/// - in `#if`/`#elif`, a float counts as its integer part, and so does a
/// macro always defined as the same float (an option: `#define LEVEL 0.5`);
/// a macro always defined empty (Iris's `MC_GL_VENDOR_OTHER`, Bloop's
/// `#define TAA_USE_YCOCG`) counts as 0: JCPP reports the missing operand
/// and goes on with 0. pp-rs stops on both;
/// - `#error "..."` (Photon's guard in programs it disables) lexes: pp-rs
/// has no string tokens and fails on the quote, even in a skipped block.
///
/// Returns the text and the added lines' 1-based numbers in it.
fn jcpp_compatible(text: &str, env: &Environment) -> (String, Vec<u32>) {
// A `#define` line's name and body.
let define = |l: &str| {
let rest = l
.trim_start()
.strip_prefix('#')?
.trim_start()
.strip_prefix("define")
.filter(|rest| rest.starts_with([' ', '\t']))?
.trim_start();
let end = rest
.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
.unwrap_or(rest.len());
let (name, body) = rest.split_at(end);
let body = body.split("//").next().unwrap_or("").trim();
(!name.is_empty()).then(|| (name.to_owned(), body.to_owned()))
};
// Each macro's body, if every definition has the same one.
let mut bodies: HashMap<String, Option<String>> = HashMap::new();
let definitions = env
.defines
.iter()
.cloned()
.chain(text.lines().filter_map(define));
for (name, body) in definitions {
bodies
.entry(name)
.and_modify(|b| {
if b.as_ref() != Some(&body) {
*b = None;
}
})
.or_insert(Some(body));
}
let number = |word: &str| -> Option<String> {
let word = match bodies.get(word) {
Some(Some(body)) if body.is_empty() => return Some("0".into()),
Some(Some(body)) => body.as_str(),
Some(None) => return None,
None => word,
};
is_float(word)
.then(|| jcpp_integer(word))
.flatten()
.map(|n| n.to_string())
};
let mut out = String::with_capacity(text.len() + text.len() / 16);
let mut added = Vec::new();
let (mut line, mut continued) = (1, false);
for l in text.split_inclusive('\n') {
if !continued && let Some((name, _)) = define(l) {
out.push_str(&format!("#undef {name}\n"));
added.push(line);
line += 1;
}
let directive = l.trim_start().strip_prefix('#').map(str::trim_start);
if !continued
&& directive.is_some_and(|d| d.starts_with("error") || d.starts_with("warning"))
{
out.push_str(&l.replace(['"', '\''], ""));
} else if !continued && is_condition(l.trim_start()) {
out.push_str(&rewrite_condition(l, number));
} else {
out.push_str(l);
}
continued = l.trim_end().ends_with('\\');
line += 1;
}
(out, added)
}
/// Expand `source` with `env`'s macros. Errors name the file and line.
pub fn preprocess(source: &Inlined, env: &Environment) -> Result<Preprocessed, String> {
let (marked, comments) = mark_comments(&source.text);
let text = &marked;
let (text, added) = jcpp_compatible(&marked, env);
let text = &text;
let line_starts: Vec<usize> = std::iter::once(0)
.chain(text.match_indices('\n').map(|(i, _)| i + 1))
.collect();
let line_of = |offset: u32| line_starts.partition_point(|&s| s <= offset as usize) as u32;
// Lines of the source: the added `#undef` lines don't count.
let line_of = |offset: u32| {
let line = line_starts.partition_point(|&s| s <= offset as usize) as u32;
line - added.partition_point(|&a| a < line) as u32
};
let mut pp = Preprocessor::new(text);
for (name, value) in &env.defines {
pp.add_define(name, value)
@@ -307,8 +470,15 @@ pub fn preprocess(source: &Inlined, env: &Environment) -> Result<Preprocessed, S
};
let mut line = 1;
for item in pp {
let token =
item.map_err(|(e, at)| format!("{}: {e:?}", source.locate(line_of(at.start))))?;
let token = match item {
// JCPP lets an `#if` run to the end of the input (Bloop's
// taa.fsh never closes its `#ifdef TAA`); pp-rs says so there,
// after the last token.
Err((PreprocessorError::UnfinishedBlock, _)) => break,
item => {
item.map_err(|(e, at)| format!("{}: {e:?}", source.locate(line_of(at.start))))?
}
};
let at = line_of(token.location.start);
let piece = match token.value {
TokenValue::Version(v) => {
+62 -6
View File
@@ -6,7 +6,7 @@
//! so `#if` blocks pick the directives that apply.
use crate::options::{OptionSet, OptionValues};
use crate::preprocess::Environment;
use crate::preprocess::{Environment, is_condition, is_float, jcpp_integer, rewrite_condition};
use pp_rs::{pp::Preprocessor, token::TokenValue};
use std::collections::BTreeMap;
@@ -120,9 +120,32 @@ const DIRECTIVES: &[&str] = &[
"#warning", "#pragma", "#line", "#include",
];
/// An `#if`/`#elif` line with its floats as JCPP reads them (Steadfast tests
/// `#if ATMOSPHERE_FOG_STRENGTH_NOON == 0.75` with the option at 0.5, which
/// Iris reads as `0 == 0`): float literals and the options set to a float
/// become their integer part.
fn jcpp_condition(line: &str, options: &OptionSet, values: &OptionValues) -> String {
rewrite_condition(line, |word| {
let value = match options.strings.get(word) {
Some(o) => values.strings.get(word).unwrap_or(&o.default).as_str(),
None => word,
};
is_float(value)
.then(|| jcpp_integer(value))
.flatten()
.map(|n| n.to_string())
})
}
/// What backslashes are while the macros expand, as in Iris: the
/// preprocessor must not join a `\`-continued value with the directive on
/// the next line (Photon ends an `#if`'d value with `) \` before `#else`).
const BACKSLASH: &str = "IRIS_PASSTHROUGHBACKSLASH";
/// `PropertiesPreprocessor.preprocessSource`: comment lines dropped, other
/// `#`s removed, then the macros expanded. Tokens keep their source spelling
/// and spacing (`0.50` stays `0.50`, `<empty>` stays one word).
/// `#`s removed, then the macros expanded with the backslashes hidden.
/// Tokens keep their source spelling and spacing (`0.50` stays `0.50`,
/// `<empty>` stays one word).
pub fn preprocess(
text: &str,
env: &Environment,
@@ -132,7 +155,6 @@ pub fn preprocess(
let filtered: String = text
.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.map(|l| match l.starts_with('#') {
// JCPP lets a #define replace a macro (Complementary sets
// COLORED_LIGHTING 0 on macOS); pp-rs refuses, so undefine first.
@@ -142,11 +164,12 @@ pub fn preprocess(
None => l.to_owned(),
}
}
true if is_condition(l) => jcpp_condition(l, options, values),
true if DIRECTIVES.iter().any(|d| l.starts_with(d)) => l.to_owned(),
true => String::new(),
false => l.replace('#', ""),
})
.map(|l| l + "\n")
.map(|l| l.replace('\\', BACKSLASH) + "\n")
.collect();
let mut pp = Preprocessor::new(&filtered);
let mut define = |name: &str, value: &str| {
@@ -202,7 +225,7 @@ pub fn preprocess(
});
}
out.push('\n');
Ok(out)
Ok(out.replace(BACKSLASH, "\\"))
}
/// One element of an option screen (`OptionMenuElement`).
@@ -698,6 +721,39 @@ mod tests {
);
}
#[test]
fn floats_in_conditions_count_as_their_integer_part() {
assert_eq!(
[".5", "0.75", "1.0", "2.5f", "1.5e1", "7", "0x10"].map(jcpp_integer),
[Some(0), Some(0), Some(1), Some(2), Some(10), Some(7), None]
);
// Steadfast's fog strength: the option is 0.5, so Iris takes the
// 0.75 branch (0 == 0).
let set = options(&["#define FOG 0.5 // [0.0 0.5 0.75 1.0]"]);
let text = "\
#if FOG == 1.0
a = 1
#elif FOG == 0.75
a = 0.75
#else
a = 0.5
#endif
#if(FOG<1e1)
b = 1
#endif
";
let env = Environment {
defines: Vec::new(),
};
let values = OptionValues::default();
let out = preprocess(text, &env, &set, &values).unwrap();
assert_eq!(out, "a = 0.75\nb = 1\n");
assert_eq!(
jcpp_condition("#elif FOG == 0.75 && X > 2.5", &set, &values),
"#elif 0 == 0 && X > 2"
);
}
#[test]
fn boolean_expressions() {
let set = options(&["#define A", "//#define B", "#define C"]);
+287 -5
View File
@@ -18,7 +18,11 @@
//! swizzled shadow lookup is widened first (naga has no scalar swizzle);
//! - global initialisers run at the start of `main` (drivers accept
//! non-constant ones), unsized global arrays are sized from them;
//! - `isnan`, `isinf` and `modf` are helper functions (WGSL has none).
//! - `isnan`, `isinf` and `modf` are helper functions (WGSL has none);
//! - what naga refuses and drivers accept: `%` goes through overloads (naga
//! won't take `ivec2 % int`), `sqrt` of a negative constant isn't folded,
//! constants naga can't fold (`?:`, `mix`) become globals set in `main`,
//! and 16/8-bit types are their 32-bit ones.
//!
//! The programs of one pass share a [`Link`], so their locations, bindings and
//! uniform block agree.
@@ -234,6 +238,106 @@ vec3 iris_modf(vec3 x, out vec3 i) { i = trunc(x); return x - i; }
vec4 iris_modf(vec4 x, out vec4 i) { i = trunc(x); return x - i; }
";
/// A fragment output narrower than four channels (`out vec3 color`,
/// Steadfast's `final`): the four-channel type it is written through and the
/// epilogue line that fills it, with alpha 1 and the rest 0. `None` when the
/// output already has four channels.
fn widen_output(ty: &str, name: &str) -> Option<(String, String)> {
let (wide, one, zero) = match ty {
"float" | "vec2" | "vec3" => ("vec4", "1.0", "0.0"),
"int" | "ivec2" | "ivec3" => ("ivec4", "1", "0"),
"uint" | "uvec2" | "uvec3" => ("uvec4", "1u", "0u"),
_ => return None,
};
let channels = match ty.chars().last() {
Some('2') => 2,
Some('3') => 3,
_ => 1,
};
let mut parts = vec![name.to_owned()];
parts.extend((channels..3).map(|_| zero.to_owned()));
parts.push(one.to_owned());
Some((
wide.to_owned(),
format!("iris_out_{name} = {wide}({});", parts.join(", ")),
))
}
/// `%` as overloads: naga's GLSL front end splats a scalar operand for
/// `+ - / & ^ |` but not for `%`, and rejects `ivec2(uv) % 256` (Noble).
fn modulo_helpers() -> String {
let mut out = String::new();
for (s, v) in [("int", "ivec"), ("uint", "uvec")] {
out.push_str(&format!("{s} iris_mod({s} a, {s} b) {{ return a % b; }}\n"));
for n in 2..=4 {
let v = format!("{v}{n}");
out.push_str(&format!("{v} iris_mod({v} a, {v} b) {{ return a % b; }}\n"));
out.push_str(&format!(
"{v} iris_mod({v} a, {s} b) {{ return a % {v}(b); }}\n"
));
out.push_str(&format!(
"{v} iris_mod({s} a, {v} b) {{ return {v}(a) % b; }}\n"
));
}
}
out
}
/// 16- and 8-bit types (`GL_NV_gpu_shader5`, `GL_EXT_shader_explicit_arithmetic_types`)
/// and their built-ins, as the 32-bit ones WGSL has: Noble declares
/// `u16vec2` & co. when Iris reports an NVIDIA GPU, and falls back to these
/// same aliases elsewhere.
const SMALL_TYPES: &[(&str, &str)] = &[
("float16_t", "float"),
("f16vec2", "vec2"),
("f16vec3", "vec3"),
("f16vec4", "vec4"),
("int16_t", "int"),
("i16vec2", "ivec2"),
("i16vec3", "ivec3"),
("i16vec4", "ivec4"),
("uint16_t", "uint"),
("u16vec2", "uvec2"),
("u16vec3", "uvec3"),
("u16vec4", "uvec4"),
("int8_t", "int"),
("i8vec2", "ivec2"),
("i8vec3", "ivec3"),
("i8vec4", "ivec4"),
("uint8_t", "uint"),
("u8vec2", "uvec2"),
("u8vec3", "uvec3"),
("u8vec4", "uvec4"),
("packFloat2x16", "packHalf2x16"),
("unpackFloat2x16", "unpackHalf2x16"),
];
/// `source` with [`SMALL_TYPES`] replaced, word by word.
fn widen_small_types(source: &str) -> std::borrow::Cow<'_, str> {
if !SMALL_TYPES.iter().any(|(t, _)| source.contains(t)) {
return source.into();
}
let mut out = String::with_capacity(source.len());
let mut rest = source;
while let Some(c) = rest.chars().next() {
let len = if c.is_ascii_alphanumeric() || c == '_' {
rest.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
.unwrap_or(rest.len())
} else {
c.len_utf8()
};
let word = &rest[..len];
out.push_str(
SMALL_TYPES
.iter()
.find(|(t, _)| *t == word)
.map_or(word, |(_, w)| w),
);
rest = &rest[len..];
}
out.into()
}
/// Translate one preprocessed program. `locate` turns a line of `source`
/// into `file:line` for errors.
pub fn translate(
@@ -248,7 +352,8 @@ pub fn translate(
Stage::Compute => naga::ShaderStage::Compute,
_ => return Err(format!("{stage:?} programs are not supported")),
};
let mut unit = ast::TranslationUnit::parse(source).map_err(|e| {
let source = widen_small_types(source);
let mut unit = ast::TranslationUnit::parse(&source).map_err(|e| {
let line = e.line() + 1;
format!("{}: {}", locate(line), e.inner())
})?;
@@ -281,6 +386,111 @@ pub fn translate(
})
}
/// The GLSL built-ins naga's constant evaluator folds (`MathFunction`s it
/// implements), besides type constructors.
const FOLDABLE: &[&str] = &[
"abs",
"acos",
"acosh",
"asin",
"asinh",
"atan",
"atanh",
"ceil",
"clamp",
"cos",
"cosh",
"cross",
"degrees",
"distance",
"dot",
"exp",
"exp2",
"floor",
"fma",
"fract",
"inversesqrt",
"length",
"log",
"log2",
"max",
"min",
"normalize",
"pow",
"radians",
"round",
"sign",
"sin",
"sinh",
"sqrt",
"step",
"tan",
"tanh",
"trunc",
];
/// Whether a constant's initialisers need what naga can't fold and drivers
/// do: a `?:`, another built-in (Bliss's `mix`), or a constant that had to
/// become a global (`runtime`).
fn needs_runtime(list: &ast::InitDeclaratorList, runtime: &HashSet<String>) -> bool {
let constructor = |name: &str| {
let n = name.trim_start_matches(['i', 'u', 'b', 'd']);
matches!(name, "float" | "int" | "uint" | "bool" | "double")
|| n.starts_with("vec")
|| n.starts_with("mat")
};
let expr = |e: &ast::Expr| {
fn walk(e: &ast::Expr, f: &dyn Fn(&ast::Expr) -> bool) -> bool {
use ast::ExprData as E;
f(e) || match &e.content {
E::Unary(_, a) | E::PostInc(a) | E::PostDec(a) | E::Dot(a, _) => walk(a, f),
E::Binary(_, a, b) | E::Assignment(a, _, b) | E::Comma(a, b) | E::Bracket(a, b) => {
walk(a, f) || walk(b, f)
}
E::Ternary(a, b, c) => walk(a, f) || walk(b, f) || walk(c, f),
E::FunCall(_, args) => args.iter().any(|a| walk(a, f)),
_ => false,
}
}
walk(e, &|e| match &e.content {
ast::ExprData::Ternary(..) => true,
ast::ExprData::Variable(v) => runtime.contains(v.as_str()),
ast::ExprData::FunCall(f, _) => {
callee(f).is_some_and(|c| !constructor(&c) && !FOLDABLE.contains(&c.as_str()))
}
_ => false,
})
};
fn init(i: &ast::Initializer, expr: &dyn Fn(&ast::Expr) -> bool) -> bool {
match &i.content {
ast::InitializerData::Simple(e) => expr(e),
ast::InitializerData::List(items) => items.iter().any(|i| init(i, expr)),
}
}
let tail = list.tail.iter().filter_map(|t| t.initializer.as_ref());
list.head
.initializer
.iter()
.chain(tail)
.any(|i| init(i, &expr))
}
/// A negative number: `-1.0`, `-1`.
fn negative_constant(e: &ast::Expr) -> bool {
use ast::ExprData as E;
match &e.content {
E::Unary(op, a) if op.content == ast::UnaryOpData::Minus => {
matches!(
a.content,
E::FloatConst(v) if v > 0.0
) || matches!(a.content, E::IntConst(v) if v > 0)
|| matches!(a.content, E::DoubleConst(v) if v > 0.0)
}
E::FloatConst(v) => *v < 0.0,
_ => false,
}
}
fn first_lines(s: &str) -> String {
s.lines().take(8).collect::<Vec<_>>().join("\n")
}
@@ -316,6 +526,14 @@ struct Legaliser<'a> {
/// Identifiers used, for the implicit declarations.
used: HashSet<String>,
errors: Vec<String>,
/// Inside a constant initialiser: no helper calls there.
constant: bool,
/// The program uses `%` ([`modulo_helpers`]) or `iris_sqrt`: their
/// helpers go in.
modulo: bool,
nan: bool,
/// Constants turned into globals ([`needs_runtime`]).
runtime_constants: HashSet<String>,
}
fn var(name: &str) -> ast::Expr {
@@ -507,6 +725,10 @@ impl<'a> Legaliser<'a> {
declared: HashSet::new(),
used: HashSet::new(),
errors: Vec::new(),
constant: false,
modulo: false,
nan: false,
runtime_constants: HashSet::new(),
}
}
@@ -727,8 +949,19 @@ impl<'a> Legaliser<'a> {
let at = explicit
.map(|l: u32| l + i as u32)
.unwrap_or_else(|| self.next_output());
self.header
.push(format!("layout(location = {at}) out {full} {name}{array};"));
if let (Some(widened), "") = (widen_output(&full, name), array.as_str()) {
// GL fills the missing channels of a narrow output;
// wgpu wants every channel of the target written.
let (wide, fill) = widened;
self.header.push(format!("{full} {name};"));
self.header.push(format!(
"layout(location = {at}) out {wide} iris_out_{name};"
));
self.epilogue.push(fill);
} else {
self.header
.push(format!("layout(location = {at}) out {full} {name}{array};"));
}
self.interface.outputs.insert(at, name.clone());
} else {
self.varying(dir, &interp, &full, name, array);
@@ -736,9 +969,25 @@ impl<'a> Legaliser<'a> {
}
return Ok(false);
}
if has(ast::StorageQualifierData::Const) || has(ast::StorageQualifierData::Shared) {
// A constant naga can't fold becomes a global set at the start of `main`.
if has(ast::StorageQualifierData::Const) && needs_runtime(list, &self.runtime_constants) {
self.runtime_constants
.extend(names.iter().map(|(n, _)| n.clone()));
let q = &mut list.head.ty.qualifier;
if let Some(q) = q {
q.qualifiers.retain(|q| {
!matches!(&q.content, ast::TypeQualifierSpecData::Storage(s)
if s.content == ast::StorageQualifierData::Const)
});
}
if q.as_ref().is_some_and(|q| q.qualifiers.is_empty()) {
*q = None;
}
} else if has(ast::StorageQualifierData::Const) || has(ast::StorageQualifierData::Shared) {
self.sized(list);
self.constant = true;
self.global_initialisers(list, false);
self.constant = false;
return Ok(true);
}
self.sized(list);
@@ -930,6 +1179,8 @@ impl<'a> Legaliser<'a> {
return;
};
self.sized(list);
self.constant =
storage(&list.head.ty.qualifier).contains(&ast::StorageQualifierData::Const);
if let Some(i) = &mut list.head.initializer {
self.initializer(i);
}
@@ -944,6 +1195,7 @@ impl<'a> Legaliser<'a> {
let n = t.ident.ident.as_str().to_owned();
self.declare(&n);
}
self.constant = false;
}
fn initializer(&mut self, i: &mut ast::Initializer) {
@@ -1148,6 +1400,24 @@ impl<'a> Legaliser<'a> {
| E::FloatConst(_)
| E::DoubleConst(_) => {}
E::Unary(_, a) | E::PostInc(a) | E::PostDec(a) => self.expr(a),
E::Binary(op, a, b) if op.content == ast::BinaryOpData::Mod && !self.constant => {
self.expr(a);
self.expr(b);
self.modulo = true;
let (a, b) = (
std::mem::replace(&mut **a, var("_")),
std::mem::replace(&mut **b, var("_")),
);
*e = call("iris_mod", vec![a, b]);
}
E::Assignment(a, op, b) if op.content == ast::AssignmentOpData::Mod => {
self.expr(a);
self.expr(b);
self.modulo = true;
let rhs = std::mem::replace(&mut **b, var("_"));
**b = call("iris_mod", vec![(**a).clone(), rhs]);
*op = ast::AssignmentOpData::Equal.into_node();
}
E::Binary(_, a, b) | E::Assignment(a, _, b) | E::Comma(a, b) => {
self.expr(a);
self.expr(b);
@@ -1268,6 +1538,12 @@ impl<'a> Legaliser<'a> {
if self.functions.contains(&name) {
return;
}
// `sqrt(-1.0)`, Bloop's NaN: naga folds it and fails, drivers give NaN.
if name == "sqrt" && !self.constant && args.len() == 1 && negative_constant(&args[0]) {
*f = ast::FunIdentifierData::Expr(Box::new(var("iris_sqrt"))).into_node();
self.nan = true;
return;
}
if let Some((_, new)) = LEGACY_CALLS.iter().find(|(old, _)| *old == name) {
*f = ast::FunIdentifierData::Expr(Box::new(var(new))).into_node();
} else if let Some((_, new)) = SHADOW_CALLS.iter().find(|(old, _)| *old == name) {
@@ -1307,6 +1583,12 @@ impl<'a> Legaliser<'a> {
}
let mut out = String::from("#version 450 core\n");
out.push_str(HELPERS);
if self.modulo {
out.push_str(&modulo_helpers());
}
if self.nan {
out.push_str("float iris_sqrt(float x) { return sqrt(x); }\n");
}
if !self.link.uniforms.is_empty() {
out.push_str("layout(std140, set = 0, binding = 0) uniform IrisUniforms {\n");
for (_, decl) in &self.link.uniforms {
+63
View File
@@ -121,6 +121,69 @@ fn preprocesses_with_defaults_and_with_values() {
);
}
/// JCPP lets a `#define` replace a macro (Bloop's `TILT_ANGLE`); the added
/// `#undef`s don't move the lines errors name.
#[test]
fn a_define_replaces_an_earlier_one() {
use horizon_shaderpack::{include::Inlined, preprocess::preprocess};
let text = "#define TILT 5.0\nfloat a = TILT;\n # define TILT 1.5 // radians\nfloat b = TILT;\n#define F(x) x\n#define F(x) (x * 2)\nfloat c = F(1);\n#if\n";
let source = Inlined {
text: text.into(),
origin: (1..=8).map(|l| ("lib/specular.glsl".into(), l)).collect(),
};
let error = preprocess(&source, &env()).unwrap_err();
assert!(error.starts_with("lib/specular.glsl:8:"), "{error}");
let source = Inlined {
text: text.replace("#if\n", ""),
..source
};
let out = preprocess(&source, &env()).unwrap().text;
let lines: Vec<&str> = out.lines().collect();
assert_eq!(lines[1], "float a = 5.0 ;");
assert_eq!(lines[3], "float b = 1.5 ;");
assert_eq!(lines[6], "float c = ( 1 * 2 ) ;");
}
/// Conditions as JCPP reads them: an empty macro counts as 0 (Bloop's
/// `#if MC_GL_VENDOR_INTEL || MC_GL_VENDOR_OTHER` with Iris's empty vendor
/// macro, its `#define TAA_USE_YCOCG`), a float as its integer part; a
/// quoted `#error` lexes, and an `#if` may run to the end.
#[test]
fn conditions_read_as_jcpp_does() {
use horizon_shaderpack::{include::Inlined, preprocess::preprocess};
let mut env = env();
env.define("MC_GL_VENDOR_OTHER", "");
let text = "#define TAA_USE_YCOCG
#define LEVEL 0.5
#if MC_GL_VENDOR_INTEL || MC_GL_VENDOR_OTHER
float gather = 0.0;
#else
float gather = 1.0;
#endif
#if TAA_USE_YCOCG
float ycocg = 1.0;
#endif
#if defined TAA_USE_YCOCG && defined(MC_GL_VENDOR_OTHER) && LEVEL == 0
float both = 1.0;
#endif
#ifndef TAA_USE_YCOCG
#error \"This program should be disabled\"
#endif
#ifdef TAA_USE_YCOCG
float open = 1.0;
";
let source = Inlined {
text: text.into(),
origin: Vec::new(),
};
let out = preprocess(&source, &env).unwrap().text;
let words: Vec<&str> = out.split_whitespace().collect();
assert_eq!(
words.join(" "),
"float gather = 1.0 ; float both = 1.0 ; float open = 1.0 ;"
);
}
#[test]
fn reports_missing_includes_and_cycles() {
let pack = JavaPack::open(&mini()).unwrap();
@@ -290,6 +290,103 @@ fn reports_errors_with_their_place() {
assert_eq!(err, "uniform a is declared as both `float a` and `int a`");
}
/// What naga refuses and drivers accept: `vec % scalar` (Noble), `sqrt` of
/// a negative constant (Bloop's NaN), constants naga can't fold (Bliss's
/// `?:`, `mix`), and 16-bit types (Noble on NVIDIA).
#[test]
fn legalises_what_naga_refuses() {
let mut link = Link::default();
let fs = run(
Stage::Fragment,
"uniform vec2 uv;
const int RES = 256 % 100;
const vec3 TARGET = length(vec3(1.0)) < 0.001 ? vec3(0.0) : normalize(vec3(1.0));
const vec3 TINT = mix(TARGET, vec3(1.0), 0.5);
const vec3 HALF = TINT * 0.5;
u16vec2 pack(uint v) { return u16vec2(v & 65535u, v >> 16u); }
float nan() { return sqrt(-1.0); }
void main() {
ivec2 texel = ivec2(uv) % RES;
texel %= 7;
uint packed = packFloat2x16(f16vec2(HALF.xy));
gl_FragColor = vec4(vec2(texel), float(pack(packed).x), nan());
}
",
&mut link,
)
.unwrap();
for wanted in [
"const int RES = 256 % 100;",
"vec3 TARGET;",
"vec3 TINT;",
"vec3 HALF;",
"ivec2 texel = iris_mod(ivec2(uv), RES);",
"texel = iris_mod(texel, 7);",
"uvec2 pack(uint v)",
"return iris_sqrt(-1.);",
"uint packed = packHalf2x16(vec2(HALF.xy));",
] {
assert!(fs.glsl.contains(wanted), "{wanted}\n{}", fs.glsl);
}
reparse(&fs.wgsl).unwrap();
}
/// A fragment output narrower than its four-channel target (Steadfast's
/// `final` writes `out vec3 color`) is written through a `vec4` with alpha 1:
/// GL fills the missing channels, wgpu refuses the pipeline.
#[test]
fn narrow_fragment_outputs_fill_four_channels() {
let mut link = Link::default();
let fs = run(
Stage::Fragment,
"uniform vec3 tint;
layout(location = 0) out vec3 color;
layout(location = 1) out float depth;
out vec4 extra;
void main() {
color = tint;
depth = 0.5;
extra = vec4(tint, 0.25);
}
",
&mut link,
)
.unwrap();
for wanted in [
"layout(location = 0) out vec4 iris_out_color;",
"iris_out_color = vec4(color, 1.0);",
"layout(location = 1) out vec4 iris_out_depth;",
"iris_out_depth = vec4(depth, 0.0, 0.0, 1.0);",
"layout(location = 2) out vec4 extra;",
] {
assert!(fs.glsl.contains(wanted), "{wanted}\n{}", fs.glsl);
}
assert_eq!(
fs.interface.outputs.values().collect::<Vec<_>>(),
["color", "depth", "extra"]
);
let module = naga::front::wgsl::parse_str(&fs.wgsl).unwrap();
let entry = &module.entry_points[0];
let result = entry.function.result.as_ref().unwrap();
let naga::TypeInner::Struct { members, .. } = &module.types[result.ty].inner else {
panic!("{}", fs.wgsl);
};
for m in members {
assert!(
matches!(
module.types[m.ty].inner,
naga::TypeInner::Vector {
size: naga::VectorSize::Quad,
..
}
),
"{}",
fs.wgsl
);
}
reparse(&fs.wgsl).unwrap();
}
/// The written WGSL, read back and validated: what wgpu is given.
fn reparse(wgsl: &str) -> Result<(), String> {
let module = naga::front::wgsl::parse_str(wgsl).map_err(|e| e.emit_to_string(wgsl))?;
+38 -1
View File
@@ -16,7 +16,7 @@ Both are off by default. With no pack selected the renderer draws exactly what i
| Horizon shader packs: `composite` stage, uniforms, hot reload, Shader Packs screen | first slice planned |
| Horizon shader packs: `deferred`, `gbuffer`, `shadow` stages, custom textures | planned |
| Java shader packs: preprocessing + GLSL parse coverage | spike done: 450 of 470 programs reach valid WGSL (below) |
| Java shader packs: preprocessor (`crates/horizon-shaderpack`: includes, options, Iris's macros) | done: every program of the three test packs preprocesses |
| Java shader packs: preprocessor (`crates/horizon-shaderpack`: includes, options, Iris's macros, JCPP's `#if` and `#define` rules) | done: every program of the three test packs preprocesses; ten packs tested (Compatibility, below) |
| Java shader packs: GLSL → WGSL (`horizon_shaderpack::translate`: syntax-tree legaliser, naga) | done: the 464 programs the three test packs enable by default translate (below) |
| Java shader packs: `shaders.properties` (`horizon_shaderpack::properties`: screens, sliders, profiles, `program.*.enabled`, image formats, blend modes) | done, no screen yet: read like Iris for the three test packs |
| Java shader packs: full-screen pass plan (`horizon_shaderpack::pipeline`: `DRAWBUFFERS`/`RENDERTARGETS`, `colortexN` formats and clearing, buffer flips) | done: planned for the three test packs |
@@ -378,6 +378,43 @@ shadows, water or sky look yet; Distant Horizons' and Voxy's depth read as far.
compute (`.csh`; a pack that needs them doesn't load), mipmapped targets (`colortexNMipmapEnabled` is read but
ignored), custom textures, the option screen; shadow matrices are identity.
### Compatibility
Tested on 2026-10-22 on the Mac mini (M4 Pro, Metal) with each pack's default options, the 26.3 builds from Modrinth or
the authors' pages (dev-only test inputs, kept outside the repository). "Loads" means every pass the pack enables for
the overworld, Nether and End is preprocessed, translated and validated, as the game does when the pack is picked
(`java_pack::tests::real_packs_load` with `HORIZON_TEST_SHADERPACKS`); "drawn" means it was also picked in the game
and screenshotted. Only full-screen passes run (above), so no pack has its own terrain, water, shadows or sky yet.
| Pack | Version | Result | First thing that stops it |
| --- | --- | --- | --- |
| BSL | v10.1.8 | drawn: 26 passes | |
| Complementary Reimagined | r5.9.3 | drawn: 27 passes | |
| Complementary Unbound | r5.8 | loads: 27 passes | |
| Sildur's Vibrant Extreme | 2.02 | drawn: 18 passes, only its sky (above) | |
| Steadfast | 0.8.0 | drawn: 3 passes | |
| Bliss | 2.1.2 | fails | `world0/deferred.vsh`: an operation naga forbids in a vertex shader |
| Bloop | 1.8.0-Alpha-3 | fails | `world0/prepare1.fsh`: `mat2(vec4)` and other constructors naga's GLSL front end refuses |
| Noble | v1.9.9 | fails (Apple and NVIDIA) | `world0/deferred4.vsh`: a `vec3[9][9]` varying (nested arrays between stages) |
| Photon | v1.4 | fails | `world0/prepare.vsh`: a struct varying (`CloudsParameters`) |
| Rethinking Voxels | r0.1-beta9 | fails | `world0/prepare.fsh`: `1 << 31` overflows naga's constant folding; it also needs images |
What the translator does for these packs, as Iris (JCPP and its GLSL transformer) does:
- **`#if` reads floats as JCPP does**: a float in a condition, written there or through a macro, counts as its
integer part, and an empty operand as 0. The same holds in `shaders.properties`, where Steadfast's
`#elif ATMOSPHERE_FOG_STRENGTH_NOON == 0.5` stopped the pack (`UnexpectedToken(Float(0.5))`).
- **A later `#define` replaces an earlier one** instead of failing (Bloop's `DefineRedefined`), and an unterminated
`#if` runs to the end of the file.
- **`shaders.properties`** keeps its empty lines and backslashes through the preprocessor, as Iris's does, so a
continued line doesn't swallow the next one.
- **16-bit and 8-bit types** (`float16_t`, `u16vec2`, `packFloat2x16`...), which Noble uses when the GPU reports
NVIDIA (`NV_gpu_shader5`), become their 32-bit types: WGSL has none.
- **What naga refuses**: `%` with a scalar and a vector operand goes through overloads, a `const` naga can't fold
(`mix`, `?:`, `smoothstep`) becomes a global set at the start of `main`, `sqrt` of a negative constant is
evaluated at run time, and a fragment output narrower than four channels (`out vec3`, Steadfast's `final`) is
written through a `vec4` with alpha 1 as OpenGL fills it.
### Order to implement
1. **Translator crate** (`horizon-shaderpack`): the preprocessor (includes, option `#define`s with the player's