8698b4ad0c
load_post takes the game's terrain vertex inputs and, given them, loads the first program of gbuffers_terrain's fallback chain that translates (gbuffers_terrain, textured_lit, textured, basic). Program loading is shared by the post-processing and gbuffers programs. The translator no longer rewrites a variable, parameter or member that has the name of a sampler (`float specular` beside `uniform sampler2D specular`), which kept Complementary's gbuffers programs from compiling. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
361 lines
13 KiB
Rust
361 lines
13 KiB
Rust
//! The post-processing programs of one dimension, ready for the renderer: `prepare`, `deferred`,
|
|
//! `composite` and `final` with their numbered variants, in the order they run (spec 2.1), each
|
|
//! preprocessed and translated, with the buffers it writes and the flips that follow it, and the
|
|
//! buffer settings their files carry (6.1).
|
|
//!
|
|
//! Decisions (impl-plan.md):
|
|
//! - OQ-12: a dimension's folder (`world0`, `world-1`, `world1`) replaces the base folder for that
|
|
//! dimension when it exists; every stage file is read from it.
|
|
//! - OQ-29: a program with a geometry stage is reported and treated as missing.
|
|
//! - A program that fails to translate is reported and treated as missing (2.5).
|
|
//! - Terrain draws with the first program of its fallback chain that loads (2.3).
|
|
|
|
use crate::config::{self, Config};
|
|
use crate::{GbuffersInputs, Macros, Pack, Preprocessed, Program, Properties, Target};
|
|
use crate::{eval_condition, preprocess, translate_composite, translate_gbuffers};
|
|
|
|
/// Which group of 2.1 a program belongs to.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum Group {
|
|
Prepare,
|
|
Deferred,
|
|
Composite,
|
|
Final,
|
|
/// A gbuffers program: the game draws its geometry with it.
|
|
Gbuffers,
|
|
}
|
|
|
|
/// `gbuffers_terrain` and its fallbacks (2.3).
|
|
const TERRAIN: [&str; 4] = [
|
|
"gbuffers_terrain",
|
|
"gbuffers_textured_lit",
|
|
"gbuffers_textured",
|
|
"gbuffers_basic",
|
|
];
|
|
|
|
const GROUPS: [(Group, &str); 4] = [
|
|
(Group::Prepare, "prepare"),
|
|
(Group::Deferred, "deferred"),
|
|
(Group::Composite, "composite"),
|
|
(Group::Final, "final"),
|
|
];
|
|
|
|
pub struct PostProgram {
|
|
/// The program's name (`composite3`).
|
|
pub name: String,
|
|
pub group: Group,
|
|
pub program: Program,
|
|
/// colortex buffer of each fragment output location (location n writes `buffers[n]`).
|
|
pub buffers: Vec<u32>,
|
|
/// `flip.<name>.<buffer>`: buffers forced to flip (true) or kept (false) after this program.
|
|
pub flips: Vec<(u32, bool)>,
|
|
}
|
|
|
|
pub struct Post {
|
|
/// The folder the programs came from: `""` for `shaders` itself, else `world0`...
|
|
pub folder: String,
|
|
pub programs: Vec<PostProgram>,
|
|
/// The flips of the virtual `deferred_pre` and `composite_pre` (6.1.6).
|
|
pub deferred_pre: Vec<(u32, bool)>,
|
|
pub composite_pre: Vec<(u32, bool)>,
|
|
/// What draws solid and cutout terrain, when the game asked for it and one loads.
|
|
pub terrain: Option<PostProgram>,
|
|
pub config: Config,
|
|
/// Programs skipped and why, as `program: message` or `file:line: message`.
|
|
pub notes: Vec<String>,
|
|
}
|
|
|
|
/// The folder a dimension reads its programs from: `world<id>` when the pack has it, else the
|
|
/// base folder `""` (1.2). `id` is the legacy number: 0 the Overworld, -1 the Nether, 1 the End.
|
|
pub fn dimension_folder(pack: &Pack, id: i32) -> String {
|
|
let folder = format!("world{id}");
|
|
if pack.list("").iter().any(|f| f == &folder) || !pack.list(&folder).is_empty() {
|
|
folder
|
|
} else {
|
|
String::new()
|
|
}
|
|
}
|
|
|
|
/// Loads the post-processing programs of `folder` and, given the game's terrain vertices, the
|
|
/// program terrain draws with.
|
|
pub fn load_post(
|
|
pack: &Pack,
|
|
folder: &str,
|
|
properties: &Properties,
|
|
macros: &Macros,
|
|
terrain: Option<&GbuffersInputs>,
|
|
) -> Post {
|
|
let mut post = Post {
|
|
folder: folder.to_owned(),
|
|
programs: Vec::new(),
|
|
deferred_pre: flips(properties, "deferred_pre"),
|
|
composite_pre: flips(properties, "composite_pre"),
|
|
terrain: None,
|
|
config: Config::default(),
|
|
notes: Vec::new(),
|
|
};
|
|
let mut loader = Loader {
|
|
pack,
|
|
folder,
|
|
properties,
|
|
macros,
|
|
post: &mut post,
|
|
};
|
|
for (group, base) in GROUPS {
|
|
let names: Vec<String> = if group == Group::Final {
|
|
vec![base.to_owned()]
|
|
} else {
|
|
std::iter::once(base.to_owned())
|
|
.chain((1..=99).map(|n| format!("{base}{n}")))
|
|
.collect()
|
|
};
|
|
let target = match group {
|
|
Group::Final => Target::Window,
|
|
_ => Target::Buffers,
|
|
};
|
|
for name in names {
|
|
if let Some(p) = loader.load(name, group, |v, f| translate_composite(v, f, target)) {
|
|
loader.post.programs.push(p);
|
|
}
|
|
}
|
|
}
|
|
if let Some(inputs) = terrain {
|
|
loader.post.terrain = TERRAIN.iter().find_map(|name| {
|
|
loader.load(name.to_string(), Group::Gbuffers, |v, f| {
|
|
translate_gbuffers(v, f, Target::Buffers, inputs)
|
|
})
|
|
});
|
|
}
|
|
post.config = std::mem::take(&mut post.config).finish();
|
|
post
|
|
}
|
|
|
|
struct Loader<'a> {
|
|
pack: &'a Pack,
|
|
folder: &'a str,
|
|
properties: &'a Properties,
|
|
macros: &'a Macros,
|
|
post: &'a mut Post,
|
|
}
|
|
|
|
impl Loader<'_> {
|
|
/// The program `name` translated by `translate`, or `None` when it is missing, disabled or
|
|
/// fails (with a note).
|
|
fn load(
|
|
&mut self,
|
|
name: String,
|
|
group: Group,
|
|
translate: impl FnOnce(&Preprocessed, &Preprocessed) -> Result<Program, Vec<crate::Error>>,
|
|
) -> Option<PostProgram> {
|
|
let path = |ext: &str| match self.folder {
|
|
"" => format!("{name}.{ext}"),
|
|
f => format!("{f}/{name}.{ext}"),
|
|
};
|
|
let (vsh, fsh) = (path("vsh"), path("fsh"));
|
|
let notes = &mut self.post.notes;
|
|
if !self.pack.exists(&fsh) || !self.pack.exists(&vsh) {
|
|
return None;
|
|
}
|
|
if !enabled(self.properties, self.folder, &name, self.macros) {
|
|
return None;
|
|
}
|
|
if self.pack.exists(&path("gsh")) {
|
|
notes.push(format!(
|
|
"{name}: uses a geometry stage (not supported); skipped"
|
|
));
|
|
return None;
|
|
}
|
|
let vertex = preprocess(self.pack, &vsh, self.macros);
|
|
let fragment = preprocess(self.pack, &fsh, self.macros);
|
|
let problems: Vec<String> = [&vertex, &fragment]
|
|
.iter()
|
|
.flat_map(|pp| diagnostics(pp))
|
|
.collect();
|
|
if !problems.is_empty() {
|
|
notes.extend(problems);
|
|
notes.push(format!("{name}: skipped"));
|
|
return None;
|
|
}
|
|
let program = match translate(&vertex, &fragment) {
|
|
Ok(p) => p,
|
|
Err(errors) => {
|
|
notes.extend(
|
|
errors
|
|
.iter()
|
|
.map(|e| format!("{}:{}: {}", e.file, e.line, e.message)),
|
|
);
|
|
notes.push(format!("{name}: skipped"));
|
|
return None;
|
|
}
|
|
};
|
|
self.post.config.read(&vertex);
|
|
self.post.config.read(&fragment);
|
|
let buffers = config::draw_buffers(&fragment).unwrap_or_else(|| (0..8).collect());
|
|
Some(PostProgram {
|
|
flips: flips(self.properties, &name),
|
|
name,
|
|
group,
|
|
program,
|
|
buffers,
|
|
})
|
|
}
|
|
}
|
|
|
|
fn diagnostics(pp: &Preprocessed) -> Vec<String> {
|
|
pp.diagnostics
|
|
.iter()
|
|
.map(|d| {
|
|
let file = pp
|
|
.files
|
|
.get(d.origin.file as usize)
|
|
.map_or("?", String::as_str);
|
|
format!("{file}:{}: {}", d.origin.line, d.message)
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// `program.<name>.enabled` (or `program.<folder>/<name>.enabled`): a boolean expression over
|
|
/// switch options (3.3). An option is on when its macro is defined.
|
|
fn enabled(properties: &Properties, folder: &str, name: &str, macros: &Macros) -> bool {
|
|
let keys = [
|
|
format!("program.{folder}/{name}.enabled"),
|
|
format!("program.{name}.enabled"),
|
|
];
|
|
let Some(expr) = keys.iter().find_map(|k| properties.get(k)) else {
|
|
return true;
|
|
};
|
|
// `true`/`false` as numbers, every other name as `defined(name)`, then the `#if` arithmetic.
|
|
let mut condition = String::new();
|
|
for token in crate::macros::lex(expr) {
|
|
match token {
|
|
"true" => condition.push('1'),
|
|
"false" => condition.push('0'),
|
|
t if t.starts_with(|c: char| c.is_alphabetic() || c == '_') => {
|
|
condition.push_str(&format!("defined({t})"));
|
|
}
|
|
t => condition.push_str(t),
|
|
}
|
|
}
|
|
eval_condition(&condition, macros).ok() != Some(0)
|
|
}
|
|
|
|
/// `flip.<program>.<buffer>=<bool>` keys of one program.
|
|
fn flips(properties: &Properties, program: &str) -> Vec<(u32, bool)> {
|
|
let prefix = format!("flip.{program}.");
|
|
properties
|
|
.entries
|
|
.iter()
|
|
.filter_map(|e| {
|
|
let buffer = config::buffer_index(e.key.strip_prefix(&prefix)?)?;
|
|
let value = match e.value.trim() {
|
|
"true" => true,
|
|
"false" => false,
|
|
_ => return None,
|
|
};
|
|
Some((buffer as u32, value))
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::pack::tests::zip;
|
|
|
|
const VSH: &str = "#version 120\nvarying vec2 uv;\nvoid main() {\n\
|
|
gl_Position = ftransform();\nuv = gl_MultiTexCoord0.xy;\n}\n";
|
|
const FSH: &str = "#version 120\nuniform sampler2D colortex0;\nvarying vec2 uv;\n\
|
|
void main() {\n/* DRAWBUFFERS:3 */\n\
|
|
gl_FragData[0] = texture2D(colortex0, uv);\n}\n";
|
|
|
|
#[test]
|
|
fn programs_load_in_order_with_their_settings() {
|
|
let pack = Pack::from_zip_bytes(
|
|
"t",
|
|
zip(&[
|
|
("shaders/composite.vsh", VSH),
|
|
("shaders/composite.fsh", FSH),
|
|
("shaders/composite2.vsh", VSH),
|
|
("shaders/composite2.fsh", FSH),
|
|
("shaders/deferred.vsh", VSH),
|
|
(
|
|
"shaders/deferred.fsh",
|
|
"#version 120\nvoid main() { gl_FragColor = vec4(1.0); }\n",
|
|
),
|
|
("shaders/composite1.fsh", FSH),
|
|
("shaders/composite3.vsh", VSH),
|
|
("shaders/composite3.fsh", FSH),
|
|
("shaders/composite4.vsh", VSH),
|
|
("shaders/composite4.fsh", FSH),
|
|
("shaders/composite4.gsh", "x"),
|
|
("shaders/composite5.vsh", VSH),
|
|
(
|
|
"shaders/composite5.fsh",
|
|
"#version 120\nvoid main() { undefined(); }\n",
|
|
),
|
|
("shaders/final.vsh", VSH),
|
|
("shaders/final.fsh", FSH),
|
|
("shaders/world-1/final.vsh", VSH),
|
|
("shaders/world-1/final.fsh", FSH),
|
|
]),
|
|
)
|
|
.unwrap();
|
|
let properties = Properties::parse(
|
|
"program.composite3.enabled = HQ && !LOW\nflip.composite2.gaux1=true\n\
|
|
flip.composite.colortex3 = false\nflip.composite_pre.colortex1=true\n",
|
|
&Macros::default(),
|
|
);
|
|
assert_eq!(dimension_folder(&pack, 0), "");
|
|
assert_eq!(dimension_folder(&pack, -1), "world-1");
|
|
let post = load_post(&pack, "", &properties, &Macros::standard(), None);
|
|
let names: Vec<&str> = post.programs.iter().map(|p| p.name.as_str()).collect();
|
|
assert_eq!(names, ["deferred", "composite", "composite2", "final"]);
|
|
let p = &post.programs;
|
|
assert_eq!(p[0].buffers, (0..8).collect::<Vec<_>>());
|
|
assert_eq!(p[1].buffers, [3]);
|
|
assert_eq!(p[1].flips, [(3, false)]);
|
|
assert_eq!(p[2].flips, [(4, true)]);
|
|
assert_eq!(post.composite_pre, [(1, true)]);
|
|
assert_eq!(p[3].group, Group::Final);
|
|
let notes = post.notes.join("\n");
|
|
assert!(
|
|
notes.contains("composite4: uses a geometry stage"),
|
|
"{notes}"
|
|
);
|
|
assert!(notes.contains("composite5.fsh:2:"), "{notes}");
|
|
assert!(notes.contains("composite5: skipped"), "{notes}");
|
|
|
|
let mut macros = Macros::standard();
|
|
macros.define("HQ", "");
|
|
let post = load_post(&pack, "world-1", &properties, ¯os, None);
|
|
let names: Vec<&str> = post.programs.iter().map(|p| p.name.as_str()).collect();
|
|
assert_eq!(names, ["final"]);
|
|
let post = load_post(&pack, "", &properties, ¯os, None);
|
|
assert!(post.programs.iter().any(|p| p.name == "composite3"));
|
|
}
|
|
|
|
#[test]
|
|
fn horizons_test_pack_loads() {
|
|
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/packs/post-test");
|
|
let pack = Pack::open(&dir).unwrap();
|
|
let macros = Macros::standard();
|
|
let properties = Properties::parse(&pack.read_text("shaders.properties").unwrap(), ¯os);
|
|
let post = load_post(
|
|
&pack,
|
|
&dimension_folder(&pack, 0),
|
|
&properties,
|
|
¯os,
|
|
None,
|
|
);
|
|
assert!(post.notes.is_empty(), "{:?}", post.notes);
|
|
let names: Vec<&str> = post.programs.iter().map(|p| p.name.as_str()).collect();
|
|
assert_eq!(names, ["composite", "composite1", "final"]);
|
|
assert_eq!(post.programs[0].buffers, [0, 2]);
|
|
assert_eq!(post.programs[1].buffers, [0]);
|
|
assert_eq!(
|
|
post.config.buffers[2].format,
|
|
crate::Format::parse("RGBA16F").unwrap()
|
|
);
|
|
}
|
|
}
|