Java shader packs: the pack's shadow programs draw the shadow map

A Java pack's shadow program (shadow_cutout, shadow or shadow_solid for
the solid layer, shadow_water or shadow for the translucent one) draws
Horizon's terrain from the light after begin, as Iris's ShadowRenderer:

- shadowModelView and shadowProjection are Iris's ShadowMatrices, with
  the pack's shadowMapResolution, shadowDistance, near and far planes,
  shadowIntervalSize and sunPathRotation; shadow programs get them as
  their model view and projection.
- The renderer picks every resident section inside the light's box (no
  cave culling, no face culling) and draws it instanced, solid then
  translucent, with origins after the camera's.
- shadowtex0 holds everything, shadowtex1 the depth before translucent
  terrain, bound as depth textures for comparisons and as float copies
  for plain reads; shadowcolor0..7 take the pack's formats and clears
  (white by default).

A shadow program that fails to compile leaves the pack without its
shadow map, with a warning; its terrain programs still run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-22 23:41:18 +02:00
parent c344a26e80
commit fe6ae937ef
6 changed files with 951 additions and 49 deletions
+155 -7
View File
@@ -120,6 +120,18 @@ struct Globals {
dynamic_lights: [[f32; 4]; crate::dynamic_light::MAX],
}
pub type SectionKey = (i32, i32, i32);
/// The sections a Java pack's shadow map draws ([`Renderer`]'s `shadow`).
#[derive(Default)]
struct ShadowList {
visible: Vec<resident::Visible>,
draws: Vec<[u32; 5]>,
pages: Vec<(u32, Option<u32>)>,
/// How many of `draws` are solid.
solid: u32,
indirect: Option<wgpu::Buffer>,
capacity: u64,
}
struct SectionGpu {
/// Arena page and first vertex in it: solid quads, then translucent ones.
page: u32,
@@ -427,6 +439,10 @@ pub struct Renderer {
/// built, and their pages.
phase2_draws: Vec<[u32; 5]>,
phase2_pages: Vec<(u32, Option<u32>)>,
/// A Java pack's shadow map (`gfx/java_terrain.rs`): the sections in
/// the light's view, their draws (solid then translucent, instances
/// after the camera's), and the indirect buffer they're uploaded to.
shadow: ShadowList,
/// Block-entity blocks per meshed section (world position, state id).
block_entities: HashMap<SectionKey, Vec<([i32; 3], u32)>>,
/// Changes whenever `block_entities` does (unique across renderers).
@@ -2193,6 +2209,7 @@ impl Renderer {
draw_pages: Vec::new(),
phase2_draws: Vec::new(),
phase2_pages: Vec::new(),
shadow: ShadowList::default(),
block_entities: HashMap::new(),
block_entity_revision: next_block_entity_revision(),
occlusion: occlusion::Occlusion::new(crate::chunk::MIN_Y, crate::chunk::HEIGHT / 16),
@@ -2518,11 +2535,26 @@ impl Renderer {
first: u32,
count: u32,
page_group: impl Fn(&mut wgpu::RenderPass<'_>, u32),
) {
let list = (&self.draws[..], &self.draw_pages[..]);
self.draw_list(pass, indirect, list, base, first, count, page_group);
}
/// [`Self::draw_sections_with`] over another list of draws and pages.
#[allow(clippy::too_many_arguments)]
fn draw_list(
&self,
pass: &mut wgpu::RenderPass<'_>,
indirect: &wgpu::Buffer,
(draws, pages): (&[[u32; 5]], &[(u32, Option<u32>)]),
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 {
let (page, index_page) = self.draw_pages[i];
let run = self.draw_pages[i..end]
let (page, index_page) = pages[i];
let run = pages[i..end]
.iter()
.take_while(|&&p| p == (page, index_page))
.count();
@@ -2534,7 +2566,7 @@ impl Renderer {
let offset = (i - base as usize) as u64 * 20;
pass.multi_draw_indexed_indirect(indirect, offset, run as u32);
} else {
for d in &self.draws[i..i + run] {
for d in &draws[i..i + run] {
pass.draw_indexed(d[2]..d[2] + d[0], d[3] as i32, d[4]..d[4] + 1);
}
}
@@ -2556,12 +2588,32 @@ impl Renderer {
culling: bool,
) {
use java_terrain::Layer;
let translucent = layer == Layer::Translucent;
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, &[]);
}
};
if matches!(layer, Layer::ShadowSolid | Layer::ShadowTranslucent) {
let shadow = &self.shadow;
let all = shadow.draws.len() as u32;
let (first, count) = if layer == Layer::ShadowSolid {
(0, shadow.solid)
} else {
(shadow.solid, all - shadow.solid)
};
// Without multi-draw the draws are read from the list.
let indirect = shadow.indirect.as_ref().unwrap_or(&self.indirect);
if count == 0 {
return;
}
pass.set_bind_group(2, pipelines.group, &[]);
pass.set_pipeline(pipelines.instanced);
pass.set_vertex_buffer(1, self.instances.slice(..));
let list = (&shadow.draws[..], &shadow.pages[..]);
self.draw_list(pass, indirect, list, 0, first, count, page);
return;
}
let translucent = layer == Layer::Translucent;
pass.set_bind_group(2, pipelines.group, &[]);
match (self.flat.as_ref().filter(|_| flat_frame), pipelines.flat) {
// The flat path doesn't cull by occlusion: phase 1 is everything.
@@ -2585,6 +2637,7 @@ impl Renderer {
(Layer::Revealed, Some(c)) => (&c.phase2, phase1, phase1, solid - phase1),
(Layer::Revealed, None) => return,
(Layer::Translucent, _) => (&self.indirect, 0, solid, translucent_draws),
(Layer::ShadowSolid | Layer::ShadowTranslucent, _) => return,
};
if count == 0 {
return;
@@ -3163,8 +3216,48 @@ impl Renderer {
visible_lods.sort_unstable_by_key(|v| (v.distance, v.key));
}
self.drawn_sections = visible.len() + visible_lods.len();
if self.drawn_sections as u64 > self.instance_capacity {
self.instance_capacity = (self.drawn_sections as u64).next_power_of_two();
// A Java pack's shadow map: the sections in the light's orthographic
// box, whatever the camera sees (Iris turns cave culling off too).
let mut shadow_visible = std::mem::take(&mut self.shadow.visible);
shadow_visible.clear();
let shadow_view = match &self.pack {
Some(Pack::Java(j)) if !frame.title && self.java_table.is_some() => j.shadow_view(
frame.shader.dimension,
&java_stages::JavaFrame {
eye_light: frame.shader.eye_light,
sun_angle: frame.sky.sun_angle,
moon_angle: frame.sky.moon_angle,
},
camera.as_vec3(),
),
_ => None,
};
if let Some((view, [half, near, far])) = shadow_view {
// Inside when `plane · (p, 1) >= 0`: |x|, |y| <= half and the
// eye depth between the near and far planes (GL looks down -z).
let (x, y, z) = (view.row(0), view.row(1), view.row(2));
let planes = [
Vec4::W * half - x,
Vec4::W * half + x,
Vec4::W * half - y,
Vec4::W * half + y,
-z - Vec4::W * near,
z + Vec4::W * far,
];
crate::spans::time("shadow visibility", || {
self.sections.visible(
camera,
(frame.detail_distance / 16.0) as i32,
&Frustum { planes },
|_| true,
|_, _| false,
&mut shadow_visible,
)
});
}
let instances = self.drawn_sections + shadow_visible.len();
if instances as u64 > self.instance_capacity {
self.instance_capacity = (instances as u64).next_power_of_two();
self.instances = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Section origins"),
size: self.instance_capacity * 16,
@@ -3179,8 +3272,63 @@ impl Renderer {
visible
.iter()
.map(|v| section_instance(v.origin))
.chain(visible_lods.iter().map(|v| lod::instance(v.origin))),
.chain(visible_lods.iter().map(|v| lod::instance(v.origin)))
.chain(shadow_visible.iter().map(|v| section_instance(v.origin))),
);
// The shadow map's draws: every solid quad (no face is culled), then
// the translucent ones in the order the camera's sort left them.
let shadow = &mut self.shadow;
shadow.draws.clear();
shadow.pages.clear();
for pass in [false, true] {
for (j, v) in shadow_visible.iter().enumerate() {
let s = self.sections.get(v.slot);
let instance = (self.drawn_sections + j) as u32;
match (pass, s.sorted_indices) {
(false, _) if s.solid > 0 => {
shadow
.draws
.push([s.solid * 6, 1, 0, s.start as u32, instance]);
shadow.pages.push((s.page, None));
}
(true, Some((index_page, index_start))) if s.translucent > 0 => {
let first = s.start + u64::from(s.solid) * 4;
shadow.draws.push([
s.translucent * 6,
1,
index_start as u32,
first as u32,
instance,
]);
shadow.pages.push((s.page, Some(index_page)));
}
_ => {}
}
}
if !pass {
shadow.solid = shadow.draws.len() as u32;
}
}
if self.multi_draw && !shadow.draws.is_empty() {
if shadow.draws.len() as u64 > shadow.capacity || shadow.indirect.is_none() {
shadow.capacity = (shadow.draws.len() as u64).next_power_of_two();
shadow.indirect = Some(self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Java shader pack shadow draws"),
size: shadow.capacity * 20,
usage: wgpu::BufferUsages::INDIRECT | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
}));
}
if let Some(indirect) = &shadow.indirect {
self.uploads.buffer(
&mut encoder,
indirect,
0,
bytemuck::cast_slice(&shadow.draws),
);
}
}
shadow.visible = shadow_visible;
if !self.origins.is_empty() {
self.uploads.buffer(
&mut encoder,
+586 -29
View File
@@ -168,6 +168,19 @@ struct Views<'a> {
depth_solid: &'a wgpu::TextureView,
atlas: Option<&'a wgpu::TextureView>,
lightmap: Option<&'a wgpu::TextureView>,
shadow: Option<&'a ShadowViews>,
}
/// The shadow map's textures, as the passes read them.
struct ShadowViews {
/// `shadowtex0` and `shadowtex1` for comparisons (`Depth32Float`).
depth: wgpu::TextureView,
depth_solid: wgpu::TextureView,
/// The same as plain floats, for `sampler2D` reads (`R32Float`).
float: wgpu::TextureView,
float_solid: wgpu::TextureView,
/// `shadowcolor<N>`, for the targets the shadow programs write.
colors: Vec<Option<wgpu::TextureView>>,
}
/// A colour target's two sides.
@@ -190,10 +203,15 @@ enum Source {
/// (the world's depth when the pack doesn't draw the terrain).
DepthSolid,
Noise,
/// `shadowtex*`: no shadow map yet, so a far depth (nothing in shadow);
/// also Distant Horizons' and Voxy's depth, as without those mods.
Shadow,
/// Anything else (`shadowcolor*`, custom textures): white or black.
/// `shadowtex0` (with translucent terrain) or `shadowtex1` (without):
/// the shadow map when the pack draws one, else a far depth (nothing in
/// shadow).
ShadowDepth(u32),
/// `shadowcolor<N>`: the shadow map's colour target, else white.
ShadowColor(u32),
/// Distant Horizons' and Voxy's depth: far, as without those mods.
Far,
/// Anything else (custom textures): white or black.
Blank(bool),
/// In geometry programs: the block atlas (`gtexture`), the lightmap,
/// and a flat normal map for `normals` (sprites have no LabPBR maps).
@@ -212,9 +230,13 @@ fn source(name: &str, geometry: bool) -> Source {
"depthtex0" | "gdepthtex" => Source::Depth,
"depthtex1" | "depthtex2" => Source::DepthSolid,
"noisetex" => Source::Noise,
"shadowtex0" | "shadowtex1" | "shadow" | "watershadow" => Source::Shadow,
n if n.starts_with("dhDepthTex") || n.starts_with("vxDepthTex") => Source::Shadow,
n if n.starts_with("shadowcolor") => Source::Blank(true),
"shadowtex0" | "shadow" | "watershadow" => Source::ShadowDepth(0),
"shadowtex1" => Source::ShadowDepth(1),
n if n.starts_with("dhDepthTex") || n.starts_with("vxDepthTex") => Source::Far,
"shadowcolor" => Source::ShadowColor(0),
n if let Some(i) = n.strip_prefix("shadowcolor").and_then(|i| i.parse().ok()) => {
Source::ShadowColor(i)
}
n => target_index(n).map_or(Source::Blank(false), Source::Target),
}
}
@@ -253,6 +275,8 @@ struct PassGpu {
/// them), and the targets written on their alternate side.
flat_pipeline: Option<wgpu::RenderPipeline>,
geometry: Option<BTreeSet<u32>>,
/// A shadow program: the light's matrices, `shadowcolor` targets.
shadow: bool,
}
/// What a pass draws into.
@@ -269,6 +293,8 @@ struct GeometrySetup<'a> {
/// Each draw buffer's blending.
blends: &'a [Option<wgpu::BlendState>],
layouts: &'a GeometryLayouts<'a>,
/// A shadow program: no face culling (Iris's `ShadowRenderer`).
shadow: bool,
}
/// The renderer's bind group layouts a geometry program's pipelines use:
@@ -284,6 +310,19 @@ struct FolderGeometry {
terrain: PassGpu,
water: Option<PassGpu>,
translucent_at: usize,
/// Its shadow programs, when it has some and they compile.
shadow: Option<FolderShadow>,
}
/// A folder's shadow map: its programs over the solid and translucent
/// terrain, its `shadowcolor` targets, and where it runs.
struct FolderShadow {
solid: PassGpu,
water: Option<PassGpu>,
/// Per `shadowcolor` target: its format and clear colour.
targets: Vec<(wgpu::TextureFormat, Option<wgpu::Color>)>,
/// How many passes run before it (`begin*`).
at: usize,
}
/// What every pass of the pack shares.
@@ -315,6 +354,7 @@ struct Bound {
/// Per pass, then `final`.
groups: Vec<wgpu::BindGroup>,
geometry: Option<BoundGeometry>,
shadow: Option<BoundShadow>,
world_in: (wgpu::RenderPipeline, wgpu::BindGroup),
/// The world goes to colortex0's alternate side.
world_alt: bool,
@@ -326,6 +366,25 @@ struct Bound {
_blank: Vec<wgpu::Texture>,
}
/// The shadow map's textures and its programs' groups.
struct BoundShadow {
views: ShadowViews,
/// The depth buffer the shadow programs draw with (`shadowtex0`), and
/// its copy before translucent terrain (`shadowtex1`).
depth: wgpu::Texture,
depth_solid: wgpu::Texture,
/// The `shadowcolor` targets cleared each frame, with their colour,
/// and those cleared only when made (kept between frames).
clears: Vec<(wgpu::TextureView, wgpu::Color)>,
initial: Vec<(wgpu::TextureView, wgpu::Color)>,
solid: wgpu::BindGroup,
water: Option<wgpu::BindGroup>,
/// `depth` for `depth_out` into the float copies.
out_group: wgpu::BindGroup,
/// A pass reads the depth as plain floats: the copies are made.
float_reads: bool,
}
/// What a folder's geometry programs draw with at one size.
struct BoundGeometry {
/// The depth buffer the geometry tests against: the world's, then the
@@ -442,6 +501,24 @@ impl JavaStages {
})
}
/// Where the pack's shadow map looks this frame in `dimension`, when
/// it draws one: its view of camera-relative positions (`camera` is the
/// camera's position), and its half width, near and far planes, for
/// the renderer to pick the sections it draws.
pub fn shadow_view(
&self,
dimension: i8,
world: &JavaFrame,
camera: Vec3,
) -> Option<(Mat4, [f32; 3])> {
let index = self.folder_for[(dimension.clamp(-1, 1) + 1) as usize].unwrap_or(0);
let folder = self.folders.get(index)?;
folder.geometry.as_ref()?.shadow.as_ref()?;
let d = folder.directives;
let (view, _) = shadow_matrices(&d, shadow_angle(world), camera);
Some((view, [d.shadow.distance, d.shadow.near, d.shadow.far]))
}
/// Whether the pack draws the terrain in `dimension` (0 overworld, -1
/// the Nether, 1 the End): the renderer then leaves it out of the world
/// and gives `run` a [`JavaWorld`].
@@ -480,9 +557,10 @@ impl JavaStages {
self.atlas = Atlas::new(device, queue, w);
self.bound = None;
}
if self.bound.as_ref().is_none_or(|b| {
let fresh = self.bound.as_ref().is_none_or(|b| {
b.folder != folder || b.size != size || b.geometry.is_some() != terrain.is_some()
}) {
});
if fresh {
self.bound = Some(self.bind(device, queue, folder, color, depth, size, post, terrain));
}
let now = std::time::Instant::now();
@@ -498,6 +576,8 @@ impl JavaStages {
self.previous,
);
inputs.set_world(&world, directives.sun_path_rotation);
(inputs.shadow_view, inputs.shadow_projection) =
shadow_matrices(&directives, inputs.shadow_angle, inputs.camera);
if let Some(atlas) = &self.atlas {
inputs.atlas_size = atlas.size().map(|v| v as f32);
}
@@ -537,7 +617,14 @@ impl JavaStages {
let translucent_at = geometry.map_or(usize::MAX, |((g, _), _)| {
g.translucent_at.min(folder.passes.len())
});
let shadow = geometry
.and_then(|((g, b), w)| Some((g.shadow.as_ref()?, bound.shadow.as_ref()?, b, w)));
for i in 0..=folder.passes.len() {
if let Some((sh, b, g, w)) = shadow
&& i == sh.at.min(folder.passes.len())
{
draw_shadow(queue, encoder, sh, b, g, &inputs, w, fresh);
}
if i == world_at {
world_in(encoder, bound);
if let Some(((g, b), w)) = geometry {
@@ -594,6 +681,151 @@ impl JavaStages {
&bound.output
}
/// The shadow map's textures at the folder's `shadowMapResolution`,
/// and its programs' groups.
#[allow(clippy::too_many_arguments)]
fn bind_shadow(
&self,
device: &wgpu::Device,
queue: &wgpu::Queue,
folder: &Folder,
shadow: &FolderShadow,
targets: &BTreeMap<u32, Target>,
world: Option<&JavaWorld>,
blank: &mut Vec<wgpu::Texture>,
) -> BoundShadow {
let side = folder
.directives
.shadow
.resolution
.clamp(1, device.limits().max_texture_dimension_2d);
let texture = |label, format, usage| {
device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d {
width: side,
height: side,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage,
view_formats: &[],
})
};
use wgpu::TextureUsages as U;
let depth = texture(
"Java shader pack shadow depth",
wgpu::TextureFormat::Depth32Float,
U::RENDER_ATTACHMENT | U::TEXTURE_BINDING | U::COPY_SRC,
);
let depth_solid = texture(
"Java shader pack shadow depth before translucent terrain",
wgpu::TextureFormat::Depth32Float,
U::TEXTURE_BINDING | U::COPY_DST,
);
let float = |label| {
texture(
label,
wgpu::TextureFormat::R32Float,
U::RENDER_ATTACHMENT | U::TEXTURE_BINDING,
)
.create_view(&Default::default())
};
// The colour targets the shadow programs write or a pass reads.
let passes = folder.passes.iter().chain(&folder.final_pass).chain(
folder
.geometry
.iter()
.flat_map(|g| std::iter::once(&g.terrain).chain(&g.water)),
);
let mut used: BTreeSet<u32> = shadow
.solid
.draw_buffers
.iter()
.chain(shadow.water.iter().flat_map(|w| &w.draw_buffers))
.copied()
.collect();
let mut float_reads = false;
for s in passes.clone().flat_map(|p| &p.samplers) {
match s.source {
Source::ShadowColor(i) => {
used.insert(i);
}
Source::ShadowDepth(_) if !s.compare => float_reads = true,
_ => {}
}
}
let mut colors = Vec::new();
let mut clears = Vec::new();
let mut initial = Vec::new();
for (i, &(format, clear)) in shadow.targets.iter().enumerate() {
if !used.contains(&(i as u32)) {
colors.push(None);
continue;
}
let view = texture(
"Java shader pack shadowcolor",
format,
U::RENDER_ATTACHMENT | U::TEXTURE_BINDING,
)
.create_view(&Default::default());
match clear {
Some(color) => clears.push((view.clone(), color)),
// Kept between frames: white to start with, as Iris's.
None => initial.push((view.clone(), wgpu::Color::WHITE)),
}
colors.push(Some(view));
}
let views = ShadowViews {
depth: depth.create_view(&Default::default()),
depth_solid: depth_solid.create_view(&Default::default()),
float: float("Java shader pack shadowtex0"),
float_solid: float("Java shader pack shadowtex1"),
colors,
};
// The shadow programs read neither the shadow map nor the size of
// the world's depth.
let unused = texture(
"Java shader pack shadow pass depth",
wgpu::TextureFormat::R32Float,
U::TEXTURE_BINDING,
)
.create_view(&Default::default());
let pass_views = Views {
depth: &unused,
depth_solid: &unused,
atlas: self.atlas.as_ref().map(|a| &a.view),
lightmap: world.map(|w| w.lightmap),
shadow: None,
};
let mut bind =
|pass: &PassGpu| pass.bind(device, queue, targets, &pass_views, &self.common, blank);
let solid = bind(&shadow.solid);
let water = shadow.water.as_ref().map(&mut bind);
let out_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Java shader pack shadow depth"),
layout: &self.common.depth_layout,
entries: &[wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&views.depth),
}],
});
BoundShadow {
views,
depth,
depth_solid,
clears,
initial,
solid,
water,
out_group,
float_reads,
}
}
#[allow(clippy::too_many_arguments)]
fn bind(
&self,
@@ -702,13 +934,17 @@ impl JavaStages {
.create_view(&Default::default()),
None => depth.clone(),
};
let mut blank = Vec::new();
let shadow = geometry
.and_then(|g| g.shadow.as_ref())
.map(|sh| self.bind_shadow(device, queue, folder, sh, &targets, world, &mut blank));
let views = Views {
depth: &depth,
depth_solid: &depth_solid,
atlas: self.atlas.as_ref().map(|a| &a.view),
lightmap: world.map(|w| w.lightmap),
shadow: shadow.as_ref().map(|s| &s.views),
};
let mut blank = Vec::new();
let groups = all
.clone()
.map(|pass| pass.bind(device, queue, &targets, &views, &self.common, &mut blank))
@@ -839,6 +1075,7 @@ impl JavaStages {
depth_solid,
groups,
geometry,
shadow,
world_in: (world_pipeline, world_group),
world_alt: plan.flipped_after_prepare.contains(&0),
final_target,
@@ -869,6 +1106,7 @@ fn folder_geometry(
flat_vertex: g.variants.first().unwrap_or(&g.program.vertex),
blends,
layouts,
shadow: false,
}),
)
};
@@ -882,11 +1120,15 @@ fn folder_geometry(
terrain,
water,
translucent_at: plan.translucent_at,
shadow: None,
})
});
let error = pollster::block_on(scope.pop());
match (made, error) {
(Ok(geometry), None) => Some(geometry),
(Ok(mut geometry), None) => {
geometry.shadow = folder_shadow(device, plan, layouts);
Some(geometry)
}
(Err(e), _) => {
log::warn!("Horizon: shader pack {}: {e}", terrain.program.pass.program);
None
@@ -898,6 +1140,210 @@ fn folder_geometry(
}
}
/// A folder's shadow programs on the GPU, or `None` (with a warning: the
/// pack then reads a shadow map with nothing in shadow) when wgpu refuses
/// them.
fn folder_shadow(
device: &wgpu::Device,
plan: &JavaFolder,
layouts: &GeometryLayouts,
) -> Option<FolderShadow> {
let solid = plan.shadow.as_ref()?;
let formats: Vec<wgpu::TextureFormat> = plan
.shadow_targets
.iter()
.map(|t| target_format(&t.format, false))
.collect();
// Instanced draws only: the flat draws hold what the camera sees.
let layouts = GeometryLayouts {
flat: None,
page: layouts.page,
};
let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
let gpu = |g: &GeometryProgram, blends: &[Option<wgpu::BlendState>]| {
PassGpu::new(
device,
&g.program,
&formats,
Output::Geometry(GeometrySetup {
flat_vertex: &g.program.vertex,
blends,
layouts: &layouts,
shadow: true,
}),
)
};
let made = gpu(solid, &plan.shadow_blends).and_then(|solid_gpu| {
let water = plan
.shadow_water
.as_ref()
.map(|w| gpu(w, &plan.shadow_water_blends))
.transpose()?;
Ok((solid_gpu, water))
});
let error = pollster::block_on(scope.pop());
let warn = |e: &dyn std::fmt::Display| {
log::warn!("Horizon: shader pack {}: {e}", solid.program.pass.program);
};
match (made, error) {
(Ok((solid_gpu, water)), None) => Some(FolderShadow {
solid: solid_gpu,
water,
targets: plan
.shadow_targets
.iter()
.zip(&formats)
.map(|(t, &format)| {
let clear = t.clear.then(|| {
let [r, g, b, a] = t.clear_color.unwrap_or([1.0; 4]);
wgpu::Color {
r: r.into(),
g: g.into(),
b: b.into(),
a: a.into(),
}
});
(format, clear)
})
.collect(),
at: plan.shadow_at,
}),
(Err(e), _) => {
warn(&e);
None
}
(_, Some(e)) => {
warn(&e);
None
}
}
}
/// The shadow map: Horizon's terrain from the light with the pack's
/// shadow programs, solid then translucent (`ShadowRenderer`), with the
/// depth before translucent terrain kept for `shadowtex1`.
#[allow(clippy::too_many_arguments)]
fn draw_shadow(
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
shadow: &FolderShadow,
b: &BoundShadow,
geometry: &BoundGeometry,
inputs: &Inputs,
world: &JavaWorld,
fresh: bool,
) {
if fresh {
for (view, color) in &b.initial {
clear_view(encoder, view, *color);
}
}
for (view, color) in &b.clears {
clear_view(encoder, view, *color);
}
let draw = |encoder: &mut wgpu::CommandEncoder,
pass: &PassGpu,
group: &wgpu::BindGroup,
layer: Layer,
first: bool| {
pass.write_uniforms(queue, inputs);
let attachments: Vec<Option<wgpu::RenderPassColorAttachment>> = pass
.draw_buffers
.iter()
.map(|&i| {
let view = b.views.colors.get(i as usize)?.as_ref()?;
Some(color_attachment(view, None))
})
.collect();
let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some(&pass.program),
color_attachments: &attachments,
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &b.views.depth,
depth_ops: Some(wgpu::Operations {
load: if first {
wgpu::LoadOp::Clear(1.0)
} else {
wgpu::LoadOp::Load
},
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
..Default::default()
});
(world.draw)(
&mut render,
layer,
&TerrainPipelines {
instanced: &pass.pipeline,
flat: None,
group,
},
);
};
let float_out = |encoder: &mut wgpu::CommandEncoder, solid: bool| {
if !b.float_reads {
return;
}
let mut attachments = vec![Some(color_attachment(&b.views.float, None))];
if solid {
attachments.push(Some(color_attachment(&b.views.float_solid, None)));
}
let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Java shader pack shadow depth"),
color_attachments: &attachments,
..Default::default()
});
render.set_pipeline(if solid {
&geometry.out_both
} else {
&geometry.out
});
render.set_bind_group(0, &b.out_group, &[]);
render.draw(0..3, 0..1);
};
draw(encoder, &shadow.solid, &b.solid, Layer::ShadowSolid, true);
encoder.copy_texture_to_texture(
b.depth.as_image_copy(),
b.depth_solid.as_image_copy(),
b.depth.size(),
);
float_out(encoder, true);
if let (Some(pass), Some(group)) = (&shadow.water, &b.water) {
draw(encoder, pass, group, Layer::ShadowTranslucent, false);
float_out(encoder, false);
}
}
/// Iris's `shadowModelView` and `shadowProjection` (`ShadowMatrices`):
/// the light's view of camera-relative positions, snapped to the pack's
/// `shadowIntervalSize` as the camera moves, and an orthographic
/// projection `shadowDistance` wide each way of the camera.
pub fn shadow_matrices(directives: &Directives, shadow_angle: f32, camera: Vec3) -> (Mat4, Mat4) {
let sky = if shadow_angle < 0.25 {
shadow_angle + 0.75
} else {
shadow_angle - 0.25
};
let mut view = Mat4::from_rotation_x(90f32.to_radians())
* Mat4::from_rotation_z((sky * -360.0).to_radians())
* Mat4::from_rotation_x(directives.sun_path_rotation.to_radians());
let d = &directives.shadow;
if d.interval != 0.0 {
// Java's `%` keeps the dividend's sign, as Rust's does.
let offset = Vec3::new(
camera.x % d.interval,
camera.y % d.interval,
camera.z % d.interval,
) - Vec3::splat(d.interval / 2.0);
view *= Mat4::from_translation(offset);
}
let h = d.distance;
let projection = Mat4::orthographic_rh_gl(-h, h, -h, h, d.near, d.far);
(view, projection)
}
fn world_in(encoder: &mut wgpu::CommandEncoder, bound: &Bound) {
let colortex0 = &bound.targets[&0];
let side = if bound.world_alt {
@@ -1257,7 +1703,10 @@ impl PassGpu {
)),
)
}
(false, Source::Depth | Source::DepthSolid | Source::Shadow) => (
(
false,
Source::Depth | Source::DepthSolid | Source::ShadowDepth(_) | Source::Far,
) => (
wgpu::TextureSampleType::Float { filterable: false },
Some(false),
),
@@ -1441,6 +1890,7 @@ impl PassGpu {
scale: program.pass.scale.clamp(0.0, 1.0),
flat_pipeline: None,
geometry: None,
shadow: false,
})
}
@@ -1523,9 +1973,10 @@ impl PassGpu {
compilation_options: Default::default(),
buffers: &buffers,
},
// The y flip into GL's layout turns the faces around.
// The y flip into GL's layout turns the faces around. The
// shadow map culls none (a mountain's back casts shadows).
primitive: wgpu::PrimitiveState {
cull_mode: Some(wgpu::Face::Back),
cull_mode: (!setup.shadow).then_some(wgpu::Face::Back),
front_face: wgpu::FrontFace::Cw,
..Default::default()
},
@@ -1583,6 +2034,7 @@ impl PassGpu {
scale: 1.0,
flat_pipeline,
geometry: Some(flipped),
shadow: setup.shadow,
})
}
@@ -1599,8 +2051,31 @@ impl PassGpu {
let depth = textures.depth;
let mut views = Vec::new();
for s in &self.samplers {
let shadow = textures
.shadow
.filter(|_| s.dimension == wgpu::TextureViewDimension::D2);
let view = match (s.compare, s.source) {
(true, Source::ShadowDepth(i)) if let Some(sh) = shadow => {
if i == 0 {
sh.depth.clone()
} else {
sh.depth_solid.clone()
}
}
(true, _) => blank_view(device, queue, blank, s, BlankKind::FarDepth),
(false, Source::ShadowDepth(i)) if let Some(sh) = shadow => {
if i == 0 {
sh.float.clone()
} else {
sh.float_solid.clone()
}
}
(false, Source::ShadowColor(i))
if let Some(view) =
shadow.and_then(|sh| sh.colors.get(i as usize)?.as_ref()) =>
{
view.clone()
}
(false, Source::Target(i)) if s.dimension == wgpu::TextureViewDimension::D2 => {
match targets.get(&i) {
Some(t) if self.reads_alt.contains(&i) => t.alt_view.clone(),
@@ -1629,7 +2104,12 @@ impl PassGpu {
(false, Source::FlatNormal) => {
blank_view(device, queue, blank, s, BlankKind::FlatNormal)
}
(false, Source::Shadow) => blank_view(device, queue, blank, s, BlankKind::Far),
(false, Source::ShadowDepth(_) | Source::Far) => {
blank_view(device, queue, blank, s, BlankKind::Far)
}
(false, Source::ShadowColor(_)) => {
blank_view(device, queue, blank, s, BlankKind::Color(true))
}
(false, Source::Noise) if s.dimension == wgpu::TextureViewDimension::D2 => {
common.noise.clone()
}
@@ -1648,7 +2128,10 @@ impl PassGpu {
(true, _) => &common.compare,
_ if s.signed.is_some() => &common.nearest,
(false, Source::Noise) => &common.repeat,
(false, Source::Depth | Source::DepthSolid | Source::Shadow) => &common.nearest,
(
false,
Source::Depth | Source::DepthSolid | Source::ShadowDepth(_) | Source::Far,
) => &common.nearest,
(false, Source::Atlas) => &common.atlas,
(false, Source::Target(i)) => {
match targets.get(&i).map(|t| sample_type(t.format)) {
@@ -1697,7 +2180,12 @@ impl PassGpu {
};
let mut bytes = vec![0u8; *block_size as usize];
for (name, slots) in &self.uniforms {
if let Some(values) = inputs.value(name, self.geometry.is_some()) {
let values = if self.shadow {
inputs.shadow(name).or_else(|| inputs.value(name, true))
} else {
inputs.value(name, self.geometry.is_some())
};
if let Some(values) = values {
for (&(offset, int), value) in slots.iter().zip(values) {
let at = offset as usize..offset as usize + 4;
bytes[at].copy_from_slice(&if int {
@@ -2073,6 +2561,19 @@ struct Inputs {
custom: HashMap<String, Vec<f32>>,
/// `atlasSize`, in geometry programs.
atlas_size: [f32; 2],
/// `shadowModelView` and `shadowProjection` ([`shadow_matrices`]).
shadow_view: Mat4,
shadow_projection: Mat4,
}
/// `shadowAngle`: the sun's angle by day, the moon's by night, 0..1.
fn shadow_angle(world: &JavaFrame) -> f32 {
let sun = celestial_angle(world.sun_angle);
if sun < 180.0 {
sun / 360.0
} else {
celestial_angle(world.moon_angle) / 360.0
}
}
/// `CelestialUniforms.getSunAngle`: the body's angle plus 90, in 0..360
@@ -2128,6 +2629,8 @@ impl Inputs {
is_day: true,
custom: HashMap::new(),
atlas_size: [0.0; 2],
shadow_view: Mat4::IDENTITY,
shadow_projection: Mat4::IDENTITY,
};
out.set_world(&JavaFrame::default(), 0.0);
out
@@ -2153,11 +2656,7 @@ impl Inputs {
let sun = celestial_angle(world.sun_angle);
self.is_day = sun < 180.0;
self.sun_angle = sun / 360.0;
self.shadow_angle = if self.is_day {
sun
} else {
celestial_angle(world.moon_angle)
} / 360.0;
self.shadow_angle = shadow_angle(world);
}
/// The value of uniform `name`, as its scalars in order: Iris's own,
@@ -2207,6 +2706,26 @@ impl Inputs {
})
}
/// The uniforms whose value differs in shadow programs: the light's
/// matrices instead of the camera's.
fn shadow(&self, name: &str) -> Option<Vec<f32>> {
let mat = |m: Mat4| m.to_cols_array().to_vec();
let (view, projection) = (self.shadow_view, self.shadow_projection);
Some(match name {
"iris_ModelViewMatrix" | "modelViewMatrix" => mat(view),
"iris_ModelViewMatrixInverse" | "modelViewMatrixInverse" => mat(view.inverse()),
"iris_ProjectionMatrix" | "projectionMatrix" => mat(projection),
"iris_ProjectionMatrixInverse" | "projectionMatrixInverse" => mat(projection.inverse()),
"iris_ModelViewProjectionMatrix" => mat(projection * view),
"iris_NormalMatrix" | "normalMatrix" => Mat3::from_mat4(view)
.inverse()
.transpose()
.to_cols_array()
.to_vec(),
_ => return None,
})
}
/// The value of Iris uniform `name`; `None` for one Horizon doesn't
/// provide.
fn builtin(&self, name: &str) -> Option<Vec<f32>> {
@@ -2269,10 +2788,10 @@ impl Inputs {
"iris_ProjectionMatrixInverse" => mat(screen.inverse()),
"iris_TextureMatrix" => (0..8).flat_map(|_| mat(Mat4::IDENTITY)).collect(),
"iris_NormalMatrix" => Mat3::IDENTITY.to_cols_array().to_vec(),
"shadowModelView"
| "shadowModelViewInverse"
| "shadowProjection"
| "shadowProjectionInverse" => mat(Mat4::IDENTITY),
"shadowModelView" => mat(self.shadow_view),
"shadowModelViewInverse" => mat(self.shadow_view.inverse()),
"shadowProjection" => mat(self.shadow_projection),
"shadowProjectionInverse" => mat(self.shadow_projection.inverse()),
_ => return None,
})
}
@@ -2310,14 +2829,52 @@ mod tests {
);
}
#[test]
fn shadow_matrices_are_iris_s() {
use horizon_shaderpack::pipeline::ShadowDirectives;
let close = |a: Mat4, b: Mat4| {
for (x, y) in a.to_cols_array().iter().zip(b.to_cols_array()) {
assert!((x - y).abs() < 1e-5, "{a} != {b}");
}
};
// ShadowMatrices.Tests: shadowDistance 32, planes 0.05 and 256.
let directives = Directives {
shadow: ShadowDirectives {
distance: 32.0,
near: 0.05,
far: 256.0,
interval: 0.0,
..ShadowDirectives::default()
},
..Directives::default()
};
let (view, projection) = shadow_matrices(&directives, 0.25, Vec3::ZERO);
close(
projection,
Mat4::from_cols_array(&[
0.03125, 0.0, 0.0, 0.0, 0.0, 0.03125, 0.0, 0.0, 0.0, 0.0, -0.007_814_026, 0.0, 0.0,
0.0, -1.000_390_6, 1.0,
]),
);
// Noon: the light looks straight down (up is toward it, +z).
assert!((view.transform_vector3(Vec3::Y) - Vec3::Z).length() < 1e-5);
// Snapped to the interval: x 5.5 % 2 = 1.5 further than 0 % 2.
let directives = Directives::default();
let (snapped, _) = shadow_matrices(&directives, 0.25, Vec3::new(5.5, 0.0, 0.0));
let (plain, _) = shadow_matrices(&directives, 0.25, Vec3::ZERO);
close(snapped, plain * Mat4::from_translation(Vec3::new(1.5, 0.0, 0.0)));
}
#[test]
fn samplers_read_what_iris_binds() {
assert_eq!(source("colortex4", false), Source::Target(4));
assert_eq!(source("gaux1", false), Source::Target(4));
assert_eq!(source("gdepthtex", false), Source::Depth);
assert_eq!(source("shadowtex1", false), Source::Shadow);
assert_eq!(source("dhDepthTex0", false), Source::Shadow);
assert_eq!(source("shadowcolor0", false), Source::Blank(true));
assert_eq!(source("shadowtex1", false), Source::ShadowDepth(1));
assert_eq!(source("shadow", false), Source::ShadowDepth(0));
assert_eq!(source("dhDepthTex0", false), Source::Far);
assert_eq!(source("shadowcolor1", false), Source::ShadowColor(1));
assert_eq!(source("shadowcolor", false), Source::ShadowColor(0));
assert_eq!(source("cloudTexture", false), Source::Blank(false));
// Before translucent terrain; geometry programs' own textures.
assert_eq!(source("depthtex1", false), Source::DepthSolid);
@@ -214,6 +214,10 @@ pub enum Layer {
/// found in sight (phase 2).
Revealed,
Translucent,
/// The shadow map's sections ([`super::Renderer`]'s shadow list), solid
/// then translucent.
ShadowSolid,
ShadowTranslucent,
}
/// Draws Horizon's terrain with a pack's pipelines. Set by the renderer,
+46 -6
View File
@@ -44,6 +44,16 @@ pub struct JavaFolder {
/// Each draw buffer's blending in `terrain` and `water`.
pub terrain_blends: Vec<Option<wgpu::BlendState>>,
pub water_blends: Vec<Option<wgpu::BlendState>>,
/// The shadow map's programs over Horizon's solid and translucent
/// terrain (instanced draws only), drawn after `begin*`, into
/// `shadowcolor` targets set by `shadow_targets`.
pub shadow: Option<GeometryProgram>,
pub shadow_water: Option<GeometryProgram>,
pub shadow_targets: Vec<TargetSettings>,
pub shadow_blends: Vec<Option<wgpu::BlendState>>,
pub shadow_water_blends: Vec<Option<wgpu::BlendState>>,
/// How many of `passes` run before the shadow map (`begin*`).
pub shadow_at: usize,
}
/// A loaded Java pack.
@@ -138,9 +148,14 @@ pub fn load(
}
// 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 geometry_with = |pass: &Option<horizon_shaderpack::pipeline::Pass>,
alpha_test,
flat: &[bool]| {
let pass = pass.as_ref()?;
let glues = [false, true].map(|flat| crate::gfx::java_terrain::glue(flat, alpha_test));
let glues: Vec<_> = flat
.iter()
.map(|&flat| crate::gfx::java_terrain::glue(flat, alpha_test))
.collect();
match pack.compile_geometry(pass, &plan.targets, &values, &env, &properties, &glues) {
Ok(program) => Some(program),
Err(e) => {
@@ -149,9 +164,20 @@ pub fn load(
}
}
};
let geometry = |pass: &Option<horizon_shaderpack::pipeline::Pass>, alpha_test| {
geometry_with(pass, alpha_test, &[false, true])
};
// 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));
// The shadow map draws only with the pack's terrain, and only from
// instanced draws (the flat draws hold what the camera sees).
let shadow = terrain
.as_ref()
.and_then(|_| geometry_with(&plan.shadow, Some(0.1), &[false]));
let shadow_water = shadow
.as_ref()
.and_then(|_| geometry_with(&plan.shadow_water, None, &[false]));
let translucent_at = early.clone().count() + plan.deferred.len();
let blends = |g: &Option<GeometryProgram>, default| {
g.as_ref().map_or_else(Vec::new, |g| {
@@ -164,6 +190,9 @@ pub fn load(
})
};
let terrain_blends = blends(&terrain, None);
// Iris's shadow programs don't blend (`BlendModeOverride.OFF`).
let shadow_blends = blends(&shadow, None);
let shadow_water_blends = blends(&shadow_water, None);
// Vanilla's translucent blending (`BlendFunction.TRANSLUCENT`).
let water_blends = blends(
&water,
@@ -195,6 +224,12 @@ pub fn load(
flipped_after_translucent: plan.flipped_after_translucent,
terrain_blends,
water_blends,
shadow,
shadow_water,
shadow_targets: plan.shadow_targets,
shadow_blends,
shadow_water_blends,
shadow_at: plan.begin.len(),
});
}
if folders.is_empty() {
@@ -324,10 +359,13 @@ 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));
let geometry = pack.folders.iter().flat_map(|f| {
f.terrain
.iter()
.chain(&f.water)
.chain(&f.shadow)
.chain(&f.shadow_water)
});
passes
.flat_map(|p| [(p, &p.vertex, "vsh"), (p, &p.fragment, "fsh")])
.chain(geometry.flat_map(|g| {
@@ -379,6 +417,8 @@ mod tests {
.terrain
.iter()
.chain(&f.water)
.chain(&f.shadow)
.chain(&f.shadow_water)
.map(|g| g.program.pass.program.as_str())
.collect();
format!("{} {n} passes, terrain {geometry:?}", f.folder)
+133
View File
@@ -325,6 +325,74 @@ pub struct Passes {
/// The program its translucent terrain is drawn with
/// ([`WATER_PROGRAMS`]), after `deferred`.
pub water: Option<Pass>,
/// The programs the shadow map's solid and translucent terrain are
/// drawn with ([`SHADOW_PROGRAMS`], [`SHADOW_WATER_PROGRAMS`]), after
/// `begin`. Their draw buffers are `shadowcolor` targets.
pub shadow: Option<Pass>,
pub shadow_water: Option<Pass>,
/// `shadowcolor0..7`: white and cleared each frame unless the pack
/// says otherwise.
pub shadow_targets: Vec<TargetSettings>,
}
/// The programs Iris draws the shadow map's solid terrain with. Horizon's
/// solid layer holds cutout blocks too, so `shadow_cutout` (with its alpha
/// test) comes first.
pub const SHADOW_PROGRAMS: &[&str] = &["shadow_cutout", "shadow", "shadow_solid"];
/// The programs Iris draws the shadow map's translucent terrain with.
pub const SHADOW_WATER_PROGRAMS: &[&str] = &["shadow_water", "shadow"];
/// How many `shadowcolor` targets Iris has.
pub const MAX_SHADOW_COLOR_BUFFERS: u32 = 8;
/// `shadowcolor<N>Format`, `Clear` and `ClearColor` from `fragments`.
pub fn shadow_target_settings<'a>(
fragments: impl IntoIterator<Item = &'a str>,
) -> Vec<TargetSettings> {
let mut targets = vec![
TargetSettings {
clear_color: Some([1.0; 4]),
..TargetSettings::default()
};
MAX_SHADOW_COLOR_BUFFERS as usize
];
let key = |key: &str, suffix: &str| {
let i: u32 = key
.strip_prefix("shadowcolor")?
.strip_suffix(suffix)?
.parse()
.ok()?;
(i < MAX_SHADOW_COLOR_BUFFERS).then_some(i as usize)
};
for fragment in fragments {
for c in const_directives(fragment) {
match c.ty {
"int" => {
if let Some(i) = key(&c.key, "Format") {
let format = c.value.to_uppercase();
if TEXTURE_FORMATS.contains(&format.as_str()) {
targets[i].format = format;
}
}
}
"bool" => {
if let (Some(i), Ok(clear)) = (key(&c.key, "Clear"), c.value.parse()) {
targets[i].clear = clear;
}
}
"vec4" => {
if let (Some(i), Some(color)) =
(key(&c.key, "ClearColor"), parse_vec4(&c.value))
{
targets[i].clear_color = Some(color);
}
}
_ => {}
}
}
}
targets
}
/// The programs Iris draws solid terrain with, the first the pack has
@@ -356,6 +424,7 @@ pub struct Directives {
pub sun_path_rotation: f32,
/// `eyeBrightnessHalflife`, tenths of a second: `eyeBrightnessSmooth`.
pub eye_brightness_half_life: f32,
pub shadow: ShadowDirectives,
}
impl Default for Directives {
@@ -363,6 +432,35 @@ impl Default for Directives {
Self {
sun_path_rotation: 0.0,
eye_brightness_half_life: 10.0,
shadow: ShadowDirectives::default(),
}
}
}
/// The shadow map's `const` directives (`PackShadowDirectives`), with
/// Iris's defaults.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ShadowDirectives {
/// `shadowMapResolution`: the shadow targets' width and height.
pub resolution: u32,
/// `shadowDistance`: half the side of the orthographic projection.
pub distance: f32,
/// `shadowNearPlane` and `shadowFarPlane` (`ShadowMatrices.NEAR`/`FAR`).
pub near: f32,
pub far: f32,
/// `shadowIntervalSize`: the light's view snaps to a grid this size as
/// the camera moves, so shadows don't shimmer.
pub interval: f32,
}
impl Default for ShadowDirectives {
fn default() -> Self {
Self {
resolution: 1024,
distance: 160.0,
near: -100.05,
far: 156.0,
interval: 2.0,
}
}
}
@@ -378,6 +476,13 @@ impl Directives {
match (c.ty, c.key.as_str(), value) {
("float", "sunPathRotation", Ok(v)) => out.sun_path_rotation = v,
("float", "eyeBrightnessHalflife", Ok(v)) => out.eye_brightness_half_life = v,
("int", "shadowMapResolution", Ok(v)) if v >= 1.0 => {
out.shadow.resolution = v as u32;
}
("float", "shadowDistance", Ok(v)) => out.shadow.distance = v,
("float", "shadowNearPlane", Ok(v)) => out.shadow.near = v,
("float", "shadowFarPlane", Ok(v)) => out.shadow.far = v,
("float", "shadowIntervalSize", Ok(v)) => out.shadow.interval = v,
_ => {}
}
}
@@ -501,6 +606,7 @@ impl JavaPack {
}
let mut out = Passes {
targets: target_settings(sources.iter().map(String::as_str), properties),
shadow_targets: shadow_target_settings(sources.iter().map(String::as_str)),
directives: Directives::read(sources.iter().map(String::as_str)),
..Passes::default()
};
@@ -529,6 +635,7 @@ impl JavaPack {
};
let mut flipped = BTreeSet::new();
out.begin = run(&groups[0], "begin_pre", &mut flipped)?;
let flipped_after_begin = flipped.clone();
out.prepare = run(&groups[1], "prepare_pre", &mut flipped)?;
out.flipped_after_prepare = flipped.clone();
out.deferred = run(&groups[2], "deferred_pre", &mut flipped)?;
@@ -551,6 +658,8 @@ impl JavaPack {
};
out.terrain = geometry(TERRAIN_PROGRAMS, &out.flipped_after_prepare)?;
out.water = geometry(WATER_PROGRAMS, &out.flipped_after_translucent)?;
out.shadow = geometry(SHADOW_PROGRAMS, &flipped_after_begin)?;
out.shadow_water = geometry(SHADOW_WATER_PROGRAMS, &flipped_after_begin)?;
if exists("final") {
out.final_pass = Some(Pass {
program: path("final"),
@@ -849,6 +958,30 @@ mod tests {
assert_eq!(d.eye_brightness_half_life, 4.0);
}
#[test]
fn shadow_directives_and_targets() {
let text = "\
const int shadowMapResolution = 2048;
const float shadowDistance = 128.0;
const float shadowIntervalSize = 3.0;
const bool shadowcolor0Clear = false;
const int shadowcolor1Format = RGBA16;
const vec4 shadowcolor1ClearColor = vec4(0.0, 0.0, 0.0, 0.0);
";
let d = Directives::read([text]);
assert_eq!(d.shadow.resolution, 2048);
assert_eq!(d.shadow.distance, 128.0);
assert_eq!(d.shadow.interval, 3.0);
assert_eq!(d.shadow.near, ShadowDirectives::default().near);
let targets = shadow_target_settings([text]);
assert!(!targets[0].clear);
assert_eq!(targets[1].format, "RGBA16");
assert_eq!(targets[1].clear_color, Some([0.0; 4]));
// Iris clears the others to white.
assert_eq!(targets[2].clear_color, Some([1.0; 4]));
assert!(targets[2].clear);
}
#[test]
fn const_directives_and_target_settings() {
let text = "\
+27 -7
View File
@@ -23,7 +23,8 @@ Both are off by default. With no pack selected the renderer draws exactly what i
| 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: custom uniforms (`horizon_shaderpack::uniforms`), `sunPathRotation`, `clouds`/`sun`/`moon`, eye light | done for the full-screen passes (below) |
| 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`, custom textures, images, compute, option screen | planned |
| Java shader packs: `shadow` programs (`gfx/java_stages.rs`: the shadow map from Horizon's terrain) | first slice: terrain shadows for MakeUp Ultra Fast, Chocapic13' and BSL (below) |
| Java shader packs: other `gbuffers_*`, entity shadows, `shadowcomp`, custom textures, images, compute, option screen | planned |
## How the renderer draws a frame today
@@ -371,6 +372,24 @@ Occlusion culling works as in Horizon's world pass where the GPU has it: the pac
sections the last test saw, the boxes of the others are tested against that depth (in OpenGL's layout, in a pass of
their own since the pack's targets vary), and the pack's program then draws the ones in sight.
When the pack has a `shadow` program (`shadow_cutout`, `shadow` or `shadow_solid` for the solid layer, which holds
cutout blocks; `shadow_water` or `shadow` for the translucent one), it draws a shadow map after `begin*`, as Iris's
`ShadowRenderer`:
- the light's matrices are Iris's `ShadowMatrices`: `shadowModelView` turns camera-relative positions toward the sun
(the moon at night) with the pack's `sunPathRotation`, snapped to `shadowIntervalSize`; `shadowProjection` is
orthographic, `shadowDistance` each way, between `shadowNearPlane` and `shadowFarPlane` (Iris's defaults when the
pack sets none); the shadow programs get them as `gl_ModelViewMatrix` and `gl_ProjectionMatrix`;
- the renderer draws every section inside that box from its own list (not the camera's: cave culling is off as in
Iris, and no face is culled), solid then translucent, instanced draws only;
- `shadowtex0` holds all of it, `shadowtex1` the depth before translucent terrain; both are bound as depth textures
for `sampler2DShadow` (linear comparison, Iris's hardware filtering) and as float copies for `sampler2D` reads;
- `shadowcolor0..7` are `shadowMapResolution` square in their `shadowcolor<N>Format`, cleared each frame to
`shadowcolor<N>ClearColor` (white by default) unless `shadowcolor<N>Clear` is false.
A shadow program that doesn't translate or that wgpu refuses leaves the pack without its shadow map, with a warning:
the terrain programs still run and every `shadowtex` reads as far (nothing in shadow).
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
@@ -402,9 +421,10 @@ 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` (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. Not supported yet: images and
Without the other `gbuffers_*`, no pack has its own sky yet, and only terrain casts shadows; 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, the option screen; shadow matrices are identity. With the pack's terrain: entities, the
ignored), custom textures, the option screen, `shadowcomp` passes, `shadowMapFov` (a perspective shadow map),
`shadow.culling` and `shadowDistanceRenderMul` (the box above is the only bound). With the pack's terrain: entities, the
sky, the hand, weather and clouds are still Horizon's (in `colortex0` only), 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.
@@ -415,8 +435,8 @@ 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. Full-screen passes, `gbuffers_terrain` and `gbuffers_water` run (above); no pack has its own
shadows, entities or sky yet.
and screenshotted. Full-screen passes, `gbuffers_terrain`, `gbuffers_water` and the terrain's shadow map run
(above); no pack has its own entities or sky yet.
| Pack | Version | Result | First thing that stops it |
| --- | --- | --- | --- |
@@ -472,7 +492,7 @@ What the translator does for these packs, as Iris (JCPP and its GLSL transformer
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.
6. **Shadow pass** (terrain done, above): entities and block entities from the sun into `shadowtex0/1` and
`shadowcolor0/1`, culled from the light's view, with the pack's distortion; `shadowcomp`.
7. **The rest**: custom textures, compute programs and images, per-dimension
folders, `entity.properties`/`item.properties`.