diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index e99f42ada..1b60f8f0a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -6628,12 +6628,25 @@ impl Game<'_> { self.tick_player_model(); Ok(()) } + /// What the loaded Java shader pack changes in this dimension's vanilla + /// sky (`sunPathRotation`, `clouds`, `sun`, `moon`); `None` without one. + fn java_sky(&self) -> Option<(f32, horizon_shaderpack::properties::SkyDirectives)> { + self.shader_packs.java_sky(match self.dim { + Dim::Overworld => 0, + Dim::Nether => -1, + Dim::End => 1, + }) + } /// SkyRenderer.renderSunMoonAndStars: bodies on a frame rotated Y -90 then X by angle. + /// A Java pack's `sunPathRotation` tilts it about Z in between, and its + /// `sun = false` / `moon = false` leave those out, as Iris does. fn celestial_geometry(&self, sky: &horizon_client::environment::Sky) -> Vec { let mut out = Vec::new(); let atlas = &self.gui.atlas; + let (tilt, keep) = self.java_sky().unwrap_or_default(); let frame = |angle: f32| { glam::Mat4::from_rotation_y((-90.0f32).to_radians()) + * glam::Mat4::from_rotation_z(tilt.to_radians()) * glam::Mat4::from_rotation_x(angle.to_radians()) }; let mut body = |name: &str, angle: f32, size: f32, color: u32| { @@ -6655,12 +6668,14 @@ impl Game<'_> { }); } }; - body( - "environment/celestial/sun", - sky.sun_angle, - 30.0, - 0xFFFF_FFFF, - ); + if keep.sun { + body( + "environment/celestial/sun", + sky.sun_angle, + 30.0, + 0xFFFF_FFFF, + ); + } let phases = [ "full_moon", "waning_gibbous", @@ -6672,12 +6687,14 @@ impl Game<'_> { "waxing_gibbous", ]; let phase = phases[(self.world.day_time / 24000).rem_euclid(8) as usize]; - body( - &format!("environment/celestial/moon/{phase}"), - sky.moon_angle, - 20.0, - 0xFFFF_FFFF, - ); + if keep.moon { + body( + &format!("environment/celestial/moon/{phase}"), + sky.moon_angle, + 20.0, + 0xFFFF_FFFF, + ); + } if sky.star_brightness > 0.0 { let b = (sky.star_brightness.clamp(0.0, 1.0) * 255.0) as u32; let color = b << 24 | b << 16 | b << 8 | b; @@ -9244,6 +9261,18 @@ impl Game<'_> { entities.extend(dragon); } } + // A Java pack's `clouds` replaces the cloud option (`renderClouds`: + // "false", "fast", "true"), as Iris overrides `getCloudsType`. + let clouds_mode = { + use horizon_shaderpack::properties::CloudSetting; + match self.java_sky().and_then(|(_, sky)| sky.clouds) { + Some(CloudSetting::Off) => "false", + Some(CloudSetting::Fast) => "fast", + Some(CloudSetting::Fancy) => "true", + None => self.settings.clouds.as_str(), + } + .to_owned() + }; let celestial = if title && !live { Vec::new() } else if self.dim == Dim::Overworld @@ -9330,7 +9359,7 @@ impl Game<'_> { hud: &hud, clouds: ((!title || live) && self.dim == Dim::Overworld - && horizon_client::clouds::visible(&self.settings.clouds, sky.cloud_color[3])) + && horizon_client::clouds::visible(&clouds_mode, sky.cloud_color[3])) .then(|| self.gui.atlas.sprites.get("horizon/white")) .flatten() .map(|white| horizon_client::clouds::Input { @@ -9340,7 +9369,7 @@ impl Game<'_> { time: self.world.game_time, partial_tick: alpha, range: self.settings.cloud_range, - fast: self.settings.clouds == "fast", + fast: clouds_mode == "fast", color: sky.cloud_color, }), entities: &entities, diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index ba07755b9..1feb1236e 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -121,6 +121,11 @@ impl Game<'_> { }; let at = [camera.x, camera.y, camera.z]; let day = self.world.day_time; + let has_sky_light = self.dim == Dim::Overworld; + // CommonUniforms.getEyeBrightness: the camera entity's eye block. + let eye = self.eye_position().unwrap_or(at).map(|v| v.floor() as i32); + let light = self.world.light(eye[0], eye[1], eye[2]); + let eye_light = [light & 15, if has_sky_light { light >> 4 } else { 0 }]; horizon_client::gfx::ShaderInputs { rain, thunder, @@ -135,10 +140,11 @@ impl Game<'_> { Dim::Nether => -1, Dim::End => 1, }, - has_sky_light: self.dim == Dim::Overworld, + has_sky_light, moon_phase: day.div_euclid(24_000).rem_euclid(8) as u8, day_fraction: (day.rem_euclid(24_000) as f32 + partial_tick) / 24_000.0, partial_tick, + eye_light, } } /// `SkyRenderer.shouldRenderDarkDisc`: eye below the horizon (y 63) and not under water. diff --git a/crates/horizon-client/src/game/shader_packs.rs b/crates/horizon-client/src/game/shader_packs.rs index da4e8f594..6b9ee33dc 100644 --- a/crates/horizon-client/src/game/shader_packs.rs +++ b/crates/horizon-client/src/game/shader_packs.rs @@ -6,6 +6,7 @@ use super::Game; use horizon_client::shader_pack::{self, ShaderPack, Stamp}; use horizon_client::text::Text; +use horizon_shaderpack::properties::SkyDirectives; use std::{ path::PathBuf, time::{Duration, Instant}, @@ -26,6 +27,14 @@ impl ShaderPacks { pub(super) fn id(&self) -> Option<&str> { self.pack.as_ref().map(|p| p.id.as_str()) } + /// What a loaded Java pack changes in the vanilla sky of `dimension` + /// (0 overworld, -1 the Nether, 1 the End): its `sunPathRotation`, and + /// whether it keeps the clouds, sun and moon (Iris's sky mixins). + pub(super) fn java_sky(&self, dimension: i8) -> Option<(f32, SkyDirectives)> { + let java = self.pack.as_ref()?.java.as_ref()?; + let folder = &java.folders[java.folder_for(dimension)?]; + Some((folder.directives.sun_path_rotation, java.sky)) + } } /// `shaderpacks/` beside `options.txt`. diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 31a1c9e72..e7fbd2d91 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -238,6 +238,9 @@ pub struct ShaderInputs { /// The time of day as a fraction (0 sunrise, 0.25 noon) and the partial tick. pub day_fraction: f32, pub partial_tick: f32, + /// The block and sky light (0..15) of the block holding the camera + /// entity's eyes; no sky light without a sky. + pub eye_light: [u8; 2], } /// One frame of the world border wall (`WorldBorderRenderer.render`). #[derive(Clone, Debug)] @@ -3552,6 +3555,11 @@ impl Renderer { size, &self.world_post, pack_uniform, + java_stages::JavaFrame { + eye_light: frame.shader.eye_light, + sun_angle: frame.sky.sun_angle, + moon_angle: frame.sky.moon_angle, + }, ), }; self.world_post diff --git a/crates/horizon-client/src/gfx/java_stages.rs b/crates/horizon-client/src/gfx/java_stages.rs index d3e393e07..e9f8ddbb1 100644 --- a/crates/horizon-client/src/gfx/java_stages.rs +++ b/crates/horizon-client/src/gfx/java_stages.rs @@ -11,8 +11,21 @@ use super::pack_stages::FrameUniform; use crate::java_pack::{JavaFolder, JavaPasses}; use glam::{Mat3, Mat4, Vec3, Vec4}; use horizon_shaderpack::pipeline::TargetSettings; -use horizon_shaderpack::pipeline::{Program, target_index}; -use std::collections::{BTreeMap, BTreeSet}; +use horizon_shaderpack::pipeline::{Directives, Program, target_index}; +use horizon_shaderpack::uniforms::{CustomUniforms, SmoothFloat, UniformState}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; + +/// What Iris's uniforms read from the game that the frame uniform doesn't +/// carry. +#[derive(Clone, Copy, Debug, Default)] +pub struct JavaFrame { + /// The block and sky light at the camera's eye block, 0..15 + /// (`CommonUniforms.getEyeBrightness`). + pub eye_light: [u8; 2], + /// `visual/sun_angle` and `visual/moon_angle`, degrees (0: overhead). + pub sun_angle: f32, + pub moon_angle: f32, +} /// Iris's `noisetex` size (`noiseTextureResolution`'s default). const NOISE_SIZE: u32 = 256; @@ -203,6 +216,7 @@ struct Folder { flipped_at_end: BTreeSet, passes: Vec, final_pass: Option, + directives: Directives, } pub struct JavaStages { @@ -216,6 +230,10 @@ pub struct JavaStages { last: Option, frames: u32, previous: Option<(Mat4, Mat4, Vec3)>, + uniforms: CustomUniforms, + uniform_state: UniformState, + /// `eyeBrightnessSmooth`, block then sky. + eye_smooth: [SmoothFloat; 2], } impl JavaStages { @@ -256,6 +274,7 @@ impl JavaStages { flipped_at_end: plan.flipped_at_end.clone(), passes, final_pass, + directives: plan.directives, }) }) .collect::, _>>()?; @@ -273,6 +292,9 @@ impl JavaStages { last: None, frames: 0, previous: None, + uniforms: pack.uniforms.clone(), + uniform_state: UniformState::default(), + eye_smooth: [SmoothFloat::default(); 2], }) } @@ -289,6 +311,7 @@ impl JavaStages { size: [u32; 2], post: &super::world_post::Post, frame: FrameUniform, + world: JavaFrame, ) -> &wgpu::BindGroup { let dimension = (frame.dimension[0] as i32).clamp(-1, 1); let folder = self.folder_for[(dimension + 1) as usize].unwrap_or(0); @@ -302,7 +325,8 @@ impl JavaStages { let now = std::time::Instant::now(); let frame_time = self.last.map_or(0.0, |t| (now - t).as_secs_f32()); self.last = Some(now); - let inputs = Inputs::new( + let directives = self.folders[folder].directives; + let mut inputs = Inputs::new( &frame, size, self.started.elapsed().as_secs_f32(), @@ -310,6 +334,16 @@ impl JavaStages { self.frames, self.previous, ); + inputs.set_world(&world, directives.sun_path_rotation); + let half_life = directives.eye_brightness_half_life; + for (i, smooth) in self.eye_smooth.iter_mut().enumerate() { + inputs.eye_smooth[i] = smooth.update(inputs.eye[i], half_life, half_life, frame_time); + } + self.uniforms + .update(&mut self.uniform_state, frame_time, &|name| { + inputs.builtin(name) + }); + inputs.custom = self.uniform_state.values().clone(); self.previous = Some((inputs.view, inputs.projection, inputs.camera)); self.frames = self.frames.wrapping_add(1); let bound = self.bound.as_ref().expect("bound above"); @@ -1405,6 +1439,32 @@ struct Inputs { frame_time: f32, frames: u32, frame: FrameUniform, + /// `eyeBrightness` and `eyeBrightnessSmooth`: block, sky light × 16. + eye: [f32; 2], + eye_smooth: [f32; 2], + /// `CelestialUniforms`, in view space. + sun_position: Vec3, + moon_position: Vec3, + up_position: Vec3, + /// `sunAngle` and `shadowAngle`, 0..1. + sun_angle: f32, + shadow_angle: f32, + is_day: bool, + /// The pack's custom uniforms this frame. + custom: HashMap>, +} + +/// `CelestialUniforms.getSunAngle`: the body's angle plus 90, in 0..360 +/// (0 at sunrise for the sun). +fn celestial_angle(degrees: f32) -> f32 { + let c = degrees + 90.0; + if c < 0.0 { + c + 360.0 + } else if c > 360.0 { + c - 360.0 + } else { + c + } } impl Inputs { @@ -1427,7 +1487,7 @@ impl Inputs { ); let projection = to_gl * Mat4::from_cols_array_2d(&frame.projection); let camera = Vec4::from(frame.camera_position).truncate(); - Self { + let mut out = Self { view, projection, camera, @@ -1437,20 +1497,64 @@ impl Inputs { frame_time, frames, frame: *frame, - } + eye: [0.0; 2], + eye_smooth: [0.0; 2], + sun_position: Vec3::ZERO, + moon_position: Vec3::ZERO, + up_position: Vec3::ZERO, + sun_angle: 0.0, + shadow_angle: 0.0, + is_day: true, + custom: HashMap::new(), + }; + out.set_world(&JavaFrame::default(), 0.0); + out } - /// The value of Iris uniform `name`, as its scalars in order; `None` for - /// one Horizon doesn't provide (it stays zero). + /// The light at the eye and the sun and moon, tilted by the pack's + /// `sunPathRotation` as Iris tilts them. + fn set_world(&mut self, world: &JavaFrame, sun_path_rotation: f32) { + self.eye = world.eye_light.map(|l| f32::from(l) * 16.0); + self.eye_smooth = self.eye; + // CelestialUniforms.getCelestialPosition: the sky's Y -90, the + // tilt, the body's angle, then (0, 100, 0) as a point. + let sky = self.view * Mat4::from_rotation_y((-90f32).to_radians()); + let body = |angle: f32| { + let m = sky + * Mat4::from_rotation_z(sun_path_rotation.to_radians()) + * Mat4::from_rotation_x(angle.to_radians()); + m.transform_point3(Vec3::new(0.0, 100.0, 0.0)) + }; + self.sun_position = body(world.sun_angle); + self.moon_position = body(world.moon_angle); + self.up_position = sky.transform_vector3(Vec3::new(0.0, 100.0, 0.0)); + 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; + } + + /// The value of uniform `name`, as its scalars in order: Iris's own, + /// else the pack's custom uniform; `None` for one Horizon doesn't + /// provide (it stays zero). fn value(&self, name: &str) -> Option> { + self.builtin(name) + .or_else(|| self.custom.get(name).cloned()) + } + + /// The value of Iris uniform `name`; `None` for one Horizon doesn't + /// provide. + fn builtin(&self, name: &str) -> Option> { if let Some(flag) = name.strip_prefix("iris_bool_") { return self.value(flag); } let f = &self.frame; let mat = |m: Mat4| m.to_cols_array().to_vec(); let vec3 = |v: Vec3| v.to_array().to_vec(); - let in_view = |v: Vec3| (self.view * v.extend(0.0)).truncate() * 100.0; - let sun = Vec4::from(f.sun).truncate(); let day = f.time[2].rem_euclid(1.0); // The full-screen passes' own matrices: 0..1 onto the screen. let screen = Mat4::orthographic_rh_gl(0.0, 1.0, 0.0, 1.0, -1.0, 1.0); @@ -1476,12 +1580,16 @@ impl Inputs { "frameCounter" => vec![(self.frames % 720_720) as f32], "worldTime" => vec![(day * 24000.0).floor()], "worldDay" => vec![0.0], - "sunAngle" => vec![day], - "shadowAngle" => vec![if day < 0.5 { day } else { day - 0.5 }], - "sunPosition" => vec3(in_view(sun)), - "moonPosition" => vec3(in_view(-sun)), - "shadowLightPosition" => vec3(in_view(if sun.y >= 0.0 { sun } else { -sun })), - "upPosition" => vec3(in_view(Vec3::Y)), + "sunAngle" => vec![self.sun_angle], + "shadowAngle" => vec![self.shadow_angle], + "sunPosition" => vec3(self.sun_position), + "moonPosition" => vec3(self.moon_position), + "shadowLightPosition" => vec3(if self.is_day { + self.sun_position + } else { + self.moon_position + }), + "upPosition" => vec3(self.up_position), "moonPhase" => vec![f.moon[3]], "rainStrength" | "wetness" => vec![f.weather[0]], "thunderStrength" => vec![f.weather[1]], @@ -1491,9 +1599,9 @@ impl Inputs { "nightVision" => vec![f.camera_state[1]], "darknessFactor" => vec![f.camera_state[2]], "screenBrightness" => vec![1.0], - // Sky light at full with a sky, no block light: Horizon doesn't - // give the light at the eye yet. - "eyeBrightness" | "eyeBrightnessSmooth" => vec![0.0, 240.0 * f.dimension[1]], + "eyeBrightness" => self.eye.to_vec(), + // An ivec2: the smoothed value truncated. + "eyeBrightnessSmooth" => self.eye_smooth.map(f32::trunc).to_vec(), "hasSkylight" => vec![f.dimension[1]], "iris_ModelViewMatrix" | "iris_ModelViewMatrixInverse" => mat(Mat4::IDENTITY), "iris_ProjectionMatrix" | "iris_ModelViewProjectionMatrix" => mat(screen), @@ -1559,6 +1667,60 @@ mod tests { ); } + #[test] + fn celestial_and_eye_uniforms_follow_iris() { + let frame = FrameUniform { + view: Mat4::IDENTITY.to_cols_array_2d(), + ..Default::default() + }; + let close = |a: Option>, b: [f32; 3]| { + let a = a.unwrap(); + assert!( + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3), + "{a:?} != {b:?}" + ); + }; + let mut inputs = Inputs::new(&frame, [300, 200], 0.0, 0.0, 0, None); + // Sunrise: the sun in the east, at angle 0; the moon in the west. + let world = |sun_angle: f32| JavaFrame { + eye_light: [3, 15], + sun_angle, + moon_angle: sun_angle + 180.0, + }; + inputs.set_world(&world(-90.0), 0.0); + close(inputs.value("sunPosition"), [100.0, 0.0, 0.0]); + close(inputs.value("moonPosition"), [-100.0, 0.0, 0.0]); + close(inputs.value("upPosition"), [0.0, 100.0, 0.0]); + assert_eq!(inputs.value("sunAngle"), Some(vec![0.0])); + assert_eq!(inputs.value("eyeBrightness"), Some(vec![48.0, 240.0])); + // Complementary Unbound's sunPathRotation of -40 at noon: the sun + // where its GetSunVector puts it, (0, cos 40, sin 40). + let tilt = (-40f32).to_radians(); + inputs.set_world(&world(0.0), -40.0); + close( + inputs.value("sunPosition"), + [0.0, 100.0 * tilt.cos(), -100.0 * tilt.sin()], + ); + assert_eq!(inputs.value("sunAngle"), Some(vec![0.25])); + close(inputs.value("shadowLightPosition"), { + let s = inputs.sun_position; + [s.x, s.y, s.z] + }); + // Night: the moon casts the shadows. + inputs.set_world(&world(150.0), 0.0); + assert!(!inputs.is_day); + assert_eq!( + inputs.value("shadowLightPosition"), + inputs.value("moonPosition") + ); + assert!((inputs.value("shadowAngle").unwrap()[0] - 60.0 / 360.0).abs() < 1e-6); + // Custom uniforms come after Iris's own. + inputs.custom.insert("eyeBrightnessM".into(), vec![0.5]); + inputs.custom.insert("sunAngle".into(), vec![9.0]); + assert_eq!(inputs.value("eyeBrightnessM"), Some(vec![0.5])); + assert_ne!(inputs.value("sunAngle"), Some(vec![9.0])); + } + #[test] fn gl_projection_from_reversed_depth() { // A point at the near plane is GL's -1, at the far plane 1. diff --git a/crates/horizon-client/src/java_pack.rs b/crates/horizon-client/src/java_pack.rs index f051cf2b6..fb170d152 100644 --- a/crates/horizon-client/src/java_pack.rs +++ b/crates/horizon-client/src/java_pack.rs @@ -6,8 +6,10 @@ //! `shadow`) don't run yet: the world is drawn by Horizon. use horizon_shaderpack::{ JavaPack, - pipeline::{Program, TargetSettings}, + pipeline::{Directives, Program, TargetSettings}, preprocess::Environment, + properties::SkyDirectives, + uniforms::CustomUniforms, }; use std::{ collections::{BTreeMap, BTreeSet}, @@ -28,11 +30,17 @@ pub struct JavaFolder { pub final_pass: Option, /// The targets whose alternate side holds the frame's last write. pub flipped_at_end: BTreeSet, + /// `sunPathRotation` and `eyeBrightnessHalflife`. + pub directives: Directives, } /// A loaded Java pack. pub struct JavaPasses { pub folders: Vec, + /// `uniform.*` / `variable.*` from `shaders.properties`. + pub uniforms: CustomUniforms, + /// What the pack keeps of the vanilla sky (`clouds`, `sun`, `moon`). + pub sky: SkyDirectives, } impl JavaPasses { @@ -122,12 +130,21 @@ pub fn load( flipped_after_prepare: plan.flipped_after_prepare, final_pass, flipped_at_end: plan.flipped_at_end, + directives: plan.directives, }); } if folders.is_empty() { return Err("no deferred, composite or final programs".into()); } - Ok(JavaPasses { folders }) + let uniforms = properties.custom_uniforms(); + for problem in &uniforms.problems { + log::warn!("Horizon: shader pack custom uniform {problem}"); + } + Ok(JavaPasses { + folders, + uniforms, + sky: properties.sky(), + }) } #[cfg(test)] diff --git a/crates/horizon-shaderpack/src/lib.rs b/crates/horizon-shaderpack/src/lib.rs index 0cfec68f9..71b6abbd3 100644 --- a/crates/horizon-shaderpack/src/lib.rs +++ b/crates/horizon-shaderpack/src/lib.rs @@ -12,6 +12,7 @@ pub mod preprocess; pub mod properties; pub mod source; pub mod translate; +pub mod uniforms; use include::{IncludeGraph, Inlined}; use options::{Annotated, OptionSet, OptionValues}; diff --git a/crates/horizon-shaderpack/src/pipeline.rs b/crates/horizon-shaderpack/src/pipeline.rs index dfff469c4..7ebb35442 100644 --- a/crates/horizon-shaderpack/src/pipeline.rs +++ b/crates/horizon-shaderpack/src/pipeline.rs @@ -318,6 +318,47 @@ pub struct Passes { /// After `final`, these targets' alternate side is copied back so the /// next frame starts unflipped. pub flipped_at_end: BTreeSet, + pub directives: Directives, +} + +/// 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)] +pub struct Directives { + /// `sunPathRotation`, degrees: how far the sun and moon's path tilts + /// toward the north or south (a Z rotation between the sky's Y -90 and + /// its angle, `CelestialUniforms`). + pub sun_path_rotation: f32, + /// `eyeBrightnessHalflife`, tenths of a second: `eyeBrightnessSmooth`. + pub eye_brightness_half_life: f32, +} + +impl Default for Directives { + fn default() -> Self { + Self { + sun_path_rotation: 0.0, + eye_brightness_half_life: 10.0, + } + } +} + +impl Directives { + /// Read from `fragments` in order, the last one winning. + pub fn read<'a>(fragments: impl IntoIterator) -> Self { + let mut out = Self::default(); + for fragment in fragments { + for c in const_directives(fragment) { + // Java's `Float.parseFloat` takes a trailing `f`. + let value = c.value.trim_end_matches(['f', 'F']).parse::(); + 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, + _ => {} + } + } + } + out + } } /// Iris's single programs (`ProgramId`), in order. @@ -435,6 +476,7 @@ impl JavaPack { } let mut out = Passes { targets: target_settings(sources.iter().map(String::as_str), properties), + directives: Directives::read(sources.iter().map(String::as_str)), ..Passes::default() }; @@ -689,6 +731,19 @@ mod tests { assert!(draw_buffers("/* DRAWBUFFERS:0a */").is_err()); } + #[test] + fn sky_directives_last_one_wins() { + assert_eq!(Directives::read([]), Directives::default()); + assert_eq!(Directives::default().eye_brightness_half_life, 10.0); + let d = Directives::read([ + "const float sunPathRotation = 30.0;\nconst float eyeBrightnessHalflife = 4.0f;", + "const float sunPathRotation = -40.0; // Complementary Unbound", + "const int sunPathRotation = 5;", + ]); + assert_eq!(d.sun_path_rotation, -40.0); + assert_eq!(d.eye_brightness_half_life, 4.0); + } + #[test] fn const_directives_and_target_settings() { let text = "\ diff --git a/crates/horizon-shaderpack/src/properties.rs b/crates/horizon-shaderpack/src/properties.rs index cc3069620..8c3f29c8f 100644 --- a/crates/horizon-shaderpack/src/properties.rs +++ b/crates/horizon-shaderpack/src/properties.rs @@ -307,6 +307,34 @@ fn parse_blend(value: &str) -> Result { } } +/// `clouds = off | fast | fancy`: replaces the player's cloud setting while +/// the pack runs (`ShaderProperties.cloudSetting`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CloudSetting { + Off, + Fast, + Fancy, +} + +/// The vanilla sky the pack keeps: Iris draws no clouds with `clouds = off`, +/// and no sun or moon with `sun = false` / `moon = false`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SkyDirectives { + pub clouds: Option, + pub sun: bool, + pub moon: bool, +} + +impl Default for SkyDirectives { + fn default() -> Self { + Self { + clouds: None, + sun: true, + moon: true, + } + } +} + /// A pack's `shaders.properties`. #[derive(Debug, Default)] pub struct ShaderProperties { @@ -484,6 +512,31 @@ impl ShaderProperties { .collect() } + /// `uniform.*` and `variable.*`: the pack's custom uniforms. + pub fn custom_uniforms(&self) -> crate::uniforms::CustomUniforms { + crate::uniforms::CustomUniforms::parse(self.preprocessed.iter()) + } + + /// `clouds`, `sun` and `moon`: what the pack does with the vanilla sky. + pub fn sky(&self) -> SkyDirectives { + let boolean = |key| { + !matches!( + self.preprocessed.get(key).map(str::trim), + Some("false" | "0") + ) + }; + SkyDirectives { + clouds: match self.preprocessed.get("clouds").map(str::trim) { + Some("off") => Some(CloudSetting::Off), + Some("fast") => Some(CloudSetting::Fast), + Some("fancy") => Some(CloudSetting::Fancy), + _ => None, + }, + sun: boolean("sun"), + moon: boolean("moon"), + } + } + /// `blend.`: the program's blend override. pub fn blend(&self, program: &str) -> Option> { self.preprocessed diff --git a/crates/horizon-shaderpack/src/uniforms.rs b/crates/horizon-shaderpack/src/uniforms.rs new file mode 100644 index 000000000..842aeb51f --- /dev/null +++ b/crates/horizon-shaderpack/src/uniforms.rs @@ -0,0 +1,838 @@ +//! Custom uniforms: `uniform.. = ` and +//! `variable.. = ` in `shaders.properties`, evaluated +//! once a frame the way Iris does (`CustomUniforms`, the `kroppeb.stareval` +//! parser, `IrisFunctions`, `SmoothFloat`). +//! +//! Values are lists of floats: one for `bool`, `int` and `float` (a bool is 0 +//! or 1), two to four for vectors. Iris types each expression; evaluating in +//! floats gives the same results for what packs write (its only integer +//! operations are `+ - * %`, exact in floats at these sizes; `/` is always a +//! float division). +//! +//! A definition Iris can't resolve (a syntax error, an unknown name or +//! function, a cycle) is left out, and so is every definition using it: the +//! shader's uniform keeps its default, zero. Here a name is unknown when it is +//! neither another definition nor a value the `builtin` lookup gives. + +use std::collections::HashMap; + +/// The custom uniforms and variables of a pack, in evaluation order. +#[derive(Clone, Debug, Default)] +pub struct CustomUniforms { + defs: Vec, + /// Evaluation order (indices into `defs`): dependencies first. + order: Vec, + /// What couldn't be parsed or resolved, for the log. + pub problems: Vec, +} + +#[derive(Clone, Debug)] +struct Def { + name: String, + /// Components of the result: 1, 2, 3 or 4. + size: usize, + /// `bool` (0 or 1) or `int` (truncated) rather than float. + kind: Kind, + /// `uniform.` (given to the shaders) rather than `variable.`. + uniform: bool, + expr: Expr, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Kind { + Bool, + Int, + Float, +} + +#[derive(Clone, Debug, PartialEq)] +enum Expr { + Number(f32), + Name(String), + /// A vector's component (`.x`, `.g`, `.t`, `.2`...). + Access(Box, usize), + Not(Box), + Negate(Box), + Binary(Op, Box, Box), + /// A function; `smooth` calls carry their own state slot. + Call(String, Vec, usize), +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Op { + Multiply, + Divide, + Remainder, + Add, + Subtract, + Equals, + NotEquals, + Less, + More, + LessOrEqual, + MoreOrEqual, + And, + Or, +} + +impl Op { + /// `IrisOptions`: lower binds tighter; equal priorities associate left. + fn priority(self) -> u8 { + match self { + Op::Multiply | Op::Divide | Op::Remainder => 0, + Op::Add | Op::Subtract => 1, + Op::Equals + | Op::NotEquals + | Op::Less + | Op::More + | Op::LessOrEqual + | Op::MoreOrEqual => 2, + Op::And | Op::Or => 3, + } + } +} + +/// The per-frame state: `smooth` accumulators, `random`'s generator and the +/// last values. +#[derive(Clone, Debug, Default)] +pub struct UniformState { + smooth: Vec, + seed: u64, + values: HashMap>, +} + +impl UniformState { + /// A uniform's value this frame; `None` for variables and for + /// definitions that couldn't be resolved. + pub fn get(&self, name: &str) -> Option<&[f32]> { + self.values.get(name).map(Vec::as_slice) + } + + /// Every uniform's value this frame, by name. + pub fn values(&self) -> &HashMap> { + &self.values + } +} + +impl CustomUniforms { + /// The definitions in `properties` (key, value), in file order. + pub fn parse<'a>(properties: impl IntoIterator) -> Self { + let mut out = Self::default(); + let mut smooth = 0; + for (key, value) in properties { + let (uniform, rest) = if let Some(rest) = key.strip_prefix("uniform.") { + (true, rest) + } else if let Some(rest) = key.strip_prefix("variable.") { + (false, rest) + } else { + continue; + }; + let Some((ty, name)) = rest.split_once('.') else { + continue; + }; + let (kind, size) = match ty { + "bool" => (Kind::Bool, 1), + "int" => (Kind::Int, 1), + "float" => (Kind::Float, 1), + "vec2" => (Kind::Float, 2), + "vec3" => (Kind::Float, 3), + "vec4" => (Kind::Float, 4), + _ => { + out.problems.push(format!("{key}: unknown type `{ty}`")); + continue; + } + }; + if out.defs.iter().any(|d| d.name == name) { + out.problems.push(format!("{key}: duplicated variable")); + continue; + } + match parse(value, &mut smooth) { + Ok(expr) => out.defs.push(Def { + name: name.to_owned(), + size, + kind, + uniform, + expr, + }), + Err(e) => out.problems.push(format!("{key}: {e} ( = {value})")), + } + } + out.order = out.sort(); + out + } + + /// Whether the pack defines none. + pub fn is_empty(&self) -> bool { + self.defs.is_empty() + } + + /// Dependencies first; a definition in a cycle is left out. + fn sort(&mut self) -> Vec { + let index: HashMap<&str, usize> = self + .defs + .iter() + .enumerate() + .map(|(i, d)| (d.name.as_str(), i)) + .collect(); + // 0 unvisited, 1 in progress, 2 done, 3 broken. + let mut mark = vec![0u8; self.defs.len()]; + let mut order = Vec::new(); + fn visit( + i: usize, + defs: &[Def], + index: &HashMap<&str, usize>, + mark: &mut [u8], + order: &mut Vec, + ) -> bool { + match mark[i] { + 1 | 3 => return false, + 2 => return true, + _ => {} + } + mark[i] = 1; + let mut names = Vec::new(); + defs[i].expr.names(&mut names); + let ok = names.iter().all(|n| match index.get(n.as_str()) { + Some(&j) => visit(j, defs, index, mark, order), + None => true, + }); + mark[i] = if ok { 2 } else { 3 }; + if ok { + order.push(i); + } + ok + } + for i in 0..self.defs.len() { + if !visit(i, &self.defs, &index, &mut mark, &mut order) && mark[i] == 3 { + self.problems + .push(format!("{}: circular reference", self.defs[i].name)); + } + } + order + } + + /// Evaluate every definition for this frame: `builtin` gives Iris's own + /// uniforms, `frame_time` (seconds) drives `smooth`. + pub fn update( + &self, + state: &mut UniformState, + frame_time: f32, + builtin: &dyn Fn(&str) -> Option>, + ) { + let mut values: HashMap<&str, Vec> = HashMap::new(); + let mut broken: Vec<&str> = Vec::new(); + state.values.clear(); + for &i in &self.order { + let def = &self.defs[i]; + let mut eval = Eval { + frame_time, + builtin, + values: &values, + broken: &broken, + smooth: &mut state.smooth, + seed: &mut state.seed, + }; + let Some(mut value) = eval.expr(&def.expr) else { + broken.push(&def.name); + continue; + }; + value.resize(def.size, value.last().copied().unwrap_or(0.0)); + match def.kind { + Kind::Bool => value[0] = f32::from(u8::from(value[0] != 0.0)), + Kind::Int => value[0] = value[0].trunc(), + Kind::Float => {} + } + if def.uniform { + state.values.insert(def.name.clone(), value.clone()); + } + values.insert(&def.name, value); + } + } +} + +impl Expr { + fn names(&self, out: &mut Vec) { + match self { + Expr::Number(_) => {} + Expr::Name(n) => out.push(n.clone()), + Expr::Access(e, _) | Expr::Not(e) | Expr::Negate(e) => e.names(out), + Expr::Binary(_, a, b) => { + a.names(out); + b.names(out); + } + Expr::Call(_, args, _) => args.iter().for_each(|a| a.names(out)), + } + } +} + +struct Eval<'a> { + frame_time: f32, + builtin: &'a dyn Fn(&str) -> Option>, + values: &'a HashMap<&'a str, Vec>, + broken: &'a [&'a str], + smooth: &'a mut Vec, + seed: &'a mut u64, +} + +/// Apply `f` component by component, a scalar standing for every component. +fn zip(args: &[Vec], f: impl Fn(&[f32]) -> f32) -> Vec { + let n = args.iter().map(Vec::len).max().unwrap_or(1); + (0..n) + .map(|i| { + let a: Vec = args + .iter() + .map(|v| { + if v.len() == 1 { + v[0] + } else { + v.get(i).copied().unwrap_or(0.0) + } + }) + .collect(); + f(&a) + }) + .collect() +} + +fn truth(b: bool) -> f32 { + f32::from(u8::from(b)) +} + +impl Eval<'_> { + fn expr(&mut self, e: &Expr) -> Option> { + Some(match e { + Expr::Number(n) => vec![*n], + Expr::Name(n) => self.name(n)?, + Expr::Access(e, i) => vec![*self.expr(e)?.get(*i)?], + Expr::Not(e) => zip(&[self.expr(e)?], |a| truth(a[0] == 0.0)), + Expr::Negate(e) => self.expr(e)?.iter().map(|v| -v).collect(), + Expr::Binary(op, a, b) => { + let a = self.expr(a)?; + let b = self.expr(b)?; + let f = |x: f32, y: f32| match op { + Op::Multiply => x * y, + Op::Divide => x / y, + // Java's `%`, on ints and floats: the sign of x. + Op::Remainder => x % y, + Op::Add => x + y, + Op::Subtract => x - y, + Op::Equals => truth(x == y), + Op::NotEquals => truth(x != y), + Op::Less => truth(x < y), + Op::More => truth(x > y), + Op::LessOrEqual => truth(x <= y), + Op::MoreOrEqual => truth(x >= y), + Op::And => truth(x != 0.0 && y != 0.0), + Op::Or => truth(x != 0.0 || y != 0.0), + }; + zip(&[a, b], |v| f(v[0], v[1])) + } + Expr::Call(name, args, slot) => self.call(name, args, *slot)?, + }) + } + + fn name(&self, n: &str) -> Option> { + if self.broken.contains(&n) { + return None; + } + if let Some(v) = self.values.get(n) { + return Some(v.clone()); + } + match n { + "true" => return Some(vec![1.0]), + "false" => return Some(vec![0.0]), + "pi" => return Some(vec![std::f32::consts::PI]), + _ => {} + } + (self.builtin)(n) + } + + fn random(&mut self) -> f32 { + // xorshift64*, seeded once. + if *self.seed == 0 { + *self.seed = 0x9E37_79B9_7F4A_7C15; + } + let mut x = *self.seed; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + *self.seed = x; + ((x.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 40) as f32) / (1u64 << 24) as f32 + } + + fn call(&mut self, name: &str, args: &[Expr], slot: usize) -> Option> { + // `if` evaluates only the branch it takes. + if name == "if" { + if args.len() < 3 || args.len() % 2 == 0 { + return None; + } + for pair in args[..args.len() - 1].chunks(2) { + if self.expr(&pair[0])?[0] != 0.0 { + return self.expr(&pair[1]); + } + } + return self.expr(&args[args.len() - 1]); + } + if name == "smooth" { + return self.smooth(args, slot); + } + let v: Vec> = args.iter().map(|a| self.expr(a)).collect::>()?; + let unary = |f: fn(f32) -> f32| { + (v.len() == 1).then(|| v[0].iter().map(|&x| f(x)).collect::>()) + }; + let n = v.len(); + Some(match (name, n) { + ("sin", 1) => unary(f32::sin)?, + ("cos", 1) => unary(f32::cos)?, + ("tan", 1) => unary(f32::tan)?, + ("asin", 1) => unary(f32::asin)?, + ("acos", 1) => unary(f32::acos)?, + ("atan", 1) => unary(f32::atan)?, + ("atan" | "atan2", 2) => zip(&v, |a| a[0].atan2(a[1])), + ("torad" | "radians", 1) => unary(f32::to_radians)?, + ("todeg" | "degrees", 1) => unary(f32::to_degrees)?, + ("pow", 2) => zip(&v, |a| a[0].powf(a[1])), + ("exp", 1) => unary(f32::exp)?, + ("exp2", 1) => unary(f32::exp2)?, + ("exp10", 1) => unary(|x| 10f32.powf(x))?, + ("log", 1) => unary(f32::ln)?, + ("log", 2) => zip(&v, |a| a[1].ln() / a[0].ln()), + ("log2", 1) => unary(f32::log2)?, + ("log10", 1) => unary(f32::log10)?, + ("sqrt", 1) => unary(f32::sqrt)?, + ("abs", 1) => unary(f32::abs)?, + // Math.signum: 0 stays 0. + ("sign" | "signum", 1) => unary(|x| if x == 0.0 { x } else { x.signum() })?, + ("floor", 1) => unary(f32::floor)?, + ("ceil", 1) => unary(f32::ceil)?, + ("frac", 1) => unary(|x| x - x.floor())?, + // Math.round: half up. + ("round", 1) => unary(|x| (x + 0.5).floor())?, + ("min", 2..) => zip(&v, |a| a.iter().copied().fold(f32::INFINITY, f32::min)), + ("max", 2..) => zip(&v, |a| a.iter().copied().fold(f32::NEG_INFINITY, f32::max)), + ("clamp", 3) => zip(&v, |a| a[0].max(a[1]).min(a[2])), + ("mix", 3) => zip(&v, |a| a[0] + (a[1] - a[0]) * a[2]), + ("edge", 2) => zip(&v, |a| truth(a[1] >= a[0])), + ("fmod", 2) => zip(&v, |a| (a[0] % a[1] + a[1]) % a[1]), + ("between", 3) => vec![truth(v[0][0] >= v[1][0] && v[0][0] <= v[2][0])], + ("equals", 3) => vec![truth((v[0][0] - v[1][0]).abs() <= v[2][0])], + ("in", 2..) => vec![truth(v[1..].iter().any(|x| x[0] == v[0][0]))], + ("random", 0) => vec![self.random()], + ("random", 2) => { + let r = self.random(); + vec![v[0][0] + r * (v[1][0] - v[0][0])] + } + ("vec2" | "ivec2" | "bvec2", 2) + | ("vec3" | "ivec3" | "bvec3", 3) + | ("vec4" | "ivec4" | "bvec4", 4) => { + let mut out: Vec = v.iter().map(|a| a[0]).collect(); + if name.starts_with('i') { + out.iter_mut().for_each(|x| *x = x.trunc()); + } else if name.starts_with('b') { + out.iter_mut().for_each(|x| *x = truth(*x != 0.0)); + } + out + } + _ => return None, + }) + } + + /// `smooth([id,] value[, fadeTime[, fadeDownTime]])`: the half-lives, in + /// tenths of a second, default to 1. A constant first argument of two or + /// three is OptiFine's id; with four it always is. + fn smooth(&mut self, args: &[Expr], slot: usize) -> Option> { + let id = matches!(args.first(), Some(Expr::Number(_))) && args.len() >= 2; + let args = if id || args.len() == 4 { + &args[1..] + } else { + args + }; + let value = self.expr(args.first()?)?[0]; + let up = match args.get(1) { + Some(e) => self.expr(e)?[0], + None => 1.0, + }; + let down = match args.get(2) { + Some(e) => self.expr(e)?[0], + None => up, + }; + if args.len() > 3 { + return None; + } + if self.smooth.len() <= slot { + self.smooth.resize(slot + 1, SmoothFloat::default()); + } + Some(vec![self.smooth[slot].update( + value, + up, + down, + self.frame_time, + )]) + } +} + +/// Iris's `SmoothFloat`: exponential smoothing with separate half-lives up +/// and down, in tenths of a second; the first value is taken as is. +#[derive(Clone, Copy, Debug, Default)] +pub struct SmoothFloat { + value: Option, +} + +impl SmoothFloat { + pub fn update(&mut self, target: f32, half_life_up: f32, half_life_down: f32, dt: f32) -> f32 { + let Some(acc) = self.value else { + self.value = Some(target); + return target; + }; + let half_life = if target > acc { + half_life_up + } else { + half_life_down + }; + let next = if half_life == 0.0 { + target + } else { + let decay = std::f32::consts::LN_2 / (half_life * 0.1); + let alpha = 1.0 - (-decay * dt).exp(); + (1.0 - alpha) * acc + alpha * target + }; + self.value = Some(next); + next + } +} + +/// Parse one expression; `smooth` counts the `smooth` calls so far (each +/// keeps its own state). +fn parse(text: &str, smooth: &mut usize) -> Result { + let tokens = tokenize(text)?; + let mut p = Parser { + tokens, + at: 0, + smooth, + }; + let e = p.binary(3)?; + match p.tokens.get(p.at) { + None => Ok(e), + Some(t) => Err(format!("unexpected {t:?}")), + } +} + +#[derive(Clone, Debug, PartialEq)] +enum Token { + Number(f32), + Id(String), + /// `.` followed by an accessor. + Access(String), + Op(String), + Open, + Close, + Comma, +} + +fn tokenize(text: &str) -> Result, String> { + let chars: Vec = text.chars().collect(); + let mut out = Vec::new(); + let mut i = 0; + let read_while = |i: &mut usize, f: &dyn Fn(char) -> bool| { + let start = *i; + while *i < chars.len() && f(chars[*i]) { + *i += 1; + } + chars[start..*i].iter().collect::() + }; + while i < chars.len() { + let c = chars[i]; + if c.is_whitespace() { + i += 1; + } else if c.is_ascii_alphabetic() || c == '_' { + out.push(Token::Id(read_while(&mut i, &|c| { + c.is_ascii_alphanumeric() || c == '_' + }))); + } else if c == '.' + && matches!( + out.last(), + Some(Token::Id(_) | Token::Close | Token::Access(_)) + ) + { + i += 1; + while i < chars.len() && chars[i].is_whitespace() { + i += 1; + } + let access = read_while(&mut i, &|c| c.is_ascii_alphanumeric() || c == '_'); + if access.is_empty() { + return Err("an expression can't end with `.`".into()); + } + out.push(Token::Access(access)); + } else if c.is_ascii_digit() || c == '.' { + let s = read_while(&mut i, &|c| c.is_ascii_alphanumeric() || c == '.'); + let n = s + .parse::() + .or_else(|_| s.trim_end_matches(['f', 'F']).parse::()) + .map_err(|_| format!("bad number `{s}`"))?; + out.push(Token::Number(n)); + } else if c == '(' { + out.push(Token::Open); + i += 1; + } else if c == ')' { + out.push(Token::Close); + i += 1; + } else if c == ',' { + out.push(Token::Comma); + i += 1; + } else { + let two: String = chars[i..(i + 2).min(chars.len())].iter().collect(); + let op = ["==", "!=", "<=", ">=", "&&", "||"] + .into_iter() + .find(|o| two == *o) + .map(str::to_owned) + .or_else(|| "*/%+-<>!≠≤≥".contains(c).then(|| c.to_string())) + .ok_or_else(|| format!("unexpected character `{c}`"))?; + i += op.chars().count(); + out.push(Token::Op(op)); + } + } + Ok(out) +} + +struct Parser<'a> { + tokens: Vec, + at: usize, + smooth: &'a mut usize, +} + +impl Parser<'_> { + fn next(&mut self) -> Option { + let t = self.tokens.get(self.at).cloned(); + self.at += 1; + t + } + + fn peek_op(&self) -> Option { + let Some(Token::Op(o)) = self.tokens.get(self.at) else { + return None; + }; + Some(match o.as_str() { + "*" => Op::Multiply, + "/" => Op::Divide, + "%" => Op::Remainder, + "+" => Op::Add, + "-" => Op::Subtract, + "==" => Op::Equals, + "!=" | "≠" => Op::NotEquals, + "<" => Op::Less, + ">" => Op::More, + "<=" | "≤" => Op::LessOrEqual, + ">=" | "≥" => Op::MoreOrEqual, + "&&" => Op::And, + "||" => Op::Or, + _ => return None, + }) + } + + /// Operators of priority `max` or tighter, left to right. + fn binary(&mut self, max: u8) -> Result { + let mut left = self.unary()?; + while let Some(op) = self.peek_op() { + let p = op.priority(); + if p > max { + break; + } + self.at += 1; + // The right side takes only tighter operators: equal priorities + // associate to the left. + let right = if p == 0 { + self.unary()? + } else { + self.binary(p - 1)? + }; + left = Expr::Binary(op, Box::new(left), Box::new(right)); + } + Ok(left) + } + + /// Prefix `!` and `-`, which bind tighter than any binary operator. + fn unary(&mut self) -> Result { + match self.tokens.get(self.at) { + Some(Token::Op(o)) if o == "!" => { + self.at += 1; + Ok(Expr::Not(Box::new(self.unary()?))) + } + Some(Token::Op(o)) if o == "-" => { + self.at += 1; + Ok(Expr::Negate(Box::new(self.unary()?))) + } + _ => self.postfix(), + } + } + + fn postfix(&mut self) -> Result { + let mut e = match self.next() { + Some(Token::Number(n)) => Expr::Number(n), + Some(Token::Id(id)) if self.tokens.get(self.at) == Some(&Token::Open) => { + self.at += 1; + let mut args = Vec::new(); + if self.tokens.get(self.at) == Some(&Token::Close) { + self.at += 1; + } else { + loop { + args.push(self.binary(3)?); + match self.next() { + Some(Token::Comma) => {} + Some(Token::Close) => break, + t => return Err(format!("expected `,` or `)`, found {t:?}")), + } + } + } + let slot = *self.smooth; + if id == "smooth" { + *self.smooth += 1; + } + Expr::Call(id, args, slot) + } + Some(Token::Id(id)) => Expr::Name(id), + Some(Token::Open) => { + let e = self.binary(3)?; + match self.next() { + Some(Token::Close) => e, + t => return Err(format!("expected `)`, found {t:?}")), + } + } + t => return Err(format!("expected a value, found {t:?}")), + }; + while let Some(Token::Access(a)) = self.tokens.get(self.at) { + let i = match a.as_str() { + "x" | "r" | "s" | "0" => 0, + "y" | "g" | "t" | "1" => 1, + "z" | "b" | "p" | "2" => 2, + "w" | "a" | "q" | "3" => 3, + _ => return Err(format!("unknown accessor `.{a}`")), + }; + self.at += 1; + e = Expr::Access(Box::new(e), i); + } + Ok(e) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn builtins(name: &str) -> Option> { + Some(match name { + "frameCounter" => vec![7.0], + "eyeBrightness" => vec![32.0, 120.0], + "isEyeInWater" => vec![0.0], + "eyeAltitude" => vec![40.0], + "cameraPosition" => vec![1.0, 64.5, -3.0], + "rainStrength" => vec![0.0], + _ => return None, + }) + } + + fn eval(text: &str) -> Option> { + let u = CustomUniforms::parse([("uniform.float.x", text)]); + let mut state = UniformState::default(); + u.update(&mut state, 0.05, &builtins); + state.get("x").map(<[f32]>::to_vec) + } + + #[test] + fn operators_follow_iris_priorities() { + assert_eq!(eval("1 + 2 * 3"), Some(vec![7.0])); + assert_eq!(eval("10 - 4 - 3"), Some(vec![3.0])); + assert_eq!(eval("2 * 3 % 4"), Some(vec![2.0])); + assert_eq!(eval("-2 * 3"), Some(vec![-6.0])); + assert_eq!(eval("1 < 2 && 3 > 4 || 1"), Some(vec![1.0])); + assert_eq!(eval("!(1 == 1)"), Some(vec![0.0])); + assert_eq!(eval("frameCounter % 2"), Some(vec![1.0])); + assert_eq!(eval("7 / 2"), Some(vec![3.5])); + assert_eq!(eval("-7 % 4"), Some(vec![-3.0])); + assert_eq!(eval("eyeBrightness.y / 240.0"), Some(vec![0.5])); + assert_eq!(eval("cameraPosition.y - 0.5"), Some(vec![64.0])); + assert_eq!(eval("2.5f * 2"), Some(vec![5.0])); + } + + #[test] + fn functions() { + assert_eq!(eval("if(eyeBrightness.y > 239.0, 1, 0)"), Some(vec![0.0])); + assert_eq!(eval("if(0, 1, 1 == 1, 2, 3)"), Some(vec![2.0])); + assert_eq!( + eval("clamp(5, 0, 1) + max(1, 4, 2) + min(3, -1)"), + Some(vec![4.0]) + ); + assert_eq!(eval("fmod(-1, 4)"), Some(vec![3.0])); + assert_eq!(eval("in(3, 1, 2, 3)"), Some(vec![1.0])); + assert_eq!( + eval("between(2, 1, 3) && equals(1.0, 1.05, 0.1)"), + Some(vec![1.0]) + ); + assert_eq!(eval("frac(2.25) + floor(-0.5) + abs(-2)"), Some(vec![1.25])); + assert_eq!(eval("vec2(1, 2).y"), Some(vec![2.0])); + // An unknown name or function leaves the uniform out (zero). + assert_eq!(eval("biome_precipitation + 1"), None); + assert_eq!(eval("nope(1)"), None); + assert_eq!(eval("1 +"), None); + } + + #[test] + fn variables_resolve_in_dependency_order() { + let u = CustomUniforms::parse([ + ("uniform.float.b", "a * 2"), + ("variable.float.a", "frameCounter + 1"), + ("uniform.vec2.v", "vec2(a, b)"), + ("uniform.bool.flag", "b > 10"), + ("uniform.float.loop1", "loop2"), + ("uniform.float.loop2", "loop1"), + ("uniform.float.bad", "unknown"), + ("uniform.float.uses_bad", "bad + 1"), + ]); + let mut state = UniformState::default(); + u.update(&mut state, 0.05, &builtins); + assert_eq!(state.get("b"), Some(&[16.0][..])); + assert_eq!(state.get("a"), None, "variables aren't uniforms"); + assert_eq!(state.get("v"), Some(&[8.0, 16.0][..])); + assert_eq!(state.get("flag"), Some(&[1.0][..])); + assert_eq!(state.get("loop1"), None); + assert_eq!(state.get("bad"), None); + assert_eq!(state.get("uses_bad"), None); + assert!(u.problems.iter().any(|p| p.contains("circular"))); + } + + #[test] + fn smooth_is_iris_exponential_smoothing() { + // Complementary's `eyeBrightnessM` and `isEyeInCave`. + let u = CustomUniforms::parse([ + ( + "uniform.float.m", + "smooth(4, eyeBrightness.y / 240.0, 5, 5)", + ), + ( + "uniform.float.cave", + "if(isEyeInWater == 0, 1.0 - smooth(202, if(eyeAltitude < 5.0, eyeBrightness.y / 240.0, 1.0), 6, 12), 0.0)", + ), + ("uniform.float.once", "smooth(frameCounter)"), + ]); + assert!(u.problems.is_empty(), "{:?}", u.problems); + let mut state = UniformState::default(); + u.update(&mut state, 0.05, &builtins); + // The first value isn't smoothed. + assert_eq!(state.get("m"), Some(&[0.5][..])); + assert_eq!(state.get("cave"), Some(&[0.0][..])); + // Half a second at a half-life of 5 tenths: halfway to the target. + let dark = |name: &str| -> Option> { + match name { + "eyeBrightness" => Some(vec![0.0, 0.0]), + _ => builtins(name), + } + }; + u.update(&mut state, 0.5, &dark); + let m = state.get("m").unwrap()[0]; + assert!((m - 0.25).abs() < 1e-5, "{m}"); + let mut s = SmoothFloat::default(); + s.update(0.0, 0.0, 10.0, 0.1); + assert_eq!(s.update(1.0, 0.0, 10.0, 0.1), 1.0, "a half-life of 0 jumps"); + let down = s.update(0.0, 0.0, 10.0, 1.0); + assert!((down - 0.5).abs() < 1e-5, "{down}"); + } +} diff --git a/crates/horizon-shaderpack/tests/pack.rs b/crates/horizon-shaderpack/tests/pack.rs index ce5115b37..7aa45e8fa 100644 --- a/crates/horizon-shaderpack/tests/pack.rs +++ b/crates/horizon-shaderpack/tests/pack.rs @@ -326,6 +326,14 @@ fn real_packs_properties() { } println!(" unknown screen options: {unknown:?}"); assert!(unknown.len() <= 2, "{unknown:?}"); + // Every custom uniform parses. + let uniforms = properties.custom_uniforms(); + println!( + " custom uniforms: {:?}, sky {:?}", + uniforms.problems, + properties.sky() + ); + assert!(uniforms.problems.is_empty(), "{:?}", uniforms.problems); } } diff --git a/docs/shader-packs.md b/docs/shader-packs.md index 5f8e88c20..3cd068f2d 100644 --- a/docs/shader-packs.md +++ b/docs/shader-packs.md @@ -21,6 +21,7 @@ Both are off by default. With no pack selected the renderer draws exactly what i | Java shader packs: `shaders.properties` (`horizon_shaderpack::properties`: screens, sliders, profiles, `program.*.enabled`, image formats, blend modes) | done, no screen yet: read like Iris for the three test packs | | Java shader packs: full-screen pass plan (`horizon_shaderpack::pipeline`: `DRAWBUFFERS`/`RENDERTARGETS`, `colortexN` formats and clearing, buffer flips) | done: planned for the three test packs | | Java shader packs: full-screen passes drawn (`java_pack.rs`, `gfx/java_stages.rs`: `begin`, `prepare`, `deferred*`, `composite*`, `final` over Horizon's world) | first slice: BSL and Complementary run (below) | +| Java shader packs: custom uniforms (`horizon_shaderpack::uniforms`), `sunPathRotation`, `clouds`/`sun`/`moon`, eye light | done for the full-screen passes (below) | | Java shader packs: `gbuffers_*`, `shadow`, custom textures, images, compute, option screen | planned | ## How the renderer draws a frame today @@ -262,7 +263,8 @@ A `shaders/` folder of GLSL programs, named by where Iris (and OptiFine before i Order: preprocessor and legaliser until the three test packs parse; then `composite`/`final`/`deferred` with the uniforms; then `gbuffers_terrain`, `gbuffers_water` and `gbuffers_skybasic`/`skytextured` (the packs' look comes -from these); then entities, hand, weather, clouds; then `shadow`; then custom uniforms, custom textures, compute. +from these); then entities, hand, weather, clouds; then `shadow`; then custom textures, compute. Custom uniforms +are done (below). The test set is Complementary Reimagined, BSL and Sildur's Vibrant. Their licences don't allow redistribution, so they are downloaded for development only, outside the repository (never committed, never shipped, never uploaded); @@ -355,15 +357,26 @@ What makes Horizon look like OpenGL to the pack: `noisetex`, `iris_compare` for shadow lookups) instead of one each. - **`isnan`/`isinf`** test the float's bits: Metal compiles with fast math, which folds `x != x` to false, and a NaN then stays forever in Complementary's TAA history (the picture turns black). -- **Uniforms.** Matrices, camera, view size, time, sun and moon, weather, fog and sky colour, eye state come from the - frame; `eyeBrightness(Smooth)` is `(0, 240)` under the sky; `noisetex` is a fixed 256² noise. +- **Uniforms.** Matrices, camera, view size, time, weather, fog and sky colour, eye state come from the frame; + `eyeBrightness` is the block and sky light (× 16) of the camera entity's eye block, and `eyeBrightnessSmooth` follows + it with the pack's `eyeBrightnessHalflife` (Iris's `SmoothedFloat`); `sunPosition`, `moonPosition`, + `shadowLightPosition`, `sunAngle` and `shadowAngle` are `CelestialUniforms`' (the sky's `sun_angle` and `moon_angle` + turned by Y -90, the pack's `sunPathRotation` about Z, then the angle about X); `noisetex` is a fixed 256² noise. +- **Custom uniforms.** `uniform..` and `variable..` in `shaders.properties` are evaluated + each frame (`horizon-shaderpack`'s `uniforms.rs`: Iris's operators and priorities, its functions, `smooth` with + `SmoothFloat`'s half-lives). A definition naming something Horizon doesn't provide (`biome`, `blindness`...) is left + out with everything that uses it, as Iris leaves out the ones it can't resolve: the uniform stays 0. +- **The vanilla sky.** While the pack runs, `sunPathRotation` tilts Horizon's sun, moon and stars as Iris tilts + vanilla's, `clouds = off | fast | fancy` replaces the cloud option, and `sun = false` / `moon = false` hide those. + Complementary and Sildur's turn the vanilla clouds off: drawn anyway, they wrote depth the packs' light shafts and + fog took for terrain. Measured on the Mac mini (M4 Pro) with the packs' default options: BSL v10.1.8 and Complementary Reimagined r5.9.3 grade and light Horizon's world as their post-processing would. Sildur's Vibrant v2.02 draws only its sky: its `deferred` reads the albedo `gbuffers_*` write to `colortex4`. Without `gbuffers_*` and `shadow`, no pack has its shadows, water or sky look yet; Distant Horizons' and Voxy's depth read as far. Not supported yet: images and compute (`.csh`; a pack that needs them doesn't load), mipmapped targets (`colortexNMipmapEnabled` is read but -ignored), custom textures, custom uniforms, the option screen; shadow matrices are identity. +ignored), custom textures, the option screen; shadow matrices are identity. ### Order to implement @@ -381,5 +394,5 @@ ignored), custom textures, custom uniforms, the option screen; shadow matrices a 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. -7. **The rest**: custom uniforms (`uniform.*` expressions), custom textures, compute programs and images, per-dimension +7. **The rest**: custom textures, compute programs and images, per-dimension folders, `entity.properties`/`item.properties`.