Merge pull request #436 from ludovic111/feat/shaderpack-client
horizon-client: run a Java pack's full-screen passes over the world
This commit is contained in:
Generated
+1
@@ -1417,6 +1417,7 @@ dependencies = [
|
||||
"horizon-friends",
|
||||
"horizon-mods",
|
||||
"horizon-protocol",
|
||||
"horizon-shaderpack",
|
||||
"horizon-telemetry",
|
||||
"horizon-theme",
|
||||
"horizon-world",
|
||||
|
||||
@@ -27,6 +27,8 @@ serde_json = { version = "1.0.151", features = ["raw_value"] }
|
||||
# Shader packs: pack.toml, and WGSL checked before it reaches wgpu.
|
||||
toml = "1.1"
|
||||
naga = { version = "30.0.1", features = ["wgsl-in"] }
|
||||
# Java (OptiFine/Iris) shader packs, translated to WGSL.
|
||||
horizon-shaderpack = { path = "../horizon-shaderpack" }
|
||||
cpal = "0.16"
|
||||
symphonia = { version = "0.5", default-features = false, features = ["ogg", "vorbis"] }
|
||||
miniz_oxide = "0.8"
|
||||
|
||||
@@ -48,7 +48,16 @@ impl Game<'_> {
|
||||
None
|
||||
} else {
|
||||
state.stamp = Stamp::of(&dir.join(&id));
|
||||
match ShaderPack::load(&dir.join(&id), &shader_pack::load_values(&dir, &id)) {
|
||||
// Java packs are told which GPU they run on.
|
||||
let (vendor, renderer) = self.renderer.as_ref().map_or(("Unknown", ""), |r| {
|
||||
let name = r.info.name.as_str();
|
||||
(
|
||||
horizon_client::java_pack::vendor_name(r.info.vendor, name),
|
||||
name,
|
||||
)
|
||||
});
|
||||
let values = shader_pack::load_values(&dir, &id);
|
||||
match ShaderPack::load_any(&dir.join(&id), &values, vendor, renderer) {
|
||||
Ok(pack) => Some(pack),
|
||||
Err(e) => return self.shader_pack_error(&id, &e),
|
||||
}
|
||||
|
||||
@@ -58,6 +58,7 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6]
|
||||
}
|
||||
|
||||
mod arena;
|
||||
mod java_stages;
|
||||
mod occlusion;
|
||||
mod pack_stages;
|
||||
pub mod panorama;
|
||||
@@ -308,7 +309,7 @@ pub struct Renderer {
|
||||
/// Resolution scale and FXAA (Horizon settings).
|
||||
world_post: world_post::Post,
|
||||
/// The selected shader pack's stages (Horizon setting; none by default).
|
||||
pack: Option<pack_stages::PackStages>,
|
||||
pack: Option<Pack>,
|
||||
pub hud: HudRenderer,
|
||||
/// The menus' backdrop blur, made on first use.
|
||||
post: Option<crate::post::Post>,
|
||||
@@ -1682,19 +1683,28 @@ impl Renderer {
|
||||
/// Run `pack`'s stages over the world from now on (`None`: no pack, the
|
||||
/// vanilla frame). On error the previous pack stays.
|
||||
pub fn set_shader_pack(&mut self, pack: Option<&crate::shader_pack::ShaderPack>) -> Result<()> {
|
||||
let format = self.config.format.remove_srgb_suffix();
|
||||
self.pack = match pack {
|
||||
Some(pack) => Some(pack_stages::PackStages::new(
|
||||
&self.device,
|
||||
self.config.format.remove_srgb_suffix(),
|
||||
pack,
|
||||
)?),
|
||||
Some(pack) => Some(match &pack.java {
|
||||
Some(java) => Pack::Java(java_stages::JavaStages::new(
|
||||
&self.device,
|
||||
&self.queue,
|
||||
format,
|
||||
&pack.id,
|
||||
java,
|
||||
)?),
|
||||
None => Pack::Horizon(pack_stages::PackStages::new(&self.device, format, pack)?),
|
||||
}),
|
||||
None => None,
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
/// The folder name of the pack `set_shader_pack` gave.
|
||||
pub fn shader_pack_id(&self) -> Option<&str> {
|
||||
self.pack.as_ref().map(|p| p.id.as_str())
|
||||
self.pack.as_ref().map(|p| match p {
|
||||
Pack::Horizon(p) => p.id.as_str(),
|
||||
Pack::Java(p) => p.id.as_str(),
|
||||
})
|
||||
}
|
||||
/// Horizon's resolution scale (world pixels per window pixel) and FXAA.
|
||||
pub fn set_world_post(&mut self, scale: f32, antialias: bool) {
|
||||
@@ -2383,16 +2393,28 @@ impl Renderer {
|
||||
if let (true, Some((color, depth)), Some(size), Some(stages)) =
|
||||
(pack, &scaled, self.world_post.size(), self.pack.as_mut())
|
||||
{
|
||||
let output = stages.run(
|
||||
&self.device,
|
||||
&self.queue,
|
||||
&mut encoder,
|
||||
color,
|
||||
depth,
|
||||
size,
|
||||
&self.world_post,
|
||||
pack_uniform,
|
||||
);
|
||||
let output = match stages {
|
||||
Pack::Horizon(stages) => stages.run(
|
||||
&self.device,
|
||||
&self.queue,
|
||||
&mut encoder,
|
||||
color,
|
||||
depth,
|
||||
size,
|
||||
&self.world_post,
|
||||
pack_uniform,
|
||||
),
|
||||
Pack::Java(stages) => stages.run(
|
||||
&self.device,
|
||||
&self.queue,
|
||||
&mut encoder,
|
||||
color,
|
||||
depth,
|
||||
size,
|
||||
&self.world_post,
|
||||
pack_uniform,
|
||||
),
|
||||
};
|
||||
self.world_post
|
||||
.finish_with(&mut encoder, &view_target, output);
|
||||
} else if scaled.is_some() {
|
||||
@@ -2713,6 +2735,13 @@ fn shader_pack_uniform(
|
||||
}
|
||||
}
|
||||
|
||||
/// The selected shader pack on the GPU: a Horizon pack's WGSL stages, or a
|
||||
/// Java pack's translated programs.
|
||||
enum Pack {
|
||||
Horizon(pack_stages::PackStages),
|
||||
Java(java_stages::JavaStages),
|
||||
}
|
||||
|
||||
fn world_projection(fov_degrees: f32, aspect: f32, far: f32) -> Mat4 {
|
||||
Mat4::perspective_rh(fov_degrees.to_radians(), aspect, far, 0.05)
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,165 @@
|
||||
//! Java (OptiFine/Iris) shader packs in `shaderpacks/` (docs/shader-packs.md):
|
||||
//! a folder holding `shaders/`, or a `.zip`. `horizon-shaderpack` translates
|
||||
//! their full-screen programs (`begin`, `prepare`, `deferred`, `composite`,
|
||||
//! `final`) to WGSL, and `gfx/java_stages.rs` runs them over Horizon's world
|
||||
//! as Iris runs them over its own. Geometry programs (`gbuffers_*`,
|
||||
//! `shadow`) don't run yet: the world is drawn by Horizon.
|
||||
use horizon_shaderpack::{
|
||||
JavaPack,
|
||||
pipeline::{Program, TargetSettings},
|
||||
preprocess::Environment,
|
||||
};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
path::Path,
|
||||
};
|
||||
|
||||
/// The passes of one program folder (`world0`, or `""` for the pack's root).
|
||||
pub struct JavaFolder {
|
||||
pub folder: String,
|
||||
pub targets: Vec<TargetSettings>,
|
||||
/// `begin*`, `prepare*`, `deferred*`, `composite*`, in order.
|
||||
pub passes: Vec<Program>,
|
||||
/// How many of `passes` run before the world (`begin*`, `prepare*`): the
|
||||
/// world's colour and depth enter `colortex0` and `depthtex*` after them.
|
||||
pub world_at: usize,
|
||||
/// The targets whose alternate side the world is written to.
|
||||
pub flipped_after_prepare: BTreeSet<u32>,
|
||||
pub final_pass: Option<Program>,
|
||||
/// The targets whose alternate side holds the frame's last write.
|
||||
pub flipped_at_end: BTreeSet<u32>,
|
||||
}
|
||||
|
||||
/// A loaded Java pack.
|
||||
pub struct JavaPasses {
|
||||
pub folders: Vec<JavaFolder>,
|
||||
}
|
||||
|
||||
impl JavaPasses {
|
||||
/// The folder Iris uses in `dimension` (0 overworld, -1 the Nether, 1 the
|
||||
/// End): `world<N>` when the pack has one, else `world0`, else the root.
|
||||
pub fn folder_for(&self, dimension: i8) -> Option<usize> {
|
||||
let find = |name: &str| self.folders.iter().position(|f| f.folder == name);
|
||||
find(&format!("world{dimension}"))
|
||||
.or_else(|| find("world0"))
|
||||
.or_else(|| find(""))
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder holding `shaders/`, or a zip.
|
||||
pub fn is_java_pack(path: &Path) -> bool {
|
||||
path.join("shaders").is_dir()
|
||||
|| path.is_file()
|
||||
&& path
|
||||
.extension()
|
||||
.is_some_and(|e| e.eq_ignore_ascii_case("zip"))
|
||||
}
|
||||
|
||||
/// The `MC_GL_VENDOR_*` name of a wgpu adapter (`AdapterInfo::vendor`, a
|
||||
/// PCI id; Apple's GPUs report 0).
|
||||
pub fn vendor_name(vendor: u32, adapter: &str) -> &'static str {
|
||||
match vendor {
|
||||
0x10de => "NVIDIA Corporation",
|
||||
0x1002 | 0x1022 => "AMD",
|
||||
0x8086 => "Intel",
|
||||
_ if adapter.starts_with("Apple") => "Apple",
|
||||
_ => "Unknown",
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the pack at `path` and translate its full-screen passes with the
|
||||
/// player's `values`; `vendor` and `renderer` name the GPU to the pack.
|
||||
pub fn load(
|
||||
path: &Path,
|
||||
values: &BTreeMap<String, String>,
|
||||
vendor: &str,
|
||||
renderer: &str,
|
||||
) -> Result<JavaPasses, String> {
|
||||
let pack = JavaPack::open(path)?;
|
||||
let values = pack.values(values);
|
||||
let env = Environment::iris(vendor, renderer, 4);
|
||||
let properties = pack.properties(&values, &env)?;
|
||||
let mut names: Vec<&str> = ["world0", "world-1", "world1"]
|
||||
.into_iter()
|
||||
.filter(|d| {
|
||||
pack.programs
|
||||
.iter()
|
||||
.any(|p| p.starts_with(&format!("{d}/")))
|
||||
})
|
||||
.collect();
|
||||
if pack.programs.iter().any(|p| !p.contains('/')) {
|
||||
names.push("");
|
||||
}
|
||||
let mut folders = Vec::new();
|
||||
for name in names {
|
||||
let plan = pack.passes(name, &values, &env, &properties)?;
|
||||
let compile = |pass| {
|
||||
let program = pack.compile(pass, &plan.targets, &values, &env, &properties)?;
|
||||
if let Some((image, _)) = program.fragment.interface.images.first() {
|
||||
return Err(format!(
|
||||
"{}: images ({image}) aren't supported yet",
|
||||
program.pass.program
|
||||
));
|
||||
}
|
||||
Ok::<_, String>(program)
|
||||
};
|
||||
let early = plan.begin.iter().chain(&plan.prepare);
|
||||
let passes = early
|
||||
.clone()
|
||||
.chain(&plan.deferred)
|
||||
.chain(&plan.composite)
|
||||
.map(compile)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let final_pass = plan.final_pass.as_ref().map(compile).transpose()?;
|
||||
if passes.is_empty() && final_pass.is_none() {
|
||||
continue;
|
||||
}
|
||||
folders.push(JavaFolder {
|
||||
folder: name.to_owned(),
|
||||
targets: plan.targets,
|
||||
world_at: early.count(),
|
||||
passes,
|
||||
flipped_after_prepare: plan.flipped_after_prepare,
|
||||
final_pass,
|
||||
flipped_at_end: plan.flipped_at_end,
|
||||
});
|
||||
}
|
||||
if folders.is_empty() {
|
||||
return Err("no deferred, composite or final programs".into());
|
||||
}
|
||||
Ok(JavaPasses { folders })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn loads_the_full_screen_passes_of_a_java_pack() {
|
||||
let dir = Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../horizon-shaderpack/tests/fixtures/passes");
|
||||
assert!(is_java_pack(&dir));
|
||||
let pack = load(&dir, &BTreeMap::new(), "Apple", "Apple M4 Pro").unwrap();
|
||||
let [folder] = &pack.folders[..] else {
|
||||
panic!("one folder, the root");
|
||||
};
|
||||
assert_eq!(folder.folder, "");
|
||||
assert_eq!(
|
||||
folder
|
||||
.passes
|
||||
.iter()
|
||||
.map(|p| p.pass.program.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["deferred", "composite", "composite1"]
|
||||
);
|
||||
assert_eq!(folder.world_at, 0);
|
||||
assert!(folder.final_pass.is_some());
|
||||
// The overworld, the Nether and the End all use the root.
|
||||
assert_eq!([-1, 0, 1].map(|d| pack.folder_for(d)), [Some(0); 3]);
|
||||
assert_eq!(
|
||||
vendor_name(0x10de, "NVIDIA GeForce RTX 4080"),
|
||||
"NVIDIA Corporation"
|
||||
);
|
||||
assert_eq!(vendor_name(0, "Apple M4 Pro"), "Apple");
|
||||
}
|
||||
}
|
||||
@@ -87,6 +87,7 @@ pub mod item_data;
|
||||
pub mod item_render;
|
||||
pub mod item_tooltip;
|
||||
pub mod items;
|
||||
pub mod java_pack;
|
||||
pub mod java_text;
|
||||
pub mod key_names;
|
||||
pub mod keybinds;
|
||||
|
||||
@@ -109,6 +109,8 @@ pub struct ShaderPack {
|
||||
pub info: Info,
|
||||
pub stages: Vec<Stage>,
|
||||
pub options: Vec<PackOption>,
|
||||
/// A Java (OptiFine/Iris) pack's translated passes, instead of `stages`.
|
||||
pub java: Option<crate::java_pack::JavaPasses>,
|
||||
dir: PathBuf,
|
||||
stamp: Stamp,
|
||||
}
|
||||
@@ -120,6 +122,11 @@ pub struct Stamp(Vec<(PathBuf, u64, Option<SystemTime>)>);
|
||||
impl Stamp {
|
||||
pub fn of(dir: &Path) -> Self {
|
||||
let mut files = Vec::new();
|
||||
if let Ok(meta) = fs::metadata(dir)
|
||||
&& meta.is_file()
|
||||
{
|
||||
files.push((dir.to_path_buf(), meta.len(), meta.modified().ok()));
|
||||
}
|
||||
let mut stack = vec![dir.to_path_buf()];
|
||||
while let Some(d) = stack.pop() {
|
||||
let Ok(entries) = fs::read_dir(&d) else {
|
||||
@@ -141,23 +148,41 @@ impl Stamp {
|
||||
}
|
||||
|
||||
/// The packs in `dir` (`shaderpacks/`): folders holding a `pack.toml`, by
|
||||
/// folder name, with their manifest or why it can't be read.
|
||||
/// folder name, with their manifest or why it can't be read, and Java packs
|
||||
/// (folders holding `shaders/`, zips).
|
||||
pub fn list(dir: &Path) -> Vec<(String, Result<Info, String>)> {
|
||||
let mut packs: Vec<_> = fs::read_dir(dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.filter(|e| e.path().join("pack.toml").is_file())
|
||||
.map(|e| {
|
||||
.filter_map(|e| {
|
||||
let id = e.file_name().to_string_lossy().into_owned();
|
||||
let info = manifest(&e.path()).map(|m| m.pack);
|
||||
(id, info)
|
||||
let path = e.path();
|
||||
if path.join("pack.toml").is_file() {
|
||||
Some((id, manifest(&path).map(|m| m.pack)))
|
||||
} else if crate::java_pack::is_java_pack(&path) {
|
||||
Some((id.clone(), Ok(java_info(id))))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
packs.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
packs
|
||||
}
|
||||
|
||||
/// A Java pack has no manifest: its name is its file name.
|
||||
fn java_info(name: String) -> Info {
|
||||
Info {
|
||||
name,
|
||||
description: String::new(),
|
||||
authors: Vec::new(),
|
||||
version: String::new(),
|
||||
license: String::new(),
|
||||
api: API,
|
||||
}
|
||||
}
|
||||
|
||||
fn manifest(dir: &Path) -> Result<Manifest, String> {
|
||||
let text = fs::read_to_string(dir.join("pack.toml")).map_err(|e| format!("pack.toml: {e}"))?;
|
||||
let manifest: Manifest = toml::from_str(&text).map_err(|e| format!("pack.toml: {e}"))?;
|
||||
@@ -228,10 +253,38 @@ impl ShaderPack {
|
||||
info: manifest.pack,
|
||||
stages,
|
||||
options,
|
||||
java: None,
|
||||
dir: dir.to_path_buf(),
|
||||
stamp,
|
||||
})
|
||||
}
|
||||
/// Load the pack at `path` (a folder or a zip): a Horizon pack, or a
|
||||
/// Java pack translated for the GPU `vendor` and `renderer` names.
|
||||
pub fn load_any(
|
||||
path: &Path,
|
||||
values: &BTreeMap<String, String>,
|
||||
vendor: &str,
|
||||
renderer: &str,
|
||||
) -> Result<Self, String> {
|
||||
if path.join("pack.toml").is_file() || !crate::java_pack::is_java_pack(path) {
|
||||
return Self::load(path, values);
|
||||
}
|
||||
let stamp = Stamp::of(path);
|
||||
let java = crate::java_pack::load(path, values, vendor, renderer)?;
|
||||
let id = path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
Ok(Self {
|
||||
info: java_info(id.clone()),
|
||||
id,
|
||||
stages: Vec::new(),
|
||||
options: Vec::new(),
|
||||
java: Some(java),
|
||||
dir: path.to_path_buf(),
|
||||
stamp,
|
||||
})
|
||||
}
|
||||
/// The pipeline-overridable constants every stage gets: the option values.
|
||||
pub fn constants(&self) -> Vec<(&str, f64)> {
|
||||
self.options
|
||||
|
||||
@@ -8,8 +8,11 @@
|
||||
//! and `CompositeRenderer` do.
|
||||
|
||||
use crate::{
|
||||
JavaPack, options::OptionValues, preprocess::Environment, properties::LEGACY_TARGETS,
|
||||
properties::ShaderProperties,
|
||||
JavaPack,
|
||||
options::OptionValues,
|
||||
preprocess::Environment,
|
||||
properties::{LEGACY_TARGETS, ShaderProperties},
|
||||
translate::{Link, Translated},
|
||||
};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
@@ -478,6 +481,91 @@ impl JavaPack {
|
||||
}
|
||||
}
|
||||
|
||||
/// A pass's programs translated, with the targets it draws to.
|
||||
pub struct Program {
|
||||
pub pass: Pass,
|
||||
pub vertex: Translated,
|
||||
pub fragment: Translated,
|
||||
/// The target each output location writes: the pass's directive, or
|
||||
/// as Iris does without one, location `i` to target `i`.
|
||||
pub draw_buffers: Vec<u32>,
|
||||
/// The bindings both programs share.
|
||||
pub link: Link,
|
||||
}
|
||||
|
||||
impl JavaPack {
|
||||
/// Translate `pass`'s `.vsh` and `.fsh`.
|
||||
pub fn compile(
|
||||
&self,
|
||||
pass: &Pass,
|
||||
targets: &[TargetSettings],
|
||||
values: &OptionValues,
|
||||
env: &Environment,
|
||||
properties: &ShaderProperties,
|
||||
) -> Result<Program, String> {
|
||||
let mut link = Link {
|
||||
image_formats: properties.image_formats(),
|
||||
shared_samplers: shared_samplers(targets),
|
||||
..Link::default()
|
||||
};
|
||||
let vertex = self.translate(&format!("{}.vsh", pass.program), values, env, &mut link)?;
|
||||
let fragment = self.translate(&format!("{}.fsh", pass.program), values, env, &mut link)?;
|
||||
let draw_buffers = match &pass.draw_buffers {
|
||||
Some(buffers) => buffers.clone(),
|
||||
None => (0..fragment.interface.outputs.keys().max().map_or(1, |m| m + 1)).collect(),
|
||||
};
|
||||
Ok(Program {
|
||||
pass: pass.clone(),
|
||||
vertex,
|
||||
fragment,
|
||||
draw_buffers,
|
||||
link,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Iris's sampler states for the textures it binds: colour targets
|
||||
/// linear (nearest for integer formats, and for 32-bit floats, which wgpu
|
||||
/// can't filter everywhere), depth nearest, noise repeating. For
|
||||
/// [`Link::shared_samplers`].
|
||||
pub fn shared_samplers(targets: &[TargetSettings]) -> BTreeMap<String, String> {
|
||||
let mut out = BTreeMap::new();
|
||||
for (i, t) in targets.iter().enumerate() {
|
||||
let f = &t.format;
|
||||
let class = if f.ends_with("32F") || f.ends_with('I') {
|
||||
"iris_nearest"
|
||||
} else {
|
||||
"iris_linear"
|
||||
};
|
||||
out.insert(format!("colortex{i}"), class.to_owned());
|
||||
if let Some(legacy) = LEGACY_TARGETS.get(i) {
|
||||
out.insert((*legacy).to_owned(), class.to_owned());
|
||||
}
|
||||
}
|
||||
for name in [
|
||||
"depthtex0",
|
||||
"depthtex1",
|
||||
"depthtex2",
|
||||
"gdepthtex",
|
||||
"shadowtex0",
|
||||
"shadowtex1",
|
||||
"shadow",
|
||||
"watershadow",
|
||||
"dhDepthTex",
|
||||
"dhDepthTex0",
|
||||
"dhDepthTex1",
|
||||
"vxDepthTexOpaque",
|
||||
"vxDepthTexTrans",
|
||||
] {
|
||||
out.insert(name.to_owned(), "iris_nearest".to_owned());
|
||||
}
|
||||
for name in ["shadowcolor", "shadowcolor0", "shadowcolor1"] {
|
||||
out.insert(name.to_owned(), "iris_linear".to_owned());
|
||||
}
|
||||
out.insert("noisetex".to_owned(), "iris_repeat".to_owned());
|
||||
out
|
||||
}
|
||||
|
||||
fn toggle(set: &mut BTreeSet<u32>, buffer: u32) {
|
||||
if !set.remove(&buffer) {
|
||||
set.insert(buffer);
|
||||
|
||||
@@ -50,6 +50,11 @@ pub struct Link {
|
||||
pub uniforms: Vec<(String, String)>,
|
||||
/// Storage formats of images whose declaration has none.
|
||||
pub image_formats: BTreeMap<String, String>,
|
||||
/// Samplers shared by texture name (`colortex0` → `iris_linear`), so a
|
||||
/// pass binds a few samplers rather than one per texture (Metal allows
|
||||
/// 16). Once any is named, comparison samplers share `iris_compare` and
|
||||
/// integer ones `iris_nearest`; textures not named keep `{name}_s`.
|
||||
pub shared_samplers: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl Link {
|
||||
@@ -81,8 +86,11 @@ impl Link {
|
||||
#[derive(Default, Debug)]
|
||||
pub struct Interface {
|
||||
/// `(name, kind)` of each sampler the program reads (`colortex0`,
|
||||
/// `sampler2D`); its bindings are `{name}_t` and `{name}_s` in the [`Link`].
|
||||
/// `sampler2D`); its bindings are `{name}_t` and its sampler's in the [`Link`].
|
||||
pub samplers: Vec<(String, String)>,
|
||||
/// Each sampler's sampler variable: `{name}_s`, or a shared one
|
||||
/// ([`Link::shared_samplers`]).
|
||||
pub sampler_vars: BTreeMap<String, String>,
|
||||
/// `(name, format)` of each image.
|
||||
pub images: Vec<(String, String)>,
|
||||
/// Uniform names the program declares or uses.
|
||||
@@ -208,16 +216,18 @@ const IRIS_IMPLICIT: &[(&str, &str, bool)] = &[
|
||||
("alphaTestRef", "float", false),
|
||||
];
|
||||
|
||||
/// Built-ins naga lacks. `isnan` and `isinf` test the bits: Metal compiles
|
||||
/// with fast math, which folds `x != x` to false.
|
||||
const HELPERS: &str = "\
|
||||
struct iris_FogParameters { vec4 color; float density; float start; float end; float scale; };
|
||||
bool iris_isnan(float x) { return x != x; }
|
||||
bvec2 iris_isnan(vec2 x) { return notEqual(x, x); }
|
||||
bvec3 iris_isnan(vec3 x) { return notEqual(x, x); }
|
||||
bvec4 iris_isnan(vec4 x) { return notEqual(x, x); }
|
||||
bool iris_isinf(float x) { return abs(x) > 3.4028235e38; }
|
||||
bvec2 iris_isinf(vec2 x) { return greaterThan(abs(x), vec2(3.4028235e38)); }
|
||||
bvec3 iris_isinf(vec3 x) { return greaterThan(abs(x), vec3(3.4028235e38)); }
|
||||
bvec4 iris_isinf(vec4 x) { return greaterThan(abs(x), vec4(3.4028235e38)); }
|
||||
bool iris_isnan(float x) { return (floatBitsToUint(x) & 0x7fffffffu) > 0x7f800000u; }
|
||||
bvec2 iris_isnan(vec2 x) { return greaterThan(floatBitsToUint(x) & 0x7fffffffu, uvec2(0x7f800000u)); }
|
||||
bvec3 iris_isnan(vec3 x) { return greaterThan(floatBitsToUint(x) & 0x7fffffffu, uvec3(0x7f800000u)); }
|
||||
bvec4 iris_isnan(vec4 x) { return greaterThan(floatBitsToUint(x) & 0x7fffffffu, uvec4(0x7f800000u)); }
|
||||
bool iris_isinf(float x) { return (floatBitsToUint(x) & 0x7fffffffu) == 0x7f800000u; }
|
||||
bvec2 iris_isinf(vec2 x) { return equal(floatBitsToUint(x) & 0x7fffffffu, uvec2(0x7f800000u)); }
|
||||
bvec3 iris_isinf(vec3 x) { return equal(floatBitsToUint(x) & 0x7fffffffu, uvec3(0x7f800000u)); }
|
||||
bvec4 iris_isinf(vec4 x) { return equal(floatBitsToUint(x) & 0x7fffffffu, uvec4(0x7f800000u)); }
|
||||
float iris_modf(float x, out float i) { i = trunc(x); return x - i; }
|
||||
vec2 iris_modf(vec2 x, out vec2 i) { i = trunc(x); return x - i; }
|
||||
vec3 iris_modf(vec3 x, out vec3 i) { i = trunc(x); return x - i; }
|
||||
@@ -288,7 +298,10 @@ struct Legaliser<'a> {
|
||||
link: &'a mut Link,
|
||||
interface: Interface,
|
||||
/// Global samplers: name → combined type.
|
||||
samplers: HashMap<String, &'static str>,
|
||||
/// Sampler uniforms: their combined type and sampler variable.
|
||||
samplers: HashMap<String, (&'static str, String)>,
|
||||
/// Sampler variables declared so far (shared ones once).
|
||||
sampler_vars: HashSet<String>,
|
||||
/// User functions → indices of their sampler parameters.
|
||||
sampler_params: HashMap<String, BTreeSet<usize>>,
|
||||
functions: HashSet<String>,
|
||||
@@ -484,6 +497,7 @@ impl<'a> Legaliser<'a> {
|
||||
link,
|
||||
interface: Interface::default(),
|
||||
samplers: HashMap::new(),
|
||||
sampler_vars: HashSet::new(),
|
||||
sampler_params: HashMap::new(),
|
||||
functions: HashSet::new(),
|
||||
scopes: Vec::new(),
|
||||
@@ -601,17 +615,35 @@ impl<'a> Legaliser<'a> {
|
||||
|| has(ast::StorageQualifierData::Out) && self.stage == Stage::Vertex
|
||||
|| has(ast::StorageQualifierData::In) && self.stage == Stage::Fragment;
|
||||
if has(ast::StorageQualifierData::Uniform) {
|
||||
if let Some(&(combined, texture, sampler, _)) = opaque(&ty) {
|
||||
if let Some(&(combined, texture, sampler, compare)) = opaque(&ty) {
|
||||
for (name, _) in &names {
|
||||
let t = self.link.binding(&format!("{name}_t"));
|
||||
let s = self.link.binding(&format!("{name}_s"));
|
||||
self.header.push(format!(
|
||||
"layout(set = 0, binding = {t}) uniform {texture} {name}_t;"
|
||||
));
|
||||
self.header.push(format!(
|
||||
"layout(set = 0, binding = {s}) uniform {sampler} {name}_s;"
|
||||
));
|
||||
self.samplers.insert(name.clone(), combined);
|
||||
let shared = &self.link.shared_samplers;
|
||||
let var = if shared.is_empty() {
|
||||
format!("{name}_s")
|
||||
} else if compare {
|
||||
"iris_compare".to_owned()
|
||||
} else if combined.starts_with(['i', 'u']) {
|
||||
"iris_nearest".to_owned()
|
||||
} else {
|
||||
shared
|
||||
.get(name)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| format!("{name}_s"))
|
||||
};
|
||||
if self.sampler_vars.insert(var.clone()) {
|
||||
let s = self.link.binding(&var);
|
||||
self.header.push(format!(
|
||||
"layout(set = 0, binding = {s}) uniform {sampler} {var};"
|
||||
));
|
||||
}
|
||||
self.interface
|
||||
.sampler_vars
|
||||
.insert(name.clone(), var.clone());
|
||||
self.samplers.insert(name.clone(), (combined, var));
|
||||
self.interface
|
||||
.samplers
|
||||
.push((name.clone(), combined.to_owned()));
|
||||
@@ -1034,13 +1066,14 @@ impl<'a> Legaliser<'a> {
|
||||
let combined = match self.local(name) {
|
||||
Some(Local::Sampler(c)) => Some(c),
|
||||
Some(Local::Plain) => return None,
|
||||
None => self.samplers.get(name).copied(),
|
||||
None => self.samplers.get(name).map(|(c, _)| *c),
|
||||
};
|
||||
if let Some(c) = combined {
|
||||
return Some(call(
|
||||
c,
|
||||
vec![var(&format!("{name}_t")), var(&format!("{name}_s"))],
|
||||
));
|
||||
let sampler = match self.samplers.get(name) {
|
||||
Some((_, v)) if self.local(name).is_none() => v.clone(),
|
||||
_ => format!("{name}_s"),
|
||||
};
|
||||
return Some(call(c, vec![var(&format!("{name}_t")), var(&sampler)]));
|
||||
}
|
||||
self.used.insert(name.to_owned());
|
||||
if let Some((_, decl)) = LEGACY_UNIFORMS.iter().find(|(n, _)| *n == name) {
|
||||
@@ -1263,6 +1296,15 @@ impl<'a> Legaliser<'a> {
|
||||
if !self.errors.is_empty() {
|
||||
return Err(self.errors.join("\n"));
|
||||
}
|
||||
if self.stage == Stage::Vertex {
|
||||
// GL's clip space to wgpu's: y flipped, so texture row 0 stays
|
||||
// the bottom of the picture as in GL (texture coordinates and
|
||||
// `gl_FragCoord` then agree with the pack's), and z from
|
||||
// [-w, w] to [0, w].
|
||||
self.epilogue.push("gl_Position.y = -gl_Position.y;".into());
|
||||
self.epilogue
|
||||
.push("gl_Position.z = (gl_Position.z + gl_Position.w) * 0.5;".into());
|
||||
}
|
||||
let mut out = String::from("#version 450 core\n");
|
||||
out.push_str(HELPERS);
|
||||
if !self.link.uniforms.is_empty() {
|
||||
|
||||
@@ -368,5 +368,31 @@ fn real_packs_passes() {
|
||||
);
|
||||
}
|
||||
assert!(passes.final_pass.is_some() || !passes.composite.is_empty());
|
||||
// Every planned pass translates, its outputs within its targets.
|
||||
for p in passes
|
||||
.begin
|
||||
.iter()
|
||||
.chain(&passes.prepare)
|
||||
.chain(&passes.deferred)
|
||||
.chain(&passes.composite)
|
||||
.chain(&passes.final_pass)
|
||||
{
|
||||
let program = pack
|
||||
.compile(p, &passes.targets, &values, &env(), &properties)
|
||||
.unwrap();
|
||||
assert!(
|
||||
program
|
||||
.fragment
|
||||
.interface
|
||||
.outputs
|
||||
.keys()
|
||||
.all(|&l| (l as usize) < program.draw_buffers.len())
|
||||
|| p.program.ends_with("final"),
|
||||
"{}: outputs {:?}, targets {:?}",
|
||||
p.program,
|
||||
program.fragment.interface.outputs,
|
||||
program.draw_buffers
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -249,6 +249,13 @@ fn translates_a_compatibility_profile_pass() {
|
||||
assert!(!fs.glsl.contains("albedo = vec4(0.);"), "{}", fs.glsl);
|
||||
assert!(fs.glsl.contains("iris_isnan(albedo.r)"), "{}", fs.glsl);
|
||||
assert!(fs.wgsl.contains("@fragment"));
|
||||
// GL's clip space becomes wgpu's after the program's own `main`.
|
||||
assert!(
|
||||
vs.glsl
|
||||
.contains("gl_Position.y = -gl_Position.y;\n gl_Position.z = (gl_Position.z + gl_Position.w) * 0.5;\n}"),
|
||||
"{}",
|
||||
vs.glsl
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -354,3 +361,47 @@ fn real_packs_translate() {
|
||||
}
|
||||
assert!(failures.is_empty(), "{}", failures.join("\n\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn textures_share_samplers_by_name() {
|
||||
let mut link = Link {
|
||||
shared_samplers: [("colortex0", "iris_linear"), ("colortex1", "iris_linear")]
|
||||
.map(|(a, b)| (a.to_owned(), b.to_owned()))
|
||||
.into(),
|
||||
..Link::default()
|
||||
};
|
||||
let fs = run(
|
||||
Stage::Fragment,
|
||||
"uniform sampler2D colortex0;\nuniform sampler2D colortex1;\nuniform sampler2D custom;\n\
|
||||
uniform sampler2DShadow shadowtex0;\nvarying vec2 uv;\n\
|
||||
void main() { gl_FragColor = texture2D(colortex0, uv) + texture2D(colortex1, uv)\n\
|
||||
+ texture2D(custom, uv) + shadow2D(shadowtex0, vec3(uv, 0.5)); }",
|
||||
&mut link,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
fs.glsl.matches("uniform sampler iris_linear;").count(),
|
||||
1,
|
||||
"{}",
|
||||
fs.glsl
|
||||
);
|
||||
assert!(
|
||||
fs.glsl.contains("sampler2D(colortex1_t, iris_linear)"),
|
||||
"{}",
|
||||
fs.glsl
|
||||
);
|
||||
assert!(fs.glsl.contains("uniform sampler custom_s;"), "{}", fs.glsl);
|
||||
assert!(
|
||||
fs.glsl.contains("uniform samplerShadow iris_compare;"),
|
||||
"{}",
|
||||
fs.glsl
|
||||
);
|
||||
assert_eq!(fs.interface.sampler_vars["colortex0"], "iris_linear");
|
||||
// Three sampler bindings for four textures.
|
||||
assert_eq!(
|
||||
bindings(&fs).keys().filter(|k| !k.ends_with("_t")).count(),
|
||||
3,
|
||||
"{:?}",
|
||||
bindings(&fs)
|
||||
);
|
||||
}
|
||||
|
||||
+39
-2
@@ -19,8 +19,9 @@ Both are off by default. With no pack selected the renderer draws exactly what i
|
||||
| Java shader packs: preprocessor (`crates/horizon-shaderpack`: includes, options, Iris's macros) | done: every program of the three test packs preprocesses |
|
||||
| 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, not drawn yet: planned for the three test packs |
|
||||
| Java shader packs: Iris pipeline emulation | planned |
|
||||
| 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 |
|
||||
| Java shader packs: full-screen passes drawn (`java_pack.rs`, `gfx/java_stages.rs`: `begin`, `prepare`, `deferred*`, `composite*`, `final` over Horizon's world) | first slice: BSL and Complementary run (below) |
|
||||
| Java shader packs: `gbuffers_*`, `shadow`, custom textures, images, compute, option screen | planned |
|
||||
|
||||
## How the renderer draws a frame today
|
||||
|
||||
@@ -328,6 +329,42 @@ The spike also showed what the real translator needs that a token rewriter does
|
||||
uniform), types (which `texture` call returns a float) and declarations split across `#if`s, so it should rewrite a
|
||||
GLSL syntax tree after preprocessing, not tokens.
|
||||
|
||||
### Running a Java pack's full-screen passes
|
||||
|
||||
A folder holding `shaders/`, or a `.zip`, in `shaderpacks/` shows in the Shader Packs screen next to Horizon packs.
|
||||
Picking one translates every planned pass of each dimension folder (`java_pack.rs`) and runs them each frame
|
||||
(`gfx/java_stages.rs`):
|
||||
|
||||
1. the targets the pack clears are cleared;
|
||||
2. `begin*` and `prepare*` run, then Horizon's world enters `colortex0` and `depthtex0..2` on the side the flips give;
|
||||
3. `deferred*` and `composite*` run in order, each reading the side its plan gives and writing the other;
|
||||
4. `final` draws into a target that replaces the world's picture, where Horizon packs' `composite` output goes: the
|
||||
hand, menus and HUD are drawn over it.
|
||||
|
||||
What makes Horizon look like OpenGL to the pack:
|
||||
|
||||
- **Layout.** The translator ends every vertex shader by flipping `gl_Position.y` and moving depth from `[-w, w]` to
|
||||
`[0, w]`, so the targets keep OpenGL's layout (row 0 at the bottom). The world is flipped going in, `final` coming out.
|
||||
- **Depth.** Horizon's depth is reversed (1 near, 0 sky); the world goes in as `1 - depth`, and the matrices the pack
|
||||
gets (`gbufferProjection` and its inverse, previous frame too) are OpenGL's, rebuilt from Horizon's.
|
||||
- **Formats.** Iris formats become renderable wgpu formats: 8-bit unorm ones and `RGB10_A2` stay, `*32F` stay (sampled
|
||||
unfiltered), integer formats become 32-bit, the rest (`R11F_G11F_B10F`, `*16F`, `*16`) 16-bit float, with the
|
||||
channel count of the name.
|
||||
- **Samplers.** Metal allows 16 samplers per stage and Complementary binds 23 textures, so textures share four
|
||||
samplers by kind (`iris_linear`, `iris_nearest` for depth and 32-bit or integer targets, `iris_repeat` for
|
||||
`noisetex`, `iris_compare` for shadow lookups) instead of one each.
|
||||
- **`isnan`/`isinf`** test the float's bits: Metal compiles with fast math, which folds `x != x` to false, and a NaN
|
||||
then stays forever in Complementary's TAA history (the picture turns black).
|
||||
- **Uniforms.** Matrices, camera, view size, time, sun and moon, weather, fog and sky colour, eye state come from the
|
||||
frame; `eyeBrightness(Smooth)` is `(0, 240)` under the sky; `noisetex` is a fixed 256² noise.
|
||||
|
||||
Measured on the Mac mini (M4 Pro) with the packs' default options: BSL v10.1.8 and Complementary Reimagined r5.9.3
|
||||
grade and light Horizon's world as their post-processing would. Sildur's Vibrant v2.02 draws only its sky: its
|
||||
`deferred` reads the albedo `gbuffers_*` write to `colortex4`. Without `gbuffers_*` and `shadow`, no pack has its
|
||||
shadows, water or sky look yet; Distant Horizons' and Voxy's depth read as far. Not supported yet: images and
|
||||
compute (`.csh`; a pack that needs them doesn't load), mipmapped targets (`colortexNMipmapEnabled` is read but
|
||||
ignored), custom textures, custom uniforms, the option screen; shadow matrices are identity.
|
||||
|
||||
### Order to implement
|
||||
|
||||
1. **Translator crate** (`horizon-shaderpack`): the preprocessor (includes, option `#define`s with the player's
|
||||
|
||||
Reference in New Issue
Block a user