Merge pull request #1277 from ludovic111/feat/java-gbuffers-terrain

🤖 Agent: merged after verify and CI parity passed (shaders stack: Java packs draw their own terrain, water and shadow map, as in Iris). BSL shows real shadows on Vulkan and Metal; frame times and screenshots are on #1326. Without a pack, nothing changes.
This commit is contained in:
Ludovic Marie
2026-10-24 03:18:46 +02:00
committed by GitHub
15 changed files with 2258 additions and 203 deletions
+4
View File
@@ -87,3 +87,7 @@ rng-trace = ["horizon-core/rng-trace"]
[lints]
workspace = true
[dev-dependencies]
# Every WGSL shader translated as wgpu's DirectX 12 backend does (gfx.rs tests).
naga = { version = "30.0.1", features = ["wgsl-in", "hlsl-out", "msl-out", "spv-out"] }
@@ -69,7 +69,7 @@ impl Game<'_> {
}
};
if let Some(r) = self.renderer.as_mut()
&& let Err(e) = r.set_shader_pack(pack.as_ref())
&& let Err(e) = r.set_shader_pack(pack.as_ref(), &self.pack.render.sprite_layers)
{
return self.shader_pack_error(&id, &e.to_string());
}
@@ -79,7 +79,10 @@ impl Game<'_> {
/// Give the loaded pack to the renderer (also after it is rebuilt).
pub(super) fn apply_shader_pack(&mut self) -> horizon_client::Result<()> {
match self.renderer.as_mut() {
Some(r) => r.set_shader_pack(self.shader_packs.pack.as_ref()),
Some(r) => r.set_shader_pack(
self.shader_packs.pack.as_ref(),
&self.pack.render.sprite_layers,
),
None => Ok(()),
}
}
+214 -13
View File
@@ -65,7 +65,8 @@ mod arena;
mod cull;
mod end_sky;
mod flat;
mod java_stages;
pub(crate) mod java_stages;
pub(crate) mod java_terrain;
pub mod lightning;
mod lod;
mod occlusion;
@@ -491,6 +492,15 @@ pub struct Renderer {
world_post: world_post::Post,
/// The selected shader pack's stages (Horizon setting; none by default).
pack: Option<Pack>,
/// A Java pack's terrain programs (`gfx/java_terrain.rs`): their page
/// groups' layout, the glue's table, each arena page's group.
java_page_layout: wgpu::BindGroupLayout,
/// The device renders to and filters 16-bit normalized formats.
java_norm16: bool,
java_table: Option<wgpu::Buffer>,
java_pages: Vec<Option<(wgpu::Buffer, wgpu::BindGroup)>>,
/// The sprite layers and mip levels `animate` wrote this frame.
animated: Vec<(u32, u32)>,
pub hud: HudRenderer,
/// Vanilla's menu background blur, made on first use.
menu_blur: Option<crate::menu_blur::MenuBlur>,
@@ -839,7 +849,10 @@ async fn open_device(
| cull::Cull::features(&adapter)
| (adapter.features()
& (wgpu::Features::INDIRECT_FIRST_INSTANCE
| wgpu::Features::MAPPABLE_PRIMARY_BUFFERS));
| wgpu::Features::MAPPABLE_PRIMARY_BUFFERS
// Java shader packs' 16-bit colour targets.
| wgpu::Features::TEXTURE_FORMAT_16BIT_NORM
| wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES));
let driver = format!("{} {}", info.driver, info.driver_info);
startup_step(format_args!(
"requesting the device (driver {}) with features [{features}] and the adapter's \
@@ -1369,8 +1382,10 @@ impl Renderer {
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
// COPY_SRC: animated sprites into a Java pack's atlas.
usage: wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::COPY_DST
| wgpu::TextureUsages::COPY_SRC
| wgpu::TextureUsages::STORAGE_BINDING,
view_formats: &[],
},
@@ -2214,6 +2229,8 @@ impl Renderer {
std::mem::size_of::<TerrainVertex>() as u64,
1 << 20,
);
let java_page_layout = java_terrain::page_layout(&device);
let java_norm16 = java_terrain::norm16_targets(&adapter, &device);
// Sections as one index list per frame where multi-draw is emulated.
let flat = flat::wanted(&adapter, &device).then(|| {
let buffers = [Some(wgpu::VertexBufferLayout {
@@ -2414,6 +2431,11 @@ impl Renderer {
occlusion: occlusion::Occlusion::new(crate::chunk::MIN_Y, crate::chunk::HEIGHT / 16),
world_post,
pack: None,
java_page_layout,
java_norm16,
java_table: None,
java_pages: Vec::new(),
animated: Vec::new(),
hud,
menu_blur: None,
info,
@@ -2722,6 +2744,18 @@ impl Renderer {
base: u32,
first: u32,
count: u32,
) {
self.draw_sections_with(pass, indirect, base, first, count, |_, _| {});
}
/// [`Self::draw_sections`]; `page` binds what else a page's draws need.
fn draw_sections_with(
&self,
pass: &mut wgpu::RenderPass<'_>,
indirect: &wgpu::Buffer,
base: u32,
first: u32,
count: u32,
page_group: impl Fn(&mut wgpu::RenderPass<'_>, u32),
) {
let (mut i, end) = (first as usize, (first + count) as usize);
while i < end {
@@ -2731,6 +2765,7 @@ impl Renderer {
.take_while(|&&p| p == (page, index_page))
.count();
pass.set_vertex_buffer(0, self.arena.buffer(page).slice(..));
page_group(pass, page);
let indices = index_page.map_or(&self.indices, |p| self.sorted_indices.buffer(p));
pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32);
if self.multi_draw {
@@ -2744,6 +2779,88 @@ impl Renderer {
i += run;
}
}
/// Horizon's terrain, solid or `translucent`, with a Java pack's
/// geometry pipelines (`java_terrain::DrawTerrain`): the frame's flat
/// draws or its section draws, each page with its group 3.
fn draw_java_terrain(
&self,
pass: &mut wgpu::RenderPass<'_>,
translucent: bool,
pipelines: &java_terrain::TerrainPipelines,
flat_frame: bool,
draws: [u32; 2],
) {
let page = |pass: &mut wgpu::RenderPass<'_>, page: u32| {
if let Some(Some((_, group))) = self.java_pages.get(page as usize) {
pass.set_bind_group(3, group, &[]);
}
};
pass.set_bind_group(2, pipelines.group, &[]);
match (self.flat.as_ref().filter(|_| flat_frame), pipelines.flat) {
(Some(flat), Some(pipeline)) => {
pass.set_pipeline(pipeline);
let calls = if translucent {
&flat.calls[flat.solid_calls..]
} else {
&flat.calls[..flat.solid_calls]
};
flat.draw(pass, calls, |p| self.arena.buffer(p), page);
}
(Some(_), None) => {}
(None, _) => {
pass.set_pipeline(pipelines.instanced);
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
pass.set_vertex_buffer(1, self.instances.slice(..));
let [solid, translucent_draws] = draws;
let (first, count) = if translucent {
(solid, translucent_draws)
} else {
(0, solid)
};
self.draw_sections_with(pass, &self.indirect, 0, first, count, page);
}
}
}
/// Each arena page's group for a Java pack's terrain programs: its
/// vertices and the glue's table.
fn prepare_java_pages(&mut self) {
let Some(table) = &self.java_table else {
return;
};
let count = self.arena.page_count() as usize;
self.java_pages.resize_with(count, || None);
let limit = self.device.limits().max_storage_buffer_binding_size;
for page in 0..count {
if !self.arena.has_page(page as u32) {
self.java_pages[page] = None;
continue;
}
let buffer = self.arena.buffer(page as u32);
if matches!(&self.java_pages[page], Some((b, _)) if b == buffer) {
continue;
}
let size = buffer.size().min(limit / 4 * 4);
let group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Java shader pack terrain page"),
layout: &self.java_page_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
buffer,
offset: 0,
size: std::num::NonZeroU64::new(size),
}),
},
wgpu::BindGroupEntry {
binding: 1,
resource: table.as_entire_binding(),
},
],
});
self.java_pages[page] = Some((buffer.clone(), group));
}
}
fn release_section(&mut self, key: SectionKey) {
if let Some(s) = self.sections.remove(key) {
self.release_mesh(s);
@@ -2827,9 +2944,29 @@ 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<()> {
/// vanilla frame). On error the previous pack stays. `sprite_layers`
/// names the block sprites, for a Java pack's `block.properties`.
pub fn set_shader_pack(
&mut self,
pack: Option<&crate::shader_pack::ShaderPack>,
sprite_layers: &std::collections::BTreeMap<String, u32>,
) -> Result<()> {
let format = self.config.format.remove_srgb_suffix();
let layouts = java_stages::GeometryLayouts {
flat: self.flat.as_ref().map(|f| f.draw_layout()),
page: &self.java_page_layout,
};
let table = pack.and_then(|p| p.java.as_ref()).map(|java| {
let table = java_terrain::table(sprite_layers, &java.block_ids);
wgpu::util::DeviceExt::create_buffer_init(
&self.device,
&wgpu::util::BufferInitDescriptor {
label: Some("Java shader pack terrain table"),
contents: bytemuck::cast_slice(&table),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
},
)
});
self.pack = match pack {
Some(pack) => Some(match &pack.java {
Some(java) => Pack::Java(java_stages::JavaStages::new(
@@ -2838,6 +2975,8 @@ impl Renderer {
format,
&pack.id,
java,
&layouts,
self.java_norm16,
)?),
None => Pack::Horizon(pack_stages::PackStages::new(
&self.device,
@@ -2848,6 +2987,8 @@ impl Renderer {
}),
None => None,
};
self.java_table = table;
self.java_pages.clear();
Ok(())
}
/// The folder name of the pack `set_shader_pack` gave.
@@ -2988,6 +3129,15 @@ impl Renderer {
}
fn animate(&mut self, encoder: &mut wgpu::CommandEncoder, tick: u64) {
self.animations.animate(encoder, &mut self.uploads, tick);
// A Java pack's atlas copies what changed, every level.
let levels = self.mip_levels;
self.animated.clear();
self.animated.extend(
self.animations
.changed
.iter()
.flat_map(|&layer| (0..levels).map(move |level| (layer, level))),
);
}
pub fn render(&mut self, frame: &Frame) -> Result<bool> {
let rendered = self.draw_frame(frame);
@@ -3272,6 +3422,12 @@ impl Renderer {
let eye = (frame.bob * crate::camera::view_matrix(frame.yaw, frame.pitch))
.inverse()
.transform_point3(Vec3::ZERO);
// A Java pack that draws the terrain (`gfx/java_terrain.rs`): the
// world pass leaves it out, and occlusion culling (which tests
// against its depth) is off.
let java_terrain = !frame.title
&& self.java_table.is_some()
&& matches!(&self.pack, Some(Pack::Java(j)) if j.draws_terrain(frame.shader.dimension));
// Occlusion culling leaves the sections its last result did not see
// to phase 2, after the others, with instance counts of 0. Whether
// the frame has draws enough goes by the last one's.
@@ -3279,7 +3435,11 @@ impl Renderer {
.cull
.as_mut()
.filter(|c| {
self.cull_on && !frame.title && self.multi_draw && self.section_draws >= c.min_draws
self.cull_on
&& !frame.title
&& self.multi_draw
&& self.section_draws >= c.min_draws
&& !java_terrain
})
.and_then(|cull| cull.begin(&self.device).then_some(cull));
self.phase2_draws.clear();
@@ -3729,6 +3889,14 @@ impl Renderer {
bytemuck::cast_slice(&self.draws),
);
}
if java_terrain {
self.prepare_java_pages();
if let Some(table) = &self.java_table {
let nether = i32::from(frame.shader.dimension == -1);
self.queue
.write_buffer(table, 4, bytemuck::bytes_of(&nether));
}
}
let view_target = target_texture.create_view(&wgpu::TextureViewDescriptor {
format: Some(self.config.format.remove_srgb_suffix()),
..Default::default()
@@ -3890,6 +4058,7 @@ impl Renderer {
}
}
match self.flat.as_ref().filter(|_| flat_frame) {
_ if java_terrain => {}
Some(flat) => {
pass.set_pipeline(&flat.solid);
let vertices = |p| self.arena.buffer(p);
@@ -3897,7 +4066,12 @@ impl Renderer {
// As below: phase 1, the test, then phase 2's draws
// that the test saw, copied after it.
Some(cull) => {
flat.draw(&mut pass, &flat.calls[..flat.phase1_calls], vertices);
flat.draw(
&mut pass,
&flat.calls[..flat.phase1_calls],
vertices,
|_, _| {},
);
cull.test(&mut pass);
drop(pass);
cull.test_pass(&mut encoder);
@@ -3912,7 +4086,12 @@ impl Renderer {
pass.set_pipeline(&flat.solid);
flat.draw_phase2(&mut pass, vertices);
}
None => flat.draw(&mut pass, &flat.calls[..flat.solid_calls], vertices),
None => flat.draw(
&mut pass,
&flat.calls[..flat.solid_calls],
vertices,
|_, _| {},
),
}
pass.set_bind_group(0, &self.group, &[]);
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
@@ -4041,11 +4220,15 @@ impl Renderer {
pass.set_bind_group(0, &self.group, &[]);
}
match self.flat.as_ref().filter(|_| flat_frame) {
_ if java_terrain => {}
Some(flat) => {
pass.set_pipeline(&flat.translucent);
flat.draw(&mut pass, &flat.calls[flat.solid_calls..], |p| {
self.arena.buffer(p)
});
flat.draw(
&mut pass,
&flat.calls[flat.solid_calls..],
|p| self.arena.buffer(p),
|_, _| {},
);
pass.set_bind_group(0, &self.group, &[]);
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
}
@@ -4120,10 +4303,26 @@ impl Renderer {
frame.shader.rain,
);
}
if let (true, Some((color, depth)), Some(size), Some(stages)) =
(pack, &scaled, self.world_post.size(), self.pack.as_mut())
if pack
&& let (Some((color, depth)), Some(size)) = (&scaled, self.world_post.size())
&& let Some(mut stages) = self.pack.take()
{
let output = match stages {
// The pack's terrain programs draw with the frame's draws.
let draws = [solid_draws, translucent_draws];
let draw = |render: &mut wgpu::RenderPass<'_>,
translucent: bool,
pipelines: &java_terrain::TerrainPipelines| {
self.draw_java_terrain(render, translucent, pipelines, flat_frame, draws);
};
let world = java_terrain::JavaWorld {
sprites: &self.sprite_textures,
split: sprite_split(),
levels: self.mipmaps,
animated: &self.animated,
lightmap: &self.lightmap_view,
draw: &draw,
};
let output = match &mut stages {
Pack::Horizon(stages) => stages.run(
&self.device,
&self.queue,
@@ -4149,10 +4348,12 @@ impl Renderer {
sun_angle: frame.sky.sun_angle,
moon_angle: frame.sky.moon_angle,
},
java_terrain.then_some(&world),
),
};
self.world_post
.finish_with(&mut encoder, &view_target, output);
self.pack = Some(stages);
} else if scaled.is_some() {
self.world_post.finish(&mut encoder, &view_target);
}
+6
View File
@@ -51,6 +51,9 @@ pub(super) struct SpriteAnimator {
pipeline: wgpu::ComputePipeline,
/// Edge of the arrays' layers.
size: u32,
/// The sprite layers (across the arrays) the last `animate` rewrote, at
/// every mip level: a Java pack's atlas copies them.
pub changed: Vec<u32>,
}
impl SpriteAnimator {
@@ -205,6 +208,7 @@ impl SpriteAnimator {
jobs,
pipeline,
size,
changed: Vec::new(),
}
}
@@ -216,6 +220,7 @@ impl SpriteAnimator {
uploads: &mut Uploads,
tick: u64,
) {
self.changed.clear();
if self.collect(tick) == 0 {
return;
}
@@ -251,6 +256,7 @@ impl SpriteAnimator {
continue;
}
sprite.shown = Some(blend);
self.changed.push(sprite.animation.layer);
let job = [
sprite.layer,
sprite.frames[blend.frame],
+8 -1
View File
@@ -65,8 +65,11 @@ pub struct Arena {
}
impl Arena {
/// Vertices; also storage, which a Java shader pack's terrain programs
/// read a quad's corners from (`gfx/java_terrain.rs`).
pub fn new(device: &wgpu::Device, stride: u64, capacity: u64) -> Self {
Self::with_usage(device, stride, capacity, wgpu::BufferUsages::VERTEX)
let usage = wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::STORAGE;
Self::with_usage(device, stride, capacity, usage)
}
/// Sorted translucent indices; `storage` when compute passes read them.
pub fn indices(device: &wgpu::Device, capacity: u64, storage: bool) -> Self {
@@ -145,6 +148,10 @@ impl Arena {
pub fn page_vertices(&self) -> u64 {
self.page_limit
}
/// One past the last page index.
pub fn page_count(&self) -> u32 {
self.pages.len() as u32
}
pub fn has_page(&self, page: u32) -> bool {
self.pages.get(page as usize).is_some_and(Option::is_some)
}
+10 -1
View File
@@ -640,17 +640,26 @@ impl Flat {
pass.set_bind_group(0, group, &[]);
pass.dispatch_workgroups((*count).min(GROUP_LIMIT), count.div_ceil(GROUP_LIMIT), 1);
}
/// The bind group layout of the draws' group 1 (block slots, slot
/// origins).
pub fn draw_layout(&self) -> &wgpu::BindGroupLayout {
&self.draw_layout
}
/// Draws `calls` with a flat pipeline set and `vertices` giving each
/// page's vertex buffer.
/// page's vertex buffer; `page` binds what else a page's draws need (a
/// Java pack's terrain reads the page's vertices).
pub fn draw<'a>(
&self,
pass: &mut wgpu::RenderPass<'_>,
calls: &[Call],
vertices: impl Fn(u32) -> &'a wgpu::Buffer,
page: impl Fn(&mut wgpu::RenderPass<'_>, u32),
) {
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
for call in calls {
self.bind_page(pass, call.page, &vertices);
page(pass, call.page);
pass.draw_indexed(call.first..call.first + call.count, 0, 0..1);
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,645 @@
//! Horizon's terrain drawn with a Java pack's `gbuffers_terrain` and
//! `gbuffers_water` (docs/shader-packs.md). The pack's vertex program runs
//! after a glue that rebuilds what Iris would feed it from Horizon's
//! `TerrainVertex`: the camera-relative position, the quad's normal and
//! tangent (from its four corners, read from the arena page as storage),
//! the colour without vanilla's directional shade, the lightmap
//! coordinates, the sprite's place in a block atlas laid out from Horizon's
//! sprite arrays, and `mc_Entity` from the pack's `block.properties`, by
//! sprite name.
use horizon_shaderpack::translate::Geometry;
use std::collections::BTreeMap;
/// `TerrainVertex` in 32-bit words.
const VERTEX_WORDS: u32 = 6;
/// The glue's declarations and `hz_vertex`; `HZ_ORIGIN_DECL` and
/// `HZ_ORIGIN` are the variant's (instanced or flat draws).
const GLUE: &str = r#"
layout(location = 0) in vec3 hz_position;
layout(location = 1) in uvec2 hz_uv;
layout(location = 2) in uint hz_layer;
layout(location = 3) in vec4 hz_color;
layout(location = 4) in uvec2 hz_light;
HZ_ORIGIN_DECL
layout(std430, set = 3, binding = 0) readonly buffer HzVertices { uint hz_vertices[]; };
// [0]: atlas columns, [1]: 1 in the Nether, then each sprite layer's block id.
layout(std430, set = 3, binding = 1) readonly buffer HzTable { int hz_table[]; };
vec4 hz_pos;
vec3 hz_normal;
vec4 hz_tangent;
vec4 hz_tint;
vec2 hz_atlas;
vec2 hz_mid;
vec2 hz_lightmap;
float hz_block;
vec3 hz_mid_block;
vec3 hz_corner(uint v) {
uint b = v * HZ_WORDSu;
return vec3(uintBitsToFloat(hz_vertices[b]), uintBitsToFloat(hz_vertices[b + 1u]),
uintBitsToFloat(hz_vertices[b + 2u]));
}
vec2 hz_corner_uv(uint v) {
uint w = hz_vertices[v * HZ_WORDSu + 3u];
return vec2(float(w & 65535u), float(w >> 16u));
}
void hz_vertex() {
vec4 origin = HZ_ORIGIN;
hz_pos = vec4(hz_position + origin.xyz, 1.0);
// The quad's corners: quads are four vertices from a multiple of four.
uint q = uint(gl_VertexIndex) & 4294967292u;
vec3 p0 = hz_corner(q);
vec3 e1 = hz_corner(q + 1u) - p0;
vec3 e2 = hz_corner(q + 2u) - p0;
vec3 n = cross(e1, e2);
if (dot(n, n) < 1e-12) {
n = cross(e2, hz_corner(q + 3u) - p0);
}
hz_normal = dot(n, n) > 0.0 ? normalize(n) : vec3(0.0, 1.0, 0.0);
vec2 t0 = hz_corner_uv(q);
vec2 d1 = hz_corner_uv(q + 1u) - t0;
vec2 d2 = hz_corner_uv(q + 2u) - t0;
float s = d1.x * d2.y - d2.x * d1.y < 0.0 ? -1.0 : 1.0;
vec3 t = (e1 * d2.y - e2 * d1.y) * s;
vec3 b = (e2 * d1.x - e1 * d2.x) * s;
t = t - hz_normal * dot(hz_normal, t);
t = dot(t, t) > 0.0 ? normalize(t) : vec3(1.0, 0.0, 0.0);
hz_tangent = vec4(t, dot(cross(hz_normal, t), b) < 0.0 ? -1.0 : 1.0);
// Iris turns vanilla's directional shade off: undo it on axis faces.
vec3 a = abs(hz_normal);
bool nether = hz_table[1] != 0;
float shade = 1.0;
if (a.y > 0.999) {
shade = nether ? 0.9 : (hz_normal.y > 0.0 ? 1.0 : 0.5);
} else if (a.z > 0.999) {
shade = 0.8;
} else if (a.x > 0.999) {
shade = 0.6;
}
hz_tint = vec4(min(hz_color.rgb / shade, vec3(1.0)), hz_color.a);
// The sprite's cell in the atlas, columns of square cells.
int layer = int(hz_layer & 16383u);
int cols = max(hz_table[0], 1);
vec2 cell = vec2(float(layer % cols), float(layer / cols));
vec2 uv = clamp(vec2(hz_uv) * origin.w, 0.0, 1.0);
hz_atlas = (cell + uv) / float(cols);
hz_mid = (cell + 0.5) / float(cols);
// Vanilla's UV2: block light, then sky light, 0..240.
hz_lightmap = vec2(float(hz_light.y), float(hz_light.x));
hz_block = float(hz_table[2 + layer]);
hz_mid_block = (floor(hz_position - hz_normal * 0.01) + 0.5 - hz_position) * 64.0;
}
"#;
/// The glue of one draw path: instanced section draws (the origin is an
/// instance attribute) or flat ones (`gfx/flat.rs`: from the block's slot).
pub fn glue(flat: bool, alpha_test: Option<f32>) -> Geometry {
let (decl, origin) = if flat {
(
"layout(std430, set = 1, binding = 0) readonly buffer HzBlockSlots { uint hz_block_slots[]; };\n\
layout(std430, set = 1, binding = 1) readonly buffer HzSlotOrigins { vec4 hz_slot_origins[]; };",
"hz_slot_origins[hz_block_slots[uint(gl_VertexIndex) >> 8u]]",
)
} else {
("layout(location = 5) in vec4 hz_origin;", "hz_origin")
};
let vertex_glue = GLUE
.replace("HZ_ORIGIN_DECL", decl)
.replace("HZ_ORIGIN", origin)
.replace("HZ_WORDS", &VERTEX_WORDS.to_string());
let lightmap = "vec4(hz_lightmap, 0.0, 1.0)";
let attributes: BTreeMap<String, String> = [
("iris_Vertex", "hz_pos"),
("vaPosition", "hz_pos"),
("iris_Normal", "vec4(hz_normal, 0.0)"),
("vaNormal", "vec4(hz_normal, 0.0)"),
("iris_Color", "hz_tint"),
("vaColor", "hz_tint"),
("iris_MultiTexCoord0", "vec4(hz_atlas, 0.0, 1.0)"),
("vaUV0", "vec4(hz_atlas, 0.0, 1.0)"),
("iris_MultiTexCoord1", lightmap),
("iris_MultiTexCoord2", lightmap),
("vaUV2", lightmap),
// OverlayTexture.NO_OVERLAY.
("vaUV1", "vec4(0.0, 10.0, 0.0, 0.0)"),
("mc_Entity", "vec4(hz_block, -1.0, 0.0, 0.0)"),
("mc_midTexCoord", "vec4(hz_mid, 0.0, 1.0)"),
("at_tangent", "hz_tangent"),
("at_midBlock", "vec4(hz_mid_block, 0.0)"),
]
.into_iter()
.map(|(k, v)| (k.to_owned(), v.to_owned()))
.collect();
Geometry {
vertex_glue,
attributes,
alpha_test,
}
}
/// The glue's table: atlas columns, the Nether flag, then each sprite
/// layer's block id from `block.properties` (-1 for blocks it doesn't
/// list, as Iris).
pub fn table(sprite_layers: &BTreeMap<String, u32>, block_ids: &BTreeMap<String, i32>) -> Vec<i32> {
let layers = sprite_layers.values().max().map_or(0, |&m| m as usize + 1);
let mut out = vec![-1; layers + 2];
out[0] = atlas_columns(layers as u32) as i32;
out[1] = 0;
for (name, &layer) in sprite_layers {
if let Some(id) = horizon_shaderpack::properties::sprite_block_id(name, block_ids) {
out[layer as usize + 2] = id;
}
}
out
}
/// The atlas's columns (and rows) of sprite cells for `layers` sprites.
pub fn atlas_columns(layers: u32) -> u32 {
(f64::from(layers.max(1)).sqrt().ceil() as u32).max(1)
}
/// Whether `device` renders to and filters the 16-bit normalized formats
/// a Java pack's `RGBA16` targets become (`java_stages::target_format`).
pub fn norm16_targets(adapter: &wgpu::Adapter, device: &wgpu::Device) -> bool {
use wgpu::TextureFormat as F;
let wanted = wgpu::Features::TEXTURE_FORMAT_16BIT_NORM
| wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES;
device.features().contains(wanted)
&& [
F::R16Unorm,
F::Rg16Unorm,
F::Rgba16Unorm,
F::R16Snorm,
F::Rg16Snorm,
F::Rgba16Snorm,
]
.into_iter()
.all(|f| {
let features = adapter.get_texture_format_features(f);
features
.allowed_usages
.contains(wgpu::TextureUsages::RENDER_ATTACHMENT)
&& features
.flags
.contains(wgpu::TextureFormatFeatureFlags::FILTERABLE)
})
}
/// The bind group layout of a page group: the page's vertices and the glue's
/// table, read by the vertex stage.
pub fn page_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
let storage = |binding| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
};
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Java shader pack terrain page"),
entries: &[storage(0), storage(1)],
})
}
/// Draws Horizon's terrain with a pack's pipelines: the solid layer or the
/// translucent one. Set by the renderer, which owns the sections.
pub type DrawTerrain<'a> = dyn Fn(&mut wgpu::RenderPass<'_>, bool, &TerrainPipelines<'_>) + 'a;
/// What the renderer binds to draw with a pack's geometry program: the
/// pipeline of its draw path and the pack's group (group 2). Group 1 is the
/// flat path's, group 3 the page's ([`page_layout`]). `flat` is `None` when
/// the renderer has no flat draws.
pub struct TerrainPipelines<'a> {
pub instanced: &'a wgpu::RenderPipeline,
pub flat: Option<&'a wgpu::RenderPipeline>,
pub group: &'a wgpu::BindGroup,
}
/// What a Java pack's geometry reads from the renderer each frame.
pub struct JavaWorld<'a> {
/// The block sprite arrays, [`super::SPRITE_SPLIT`]-layer each.
pub sprites: &'a [wgpu::Texture],
pub split: u32,
/// Mipmap levels the terrain samples.
pub levels: u32,
/// The sprite layers and mip levels animation rewrote this frame.
pub animated: &'a [(u32, u32)],
pub lightmap: &'a wgpu::TextureView,
pub draw: &'a DrawTerrain<'a>,
}
const ATLAS: &str = r#"
struct Atlas { cols: u32, layers: u32, split: u32, pad: u32 }
@group(0) @binding(0) var<uniform> atlas: Atlas;
@group(0) @binding(1) var s0: texture_2d_array<f32>;
@group(0) @binding(2) var s1: texture_2d_array<f32>;
@group(0) @binding(3) var s2: texture_2d_array<f32>;
@group(0) @binding(4) var s3: texture_2d_array<f32>;
@group(0) @binding(5) var s4: texture_2d_array<f32>;
@group(0) @binding(6) var s5: texture_2d_array<f32>;
@group(0) @binding(7) var s6: texture_2d_array<f32>;
@group(0) @binding(8) var s7: texture_2d_array<f32>;
struct Out {
@builtin(position) p: vec4f,
@location(0) @interpolate(flat) mip: u32,
}
@vertex
fn vs(@builtin(vertex_index) i: u32, @builtin(instance_index) mip: u32) -> Out {
let uv = vec2f(f32((i << 1u) & 2u), f32(i & 2u));
return Out(vec4f(uv * 2.0 - 1.0, 0.0, 1.0), mip);
}
// Each sprite layer into its cell, at mip level `mip`.
@fragment
fn fs(in: Out) -> @location(0) vec4f {
let cell = max(textureDimensions(s0, in.mip).x, 1u);
let px = vec2u(in.p.xy);
let c = px / cell;
let layer = c.y * atlas.cols + c.x;
if c.x >= atlas.cols || layer >= atlas.layers {
return vec4f(0.0);
}
let at = px % cell;
let l = i32(layer % atlas.split);
let m = i32(in.mip);
switch layer / atlas.split {
case 0u: { return textureLoad(s0, at, l, m); }
case 1u: { return textureLoad(s1, at, l, m); }
case 2u: { return textureLoad(s2, at, l, m); }
case 3u: { return textureLoad(s3, at, l, m); }
case 4u: { return textureLoad(s4, at, l, m); }
case 5u: { return textureLoad(s5, at, l, m); }
case 6u: { return textureLoad(s6, at, l, m); }
default: { return textureLoad(s7, at, l, m); }
}
}
"#;
/// Horizon's block sprites as one 2D atlas, as Iris binds `gtexture`:
/// square cells, [`atlas_columns`] to a row. Drawn from the sprite arrays
/// once, then animated sprites are copied in as they change.
pub struct Atlas {
texture: wgpu::Texture,
pub view: wgpu::TextureView,
mips: Vec<wgpu::TextureView>,
pipeline: wgpu::RenderPipeline,
layout: wgpu::BindGroupLayout,
uniform: wgpu::Buffer,
/// Layers, sprite size, mip levels it was made for.
key: (u32, u32, u32),
/// The first sprite array it was drawn from (resource reloads make
/// new ones).
source: wgpu::Texture,
drawn: bool,
}
impl Atlas {
/// The atlas for `world`'s sprites; `None` without any.
pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, world: &JavaWorld) -> Option<Self> {
let key = Self::key(world)?;
let (layers, size, levels) = key;
let cols = atlas_columns(layers);
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Java shader pack block atlas"),
size: wgpu::Extent3d {
width: cols * size,
height: cols * size,
depth_or_array_layers: 1,
},
mip_level_count: levels,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let mips = (0..levels)
.map(|level| {
texture.create_view(&wgpu::TextureViewDescriptor {
base_mip_level: level,
mip_level_count: Some(1),
..Default::default()
})
})
.collect();
let mut entries = vec![wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}];
entries.extend((1..=8).map(|binding| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2Array,
multisampled: false,
},
count: None,
}));
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Java shader pack block atlas"),
entries: &entries,
});
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Java shader pack block atlas"),
source: wgpu::ShaderSource::Wgsl(ATLAS.into()),
});
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Java shader pack block atlas"),
layout: Some(
&device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Java shader pack block atlas"),
bind_group_layouts: &[Some(&layout)],
..Default::default()
}),
),
vertex: wgpu::VertexState {
module: &module,
entry_point: Some("vs"),
compilation_options: Default::default(),
buffers: &[],
},
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &module,
entry_point: Some("fs"),
compilation_options: Default::default(),
targets: &[Some(wgpu::TextureFormat::Rgba8Unorm.into())],
}),
multiview_mask: None,
cache: None,
});
let uniform = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Java shader pack block atlas"),
size: 16,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
queue.write_buffer(
&uniform,
0,
bytemuck::cast_slice(&[cols, layers, world.split.max(1), 0]),
);
Some(Self {
view: texture.create_view(&Default::default()),
texture,
mips,
pipeline,
layout,
uniform,
key,
source: world.sprites[0].clone(),
drawn: false,
})
}
fn key(world: &JavaWorld) -> Option<(u32, u32, u32)> {
let first = world.sprites.first()?;
let layers = world
.sprites
.iter()
.map(|t| t.depth_or_array_layers())
.sum();
let levels = (world.levels + 1).min(first.mip_level_count()).max(1);
Some((layers, first.width(), levels))
}
/// Whether it was made for `world`'s sprites.
pub fn fits(&self, world: &JavaWorld) -> bool {
Self::key(world) == Some(self.key) && world.sprites.first() == Some(&self.source)
}
/// Bring it up to date: drawn the first time, then the sprites
/// animation rewrote copied into their cells.
pub fn update(
&mut self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
world: &JavaWorld,
) {
if !self.drawn {
self.draw(device, encoder, world);
self.drawn = true;
return;
}
let (layers, size, levels) = self.key;
let cols = atlas_columns(layers);
let split = world.split.max(1);
for &(layer, level) in world.animated {
let Some(array) = world.sprites.get((layer / split) as usize) else {
continue;
};
if level >= levels || layer >= layers {
continue;
}
let edge = (size >> level).max(1);
encoder.copy_texture_to_texture(
wgpu::TexelCopyTextureInfo {
texture: array,
mip_level: level,
origin: wgpu::Origin3d {
x: 0,
y: 0,
z: layer % split,
},
aspect: wgpu::TextureAspect::All,
},
wgpu::TexelCopyTextureInfo {
texture: &self.texture,
mip_level: level,
origin: wgpu::Origin3d {
x: (layer % cols) * edge,
y: (layer / cols) * edge,
z: 0,
},
aspect: wgpu::TextureAspect::All,
},
wgpu::Extent3d {
width: edge,
height: edge,
depth_or_array_layers: 1,
},
);
}
}
/// The atlas's size in pixels (`atlasSize`).
pub fn size(&self) -> [u32; 2] {
[self.texture.width(), self.texture.height()]
}
/// Draw the sprites into the atlas, every mip level.
fn draw(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, world: &JavaWorld) {
let views: Vec<wgpu::TextureView> = (0..8)
.map(|i| {
let t = world.sprites.get(i).unwrap_or(&world.sprites[0]);
t.create_view(&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2Array),
mip_level_count: Some(self.key.2),
..Default::default()
})
})
.collect();
let mut entries = vec![wgpu::BindGroupEntry {
binding: 0,
resource: self.uniform.as_entire_binding(),
}];
entries.extend(views.iter().enumerate().map(|(i, v)| wgpu::BindGroupEntry {
binding: i as u32 + 1,
resource: wgpu::BindingResource::TextureView(v),
}));
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Java shader pack block atlas"),
layout: &self.layout,
entries: &entries,
});
for (mip, view) in self.mips.iter().enumerate() {
let attachments = [Some(wgpu::RenderPassColorAttachment {
view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
})];
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Java shader pack block atlas"),
color_attachments: &attachments,
..Default::default()
});
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, &group, &[]);
pass.draw(0..3, mip as u32..mip as u32 + 1);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// `module` validates and translates for Metal, Vulkan and DirectX 12.
fn backends(module: &naga::Module, label: &str) {
let info = naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
naga::valid::Capabilities::all(),
)
.validate(module)
.unwrap_or_else(|e| panic!("{label}: {e:?}"));
naga::back::msl::write_string(
module,
&info,
// wgpu's Metal backend asks for MSL 2.x.
&naga::back::msl::Options {
lang_version: (2, 4),
..Default::default()
},
&naga::back::msl::PipelineOptions::default(),
)
.unwrap_or_else(|e| panic!("{label} (MSL): {e}"));
naga::back::spv::write_vec(module, &info, &Default::default(), None)
.unwrap_or_else(|e| panic!("{label} (SPIR-V): {e}"));
for entry in &module.entry_points {
let mut hlsl = String::new();
naga::back::hlsl::Writer::new(
&mut hlsl,
&naga::back::hlsl::Options::default(),
&naga::back::hlsl::PipelineOptions {
entry_point: Some((entry.stage, entry.name.clone())),
},
)
.write(module, &info, None)
.unwrap_or_else(|e| panic!("{label} {} (HLSL): {e}", entry.name));
}
}
/// A terrain program reading every attribute the glue fills, run after
/// each draw path's glue, and the atlas shader, on every backend.
#[test]
fn the_glue_feeds_a_terrain_program_on_every_backend() {
let program = "#version 120
attribute vec4 mc_Entity;
attribute vec4 mc_midTexCoord;
attribute vec4 at_tangent;
attribute vec3 at_midBlock;
varying vec4 color;
varying vec2 uv;
varying vec2 lm;
varying vec3 normal;
varying float id;
void main() {
vec4 p = gl_ModelViewMatrix * gl_Vertex;
p.xyz += at_midBlock / 64.0 * 0.0 + at_tangent.xyz * 0.0;
gl_Position = gl_ProjectionMatrix * p;
color = gl_Color;
uv = (gl_TextureMatrix[0] * gl_MultiTexCoord0).xy + mc_midTexCoord.xy * 0.0;
lm = (gl_TextureMatrix[1] * gl_MultiTexCoord1).xy;
normal = gl_NormalMatrix * gl_Normal;
id = mc_Entity.x;
}
";
for flat in [false, true] {
let mut link = horizon_shaderpack::translate::Link {
set: 2,
geometry: Some(glue(flat, Some(0.1))),
..Default::default()
};
let t = horizon_shaderpack::translate::translate(
horizon_shaderpack::Stage::Vertex,
program,
&mut link,
&|l| format!("line {l}"),
)
.unwrap_or_else(|e| panic!("flat {flat}: {e}"));
for wanted in ["hz_vertex();", "mc_Entity = vec4(vec4(hz_block"] {
assert!(t.glsl.contains(wanted), "{wanted}\n{}", t.glsl);
}
// The glue's inputs are Horizon's vertex layout.
let inputs = t.module.entry_points[0].function.arguments.len();
assert_eq!(inputs, if flat { 6 } else { 7 }, "{}", t.wgsl);
let reparsed = naga::front::wgsl::parse_str(&t.wgsl).unwrap();
backends(&reparsed, &format!("terrain glue (flat {flat})"));
}
backends(&naga::front::wgsl::parse_str(ATLAS).unwrap(), "atlas");
backends(
&naga::front::wgsl::parse_str(super::super::java_stages::BLIT).unwrap(),
"Java shader pack blits",
);
}
#[test]
fn sprites_take_their_blocks_ids() {
let layers: BTreeMap<String, u32> = [
("minecraft:block/oak_leaves", 0),
("minecraft:block/water_still", 1),
("minecraft:block/stone", 2),
("minecraft:block/oak_log_top", 3),
]
.into_iter()
.map(|(n, l)| (n.to_owned(), l))
.collect();
let ids: BTreeMap<String, i32> = [("oak_leaves", 10003), ("water", 8), ("oak_log", 7)]
.into_iter()
.map(|(n, i)| (n.to_owned(), i))
.collect();
assert_eq!(table(&layers, &ids), [2, 0, 10003, 8, -1, 7]);
assert_eq!(atlas_columns(5), 3);
assert_eq!(atlas_columns(0), 1);
}
}
+138 -5
View File
@@ -2,13 +2,14 @@
//! 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.
//! as Iris runs them over its own. Of the geometry programs, the terrain's
//! (`gbuffers_terrain`, `gbuffers_water` and their fallbacks) draw Horizon's
//! terrain (`gfx/java_terrain.rs`); the rest of the world is Horizon's.
use horizon_shaderpack::{
JavaPack,
pipeline::{Directives, Program, TargetSettings},
pipeline::{Directives, GeometryProgram, Pass, Program, TargetSettings},
preprocess::Environment,
properties::SkyDirectives,
properties::{Blend, SkyDirectives},
uniforms::CustomUniforms,
};
use std::{
@@ -36,6 +37,17 @@ pub struct JavaFolder {
/// `sunPathRotation`, `eyeBrightnessHalflife`, `wetnessHalflife` and
/// `drynessHalflife`.
pub directives: Directives,
/// The programs Horizon's solid and translucent terrain are drawn with,
/// each translated for instanced and flat draws (`variants[0]`).
pub terrain: Option<GeometryProgram>,
pub water: Option<GeometryProgram>,
/// How many of `passes` run before translucent terrain (`begin*`,
/// `prepare*`, `deferred*`).
pub translucent_at: usize,
pub flipped_after_translucent: BTreeSet<u32>,
/// Each draw buffer's blending in `terrain` and `water`.
pub terrain_blends: Vec<Option<wgpu::BlendState>>,
pub water_blends: Vec<Option<wgpu::BlendState>>,
}
/// The key of `texture.noise` (`noisetex`) in [`JavaPasses::custom_textures`].
@@ -60,6 +72,8 @@ pub struct JavaPasses {
pub uniforms: CustomUniforms,
/// What the pack keeps of the vanilla sky (`clouds`, `sun`, `moon`).
pub sky: SkyDirectives,
/// `block.properties`: block name → `mc_Entity` id.
pub block_ids: BTreeMap<String, i32>,
/// `texture.<stage>.<sampler>` and `texture.noise` images, by
/// `"<stage>.<sampler>"` and [`NOISE_KEY`].
pub custom_textures: BTreeMap<String, crate::shader_pack::Rgba>,
@@ -144,6 +158,45 @@ pub fn load(
if passes.is_empty() && final_pass.is_none() {
continue;
}
// A geometry program that doesn't translate leaves that terrain to
// Horizon, with a warning.
let geometry = |pass: &Option<horizon_shaderpack::pipeline::Pass>, alpha_test| {
let pass = pass.as_ref()?;
let glues = [false, true].map(|flat| crate::gfx::java_terrain::glue(flat, alpha_test));
match pack.compile_geometry(pass, &plan.targets, &values, &env, &properties, &glues) {
Ok(program) => Some(program),
Err(e) => {
log::warn!("Horizon: shader pack {}: {e}", pass.program);
None
}
}
};
// Iris's alpha test of cutout terrain (`AlphaTests.ONE_TENTH_ALPHA`).
let terrain = geometry(&plan.terrain, Some(0.1));
let water = terrain.as_ref().and_then(|_| geometry(&plan.water, None));
let translucent_at = early.clone().count() + plan.deferred.len();
let blends = |g: &Option<GeometryProgram>, default| {
g.as_ref().map_or_else(Vec::new, |g| {
pass_blends(&g.program.pass, &g.program.draw_buffers, default)
})
};
let terrain_blends = blends(&terrain, None);
// Vanilla's translucent blending (`BlendFunction.TRANSLUCENT`).
let water_blends = blends(
&water,
Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::SrcAlpha,
dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
operation: wgpu::BlendOperation::Add,
},
}),
);
folders.push(JavaFolder {
folder: name.to_owned(),
targets: plan.targets,
@@ -154,6 +207,12 @@ pub fn load(
final_pass,
flipped_at_end: plan.flipped_at_end,
directives: plan.directives,
terrain,
water,
translucent_at,
flipped_after_translucent: plan.flipped_after_translucent,
terrain_blends,
water_blends,
});
}
if folders.is_empty() {
@@ -184,11 +243,69 @@ pub fn load(
for problem in &uniforms.problems {
log::warn!("Horizon: shader pack custom uniform {problem}");
}
let block_ids = pack.block_ids(&values, &env).unwrap_or_else(|e| {
log::warn!("Horizon: shader pack {e}");
BTreeMap::new()
});
Ok(JavaPasses {
folders,
uniforms,
sky: properties.sky(),
custom_textures,
block_ids,
})
}
/// Each draw buffer's blending, as Iris's `BlendModeOverride`:
/// `blend.<program>.<buffer>`, else `blend.<program>`, else `default`
/// (none for full-screen passes, vanilla's for the geometry programs).
pub(crate) fn pass_blends(
pass: &Pass,
draw_buffers: &[u32],
default: Option<wgpu::BlendState>,
) -> Vec<Option<wgpu::BlendState>> {
let all = pass.blend.as_ref().map_or(default, blend_state);
draw_buffers
.iter()
.map(|i| {
pass.buffer_blends
.iter()
.find(|(b, _)| b == i)
.map_or(all, |(_, b)| blend_state(b))
})
.collect()
}
/// A `blend.*` value as wgpu's blending (`off`: none). The factors are the
/// GL ones `ShaderProperties` accepts.
pub(crate) fn blend_state(blend: &Blend) -> Option<wgpu::BlendState> {
let Blend::Factors(factors) = blend else {
return None;
};
let factor = |name: &str| {
use wgpu::BlendFactor as F;
match name {
"ZERO" => F::Zero,
"SRC_COLOR" => F::Src,
"ONE_MINUS_SRC_COLOR" => F::OneMinusSrc,
"DST_COLOR" => F::Dst,
"ONE_MINUS_DST_COLOR" => F::OneMinusDst,
"SRC_ALPHA" => F::SrcAlpha,
"ONE_MINUS_SRC_ALPHA" => F::OneMinusSrcAlpha,
"DST_ALPHA" => F::DstAlpha,
"ONE_MINUS_DST_ALPHA" => F::OneMinusDstAlpha,
"SRC_ALPHA_SATURATE" => F::SrcAlphaSaturated,
_ => F::One,
}
};
let component = |src: &str, dst: &str| wgpu::BlendComponent {
src_factor: factor(src),
dst_factor: factor(dst),
operation: wgpu::BlendOperation::Add,
};
Some(wgpu::BlendState {
color: component(&factors[0], &factors[1]),
alpha: component(&factors[2], &factors[3]),
})
}
@@ -242,8 +359,18 @@ mod tests {
.folders
.iter()
.flat_map(|f| f.passes.iter().chain(&f.final_pass));
let geometry = pack
.folders
.iter()
.flat_map(|f| f.terrain.iter().chain(&f.water));
passes
.flat_map(|p| [(p, &p.vertex, "vsh"), (p, &p.fragment, "fsh")])
.chain(geometry.flat_map(|g| {
let p = &g.program;
[(p, &p.vertex, "vsh"), (p, &p.fragment, "fsh")]
.into_iter()
.chain(g.variants.iter().map(move |v| (p, v, "vsh (flat)")))
}))
.find_map(|(p, t, ext)| {
let e = naga::front::wgsl::parse_str(&t.wgsl).err()?;
Some(format!(
@@ -283,7 +410,13 @@ mod tests {
.iter()
.map(|f| {
let n = f.passes.len() + usize::from(f.final_pass.is_some());
format!("{} {n} passes", f.folder)
let geometry: Vec<&str> = f
.terrain
.iter()
.chain(&f.water)
.map(|g| g.program.pass.program.as_str())
.collect();
format!("{} {n} passes, terrain {geometry:?}", f.folder)
})
.collect();
println!("{name}: loads ({})", folders.join(", "));
+16
View File
@@ -182,6 +182,22 @@ impl JavaPack {
}
}
impl JavaPack {
/// The block ids of the pack's `block.properties` (empty without one),
/// [`properties::block_ids`].
pub fn block_ids(
&self,
values: &OptionValues,
env: &Environment,
) -> Result<BTreeMap<String, i32>, String> {
match self.files.read("block.properties") {
Some(text) => properties::block_ids(&text, env, &self.options, values)
.map_err(|e| format!("block.properties: {e}")),
None => Ok(BTreeMap::new()),
}
}
}
/// A program's name in `shaders.properties` (`world-1/composite1.fsh` is
/// `world-1/composite1`).
pub fn program_name(program: &str) -> &str {
+109 -1
View File
@@ -12,7 +12,7 @@ use crate::{
options::OptionValues,
preprocess::Environment,
properties::{Blend, LEGACY_TARGETS, ShaderProperties},
translate::{Link, Translated},
translate::{Geometry, Link, Translated},
};
use std::collections::{BTreeMap, BTreeSet};
@@ -327,8 +327,33 @@ pub struct Passes {
/// next frame starts unflipped.
pub flipped_at_end: BTreeSet<u32>,
pub directives: Directives,
/// The program Horizon's solid terrain is drawn with
/// ([`TERRAIN_PROGRAMS`]), before `deferred`.
pub terrain: Option<Pass>,
/// The program its translucent terrain is drawn with
/// ([`WATER_PROGRAMS`]), after `deferred`.
pub water: Option<Pass>,
}
/// The programs Iris draws solid terrain with, the first the pack has
/// (`ProgramId.Terrain`'s fallbacks).
pub const TERRAIN_PROGRAMS: &[&str] = &[
"gbuffers_terrain",
"gbuffers_textured_lit",
"gbuffers_textured",
"gbuffers_basic",
];
/// The programs Iris draws translucent terrain with (`ProgramId.Water`'s
/// fallbacks).
pub const WATER_PROGRAMS: &[&str] = &[
"gbuffers_water",
"gbuffers_terrain",
"gbuffers_textured_lit",
"gbuffers_textured",
"gbuffers_basic",
];
/// The `const` directives of a program folder that aren't about targets
/// (`PackDirectives`), read from the same programs in the same order.
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -554,6 +579,25 @@ impl JavaPack {
out.flipped_after_translucent = flipped.clone();
out.composite = run(&groups[3], "composite_pre", &mut flipped)?;
out.flipped_at_end = flipped;
// Geometry writes the side the next passes read.
let geometry = |chain: &[&str], flipped: &BTreeSet<u32>| {
let Some(name) = chain.iter().find(|n| exists(n)) else {
return Ok::<_, String>(None);
};
let text = fragment(name)?;
let (blend, buffer_blends) = resolve_blends(&path(name));
Ok(Some(Pass {
program: path(name),
draw_buffers: draw_buffers(&text).map_err(|e| format!("{}: {e}", path(name)))?,
reads_alt: flipped.clone(),
mipmapped: BTreeSet::new(),
scale: 1.0,
blend,
buffer_blends,
}))
};
out.terrain = geometry(TERRAIN_PROGRAMS, &out.flipped_after_prepare)?;
out.water = geometry(WATER_PROGRAMS, &out.flipped_after_translucent)?;
if exists("final") {
let prog = path("final");
let (blend, buffer_blends) = resolve_blends(&prog);
@@ -614,6 +658,70 @@ impl JavaPack {
}
}
/// A geometry program translated: the program (its vertex with the first
/// glue), and its vertex with each other glue.
pub struct GeometryProgram {
pub program: Program,
pub variants: Vec<Translated>,
}
impl JavaPack {
/// Translate geometry program `pass` (`gbuffers_*`) to run over
/// Horizon's geometry: its bindings in group 2, its attributes from
/// each of `glues` (the vertex program is translated once per glue).
#[allow(clippy::too_many_arguments)]
pub fn compile_geometry(
&self,
pass: &Pass,
targets: &[TargetSettings],
values: &OptionValues,
env: &Environment,
properties: &ShaderProperties,
glues: &[Geometry],
) -> Result<GeometryProgram, String> {
let (first, rest) = glues
.split_first()
.ok_or("a geometry program needs a glue")?;
let mut link = Link {
image_formats: properties.image_formats(),
shared_samplers: shared_samplers(targets),
set: 2,
geometry: Some(first.clone()),
..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 mut variants = Vec::new();
for glue in rest {
let mut other = link.clone();
other.geometry = Some(glue.clone());
variants.push(self.translate(
&format!("{}.vsh", pass.program),
values,
env,
&mut other,
)?);
if other.uniforms != link.uniforms || other.bindings != link.bindings {
return Err(format!("{}: its variants bind differently", pass.program));
}
}
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(GeometryProgram {
program: Program {
pass: pass.clone(),
vertex,
fragment,
draw_buffers,
link,
},
variants,
})
}
}
/// 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
@@ -639,6 +639,58 @@ impl ShaderProperties {
}
}
/// `block.properties` (`block.<id>=<blocks>`), preprocessed as
/// `shaders.properties` is: each block's id by its name without namespace
/// (`oak_leaves`). A block listed with a state (`grass_block:snowy=true`)
/// takes that id only when no entry names it without one; numeric ids
/// (before 1.13) are skipped.
pub fn block_ids(
text: &str,
env: &Environment,
options: &OptionSet,
values: &OptionValues,
) -> Result<BTreeMap<String, i32>, String> {
let properties = Properties::parse(&preprocess(text, env, options, values)?);
let mut plain = BTreeMap::new();
let mut with_state = BTreeMap::new();
for (key, value) in properties.iter() {
let Some(Ok(id)) = key.strip_prefix("block.").map(str::parse::<i32>) else {
continue;
};
for entry in value.split_whitespace() {
let entry = entry.strip_prefix("minecraft:").unwrap_or(entry);
if entry.contains(':') && entry.split(':').nth(1).is_some_and(|s| s.contains('=')) {
let name = entry.split(':').next().unwrap_or(entry);
with_state.entry(name.to_owned()).or_insert(id);
} else if !entry.chars().all(|c| c.is_ascii_digit()) && !entry.contains('=') {
plain.insert(entry.to_owned(), id);
}
}
}
for (name, id) in with_state {
plain.entry(name).or_insert(id);
}
Ok(plain)
}
/// The block a block sprite (`minecraft:block/oak_log_top`) belongs to in
/// `ids` ([`block_ids`]): the block named like it, else the longest one its
/// name starts with followed by `_` (`oak_log`, `water` for `water_still`).
pub fn sprite_block_id(sprite: &str, ids: &BTreeMap<String, i32>) -> Option<i32> {
let name = sprite.rsplit(['/', ':']).next()?;
if let Some(&id) = ids.get(name) {
return Some(id);
}
let mut end = name.len();
while let Some(cut) = name[..end].rfind('_') {
if let Some(&id) = ids.get(&name[..cut]) {
return Some(id);
}
end = cut;
}
None
}
/// Iris's `BooleanParser`: options joined by `!`, `&&`, `||` and brackets,
/// `&&` binding tighter. `true`/`1` and `false`/`0` are literals; a name that
/// isn't a boolean option is true; a malformed expression is true.
@@ -757,6 +809,42 @@ mod tests {
set
}
/// `block.properties` as Chocapic13' writes it, and sprites matched to
/// its blocks.
#[test]
fn block_ids_and_the_sprites_of_their_blocks() {
let text = "\
#if MC_VERSION >= 11300
block.10001= minecraft:wheat minecraft:short_grass
block.10003 = minecraft:oak_leaves \\
minecraft:vine
block.10006 = minecraft:grass_block:snowy=true minecraft:snow
block.8 = minecraft:water
block.2 = minecraft:grass_block
#else
block.10001= 6 31
#endif
layer.translucent=minecraft:glass
";
let env = Environment {
defines: vec![("MC_VERSION".into(), "260300".into())],
};
let ids = block_ids(text, &env, &OptionSet::default(), &OptionValues::default()).unwrap();
assert_eq!(ids.get("vine"), Some(&10003));
// The stateless entry wins over the snowy one.
assert_eq!(ids.get("grass_block"), Some(&2));
assert!(!ids.contains_key("6") && !ids.contains_key("glass"));
for (sprite, id) in [
("minecraft:block/oak_leaves", Some(10003)),
("minecraft:block/water_still", Some(8)),
("minecraft:block/grass_block_top", Some(2)),
("minecraft:block/wheat_stage7", Some(10001)),
("minecraft:block/stone", None),
] {
assert_eq!(sprite_block_id(sprite, &ids), id, "{sprite}");
}
}
#[test]
fn java_properties_syntax() {
let p = Properties::parse(
+142 -16
View File
@@ -45,7 +45,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
/// Locations, bindings and uniforms shared by the programs of one pass: a
/// pass's vertex program is translated first, its fragment program second.
#[derive(Default, Debug)]
#[derive(Clone, Default, Debug)]
pub struct Link {
/// Varying name → location (split matrices and arrays as `name#i`).
pub varyings: BTreeMap<String, u32>,
@@ -64,6 +64,27 @@ pub struct Link {
/// 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>,
/// The bind group of the pack's bindings (0; 2 for geometry programs,
/// whose first groups are Horizon's).
pub set: u32,
/// Set for `gbuffers_*` programs drawn over Horizon's own geometry.
pub geometry: Option<Geometry>,
}
/// How a `gbuffers_*` program runs over Horizon's geometry: its vertex
/// attributes aren't inputs but globals the glue fills from Horizon's
/// vertices before the program's `main`.
#[derive(Clone, Debug, Default)]
pub struct Geometry {
/// GLSL put before the vertex program: Horizon's vertex inputs and
/// buffers, and a `void hz_vertex()` run first in `main`.
pub vertex_glue: String,
/// Each attribute's value as a `vec4` expression of the glue
/// (`iris_Vertex`, `mc_Entity`, `vaUV0`...). Others are zero.
pub attributes: BTreeMap<String, String>,
/// Iris's alpha test: the fragment is discarded unless output 0's
/// alpha is above it.
pub alpha_test: Option<f32>,
}
impl Link {
@@ -385,6 +406,7 @@ pub fn translate(
.parse(&options, &glsl)
.map_err(|e| first_lines(&e.emit_to_string(&glsl)))?;
unpad_private_arrays(&mut module);
end_returning_cases(&mut module);
let info = naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
naga::valid::Capabilities::all(),
@@ -403,6 +425,49 @@ pub fn translate(
})
}
/// A `case` that ends with `return` or `discard` rather than `break`
/// (Photon's displacement) is a fall-through one to naga's GLSL front end,
/// which its WGSL writer refuses: nothing falls through it.
fn end_returning_cases(module: &mut naga::Module) {
fn block(b: &mut naga::Block) {
for s in b.iter_mut() {
match s {
naga::Statement::Block(inner) => block(inner),
naga::Statement::If { accept, reject, .. } => {
block(accept);
block(reject);
}
naga::Statement::Loop {
body, continuing, ..
} => {
block(body);
block(continuing);
}
naga::Statement::Switch { cases, .. } => {
for case in cases {
block(&mut case.body);
if case.fall_through
&& matches!(
case.body.last(),
Some(naga::Statement::Return { .. } | naga::Statement::Kill)
)
{
case.fall_through = false;
}
}
}
_ => {}
}
}
}
for (_, f) in module.functions.iter_mut() {
block(&mut f.body);
}
for e in &mut module.entry_points {
block(&mut e.function.body);
}
}
/// Built-in functions naga folds in `const` initialisers.
const FOLDABLE: &[&str] = &[
"radians",
@@ -634,6 +699,8 @@ struct Legaliser<'a> {
mat2_ctor: bool,
/// Constants turned into globals ([`needs_runtime`]).
runtime_constants: HashSet<String>,
/// Geometry programs: each attribute's type, for the glue.
attribute_types: BTreeMap<String, String>,
}
fn var(name: &str) -> ast::Expr {
@@ -952,6 +1019,7 @@ impl<'a> Legaliser<'a> {
gather: false,
mat2_ctor: false,
runtime_constants: HashSet::new(),
attribute_types: BTreeMap::new(),
}
}
@@ -1043,7 +1111,8 @@ impl<'a> Legaliser<'a> {
show_declaration(&mut text, d, &mut FormattingState::default())
.map_err(|e| e.to_string())?;
self.header.push(format!(
"layout({kind}, set = 0, binding = {binding}) {}",
"layout({kind}, set = {}, binding = {binding}) {}",
self.link.set,
text.trim()
));
Ok(false)
@@ -1099,7 +1168,8 @@ impl<'a> Legaliser<'a> {
for (name, _) in &names {
let t = self.link.binding(&format!("{name}_t"));
self.header.push(format!(
"layout(set = 0, binding = {t}) uniform {texture} {name}_t;"
"layout(set = {}, binding = {t}) uniform {texture} {name}_t;",
self.link.set
));
let shared = &self.link.shared_samplers;
let var = if shared.is_empty() {
@@ -1117,7 +1187,8 @@ impl<'a> Legaliser<'a> {
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};"
"layout(set = {}, binding = {s}) uniform {sampler} {var};",
self.link.set
));
}
self.interface
@@ -1156,7 +1227,8 @@ impl<'a> Legaliser<'a> {
.unwrap_or_else(|| "rgba8".to_owned());
let binding = self.link.binding(name);
layout.push(format!(
"layout({f}, set = 0, binding = {binding}) {memory}uniform {ty} {name};"
"layout({f}, set = {}, binding = {binding}) {memory}uniform {ty} {name};",
self.link.set
));
self.interface.images.push((name.clone(), f));
}
@@ -1199,10 +1271,8 @@ impl<'a> Legaliser<'a> {
for (i, (name, array)) in names.iter().enumerate() {
let full_array = format!("{ty_array}{array}");
if input {
let at = Link::location(&mut self.link.attributes, name);
self.header.push(format!(
"layout(location = {at}) in {ty} {name}{full_array};"
));
let decl = self.attribute(&ty, name, &full_array);
self.header.push(decl);
self.interface.attributes.insert(name.clone());
} else if !varying {
let at = explicit
@@ -1670,9 +1740,8 @@ impl<'a> Legaliser<'a> {
let ty = LEGACY_ATTRIBUTES.iter().find(|(a, _)| *a == n).unwrap().1;
let renamed = n.replacen("gl_", "iris_", 1);
if self.interface.attributes.insert(renamed.clone()) {
let at = Link::location(&mut self.link.attributes, &renamed);
self.header
.push(format!("layout(location = {at}) in {ty} {renamed};"));
let decl = self.attribute(ty, &renamed, "");
self.header.push(decl);
}
renamed
}
@@ -1694,6 +1763,21 @@ impl<'a> Legaliser<'a> {
}
}
/// A vertex attribute's declaration: an input, or for geometry programs
/// a global the glue fills ([`Geometry`]).
fn attribute(&mut self, ty: &str, name: &str, array: &str) -> String {
match &self.link.geometry {
Some(_) => {
self.attribute_types.insert(name.to_owned(), ty.to_owned());
format!("{ty} {name}{array};")
}
None => {
let at = Link::location(&mut self.link.attributes, name);
format!("layout(location = {at}) in {ty} {name}{array};")
}
}
}
fn frag_data(&mut self, n: u32) -> ast::Expr {
let name = format!("iris_FragData{n}");
if self.interface.outputs.insert(n, name.clone()).is_none() {
@@ -1959,9 +2043,8 @@ impl<'a> Legaliser<'a> {
continue;
}
if attribute && self.stage == Stage::Vertex {
let at = Link::location(&mut self.link.attributes, name);
self.header
.push(format!("layout(location = {at}) in {ty} {name};"));
let decl = self.attribute(ty, name, "");
self.header.push(decl);
self.interface.attributes.insert(name.to_owned());
} else if !attribute {
self.link.uniform(name, format!("{ty} {name}"))?;
@@ -1971,6 +2054,42 @@ impl<'a> Legaliser<'a> {
if !self.errors.is_empty() {
return Err(self.errors.join("\n"));
}
if let Some(geometry) = &self.link.geometry {
match self.stage {
Stage::Vertex => {
// The glue first, then the attributes from it, before
// the global initialisers (which may read them).
let mut first = vec!["hz_vertex();".to_owned()];
for (name, ty) in &self.attribute_types {
first.push(match geometry.attributes.get(name) {
Some(value) => format!("{name} = {ty}({value});"),
None => format!("{name} = {ty}(0);"),
});
}
self.prologue.splice(0..0, first);
}
Stage::Fragment => {
if let (Some(reference), Some(name)) =
(geometry.alpha_test, self.interface.outputs.get(&0))
{
let written = format!("iris_out_{name}");
let name = if self.declared.contains(&written)
|| self
.header
.iter()
.any(|h| h.ends_with(&format!(" {written};")))
{
written
} else {
name.clone()
};
self.epilogue
.push(format!("if (!({name}.a > {reference:?})) discard;"));
}
}
_ => {}
}
}
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
@@ -1982,6 +2101,10 @@ impl<'a> Legaliser<'a> {
}
let mut out = String::from("#version 450 core\n");
out.push_str(HELPERS);
if let (Some(geometry), Stage::Vertex) = (&self.link.geometry, self.stage) {
out.push_str(&geometry.vertex_glue);
out.push('\n');
}
if self.modulo {
out.push_str(&modulo_helpers());
}
@@ -1995,7 +2118,10 @@ impl<'a> Legaliser<'a> {
out.push_str(MAT2_HELPERS);
}
if !self.link.uniforms.is_empty() {
out.push_str("layout(std140, set = 0, binding = 0) uniform IrisUniforms {\n");
out.push_str(&format!(
"layout(std140, set = {}, binding = 0) uniform IrisUniforms {{\n",
self.link.set
));
for (_, decl) in &self.link.uniforms {
out.push_str(&format!(" {decl};\n"));
}
+90 -1
View File
@@ -7,7 +7,7 @@ use horizon_shaderpack::{
include::Inlined,
preprocess::{Environment, preprocess},
program_name,
translate::{Link, Translated, translate},
translate::{Geometry, Link, Translated, translate},
};
use std::collections::{BTreeMap, BTreeSet};
@@ -440,6 +440,95 @@ void main() {{
);
}
/// A `gbuffers_*` program over Horizon's geometry: its attributes are
/// globals the glue fills before `main`, its bindings in group 2, and its
/// fragment discards below Iris's alpha test. A `case` ending in `return`
/// (Photon's displacement) isn't a fall-through for naga.
#[test]
fn geometry_programs_take_their_attributes_from_the_glue() {
let glue = Geometry {
vertex_glue: "layout(location = 0) in vec3 hz_position;
layout(std430, set = 3, binding = 0) readonly buffer HzTable { int hz_table[]; };
vec4 hz_pos;
void hz_vertex() { hz_pos = vec4(hz_position, 1.0) + float(hz_table[0]); }"
.into(),
attributes: [
("iris_Vertex".to_owned(), "hz_pos".to_owned()),
(
"mc_Entity".to_owned(),
"vec4(8.0, -1.0, 0.0, 0.0)".to_owned(),
),
]
.into(),
alpha_test: Some(0.1),
};
let mut link = Link {
set: 2,
geometry: Some(glue),
..Link::default()
};
let vs = run(
Stage::Vertex,
"uniform sampler2D noisetex;
attribute vec4 mc_Entity;
attribute vec2 mc_midTexCoord;
varying vec2 uv;
vec3 sway(vec3 p, int id) {
switch (id) {
case 8:
return p + 1.0;
case 9:
case 10:
return p - 1.0;
default:
return p;
}
}
void main() {
uv = gl_MultiTexCoord0.xy + mc_midTexCoord;
gl_Position = gl_ModelViewProjectionMatrix * vec4(sway(gl_Vertex.xyz, int(mc_Entity.x)), 1.0);
}
",
&mut link,
)
.unwrap();
for wanted in [
"hz_vertex();",
"mc_Entity = vec4(vec4(8.0, -1.0, 0.0, 0.0));",
"iris_Vertex = vec4(hz_pos);",
"mc_midTexCoord = vec2(0);",
"set = 2, binding = 0) uniform IrisUniforms",
] {
assert!(vs.glsl.contains(wanted), "{wanted}\n{}", vs.glsl);
}
// Horizon's vertex input is the only one.
assert_eq!(
io(&vs, false).into_keys().collect::<Vec<_>>(),
["hz_position"]
);
reparse(&vs.wgsl).unwrap();
let fs = run(
Stage::Fragment,
"uniform sampler2D gtexture;
varying vec2 uv;
void main() {
/* DRAWBUFFERS:02 */
gl_FragData[0] = texture2D(gtexture, uv);
gl_FragData[1] = vec4(1.0);
}
",
&mut link,
)
.unwrap();
assert!(
fs.glsl.contains("if (!(iris_FragData0.a > 0.1)) discard;"),
"{}",
fs.glsl
);
assert!(fs.glsl.contains("set = 2, binding = "), "{}", fs.glsl);
reparse(&fs.wgsl).unwrap();
}
/// A fragment output narrower than its four-channel target (Steadfast's
/// `final` writes `out vec3 color`) is written through a `vec4` with alpha 1:
/// GL fills the missing channels, wgpu refuses the pipeline.
+39 -16
View File
@@ -24,7 +24,8 @@ Both are off by default. With no pack selected the renderer draws exactly what i
| Java shader packs: full-screen pass plan (`horizon_shaderpack::pipeline`: `DRAWBUFFERS`/`RENDERTARGETS`, `colortexN` formats and clearing, buffer flips, `blend.*`) | 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); `depthtex1`/`depthtex2` before translucent geometry, `blend.*`, PNG `texture.<stage>.*` and `texture.noise` |
| Java shader packs: custom uniforms (`horizon_shaderpack::uniforms`), `sunPathRotation`, `clouds`/`sun`/`moon`, eye light, `wetness` | done for the full-screen passes (below) |
| Java shader packs: `gbuffers_*`, `shadow`, `.dat` and resource-location textures, images, compute | planned |
| Java shader packs: `gbuffers_terrain`, `gbuffers_water` (`gfx/java_terrain.rs`: Horizon's terrain fed to the pack's programs) | first slice: MakeUp Ultra Fast, Chocapic13' and BSL draw their own terrain and water (below) |
| Java shader packs: other `gbuffers_*`, `shadow`, `.dat` and resource-location textures, images, compute | planned |
## How the renderer draws a frame today
@@ -396,6 +397,25 @@ Picking one translates every planned pass of each dimension folder (`java_pack.r
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.
When the pack has a `gbuffers_terrain` (or `textured_lit`, `textured`, `basic`, the program Iris falls back to), the
pack draws the terrain itself (`gfx/java_terrain.rs`): Horizon's world pass skips its own solid and translucent
terrain, then
- at step 2, after Horizon's sky, entities and the rest enter `colortex0` and depth, the pack's terrain program draws
every visible section into its `RENDERTARGETS` (the side the next pass reads), tested against that depth; the
depth is then copied into `depthtex0` and `depthtex1`;
- before the first `composite`, as Iris does, `gbuffers_water` (or the terrain program) draws the translucent
layer with the pack's `blend.*` or vanilla's blending; the depth goes into `depthtex0` only.
The pack's vertex program reads Horizon's own terrain vertices (the arena pages, instanced or flat draws): a glue
function written before `main` decodes them into Iris's attributes (`vaPosition`/`gl_Vertex` relative to the camera,
`gl_Color` with vanilla's face shading undone, `gl_MultiTexCoord0/1`, the normal and `at_tangent` from the quad's
four corners, `mc_midTexCoord`, `at_midBlock`), and `mc_Entity.x` is the block's id from the pack's
`block.properties`, matched to the sprite's block by name. `gtexture`/`texture` is a 2D atlas built from Horizon's
sprite arrays (animated sprites copied in each frame), `lightmap` is Horizon's lightmap with Iris's texture matrix,
and fragments under alpha 0.1 are discarded (`alphaTestRef`). `RGBA16` targets are 16-bit unorm where the GPU can
render them (Chocapic13' packs its G-buffer into them; half floats broke 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
@@ -426,12 +446,15 @@ What makes Horizon look like OpenGL to the pack:
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. Horizon's world goes into the target
the pack's `gbuffers_terrain` (or the program Iris falls back to) draws to first: `colortex0` for most packs,
`colortex1` for MakeUp. Not supported yet: images and compute (`.csh`; a pack that needs them doesn't load),
mipmapped targets (`colortexNMipmapEnabled` is read but ignored), `.dat` and resource-location custom textures (PNG
files in the pack only); shadow matrices are identity.
`deferred` reads the albedo `gbuffers_*` write to `colortex4` (not checked again since the terrain programs run).
Without the other `gbuffers_*` and `shadow`, no pack has its shadows or sky look yet; Distant Horizons' and Voxy's
depth read as far. Horizon's world goes into the target the pack's `gbuffers_terrain` (or the program Iris falls back
to) draws to first: `colortex0` for most packs, `colortex1` for MakeUp. Not supported yet: images and compute (`.csh`;
a pack that needs them doesn't load), mipmapped targets (`colortexNMipmapEnabled` is read but ignored), `.dat` and
resource-location custom textures (PNG files in the pack only); shadow matrices are identity. With the pack's terrain:
entities, the sky, the hand, weather and clouds are still Horizon's (in that first target only), GPU occlusion culling
is off, block ids come from sprite names rather than block states, distant (LOD) terrain doesn't repeat its textures,
and only the overworld has been checked.
### Compatibility
@@ -439,19 +462,19 @@ Tested on 2026-10-22 on the Mac mini (M4 Pro, Metal) with each pack's default op
the authors' pages (dev-only test inputs, kept outside the repository). "Loads" means every pass the pack enables for
the overworld, Nether and End is preprocessed, translated and validated, as the game does when the pack is picked
(`java_pack::tests::real_packs_load` with `HORIZON_TEST_SHADERPACKS`); "drawn" means it was also picked in the game
and screenshotted. Only full-screen passes run (above), so no pack has its own terrain, water, shadows or sky yet.
The MakeUp, Chocapic13' and Photon rows are from 2026-10-23, on Metal and on Vulkan (RTX 4080).
and screenshotted. Full-screen passes, `gbuffers_terrain` and `gbuffers_water` run (above); no pack has its own
shadows, entities or sky yet.
| Pack | Version | Result | First thing that stops it |
| --- | --- | --- | --- |
| BSL | v10.1.8 | drawn: 26 passes | |
| BSL | v10.1.8 | drawn: 26 passes and its terrain and water programs | |
| Complementary Reimagined | r5.9.3 | drawn: 27 passes | |
| Complementary Unbound | r5.8 | loads: 27 passes | |
| Sildur's Vibrant Extreme | 2.02 | drawn: 18 passes, only its sky (above) | |
| Steadfast | 0.8.0 | drawn: 3 passes | |
| MakeUp Ultra Fast | 9.6 | drawn: 6 passes, its fog, light shafts and grade over Horizon's world | |
| Chocapic13' | V9 High | drawn: 16 passes; its default TAA upscaling shrinks the world in its `gbuffers_*` vertex programs, which don't run, so the picture is magnified 1/0.7: turn TAA Upscaling off in its settings | |
| Photon | v1.4 | loads: 27 passes; draws black: it lights the scene from the G-buffer its `gbuffers_*` write | |
| Chocapic13' | V9 High | drawn: 16 passes and its terrain and water programs | |
| MakeUp Ultra Fast | 9.6 | drawn: 6 passes and its terrain and water programs | |
| Photon | v1.4 | loads: 27 passes and its terrain and water programs; draws black | its sky and light come from a compute pass and `.dat` look-up tables, not loaded yet |
| Bliss | 2.1.2 | fails | `world0/composite1.fsh`: a vector component passed to an `inout` parameter (WGSL can't point at one) |
| Bloop | 1.8.0-Alpha-3 | fails | `world0/prepare1.fsh`: `mat2(vec4)` and other constructors naga's GLSL front end refuses |
| Noble | v1.9.9 | fails (Apple and NVIDIA) | `world0/deferred4.vsh`: a `vec3[9][9]` varying (nested arrays between stages) |
@@ -492,9 +515,9 @@ What the translator does for these packs, as Iris (JCPP and its GLSL transformer
3. **Full-screen programs**: `deferred*`, `composite*`, `final` with `colortex0..15` (formats from the pack),
`depthtex0..2`, `noisetex` and the uniforms (most are already computed for the world shaders). This alone runs
Sildur's and BSL post-processing over Horizon's own world.
4. **`gbuffers_terrain`, `gbuffers_water`, `gbuffers_sky*`**: Horizon's terrain vertices extended with Iris's
attributes (`mc_Entity` from `block.properties`, `mc_midTexCoord`, `at_tangent`, lightmap), a second set of
terrain pipelines writing the pack's render targets.
4. **`gbuffers_terrain`, `gbuffers_water`** (done, above), **`gbuffers_sky*`**: Horizon's terrain vertices decoded
into Iris's attributes (`mc_Entity` from `block.properties`, `mc_midTexCoord`, `at_tangent`, lightmap), a second
set of terrain pipelines writing the pack's render targets.
5. **Entities, block entities, hand, weather, clouds, particles** `gbuffers_*`.
6. **Shadow pass**: terrain and entities from the sun into `shadowtex0/1` and `shadowcolor0/1`, culled from the
light's view, with the pack's distortion.