diff --git a/Cargo.lock b/Cargo.lock index d6bbf30d9..536ba6a55 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1364,6 +1364,14 @@ dependencies = [ "serde_json", ] +[[package]] +name = "horizon-shaderpack" +version = "0.1.0" +dependencies = [ + "pp-rs", + "zip", +] + [[package]] name = "horizon-telemetry" version = "0.1.0" @@ -2542,6 +2550,15 @@ dependencies = [ "zerovec", ] +[[package]] +name = "pp-rs" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb458bb7f6e250e6eb79d5026badc10a3ebb8f9a15d1fff0f13d17c71f4d6dee" +dependencies = [ + "unicode-xid", +] + [[package]] name = "presser" version = "0.3.1" diff --git a/Cargo.toml b/Cargo.toml index 19fbabc55..49ef5785f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server"] -members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] +members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] resolver = "2" [workspace.package] diff --git a/crates/horizon-shaderpack/Cargo.toml b/crates/horizon-shaderpack/Cargo.toml new file mode 100644 index 000000000..da9ae1a12 --- /dev/null +++ b/crates/horizon-shaderpack/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "horizon-shaderpack" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version.workspace = true +description = "Java (OptiFine/Iris) shader packs for Horizon: Iris's preprocessor and the GLSL to WGSL translation" + +[dependencies] +# The C preprocessor naga's GLSL front end uses. +pp-rs = "0.2.1" +zip = { version = "2", default-features = false, features = ["deflate"] } + +[lints] +workspace = true + +[dev-dependencies] +zip = { version = "2", default-features = false, features = ["deflate"] } diff --git a/crates/horizon-shaderpack/src/include.rs b/crates/horizon-shaderpack/src/include.rs new file mode 100644 index 000000000..34455a88e --- /dev/null +++ b/crates/horizon-shaderpack/src/include.rs @@ -0,0 +1,198 @@ +//! `#include` the way Iris resolves it (`IncludeGraph`, `IncludeProcessor`): +//! before any other directive, so include guards don't apply; `/lib/x.glsl` +//! from `shaders/`, `x.glsl` from the including file's folder. Every file +//! reachable from the programs is read once into a graph, and a program is +//! the graph inlined from its file. + +use crate::source::PackFiles; +use std::collections::{BTreeMap, BTreeSet}; + +/// One file of the graph: its lines and the include on each `#include` line. +pub struct FileNode { + pub lines: Vec, + /// Line index → included file (a normalised path relative to `shaders/`). + pub includes: BTreeMap, +} + +pub struct IncludeGraph { + pub files: BTreeMap, + /// Files that couldn't be read or include themselves, with the reason. + pub failures: BTreeMap, +} + +/// A program after inlining: the source and, for each of its lines, the +/// file and 1-based line it came from (to report errors where they are). +pub struct Inlined { + pub text: String, + pub origin: Vec<(String, u32)>, +} + +impl Inlined { + /// `file:line` of 1-based `line` of the inlined text. + pub fn locate(&self, line: u32) -> String { + match self.origin.get(line.saturating_sub(1) as usize) { + Some((file, at)) => format!("{file}:{at}"), + None => format!("line {line}"), + } + } +} + +/// `target` from an `#include` in `from`, as a path relative to `shaders/` +/// with `.` and `..` resolved (Iris's `AbsolutePackPath`). +pub fn resolve(from: &str, target: &str) -> String { + let joined = match target.strip_prefix('/') { + Some(absolute) => absolute.to_owned(), + None => match from.rsplit_once('/') { + Some((dir, _)) => format!("{dir}/{target}"), + None => target.to_owned(), + }, + }; + let mut parts: Vec<&str> = Vec::new(); + for segment in joined.split('/') { + match segment { + "" | "." => {} + ".." => { + parts.pop(); + } + s => parts.push(s), + } + } + parts.join("/") +} + +/// The target of an `#include` line, or `None` for any other line. +fn include_target(line: &str) -> Option<&str> { + let t = line.trim(); + if !t.starts_with("#include") { + return None; + } + let target = t.get("#include ".len()..).unwrap_or("").trim(); + let target = target.strip_prefix('"').unwrap_or(target); + Some(target.strip_suffix('"').unwrap_or(target)) +} + +impl IncludeGraph { + /// Read `starts` and every file they include, transitively. + pub fn build(files: &PackFiles, starts: &[String]) -> Self { + let mut graph = Self { + files: BTreeMap::new(), + failures: BTreeMap::new(), + }; + let mut seen: BTreeSet = starts.iter().cloned().collect(); + let mut queue: Vec<(String, Option<(String, usize)>)> = + starts.iter().map(|s| (s.clone(), None)).collect(); + while let Some((path, from)) = queue.pop() { + let Some(text) = files.read(&path) else { + let why = match from { + Some((file, line)) => { + format!("{file}:{}: #include \"{path}\": file not found", line + 1) + } + None => format!("{path}: file not found"), + }; + graph.failures.insert(path, why); + continue; + }; + let lines: Vec = text.lines().map(str::to_owned).collect(); + let includes: BTreeMap = lines + .iter() + .enumerate() + .filter_map(|(i, l)| Some((i, resolve(&path, include_target(l)?)))) + .collect(); + if let Some((line, _)) = includes.iter().find(|(_, target)| **target == path) { + graph.failures.insert( + path.clone(), + format!("{path}:{}: file includes itself", line + 1), + ); + continue; + } + for (&line, target) in &includes { + if seen.insert(target.clone()) { + queue.push((target.clone(), Some((path.clone(), line)))); + } + } + graph.files.insert(path, FileNode { lines, includes }); + } + graph + } + + /// The graph's weakly connected components (files linked by includes in + /// either direction), each sorted. Iris discovers options per component. + pub fn components(&self) -> Vec> { + let names: Vec<&String> = self.files.keys().collect(); + let index: BTreeMap<&str, usize> = names + .iter() + .enumerate() + .map(|(i, n)| (n.as_str(), i)) + .collect(); + let mut parent: Vec = (0..names.len()).collect(); + fn root(parent: &mut [usize], mut i: usize) -> usize { + while parent[i] != i { + parent[i] = parent[parent[i]]; + i = parent[i]; + } + i + } + for (i, node) in self.files.values().enumerate() { + for target in node.includes.values() { + if let Some(&j) = index.get(target.as_str()) { + let (a, b) = (root(&mut parent, i), root(&mut parent, j)); + parent[a] = b; + } + } + } + let mut groups: BTreeMap> = BTreeMap::new(); + for (i, name) in names.iter().enumerate() { + let r = root(&mut parent, i); + groups.entry(r).or_default().push((*name).clone()); + } + groups.into_values().collect() + } + + /// Inline `start`, passing every line that isn't an `#include` through + /// `edit(file, line index, text)` first (Iris applies option values there). + pub fn inline( + &self, + start: &str, + edit: &dyn Fn(&str, usize, &str) -> String, + ) -> Result { + let mut out = Inlined { + text: String::new(), + origin: Vec::new(), + }; + let mut stack = Vec::new(); + self.inline_into(start, edit, &mut stack, &mut out)?; + Ok(out) + } + + fn inline_into( + &self, + path: &str, + edit: &dyn Fn(&str, usize, &str) -> String, + stack: &mut Vec, + out: &mut Inlined, + ) -> Result<(), String> { + if let Some(why) = self.failures.get(path) { + return Err(why.clone()); + } + if stack.iter().any(|p| p == path) { + return Err(format!("#include cycle: {} -> {path}", stack.join(" -> "))); + } + let node = self + .files + .get(path) + .ok_or_else(|| format!("{path}: file not found"))?; + stack.push(path.to_owned()); + for (i, line) in node.lines.iter().enumerate() { + match node.includes.get(&i) { + Some(target) => self.inline_into(target, edit, stack, out)?, + None => { + out.text.push_str(&edit(path, i, line)); + out.text.push('\n'); + out.origin.push((path.to_owned(), i as u32 + 1)); + } + } + } + stack.pop(); + Ok(()) + } +} diff --git a/crates/horizon-shaderpack/src/lib.rs b/crates/horizon-shaderpack/src/lib.rs new file mode 100644 index 000000000..36bfaf37d --- /dev/null +++ b/crates/horizon-shaderpack/src/lib.rs @@ -0,0 +1,122 @@ +//! Java shader packs (OptiFine/Iris) for Horizon (docs/shader-packs.md, +//! "Java shader packs"). This crate does the part that needs no GPU: open a +//! pack, find its programs and options, and turn a program into plain GLSL +//! the way Iris does before compiling it (`#include`s inlined, the player's +//! option values written into the source, Iris's macros expanded). + +pub mod include; +pub mod options; +pub mod preprocess; +pub mod source; + +use include::{IncludeGraph, Inlined}; +use options::{Annotated, OptionSet, OptionValues}; +use preprocess::{Environment, Preprocessed}; +use source::PackFiles; +use std::{ + collections::{BTreeMap, BTreeSet}, + path::Path, +}; + +/// A program's pipeline stage, from its file extension. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Stage { + Vertex, + Fragment, + Geometry, + Compute, + TessControl, + TessEval, +} + +impl Stage { + /// The stage of `composite1.fsh` and the like; `None` for other files. + pub fn of(program: &str) -> Option { + Some(match program.rsplit_once('.')?.1 { + "vsh" => Self::Vertex, + "fsh" => Self::Fragment, + "gsh" => Self::Geometry, + "csh" => Self::Compute, + "tcs" => Self::TessControl, + "tes" => Self::TessEval, + _ => return None, + }) + } +} + +/// An opened Java shader pack. +pub struct JavaPack { + pub files: PackFiles, + /// Every program source file (`composite1.fsh`, `world-1/final.vsh`). + pub programs: Vec, + pub graph: IncludeGraph, + annotations: BTreeMap, + /// The options the player can set (`ShaderPackOptions`). + pub options: OptionSet, +} + +impl JavaPack { + /// Open the pack folder or zip at `path` and read every program and file + /// they include. + pub fn open(path: &Path) -> Result { + let files = PackFiles::open(path)?; + let programs = files.programs(); + if programs.is_empty() { + return Err("no programs in shaders/".into()); + } + let graph = IncludeGraph::build(&files, &programs); + let annotations: BTreeMap = graph + .files + .iter() + .map(|(path, node)| (path.clone(), Annotated::parse(&node.lines))) + .collect(); + // A boolean #define is an option when an #ifdef in its component + // refers to it. + let mut options = OptionSet::default(); + for component in graph.components() { + let refs: BTreeSet<&String> = component + .iter() + .flat_map(|f| &annotations[f].ifdef_refs) + .collect(); + for file in &component { + let a = &annotations[file]; + a.bools + .values() + .filter(|o| refs.contains(&o.name)) + .for_each(|o| options.add_bool(o)); + a.strings.values().for_each(|o| options.add_string(o)); + } + } + Ok(Self { + files, + programs, + graph, + annotations, + options, + }) + } + + /// The player's values from saved `name=value` pairs (`shaderpacks/.txt`). + pub fn values(&self, saved: &BTreeMap) -> OptionValues { + OptionValues::new(&self.options, saved) + } + + /// `program` with its includes inlined and `values` applied. + pub fn source(&self, program: &str, values: &OptionValues) -> Result { + self.graph + .inline(program, &|file, i, line| match self.annotations.get(file) { + Some(a) => a.edit(values, i, line), + None => line.to_owned(), + }) + } + + /// `program` as plain GLSL: [`JavaPack::source`], then the preprocessor. + pub fn preprocess( + &self, + program: &str, + values: &OptionValues, + env: &Environment, + ) -> Result { + preprocess::preprocess(&self.source(program, values)?, env) + } +} diff --git a/crates/horizon-shaderpack/src/options.rs b/crates/horizon-shaderpack/src/options.rs new file mode 100644 index 000000000..d25a3d776 --- /dev/null +++ b/crates/horizon-shaderpack/src/options.rs @@ -0,0 +1,659 @@ +//! A pack's options, found in its source the way Iris finds them +//! (`OptionAnnotatedSource`, `ParsedString`, `OptionSet`), and the player's +//! values written back into the lines they came from. +//! +//! - `#define NAME` / `//#define NAME` (optionally `// comment`): a boolean, +//! on unless commented out, and an option only if some `#ifdef NAME` / +//! `#ifndef NAME` in the same include component refers to it. +//! - `#define NAME VALUE // comment [A B C]`: a value with its allowed list. +//! - `const int|float|bool NAME = VALUE; // [A B C]`: only for the constants +//! Iris lets players configure ([`CONST_OPTIONS`]). + +use std::collections::{BTreeMap, BTreeSet}; + +/// The `const` names Iris configures (`VALID_CONST_OPTION_NAMES`), apart from +/// the per-buffer ones [`is_const_option`] adds. +pub const CONST_OPTIONS: &[&str] = &[ + "shadowMapResolution", + "shadowDistance", + "voxelDistance", + "shadowDistanceRenderMul", + "entityShadowDistanceMul", + "shadowIntervalSize", + "generateShadowMipmap", + "generateShadowColorMipmap", + "shadowHardwareFiltering", + "shadowtex0Mipmap", + "shadowtexMipmap", + "shadowtex1Mipmap", + "shadowtex0Nearest", + "shadowtexNearest", + "shadow0MinMagNearest", + "shadowtex1Nearest", + "shadow1MinMagNearest", + "wetnessHalflife", + "drynessHalflife", + "eyeBrightnessHalflife", + "centerDepthHalflife", + "sunPathRotation", + "ambientOcclusionLevel", + "superSamplingLevel", + "noiseTextureResolution", +]; + +/// Iris's shadow colour buffer count (`MAX_SHADOW_COLOR_BUFFERS_IRIS`). +const SHADOW_COLOR_BUFFERS: u32 = 8; + +pub fn is_const_option(name: &str) -> bool { + CONST_OPTIONS.contains(&name) + || (0..SHADOW_COLOR_BUFFERS).any(|i| { + [ + format!("shadowcolor{i}Mipmap"), + format!("shadowColor{i}Mipmap"), + format!("shadowcolor{i}Nearest"), + format!("shadowColor{i}Nearest"), + format!("shadowcolor{i}MinMagNearest"), + format!("shadowColor{i}MinMagNearest"), + format!("shadowHardwareFiltering{i}"), + ] + .iter() + .any(|n| n == name) + }) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OptionKind { + Define, + Const, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct BoolOption { + pub kind: OptionKind, + pub name: String, + pub comment: Option, + pub default: bool, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct StringOption { + pub kind: OptionKind, + pub name: String, + pub comment: Option, + pub default: String, + /// The bracketed list, with the default added at the end when missing. + pub allowed: Vec, +} + +impl StringOption { + /// `StringOption.create`: `None` without a `[...]` list in the comment. + fn create(kind: OptionKind, name: &str, comment: Option<&str>, default: &str) -> Option { + let comment = comment?; + let open = comment.find('[')?; + let close = open + comment[open..].find(']')?; + // Java's split(" "): empty strings between doubled spaces stay, + // trailing ones go. + let mut allowed: Vec = comment[open + 1..close] + .split(' ') + .map(str::to_owned) + .collect(); + while allowed.last().is_some_and(String::is_empty) { + allowed.pop(); + } + if !allowed.iter().any(|v| v == default) { + allowed.push(default.to_owned()); + } + let rest = format!("{}{}", &comment[..open], &comment[close + 1..]); + Some(Self { + kind, + name: name.to_owned(), + comment: non_empty(&rest), + default: default.to_owned(), + allowed, + }) + } +} + +/// An option's comment; empty is none (`BaseOption`). +fn non_empty(comment: &str) -> Option { + let c = comment.trim(); + (!c.is_empty()).then(|| c.to_owned()) +} + +/// Iris's `ParsedString`: a cursor over a trimmed line. +struct Cursor(Vec); + +impl Cursor { + fn new(s: &str) -> Self { + Self(s.chars().collect()) + } + fn literal(&mut self, token: &str) -> bool { + let t: Vec = token.chars().collect(); + if self.0.starts_with(&t) { + self.0.drain(..t.len()); + true + } else { + false + } + } + /// Whitespace first, then trims both ends (as Iris does). + fn whitespace(&mut self) -> bool { + if !self.0.first().is_some_and(|c| c.is_whitespace()) { + return false; + } + let s: String = self.0.iter().collect(); + self.0 = s.trim().chars().collect(); + true + } + /// `//` and any further slashes. + fn comments(&mut self) -> bool { + if !self.literal("//") { + return false; + } + while self.literal("/") {} + true + } + fn contains(&self, s: &str) -> bool { + self.rest().contains(s) + } + fn is_end(&self) -> bool { + self.0.is_empty() + } + fn rest(&self) -> String { + self.0.iter().collect() + } + fn take(&mut self, n: usize) -> String { + self.0.drain(..n).collect() + } + fn word(&mut self) -> Option { + let n = self + .0 + .iter() + .take_while(|c| c.is_alphanumeric() || **c == '_') + .count(); + (n > 0).then(|| self.take(n)) + } + /// Iris's `takeNumber`: digits and any character next to a digit, an `f` + /// suffix, and the whole must parse as a Java float. + fn number(&mut self) -> Option { + let c = &self.0; + let mut n = 0; + while n < c.len() { + if n + 1 < c.len() { + if !c[n].is_ascii_digit() && !c[n + 1].is_ascii_digit() { + break; + } + } else if !c[n].is_ascii_digit() { + break; + } + n += 1; + } + if n > 0 && n + 1 < c.len() && (c[n] == 'f' || c[n] == 'F') { + n += 1; + } + let text: String = c[..n].iter().collect(); + java_float(&text).then(|| self.take(n)) + } + fn word_or_number(&mut self) -> Option { + self.number().or_else(|| self.word()) + } +} + +/// Whether Java's `Float.parseFloat` accepts `s` (decimal forms; a trailing +/// `f`/`d` is allowed). +fn java_float(s: &str) -> bool { + let s = s.trim(); + let s = s.strip_suffix(['f', 'F', 'd', 'D']).unwrap_or(s); + !s.is_empty() && s.parse::().is_ok() +} + +/// The options and `#ifdef` references of one file, by line index. +#[derive(Default, Debug)] +pub struct Annotated { + pub bools: BTreeMap, + pub strings: BTreeMap, + /// Names tested by a bare `#ifdef NAME` / `#ifndef NAME` line. + pub ifdef_refs: BTreeSet, + /// Why a line that looks like an option isn't one. + pub diagnostics: BTreeMap, +} + +impl Annotated { + pub fn parse(lines: &[String]) -> Self { + let mut out = Self::default(); + for (i, line) in lines.iter().enumerate() { + if !["#define", "const", "#ifdef", "#ifndef"] + .iter() + .any(|k| line.contains(k)) + { + continue; + } + let mut c = Cursor::new(line.trim()); + if c.literal("#ifdef") || c.literal("#ifndef") { + if !c.whitespace() { + continue; + } + let name = c.word(); + c.whitespace(); + if let (Some(name), true) = (name, c.is_end()) { + out.ifdef_refs.insert(name); + } + } else if c.literal("const") { + if let Err(why) = out.parse_const(i, &mut c) { + out.diagnostics.insert(i, why.into()); + } + } else if c.contains("#define") { + if let Err(why) = out.parse_define(i, &mut c) { + out.diagnostics.insert(i, why.into()); + } + } + } + out + } + + fn parse_const(&mut self, i: usize, c: &mut Cursor) -> Result<(), &'static str> { + if !c.whitespace() { + return Err("expected whitespace after const"); + } + let is_bool = if c.literal("int") || c.literal("float") { + false + } else if c.literal("bool") { + true + } else { + return Err("only int, float and bool consts are options"); + }; + if !c.whitespace() { + return Err("expected whitespace after the type"); + } + let name = c.word().ok_or("expected a name after the type")?; + c.whitespace(); + if !c.literal("=") { + return Err("expected = after the name"); + } + c.whitespace(); + let value = c + .word_or_number() + .ok_or("expected a word or number after =")?; + c.whitespace(); + if !c.literal(";") { + return Err("expected ; after the value"); + } + c.whitespace(); + let comment = if c.comments() { + non_empty(&c.rest()) + } else if !c.is_end() { + return Err("only a comment may follow the ;"); + } else { + None + }; + if !is_const_option(&name) { + return Err("not one of the configurable consts"); + } + if is_bool { + let default = match value.as_str() { + "true" => true, + "false" => false, + _ => return Err("a bool const option must be true or false"), + }; + self.bools.insert( + i, + BoolOption { + kind: OptionKind::Const, + name, + comment, + default, + }, + ); + return Ok(()); + } + let option = StringOption::create(OptionKind::Const, &name, comment.as_deref(), &value) + .ok_or("a const option needs a [...] list of values in its comment")?; + self.strings.insert(i, option); + Ok(()) + } + + fn parse_define(&mut self, i: usize, c: &mut Cursor) -> Result<(), &'static str> { + let commented = c.comments(); + c.whitespace(); + if !c.literal("#define") { + return Err("#define isn't where an option's would be"); + } + if !c.whitespace() { + return Err("expected whitespace after #define"); + } + let name = c.word().ok_or("expected a name after #define")?; + let mut spaced = c.whitespace(); + if c.is_end() { + self.bools.insert( + i, + BoolOption { + kind: OptionKind::Define, + name, + comment: None, + default: !commented, + }, + ); + return Ok(()); + } + if c.comments() { + let comment = non_empty(&c.rest()); + self.bools.insert( + i, + BoolOption { + kind: OptionKind::Define, + name, + comment, + default: !commented, + }, + ); + return Ok(()); + } + if !spaced { + return Err("only letters, digits and _ may be in an option's name"); + } + if commented { + return Err("only boolean #define options may be commented out"); + } + let value = c + .word_or_number() + .ok_or("the value is neither a number nor a word")?; + spaced = c.whitespace(); + if c.is_end() { + return Err("a value #define needs a comment with a [...] list of values"); + } + if !c.comments() { + return Err(if spaced { + "only a comment may follow the value" + } else { + "unexpected characters after the value" + }); + } + let comment = c.rest().trim().to_owned(); + let option = StringOption::create(OptionKind::Define, &name, Some(&comment), &value) + .ok_or("a value #define needs a [...] list of values in its comment")?; + self.strings.insert(i, option); + Ok(()) + } + + /// Line `i` (text `line`) with the player's values applied + /// (`OptionAnnotatedSource.edit`). + pub fn edit(&self, values: &OptionValues, i: usize, line: &str) -> String { + if let Some(o) = self.bools.get(&i) { + let value = values.bools.get(&o.name).copied(); + return match o.kind { + OptionKind::Define => { + let on = value.unwrap_or(o.default); + let commented = line.trim().starts_with("//"); + if commented && on { + let mut c = Cursor::new(line); + c.whitespace(); + c.comments(); + c.rest() + } else if !on { + format!("//{line}") + } else { + line.to_owned() + } + } + OptionKind::Const => match value { + Some(v) => edit_const(line, &o.default.to_string(), &v.to_string()), + None => line.to_owned(), + }, + }; + } + if let Some(o) = self.strings.get(&i) { + if let Some(v) = values.strings.get(&o.name) { + return match o.kind { + OptionKind::Define => format!( + "#define {} {v} // OptionAnnotatedSource: Changed option", + o.name + ), + OptionKind::Const => edit_const(line, &o.default, v), + }; + } + } + line.to_owned() + } +} + +/// The first `current` after the `=` replaced by `new`. +fn edit_const(line: &str, current: &str, new: &str) -> String { + match line.find('=') { + Some(eq) => format!("{}{}", &line[..eq], line[eq..].replacen(current, new, 1)), + None => line.to_owned(), + } +} + +/// Every option of a pack by name. Two definitions with different defaults +/// make the name ambiguous: Iris drops it. +#[derive(Default, Debug)] +pub struct OptionSet { + pub bools: BTreeMap, + pub strings: BTreeMap, +} + +impl OptionSet { + pub fn add_bool(&mut self, o: &BoolOption) { + match self.bools.get_mut(&o.name) { + Some(existing) if existing.default != o.default => { + self.bools.remove(&o.name); + } + Some(existing) => { + if existing.comment.is_none() { + *existing = o.clone(); + } + } + None => { + self.bools.insert(o.name.clone(), o.clone()); + } + } + } + + pub fn add_string(&mut self, o: &StringOption) { + match self.strings.get_mut(&o.name) { + Some(existing) if existing.default != o.default => { + self.strings.remove(&o.name); + } + Some(existing) => { + if existing.comment.is_none() { + *existing = o.clone(); + } + } + None => { + self.strings.insert(o.name.clone(), o.clone()); + } + } + } +} + +/// The player's values that differ from the defaults (`MutableOptionValues`). +#[derive(Default, Debug, Clone, PartialEq)] +pub struct OptionValues { + pub bools: BTreeMap, + pub strings: BTreeMap, +} + +impl OptionValues { + /// From saved `name=value` pairs. A boolean other than `true`/`false` is + /// ignored; a value outside an option's allowed list is kept (profiles and + /// hand-edited files may set one, as in OptiFine). + pub fn new(options: &OptionSet, saved: &BTreeMap) -> Self { + let mut out = Self::default(); + for (name, o) in &options.bools { + let value = match saved.get(name).map(String::as_str) { + Some("true") => true, + Some("false") => false, + _ => continue, + }; + if value != o.default { + out.bools.insert(name.clone(), value); + } + } + for (name, o) in &options.strings { + if let Some(v) = saved.get(name) { + if *v != o.default { + out.strings.insert(name.clone(), v.clone()); + } + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn one(line: &str) -> Annotated { + Annotated::parse(&[line.to_owned()]) + } + + fn string(line: &str) -> Option<(String, String, Vec)> { + one(line) + .strings + .into_values() + .next() + .map(|o| (o.name, o.default, o.allowed)) + } + + #[test] + fn value_defines_need_an_allowed_list() { + // Iris's OptionDiscoverTest cases. + let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::>(); + assert_eq!( + string("#define SECRET 0 //[0]"), + Some(("SECRET".into(), "0".into(), s(&["0"]))) + ); + assert_eq!( + string("#define SECRET 0//[0]"), + Some(("SECRET".into(), "0".into(), s(&["0"]))) + ); + assert_eq!( + string("#define OPT 1 //[0]"), + Some(("OPT".into(), "1".into(), s(&["0", "1"]))) + ); + for none in [ + "#define PI 3.14 // It's PI.", + "#define PI 3.14", + "const int noiseTextureResolution = 512;", + "const int noiseTextureResolution = 512; // Default noise texture size [", + ] { + let a = one(none); + assert!(a.strings.is_empty() && a.bools.is_empty(), "{none}"); + } + assert_eq!( + string(" #define SHADOW_QUALITY 2.0f // Shadows [1.0f 2.0f 3.0f]"), + Some(( + "SHADOW_QUALITY".into(), + "2.0f".into(), + s(&["1.0f", "2.0f", "3.0f"]) + )) + ); + assert_eq!( + string("#define SKY_STYLE SKY_REALISTIC // [SKY_REALISTIC SKY_STYLISED]") + .unwrap() + .1, + "SKY_REALISTIC" + ); + assert_eq!( + string("const int shadowMapResolution = 2048; // [1024 2048 4096]") + .unwrap() + .0, + "shadowMapResolution" + ); + assert!(string("const int myResolution = 2048; // [1024 2048 4096]").is_none()); + assert!(string("//#define SHADOW_QUALITY 2 // [1 2 3]").is_none()); + } + + #[test] + fn boolean_defines_and_references() { + let a = Annotated::parse(&[ + "#define BLOOM // Bloom".into(), + "//#define DOF".into(), + "// #define MOTION_BLUR // Blur".into(), + "#define FOG(x) x".into(), + "#ifdef BLOOM".into(), + "#ifndef DOF // trailing text: not a reference".into(), + "#if defined MOTION_BLUR".into(), + "const bool shadowHardwareFiltering = true; // Filtering".into(), + ]); + let b: Vec<(&str, bool, Option<&str>)> = a + .bools + .values() + .map(|o| (o.name.as_str(), o.default, o.comment.as_deref())) + .collect(); + assert_eq!( + b, + [ + ("BLOOM", true, Some("Bloom")), + ("DOF", false, None), + ("MOTION_BLUR", false, Some("Blur")), + ("shadowHardwareFiltering", true, Some("Filtering")) + ] + ); + assert_eq!(a.ifdef_refs.iter().collect::>(), ["BLOOM"]); + } + + #[test] + fn values_are_written_into_the_lines() { + let lines: Vec = [ + "#define BLOOM", + "//#define DOF", + "#define QUALITY 2 // [1 2 3]", + "const float sunPathRotation = -40.0; // [-40.0 0.0 40.0]", + "const bool shadowHardwareFiltering = false;", + ] + .map(String::from) + .into(); + let a = Annotated::parse(&lines); + let mut set = OptionSet::default(); + a.bools.values().for_each(|o| set.add_bool(o)); + a.strings.values().for_each(|o| set.add_string(o)); + let saved: BTreeMap = [ + ("BLOOM", "false"), + ("DOF", "true"), + ("QUALITY", "3"), + ("sunPathRotation", "0.0"), + ("shadowHardwareFiltering", "yes"), + ] + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .into(); + let values = OptionValues::new(&set, &saved); + assert!( + !values.bools.contains_key("shadowHardwareFiltering"), + "not a boolean: ignored" + ); + let edited: Vec = lines + .iter() + .enumerate() + .map(|(i, l)| a.edit(&values, i, l)) + .collect(); + assert_eq!( + edited, + [ + "//#define BLOOM", + "#define DOF", + "#define QUALITY 3 // OptionAnnotatedSource: Changed option", + "const float sunPathRotation = 0.0; // [-40.0 0.0 40.0]", + "const bool shadowHardwareFiltering = false;", + ] + ); + } + + #[test] + fn conflicting_defaults_drop_the_option() { + let mut set = OptionSet::default(); + let a = Annotated::parse(&["#define Q 1 // [1 2]".into()]); + let b = Annotated::parse(&["#define Q 2 // Quality [1 2]".into()]); + let c = Annotated::parse(&["#define Q 1 // Quality [1 2]".into()]); + set.add_string(&a.strings[&0]); + set.add_string(&c.strings[&0]); + assert_eq!( + set.strings["Q"].comment.as_deref(), + Some("Quality"), + "the commented one wins" + ); + set.add_string(&b.strings[&0]); + assert!(set.strings.is_empty()); + } +} diff --git a/crates/horizon-shaderpack/src/preprocess.rs b/crates/horizon-shaderpack/src/preprocess.rs new file mode 100644 index 000000000..f5b8478a6 --- /dev/null +++ b/crates/horizon-shaderpack/src/preprocess.rs @@ -0,0 +1,332 @@ +//! The C preprocessor pass: Iris's standard macros (`StandardMacros`, +//! `IrisDefines`) defined, then every directive and macro expanded by pp-rs, +//! the preprocessor naga's GLSL front end uses. The output keeps the inlined +//! source's line numbers, so an error later on still names `file:line`. + +use crate::include::Inlined; +use pp_rs::{ + pp::Preprocessor, + token::{Punct, TokenValue}, +}; + +/// The version of Minecraft packs are told they run on (`MC_VERSION`, +/// Iris's `formatVersionString("26.3")`). +pub const MC_VERSION: &str = "260300"; +/// The Iris release whose behaviour the translation follows (`IRIS_VERSION`, 1.10.0). +pub const IRIS_VERSION: &str = "11000"; + +/// Iris's `WorldRenderingPhase`, in order: `MC_RENDER_STAGE_` is the index. +pub const RENDER_STAGES: &[&str] = &[ + "NONE", + "SKY", + "SUNSET", + "CUSTOM_SKY", + "SUN", + "MOON", + "STARS", + "VOID", + "TERRAIN_SOLID", + "TERRAIN_CUTOUT_MIPPED", + "TERRAIN_CUTOUT", + "ENTITIES", + "BLOCK_ENTITIES", + "DESTROY", + "OUTLINE", + "DEBUG", + "HAND_SOLID", + "TERRAIN_TRANSLUCENT", + "TRIPWIRE", + "PARTICLES", + "CLOUDS", + "RAIN_SNOW", + "WORLD_BORDER", + "HAND_TRANSLUCENT", +]; + +/// Iris's `BiomeCategories`, in order: `CAT_` is the index. +pub const BIOME_CATEGORIES: &[&str] = &[ + "NONE", + "TAIGA", + "EXTREME_HILLS", + "JUNGLE", + "MESA", + "PLAINS", + "SAVANNA", + "ICY", + "THE_END", + "BEACH", + "FOREST", + "OCEAN", + "DESERT", + "RIVER", + "SWAMP", + "MUSHROOM", + "NETHER", + "MOUNTAIN", + "UNDERGROUND", +]; + +/// Distant Horizons block kinds Iris always defines (`DH_BLOCK_`). +const DH_BLOCKS: &[&str] = &[ + "UNKNOWN", + "LEAVES", + "STONE", + "WOOD", + "METAL", + "DIRT", + "LAVA", + "DEEPSLATE", + "SNOW", + "SAND", + "TERRACOTTA", + "NETHER_STONE", + "WATER", + "GRASS", + "AIR", + "ILLUMINATED", +]; + +/// The macros every program is preprocessed with. +#[derive(Clone, Debug)] +pub struct Environment { + pub defines: Vec<(String, String)>, +} + +impl Environment { + /// What Iris defines (`IrisDefines.createIrisReplacements`) for a GPU + /// whose adapter reports `vendor` and `renderer`, without any GL + /// extension (`MC_GL_*`) or mod macro: packs then take their portable + /// paths. Biomes (`BIOME_*`) and the texture format come from the game: + /// add them with [`Environment::define`]. + pub fn iris(vendor: &str, renderer: &str, mipmap_levels: u32) -> Self { + let mut env = Self { + defines: Vec::new(), + }; + env.define("MC_VERSION", MC_VERSION); + env.define("MC_MIPMAP_LEVEL", &mipmap_levels.to_string()); + env.define("IRIS_VERSION", IRIS_VERSION); + // Horizon's renderer stands in for GL 4.6 / GLSL 4.60. + env.define("MC_GL_VERSION", "460"); + env.define("MC_GLSL_VERSION", "460"); + env.define(os_macro(), ""); + env.define(vendor_macro(vendor), ""); + env.define(renderer_macro(renderer), ""); + for flag in [ + "IS_IRIS", + "IRIS_REQUIRES_SEPARATE_ENTITY_DRAWS", + "IRIS_HAS_TRANSLUCENCY_SORTING", + ] { + env.define(flag, ""); + } + env.define("MAX_COLOR_BUFFERS", "32"); + env.define("IRIS_TAG_SUPPORT", "2"); + for (i, name) in DH_BLOCKS.iter().enumerate() { + env.define(&format!("DH_BLOCK_{name}"), &i.to_string()); + } + env.define("MC_NORMAL_MAP", ""); + env.define("MC_SPECULAR_MAP", ""); + env.define("MC_RENDER_QUALITY", "1.0"); + env.define("MC_SHADOW_QUALITY", "1.0"); + env.define("MC_HAND_DEPTH", "0.125"); + for (i, name) in RENDER_STAGES.iter().enumerate() { + env.define(&format!("MC_RENDER_STAGE_{name}"), &i.to_string()); + } + for (i, name) in BIOME_CATEGORIES.iter().enumerate() { + env.define(&format!("CAT_{name}"), &i.to_string()); + } + env.define("PPT_NONE", "0"); + env.define("PPT_RAIN", "1"); + env.define("PPT_SNOW", "2"); + env + } + + /// Define `name` (replacing an earlier value). + pub fn define(&mut self, name: &str, value: &str) { + self.defines.retain(|(n, _)| n != name); + self.defines.push((name.to_owned(), value.to_owned())); + } +} + +fn os_macro() -> &'static str { + if cfg!(target_os = "macos") { + "MC_OS_MAC" + } else if cfg!(windows) { + "MC_OS_WINDOWS" + } else { + "MC_OS_LINUX" + } +} + +/// `StandardMacros.getVendor`. +pub fn vendor_macro(vendor: &str) -> &'static str { + let v = vendor.to_lowercase(); + const TABLE: &[(&str, &str)] = &[ + ("ati", "MC_GL_VENDOR_ATI"), + ("intel", "MC_GL_VENDOR_INTEL"), + ("nvidia", "MC_GL_VENDOR_NVIDIA"), + ("amd", "MC_GL_VENDOR_AMD"), + ("x.org", "MC_GL_VENDOR_XORG"), + ]; + TABLE + .iter() + .find(|(prefix, _)| v.starts_with(prefix)) + .map_or("MC_GL_VENDOR_OTHER", |(_, m)| m) +} + +/// `StandardMacros.getRenderer`. +pub fn renderer_macro(renderer: &str) -> &'static str { + let r = renderer.to_lowercase(); + const TABLE: &[(&str, &str)] = &[ + ("amd", "MC_GL_RENDERER_RADEON"), + ("ati", "MC_GL_RENDERER_RADEON"), + ("radeon", "MC_GL_RENDERER_RADEON"), + ("gallium", "MC_GL_RENDERER_GALLIUM"), + ("intel", "MC_GL_RENDERER_INTEL"), + ("geforce", "MC_GL_RENDERER_GEFORCE"), + ("nvidia", "MC_GL_RENDERER_GEFORCE"), + ("quadro", "MC_GL_RENDERER_QUADRO"), + ("nvs", "MC_GL_RENDERER_QUADRO"), + ("mesa", "MC_GL_RENDERER_MESA"), + ("apple", "MC_GL_RENDERER_APPLE"), + ]; + TABLE + .iter() + .find(|(prefix, _)| r.starts_with(prefix)) + .map_or("MC_GL_RENDERER_OTHER", |(_, m)| m) +} + +/// A program after the preprocessor: plain GLSL with no directives. +#[derive(Debug)] +pub struct Preprocessed { + /// The source, one output line per inlined line (macro expansions joined). + pub text: String, + /// The `#version` line's words (`["330", "compatibility"]`), if any. + pub version: Vec, + /// `#extension` lines' words (`["GL_ARB_gpu_shader5", ":", "enable"]`). + pub extensions: Vec>, +} + +/// Expand `source` with `env`'s macros. Errors name the file and line. +pub fn preprocess(source: &Inlined, env: &Environment) -> Result { + let text = &source.text; + let line_starts: Vec = 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; + let mut pp = Preprocessor::new(text); + for (name, value) in &env.defines { + pp.add_define(name, value) + .map_err(|e| format!("macro {name}: {:?}", e.0))?; + } + let mut out = Preprocessed { + text: String::new(), + version: Vec::new(), + extensions: Vec::new(), + }; + let mut line = 1; + for item in pp { + let token = + 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) => { + out.version = v.tokens.into_iter().map(|t| spelling(t.value)).collect(); + continue; + } + TokenValue::Extension(e) => { + out.extensions + .push(e.tokens.into_iter().map(|t| spelling(t.value)).collect()); + continue; + } + TokenValue::Pragma(_) => continue, + value => spelling(value), + }; + if at > line { + out.text + .extend(std::iter::repeat_n('\n', (at - line) as usize)); + line = at; + } else if !out.text.is_empty() { + out.text.push(' '); + } + out.text.push_str(&piece); + } + out.text.push('\n'); + Ok(out) +} + +/// A token as GLSL source. +fn spelling(value: TokenValue) -> String { + match value { + TokenValue::Ident(s) => s, + TokenValue::Integer(i) => { + let suffix = if i.signed { "" } else { "u" }; + // Bit patterns such as 0xFFFFFFFF stay hexadecimal: as decimals + // they would overflow a signed int. + if i.value > i32::MAX as u64 { + format!("{:#X}{suffix}", i.value) + } else { + format!("{}{suffix}", i.value) + } + } + TokenValue::Float(f) => { + let mut s = format!("{:?}", f.value); + if !s.contains(['.', 'e', 'i', 'N']) { + s.push_str(".0"); + } + s + } + TokenValue::Punct(p) => punct(p).to_owned(), + TokenValue::Version(_) | TokenValue::Extension(_) | TokenValue::Pragma(_) => String::new(), + } +} + +fn punct(p: Punct) -> &'static str { + use Punct::*; + match p { + AddAssign => "+=", + SubAssign => "-=", + MulAssign => "*=", + DivAssign => "/=", + ModAssign => "%=", + LeftShiftAssign => "<<=", + RightShiftAssign => ">>=", + AndAssign => "&=", + XorAssign => "^=", + OrAssign => "|=", + Increment => "++", + Decrement => "--", + LogicalAnd => "&&", + LogicalOr => "||", + LogicalXor => "^^", + LessEqual => "<=", + GreaterEqual => ">=", + EqualEqual => "==", + NotEqual => "!=", + LeftShift => "<<", + RightShift => ">>", + LeftBrace => "{", + RightBrace => "}", + LeftParen => "(", + RightParen => ")", + LeftBracket => "[", + RightBracket => "]", + LeftAngle => "<", + RightAngle => ">", + Semicolon => ";", + Comma => ",", + Colon => ":", + Dot => ".", + Equal => "=", + Bang => "!", + Minus => "-", + Tilde => "~", + Plus => "+", + Star => "*", + Slash => "/", + Percent => "%", + Pipe => "|", + Caret => "^", + Ampersand => "&", + Question => "?", + } +} diff --git a/crates/horizon-shaderpack/src/source.rs b/crates/horizon-shaderpack/src/source.rs new file mode 100644 index 000000000..0501661ce --- /dev/null +++ b/crates/horizon-shaderpack/src/source.rs @@ -0,0 +1,141 @@ +//! A Java shader pack's files: a folder or a zip holding a `shaders/` folder, +//! found the way Iris finds it (`Iris.loadExternalZipShaderpack`). + +use std::{ + collections::BTreeMap, + fs, + io::Read, + path::{Path, PathBuf}, +}; + +/// Program source extensions Iris loads (vertex, fragment, geometry, +/// compute, tessellation control and evaluation). +pub const PROGRAM_EXTENSIONS: &[&str] = &["vsh", "fsh", "gsh", "csh", "tcs", "tes"]; + +/// The files under a pack's `shaders/` folder, addressed by `/`-separated +/// paths relative to it (`lib/common.glsl`). +pub enum PackFiles { + Folder(PathBuf), + /// A zip is small (a few MB of text), so it is read once. + Zip(BTreeMap>), +} + +impl PackFiles { + /// Open `path`, a pack folder (with `shaders/` in it) or a `.zip`. + pub fn open(path: &Path) -> Result { + if path.is_dir() { + let shaders = path.join("shaders"); + return if shaders.is_dir() { + Ok(Self::Folder(shaders)) + } else { + Err("no shaders folder".into()) + }; + } + let file = fs::File::open(path).map_err(|e| e.to_string())?; + let mut zip = zip::ZipArchive::new(file).map_err(|e| format!("not a zip: {e}"))?; + let names: Vec = zip.file_names().map(str::to_owned).collect(); + // `shaders/` at the root, else the first folder ending in `shaders` + // (`Pack-main/shaders/`), as Iris walks the zip. + let mut prefixes: Vec<&str> = names + .iter() + .filter_map(|n| { + let at = n.find("shaders/")?; + (at == 0 || n.as_bytes()[at - 1] == b'/').then(|| &n[..at + "shaders/".len()]) + }) + .collect(); + prefixes.sort_by_key(|p| (p.len(), *p)); + let prefix = prefixes.first().ok_or("no shaders folder")?.to_string(); + let mut files = BTreeMap::new(); + for name in &names { + let Some(rel) = name.strip_prefix(&prefix) else { + continue; + }; + if rel.is_empty() || rel.ends_with('/') { + continue; + } + let mut entry = zip.by_name(name).map_err(|e| e.to_string())?; + let mut bytes = Vec::new(); + entry + .read_to_end(&mut bytes) + .map_err(|e| format!("{name}: {e}"))?; + files.insert(rel.to_owned(), bytes); + } + Ok(Self::Zip(files)) + } + + /// A text file, or `None` when it doesn't exist. Invalid UTF-8 is + /// replaced, as packs are often saved in Latin-1. + pub fn read(&self, rel: &str) -> Option { + let bytes = match self { + Self::Folder(root) => fs::read(root.join(rel)).ok()?, + Self::Zip(files) => files.get(rel)?.clone(), + }; + Some(String::from_utf8_lossy(&bytes).into_owned()) + } + + /// The files directly in folder `dir` (`""` for `shaders/` itself), sorted. + pub fn list(&self, dir: &str) -> Vec { + let prefix = if dir.is_empty() { + String::new() + } else { + format!("{dir}/") + }; + let mut out: Vec = match self { + Self::Folder(root) => fs::read_dir(root.join(dir)) + .into_iter() + .flatten() + .flatten() + .filter(|e| e.file_type().is_ok_and(|t| t.is_file())) + .filter_map(|e| Some(format!("{prefix}{}", e.file_name().to_str()?))) + .collect(), + Self::Zip(files) => files + .keys() + .filter(|k| { + k.strip_prefix(&prefix) + .is_some_and(|rest| !rest.contains('/')) + }) + .cloned() + .collect(), + }; + out.sort(); + out + } + + /// The program folders: `shaders/` itself and the per-dimension folders, + /// from `dimension.properties` (`dimension.world-1=minecraft:the_nether`) + /// or, without one, Iris's defaults `world0`, `world-1` and `world1`. + pub fn program_dirs(&self) -> Vec { + let mut dirs = vec![String::new()]; + match self.read("dimension.properties") { + Some(text) => { + for line in text.lines() { + if let Some((key, _)) = line.trim().split_once('=') { + if let Some(dir) = key.trim().strip_prefix("dimension.") { + dirs.push(dir.to_owned()); + } + } + } + } + None => dirs.extend(["world0", "world-1", "world1"].map(String::from)), + } + dirs.dedup(); + dirs + } + + /// Every program source file of the pack (`composite1.fsh`, + /// `world-1/gbuffers_water.vsh`), sorted. + pub fn programs(&self) -> Vec { + let mut out: Vec = self + .program_dirs() + .iter() + .flat_map(|d| self.list(d)) + .filter(|f| { + f.rsplit_once('.') + .is_some_and(|(_, ext)| PROGRAM_EXTENSIONS.contains(&ext)) + }) + .collect(); + out.sort(); + out.dedup(); + out + } +} diff --git a/crates/horizon-shaderpack/tests/fixtures/mini/shaders/composite.fsh b/crates/horizon-shaderpack/tests/fixtures/mini/shaders/composite.fsh new file mode 100644 index 000000000..948ee25c6 --- /dev/null +++ b/crates/horizon-shaderpack/tests/fixtures/mini/shaders/composite.fsh @@ -0,0 +1,10 @@ +#version 120 +#extension GL_ARB_shader_texture_lod : enable +#include "/lib/common.glsl" +uniform sampler2D colortex0; +varying vec2 texcoord; +void main() { +#if MC_VERSION >= 260300 && defined IS_IRIS + gl_FragData[0] = texture2D(colortex0, texcoord) * float(MC_RENDER_STAGE_TERRAIN_SOLID); +#endif +} diff --git a/crates/horizon-shaderpack/tests/fixtures/mini/shaders/composite.vsh b/crates/horizon-shaderpack/tests/fixtures/mini/shaders/composite.vsh new file mode 100644 index 000000000..eb261aadd --- /dev/null +++ b/crates/horizon-shaderpack/tests/fixtures/mini/shaders/composite.vsh @@ -0,0 +1,3 @@ +#version 120 +varying vec2 texcoord; +void main() { gl_Position = ftransform(); texcoord = gl_MultiTexCoord0.xy; } diff --git a/crates/horizon-shaderpack/tests/fixtures/mini/shaders/lib/common.glsl b/crates/horizon-shaderpack/tests/fixtures/mini/shaders/lib/common.glsl new file mode 100644 index 000000000..bb88b82c3 --- /dev/null +++ b/crates/horizon-shaderpack/tests/fixtures/mini/shaders/lib/common.glsl @@ -0,0 +1,7 @@ +#include "settings.glsl" +#ifdef BLOOM +float bloomStrength = 0.5 * QUALITY; +#endif +#ifdef DOF +float dofStrength = 1.0; +#endif diff --git a/crates/horizon-shaderpack/tests/fixtures/mini/shaders/lib/settings.glsl b/crates/horizon-shaderpack/tests/fixtures/mini/shaders/lib/settings.glsl new file mode 100644 index 000000000..0d5b4b1c9 --- /dev/null +++ b/crates/horizon-shaderpack/tests/fixtures/mini/shaders/lib/settings.glsl @@ -0,0 +1,7 @@ +// Options, as packs write them. +#define BLOOM // Bloom on bright light +//#define DOF // Depth of field +//#define UNREFERENCED +#define QUALITY 2 // Quality [1 2 3] +#define NOT_AN_OPTION 3 +const float sunPathRotation = -40.0; // [-40.0 0.0 40.0] diff --git a/crates/horizon-shaderpack/tests/fixtures/mini/shaders/notes.txt b/crates/horizon-shaderpack/tests/fixtures/mini/shaders/notes.txt new file mode 100644 index 000000000..528b86abe --- /dev/null +++ b/crates/horizon-shaderpack/tests/fixtures/mini/shaders/notes.txt @@ -0,0 +1 @@ +Not a program. diff --git a/crates/horizon-shaderpack/tests/fixtures/mini/shaders/world-1/composite.fsh b/crates/horizon-shaderpack/tests/fixtures/mini/shaders/world-1/composite.fsh new file mode 100644 index 000000000..7d2f794da --- /dev/null +++ b/crates/horizon-shaderpack/tests/fixtures/mini/shaders/world-1/composite.fsh @@ -0,0 +1,4 @@ +#version 120 +#include "../lib/common.glsl" +#include "/lib/missing.glsl" +void main() {} diff --git a/crates/horizon-shaderpack/tests/pack.rs b/crates/horizon-shaderpack/tests/pack.rs new file mode 100644 index 000000000..a21f48fde --- /dev/null +++ b/crates/horizon-shaderpack/tests/pack.rs @@ -0,0 +1,223 @@ +//! The preprocessing half of the Java shader pack translation on a small +//! hand-written pack (`tests/fixtures/mini`), and on real packs when +//! `HORIZON_TEST_SHADERPACKS` names a folder of them (development only: +//! third-party packs are never committed). + +use horizon_shaderpack::{JavaPack, Stage, preprocess::Environment}; +use std::{ + collections::BTreeMap, + io::Write, + path::{Path, PathBuf}, +}; + +fn mini() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mini") +} + +fn env() -> Environment { + Environment::iris("Apple", "Apple M4 Pro", 4) +} + +fn saved(pairs: &[(&str, &str)]) -> BTreeMap { + pairs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect() +} + +#[test] +fn finds_programs_and_options() { + let pack = JavaPack::open(&mini()).unwrap(); + assert_eq!( + pack.programs, + ["composite.fsh", "composite.vsh", "world-1/composite.fsh"] + ); + assert_eq!(Stage::of(&pack.programs[1]), Some(Stage::Vertex)); + let bools: Vec<(&str, bool)> = pack + .options + .bools + .values() + .map(|o| (o.name.as_str(), o.default)) + .collect(); + assert_eq!( + bools, + [("BLOOM", true), ("DOF", false)], + "UNREFERENCED has no #ifdef" + ); + let strings: Vec<(&str, &str)> = pack + .options + .strings + .values() + .map(|o| (o.name.as_str(), o.default.as_str())) + .collect(); + assert_eq!(strings, [("QUALITY", "2"), ("sunPathRotation", "-40.0")]); + assert_eq!( + pack.options.strings["QUALITY"].comment.as_deref(), + Some("Quality") + ); +} + +#[test] +fn preprocesses_with_defaults_and_with_values() { + let pack = JavaPack::open(&mini()).unwrap(); + let defaults = pack + .preprocess("composite.fsh", &pack.values(&BTreeMap::new()), &env()) + .unwrap(); + assert_eq!(defaults.version, ["120"]); + assert_eq!( + defaults.extensions, + [["GL_ARB_shader_texture_lod", ":", "enable"]] + ); + let text = defaults + .text + .split_whitespace() + .collect::>() + .join(" "); + assert!(text.contains("float bloomStrength = 0.5 * 2 ;"), "{text}"); + assert!(!text.contains("dofStrength"), "{text}"); + assert!( + text.contains("float ( 8 )"), + "Iris's render stage macros: {text}" + ); + assert!(!text.contains('#'), "no directive is left: {text}"); + + let values = pack.values(&saved(&[ + ("BLOOM", "false"), + ("DOF", "true"), + ("QUALITY", "3"), + ])); + let changed = pack + .preprocess("composite.fsh", &values, &env()) + .unwrap() + .text; + assert!( + !changed.contains("bloomStrength") && changed.contains("dofStrength"), + "{changed}" + ); + + let mut source = pack.source("composite.fsh", &values).unwrap(); + assert!( + source + .text + .contains("#define QUALITY 3 // OptionAnnotatedSource: Changed option") + ); + // Output lines are the inlined lines: errors can name file:line. + let line = defaults + .text + .lines() + .position(|l| l.contains("bloomStrength")) + .unwrap() as u32 + + 1; + assert_eq!(source.locate(line), "lib/common.glsl:3"); + source.text = "#if\n".into(); + assert!( + horizon_shaderpack::preprocess::preprocess(&source, &env()) + .unwrap_err() + .starts_with("composite.fsh:1:") + ); +} + +#[test] +fn reports_missing_includes_and_cycles() { + let pack = JavaPack::open(&mini()).unwrap(); + let err = pack + .source("world-1/composite.fsh", &Default::default()) + .err() + .unwrap(); + assert_eq!( + err, + "world-1/composite.fsh:3: #include \"lib/missing.glsl\": file not found" + ); + + let dir = scratch("cycle"); + std::fs::create_dir_all(dir.join("shaders/lib")).unwrap(); + std::fs::write( + dir.join("shaders/final.fsh"), + "#include \"/lib/a.glsl\"\nvoid main() {}\n", + ) + .unwrap(); + std::fs::write(dir.join("shaders/lib/a.glsl"), "#include \"b.glsl\"\n").unwrap(); + std::fs::write(dir.join("shaders/lib/b.glsl"), "#include \"a.glsl\"\n").unwrap(); + let pack = JavaPack::open(&dir).unwrap(); + let err = pack.source("final.fsh", &Default::default()).err().unwrap(); + assert_eq!( + err, + "#include cycle: final.fsh -> lib/a.glsl -> lib/b.glsl -> lib/a.glsl" + ); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn opens_zips_with_shaders_in_a_subfolder() { + let dir = scratch("zip"); + std::fs::create_dir_all(&dir).unwrap(); + let zip_path = dir.join("Mini-main.zip"); + let mut zip = zip::ZipWriter::new(std::fs::File::create(&zip_path).unwrap()); + let options = zip::write::SimpleFileOptions::default(); + let root = mini().join("shaders"); + for rel in [ + "composite.fsh", + "composite.vsh", + "lib/common.glsl", + "lib/settings.glsl", + "world-1/composite.fsh", + ] { + zip.start_file(format!("Mini-main/shaders/{rel}"), options) + .unwrap(); + zip.write_all(&std::fs::read(root.join(rel)).unwrap()) + .unwrap(); + } + zip.start_file("Mini-main/docs/shaders/readme.txt", options) + .unwrap(); + zip.finish().unwrap(); + let zipped = JavaPack::open(&zip_path).unwrap(); + let folder = JavaPack::open(&mini()).unwrap(); + assert_eq!(zipped.programs, folder.programs); + let values = zipped.values(&BTreeMap::new()); + assert_eq!( + zipped + .preprocess("composite.fsh", &values, &env()) + .unwrap() + .text, + folder + .preprocess("composite.fsh", &values, &env()) + .unwrap() + .text + ); + std::fs::remove_dir_all(dir).unwrap(); +} + +fn scratch(name: &str) -> PathBuf { + std::env::temp_dir().join(format!("horizon-shaderpack-{name}-{}", std::process::id())) +} + +/// Every program of the packs in `HORIZON_TEST_SHADERPACKS` (folders or +/// zips) preprocesses. Skipped when the variable isn't set. +#[test] +fn real_packs_preprocess() { + let Some(dir) = std::env::var_os("HORIZON_TEST_SHADERPACKS") else { + return; + }; + let mut failures = Vec::new(); + for entry in std::fs::read_dir(dir).unwrap().flatten() { + let Ok(pack) = JavaPack::open(&entry.path()) else { + continue; + }; + let values = pack.values(&BTreeMap::new()); + let mut ok = 0; + for program in &pack.programs { + match pack.preprocess(program, &values, &env()) { + Ok(_) => ok += 1, + Err(e) => failures.push(format!("{}: {program}: {e}", entry.path().display())), + } + } + println!( + "{}: {ok}/{} programs, {} boolean and {} value options", + entry.file_name().to_string_lossy(), + pack.programs.len(), + pack.options.bools.len(), + pack.options.strings.len() + ); + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} diff --git a/docs/shader-packs.md b/docs/shader-packs.md index e3dd5fbca..025e28894 100644 --- a/docs/shader-packs.md +++ b/docs/shader-packs.md @@ -16,6 +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: Iris pipeline emulation | planned | ## How the renderer draws a frame today