diff --git a/crates/horizon-client/examples/hud_fixture.rs b/crates/horizon-client/examples/hud_fixture.rs index 46da5e0ad..dcb594088 100644 --- a/crates/horizon-client/examples/hud_fixture.rs +++ b/crates/horizon-client/examples/hud_fixture.rs @@ -33,11 +33,14 @@ fn main() -> Result<()> { .filter(|l| !l.is_empty()) { let c: Value = serde_json::from_str(line)?; + // State the case reads back besides the draws (e.g. `scopeScale`). + let mut state = serde_json::Map::new(); let draws = match c["kind"].as_str().unwrap_or("decorations") { "decorations" => decorations(&c, &atlas), - kind => kinds::run(kind, &c, &atlas), + kind => kinds::run(kind, &c, &atlas, &mut state), }; - writeln!(out, "{}", json!({ "draws": encode(&draws) }))?; + state.insert("draws".into(), json!(encode(&draws))); + writeln!(out, "{}", Value::Object(state))?; } Ok(()) } diff --git a/crates/horizon-client/examples/hud_fixture/kinds.rs b/crates/horizon-client/examples/hud_fixture/kinds.rs index 912df200c..0c423c76a 100644 --- a/crates/horizon-client/examples/hud_fixture/kinds.rs +++ b/crates/horizon-client/examples/hud_fixture/kinds.rs @@ -3,7 +3,9 @@ use horizon_client::{ brewing, component, hud::HudAtlas, hud_layout::{self, GuiDraw}, - hud_overlays::{self, BossBar, EffectIcon, HeldName, ItemDecorations, Titles, ToolHighlight}, + hud_overlays::{ + self, BossBar, CameraOverlays, EffectIcon, HeldName, ItemDecorations, Titles, ToolHighlight, + }, scoreboard::{NumberFormat, RenderType, Scoreboard}, text::{self, Text}, }; @@ -28,7 +30,12 @@ fn background(c: &Value) -> u32 { ) } -pub fn run(kind: &str, c: &Value, atlas: &HudAtlas) -> Vec { +pub fn run( + kind: &str, + c: &Value, + atlas: &HudAtlas, + state: &mut serde_json::Map, +) -> Vec { let (w, h) = (int(c, "width", 0), int(c, "height", 0)); match kind { "effects" => effects(c, w), @@ -38,6 +45,7 @@ pub fn run(kind: &str, c: &Value, atlas: &HudAtlas) -> Vec { "jump" => hud_overlays::jump_bar(w, h, int(c, "cooldown", 0), float(c, "jumpScale", 0.0)), "sidebar" => sidebar(c, w, h, atlas), "decor" => decor(c, atlas), + "overlays" => overlays(c, w, h, state), _ => Vec::new(), } } @@ -221,3 +229,63 @@ fn decor(c: &Value, atlas: &HudAtlas) -> Vec { }; hud_overlays::item_decorations(int(c, "x", 0), int(c, "y", 0), &d, &atlas.font) } + +/// `Hud.extractCameraOverlays` then `extractSleepOverlay`; the border is +/// static, so only its warning blocks matter. +fn overlays(c: &Value, w: i32, h: i32, state: &mut serde_json::Map) -> Vec { + let partial = float(c, "partial", 0.0); + let warning = match &c["border"] { + Value::Null => 0.0, + b => { + // WorldBorder.getDistanceToBorder with the static extent's clamped box. + let max = 29_999_984.0; + let half = b["size"].as_f64().unwrap_or(0.0) / 2.0; + let (cx, cz) = ( + b["centerX"].as_f64().unwrap_or(0.0), + b["centerZ"].as_f64().unwrap_or(0.0), + ); + let (min_x, max_x) = ((cx - half).clamp(-max, max), (cx + half).clamp(-max, max)); + let (min_z, max_z) = ((cz - half).clamp(-max, max), (cz + half).clamp(-max, max)); + let (x, z) = ( + f64::from(float(c, "camX", 0.0)), + f64::from(float(c, "camZ", 0.0)), + ); + let distance = (x - min_x).min(max_x - x).min(z - min_z).min(max_z - z); + hud_overlays::border_warning( + distance as f32, + int(b, "warningBlocks", 5), + int(b, "warningTime", 15), + 0.0, + 0.0, + ) + } + }; + let ticks_frozen = int(c, "ticksFrozen", 0); + let inputs = CameraOverlays { + vignette: c["vignette"] + .as_bool() + .unwrap_or(false) + .then(|| (float(c, "vignetteBrightness", 1.0), warning)), + first_person: c["firstPerson"].as_bool().unwrap_or(false), + scoping: c["scoping"].as_bool().unwrap_or(false), + game_time_delta: partial, + equipment: match c["head"].as_str() { + Some("carved_pumpkin") => vec!["misc/pumpkinblur".to_owned()], + _ => Vec::new(), + }, + ticks_frozen, + percent_frozen: ticks_frozen.min(140) as f32 / 140.0, + partial, + portal: [ + c["portal"][0].as_f64().unwrap_or(0.0) as f32, + c["portal"][1].as_f64().unwrap_or(0.0) as f32, + ], + nausea: float(c, "nausea", 0.0), + screen_effect_scale: float(c, "screenEffectScale", 1.0), + }; + let mut scope = float(c, "scopeScale", 0.5); + let mut out = hud_overlays::camera_overlays(w, h, &inputs, &mut scope); + out.extend(hud_overlays::sleep_overlay(w, h, int(c, "sleepTimer", 0))); + state.insert("scopeScale".into(), serde_json::json!(scope)); + out +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 673f80210..c44806b4e 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2936,6 +2936,11 @@ impl Game<'_> { self.draw_effect_icons(&mut batch); // Hud: the action bar and titles draw over the hotbar (nextStratum). self.draw_boss_bars(&mut batch); + // Hud.extractSleepOverlay, under the sidebar, titles and chat. + if let Some((_, ticks)) = self.sleeping { + let draws = hud_overlays::sleep_overlay(wi, hi, ticks as i32); + hud_layout::paint(&mut batch, &self.res.atlas, &draws); + } self.draw_titles(&mut batch); self.draw_scoreboard(&mut batch); self.draw_subtitles(&mut batch); @@ -3109,12 +3114,6 @@ impl Game<'_> { batch.text(atlas, text, (w - tw) / 2.0, h - 59.0, u32::MAX, true); } self.draw_chat(&mut batch); - let atlas = &self.res.atlas; - if let Some((_, ticks)) = self.sleeping { - // Gui sleep overlay fading in over 100 ticks. - let a = ((ticks as f32 / 100.0).min(1.0) * 204.0) as u8; - batch.fill(atlas, 0.0, 0.0, w, h, rgba(16, 16, 32, a)); - } match self.screen { Screen::Paused => self.draw_pause_menu(&mut batch), Screen::Dead => self.draw_death_screen(&mut batch), diff --git a/crates/horizon-client/src/game/fov.rs b/crates/horizon-client/src/game/fov.rs index faf0f0924..d584d6721 100644 --- a/crates/horizon-client/src/game/fov.rs +++ b/crates/horizon-client/src/game/fov.rs @@ -8,7 +8,8 @@ use horizon_client::{ BobState, CameraFluid, FovPlayer, HurtBob, UseItem, bob_matrix, field_of_view_modifier, }, fog::{FogType, fog_type}, - hud::{HudBatch, rgba}, + hud::HudBatch, + hud_layout, hud_overlays, }; /// `Abilities.walkingSpeed`. @@ -145,26 +146,20 @@ impl Game<'_> { self.audio .play("minecraft:item.spyglass.stop_using", at, 1.0, 1.0); } - /// `Hud.extractCameraOverlays`: the scope, its size easing from 0.5 to - /// 1.125 at half a step per tick of frame time. + /// `Hud.extractCameraOverlays`: the spyglass scope, its size easing + /// towards 1.125 by half the frame's game ticks and reset to 0.5 while + /// not scoping in first person. pub(super) fn draw_spyglass(&mut self, batch: &mut HudBatch) { + self.scope_scale += 0.5 * self.frame_ticks * (1.125 - self.scope_scale); + if !self.camera_type.first_person() { + return; + } if !self.scoping() { self.scope_scale = 0.5; return; } - self.scope_scale += (1.125 - self.scope_scale) * (0.5 * self.frame_ticks).min(1.0); - let atlas = &self.res.atlas; - let (w, h) = (batch.width, batch.height); - let src = w.min(h); - let ratio = (w / src).min(h / src) * self.scope_scale; - let (sw, sh) = ((src * ratio).floor(), (src * ratio).floor()); - let (left, top) = (((w - sw) / 2.0).floor(), ((h - sh) / 2.0).floor()); - let (right, bottom) = (left + sw, top + sh); - batch.sprite_scaled(atlas, "misc/spyglass_scope", left, top, sw, sh, u32::MAX); - let black = rgba(0, 0, 0, 255); - batch.fill(atlas, 0.0, bottom, w, h - bottom, black); - batch.fill(atlas, 0.0, 0.0, w, top, black); - batch.fill(atlas, 0.0, top, left, bottom - top, black); - batch.fill(atlas, right, top, w - right, bottom - top, black); + let draws = + hud_overlays::spyglass(batch.width as i32, batch.height as i32, self.scope_scale); + hud_layout::paint(batch, &self.res.atlas, &draws); } } diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index c7605f257..a915619a1 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -2,7 +2,6 @@ //! campfire smoke and rain splashes (`ClientLevel.tickWeatherEffects`). use super::{Dim, Game}; use horizon_client::fog::{FogData, FogInputs, FogType, fog_type, update_rain_fog}; -use horizon_client::screen_effects::{ScreenInputs, ScreenQuad, lightmap_brightness}; use horizon_client::{ animate_tick::{AnimateContext, animate_tick, campfire_particles}, biome::Biomes, @@ -11,6 +10,10 @@ use horizon_client::{ particles::{ParticleLevel, ParticleOptions, ParticleType}, world::World, }; +use horizon_client::{ + hud_overlays, + screen_effects::{ScreenInputs, ScreenQuad, lightmap_brightness}, +}; use horizon_core::random::{LegacyRandom, RandomSource}; /// The first motion-blocking block at or below `from` (Heightmap MOTION_BLOCKING), plus one. @@ -140,12 +143,33 @@ impl Game<'_> { fog_type(&self.world, &self.res.facts, eye, self.forward()) == FogType::Water; let water = (in_water && !spectator).then(|| (self.eye_brightness(eye), self.yaw, self.pitch)); - let camera_overlays = match &self.armor[0] { - Some(stack) if &*stack.item == "minecraft:carved_pumpkin" => { - vec!["misc/pumpkinblur".to_owned()] - } - _ => Vec::new(), + // Hud.extractCameraOverlays; the spyglass scope (and its easing) is + // drawn on the HUD by draw_spyglass. + let fx = &self.res.screen_fx; + let overlays = hud_overlays::CameraOverlays { + vignette: self + .settings + .vignette + .then_some((fx.vignette_brightness, 0.0)), + first_person: self.camera_type.first_person(), + scoping: self.scoping(), + game_time_delta: 0.0, + equipment: match &self.armor[0] { + Some(stack) if &*stack.item == "minecraft:carved_pumpkin" => { + vec!["misc/pumpkinblur".to_owned()] + } + _ => Vec::new(), + }, + ticks_frozen: 0, + percent_frozen: 0.0, + partial, + portal: [fx.o_portal, fx.portal], + nausea: 0.0, + screen_effect_scale: 1.0, }; + let mut scope = self.scope_scale; + let gui_overlays = + hud_overlays::camera_overlays(size[0] as i32, size[1] as i32, &overlays, &mut scope); self.res.screen_fx.build(&ScreenInputs { sprites: &self.res.atlas.sprites, aspect: size[0] as f32 / size[1].max(1) as f32, @@ -153,10 +177,7 @@ impl Game<'_> { block_overlay, water, on_fire: false, - camera_overlays, - frozen: 0.0, - vignette: true, - border_warning: None, + gui_overlays: &gui_overlays, }) } /// `Lightmap.getBrightness(getMaxLocalRawBrightness(eye))`. diff --git a/crates/horizon-client/src/hud_overlays.rs b/crates/horizon-client/src/hud_overlays.rs index ae6ca88e6..7c43c1a43 100644 --- a/crates/horizon-client/src/hud_overlays.rs +++ b/crates/horizon-client/src/hud_overlays.rs @@ -5,7 +5,9 @@ //! selected item name (`extractSelectedItemName` and its `toolHighlightTimer`). use crate::{ font::Font, - hud_layout::{GuiDraw, PoseOp, fill, hsv_to_argb, multiply, white, width}, + hud_layout::{ + Blend, GuiDraw, PoseOp, color_from_float, fill, hsv_to_argb, multiply, white, width, + }, text::{Style, Text}, }; use std::{borrow::Cow, cmp::Ordering}; @@ -692,3 +694,209 @@ pub fn item_decorations(x: i32, y: i32, d: &ItemDecorations, font: &Font) -> Vec out.push(GuiDraw::Pop); out } + +/// A full-screen `graphics.blit` of `textures/.png`. +fn screen_blit( + w: i32, + h: i32, + texture: impl Into>, + blend: Blend, + color: u32, +) -> GuiDraw { + GuiDraw::Blit { + texture: texture.into(), + blend, + x: 0, + y: 0, + w, + h, + uv: [0.0, 0.0], + src: [w, h], + tex: [w, h], + color, + } +} + +/// `Hud.extractVignette`: `brightness` is `vignetteBrightness` and +/// `border_warning` the world border warning strength (0 when far). +pub fn vignette(w: i32, h: i32, brightness: f32, border_warning: f32) -> GuiDraw { + let brightness = brightness.clamp(0.0, 1.0); + let color = if border_warning > 0.0 { + let warning = border_warning.clamp(0.0, 1.0); + let red = brightness * (1.0 - warning); + let green_blue = brightness + (1.0 - brightness) * warning; + color_from_float(1.0, red, green_blue, green_blue) + } else { + color_from_float(1.0, brightness, brightness, brightness) + }; + screen_blit(w, h, "misc/vignette", Blend::Vignette, color) +} + +/// The border warning strength of `extractVignette` for a camera +/// `distance` from a border with `warning_blocks`, `warning_time`, its +/// `lerp_speed` and how far its size still has to move. +pub fn border_warning( + distance: f32, + warning_blocks: i32, + warning_time: i32, + lerp_speed: f64, + size_left: f64, +) -> f32 { + let moving = (lerp_speed * f64::from(warning_time)).min(size_left.abs()); + let warning_distance = f64::from(warning_blocks).max(moving); + if f64::from(distance) < warning_distance { + 1.0 - (f64::from(distance) / warning_distance) as f32 + } else { + 0.0 + } +} + +/// `Hud.extractSpyglassOverlay`. +pub fn spyglass(w: i32, h: i32, scale: f32) -> Vec { + let src = w.min(h) as f32; + let ratio = (w as f32 / src).min(h as f32 / src) * scale; + let width = crate::hud_layout::floor(src * ratio); + let height = crate::hud_layout::floor(src * ratio); + let left = (w - width) / 2; + let top = (h - height) / 2; + let (right, bottom) = (left + width, top + height); + vec![ + GuiDraw::Blit { + texture: Cow::Borrowed("misc/spyglass_scope"), + blend: Blend::Textured, + x: left, + y: top, + w: width, + h: height, + uv: [0.0, 0.0], + src: [width, height], + tex: [width, height], + color: crate::hud_layout::WHITE, + }, + fill(0, bottom, w, h, 0xFF00_0000), + fill(0, 0, w, top, 0xFF00_0000), + fill(0, top, left, bottom, 0xFF00_0000), + fill(right, top, w, bottom, 0xFF00_0000), + ] +} + +/// `Hud.extractPortalOverlay`: the nether portal block sprite over the screen. +pub fn portal_overlay(w: i32, h: i32, mut alpha: f32) -> GuiDraw { + if alpha < 1.0 { + alpha *= alpha; + alpha *= alpha; + alpha = alpha * 0.8 + 0.2; + } + GuiDraw::AtlasSprite { + sprite: Cow::Borrowed("block/nether_portal"), + x: 0, + y: 0, + w, + h, + color: white(alpha), + } +} + +/// `Hud.extractConfusionOverlay`: the nausea swirl scaled about the centre. +pub fn confusion_overlay(w: i32, h: i32, strength: f32) -> Vec { + let size = 2.0 + strength * (1.0 - 2.0); + let (cx, cy) = (w as f32 / 2.0, h as f32 / 2.0); + vec![ + GuiDraw::Push(vec![ + PoseOp::Translate(cx, cy), + PoseOp::Scale(size, size), + PoseOp::Translate(-cx, -cy), + ]), + screen_blit( + w, + h, + "misc/nausea", + Blend::Nausea, + color_from_float(1.0, 0.2 * strength, 0.4 * strength, 0.2 * strength), + ), + GuiDraw::Pop, + ] +} + +/// What `Hud.extractCameraOverlays` reads. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CameraOverlays { + /// `Options.vignette`: `vignetteBrightness` and the border warning strength. + pub vignette: Option<(f32, f32)>, + pub first_person: bool, + /// `LocalPlayer.isScoping`. + pub scoping: bool, + /// `DeltaTracker.getGameTimeDeltaTicks`. + pub game_time_delta: f32, + /// `Equippable.cameraOverlay` textures (`misc/pumpkinblur`) of the worn + /// items in `EquipmentSlot` order. + pub equipment: Vec, + /// `getTicksFrozen` and `getPercentFrozen`. + pub ticks_frozen: i32, + pub percent_frozen: f32, + /// The partial tick and `oPortalEffectIntensity` / `portalEffectIntensity`. + pub partial: f32, + pub portal: [f32; 2], + /// `getEffectBlendFactor(NAUSEA, partial)` and `Options.screenEffectScale`. + pub nausea: f32, + pub screen_effect_scale: f32, +} + +/// `Hud.extractCameraOverlays`, easing `scope_scale` (`Hud.scopeScale`). +pub fn camera_overlays(w: i32, h: i32, i: &CameraOverlays, scope_scale: &mut f32) -> Vec { + let mut out = Vec::new(); + if let Some((brightness, warning)) = i.vignette { + out.push(vignette(w, h, brightness, warning)); + } + *scope_scale += 0.5 * i.game_time_delta * (1.125 - *scope_scale); + if i.first_person { + if i.scoping { + out.extend(spyglass(w, h, *scope_scale)); + } else { + *scope_scale = 0.5; + for texture in &i.equipment { + out.push(screen_blit( + w, + h, + texture.clone(), + Blend::Textured, + crate::hud_layout::WHITE, + )); + } + } + } + if i.ticks_frozen > 0 { + out.push(screen_blit( + w, + h, + "misc/powder_snow_outline", + Blend::Textured, + white(i.percent_frozen), + )); + } + let portal = i.portal[0] + i.partial * (i.portal[1] - i.portal[0]); + if portal > 0.0 { + out.push(portal_overlay(w, h, portal)); + } else if i.nausea > 0.0 && i.screen_effect_scale < 1.0 { + out.extend(confusion_overlay( + w, + h, + i.nausea * (1.0 - i.screen_effect_scale), + )); + } + out +} + +/// `Hud.extractSleepOverlay`. +pub fn sleep_overlay(w: i32, h: i32, sleep_timer: i32) -> Vec { + if sleep_timer <= 0 { + return Vec::new(); + } + let timer = sleep_timer as f32; + let mut amount = timer / 100.0; + if amount > 1.0 { + amount = 1.0 - (timer - 100.0) / 10.0; + } + let color = (((220.0 * amount) as i32) << 24) as u32 | 0x10_1020; + vec![fill(0, 0, w, h, color)] +} diff --git a/crates/horizon-client/src/screen_effects.rs b/crates/horizon-client/src/screen_effects.rs index ca728779c..bc7756453 100644 --- a/crates/horizon-client/src/screen_effects.rs +++ b/crates/horizon-client/src/screen_effects.rs @@ -1,9 +1,10 @@ //! Full-screen camera effects drawn between the world and the HUD: //! `ScreenEffectRenderer` (in-wall block texture, underwater overlay, fire) -//! and the `Hud` camera overlays (vignette, pumpkin blur, powder-snow +//! and the full-screen `Hud` camera overlays laid out by +//! `hud_overlays::camera_overlays` (vignette, pumpkin blur, powder-snow //! outline, nether portal swirl). Positions are clip-space quads; textures //! come from the shared 2D atlas and may repeat. -use crate::hud::Rect; +use crate::{hud::Rect, hud_layout::GuiDraw}; use std::collections::HashMap; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -40,14 +41,9 @@ pub struct ScreenInputs<'a> { /// Eye in water: (lightmap brightness at the eye, yaw, pitch). pub water: Option<(f32, f32, f32)>, pub on_fire: bool, - /// Equipment camera overlays (`Equippable.cameraOverlay`, e.g. `misc/pumpkinblur`). - pub camera_overlays: Vec, - /// `Player.getPercentFrozen`. - pub frozen: f32, - /// `Options.vignette`. - pub vignette: bool, - /// Distance to the world border and its warning distance, when close. - pub border_warning: Option, + /// `Hud.extractCameraOverlays` draws: the full-screen blits become + /// screen quads (the spyglass, its fills and the nausea swirl do not). + pub gui_overlays: &'a [GuiDraw], } /// Effect state advanced every tick. @@ -170,43 +166,43 @@ impl ScreenEffects { }), blend, }; - if input.vignette - && let Some(rect) = sprite("misc/vignette") - { - let b = self.vignette_brightness.clamp(0.0, 1.0); - let color = match input.border_warning { - Some(w) if w > 0.0 => { - let w = w.clamp(0.0, 1.0); - let red = b * (1.0 - w); - let gb = b + (1.0 - b) * w; - [red, gb, gb, 1.0] + let rgba = |c: u32| { + let [a, r, g, b] = c.to_be_bytes(); + [r, g, b, a].map(|v| f32::from(v) / 255.0) + }; + for d in input.gui_overlays { + match d { + GuiDraw::Blit { + texture, + blend, + x: 0, + y: 0, + color, + .. + } if *blend != crate::hud_layout::Blend::Nausea + && texture != "misc/spyglass_scope" => + { + let blend = if *blend == crate::hud_layout::Blend::Vignette { + Blend::Vignette + } else { + Blend::Alpha + }; + if let Some(rect) = sprite(texture) { + out.push(gui(rect, rgba(*color), blend)); + } } - _ => [b, b, b, 1.0], - }; - out.push(gui(rect, color, Blend::Vignette)); - } - for overlay in &input.camera_overlays { - if let Some(rect) = sprite(overlay) { - out.push(gui(rect, [1.0; 4], Blend::Alpha)); + GuiDraw::AtlasSprite { + sprite: name, + color, + .. + } => { + if let Some(rect) = sprite(name) { + out.push(gui(rect, rgba(*color), Blend::Alpha)); + } + } + _ => {} } } - if input.frozen > 0.0 - && let Some(rect) = sprite("misc/powder_snow_outline") - { - out.push(gui(rect, [1.0, 1.0, 1.0, input.frozen], Blend::Alpha)); - } - let portal = self.o_portal + (self.portal - self.o_portal) * input.partial; - if portal > 0.0 - && let Some(rect) = sprite("block/nether_portal") - { - let mut a = portal; - if a < 1.0 { - a *= a; - a *= a; - a = a * 0.8 + 0.2; - } - out.push(gui(rect, [1.0, 1.0, 1.0, a], Blend::Alpha)); - } out } } @@ -254,10 +250,7 @@ mod tests { block_overlay: None, water: Some((1.0, 0.0, 0.0)), on_fire: false, - camera_overlays: vec![], - frozen: 0.0, - vignette: true, - border_warning: None, + gui_overlays: &[crate::hud_overlays::vignette(320, 240, 1.0, 0.0)], }; let quads = e.build(&input); assert_eq!(quads.len(), 1); diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHudOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHudOracle.java index caa521847..322087a83 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHudOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHudOracle.java @@ -148,6 +148,16 @@ public final class VanillaHudOracle { : method.getReturnType() == boolean.class ? false : method.getReturnType() == float.class ? 0.0F : null); } @Override public float getJumpRidingScale() { return f("jumpScale", 0); } + @Override public ItemStack getItemBySlot(net.minecraft.world.entity.EquipmentSlot slot) { + return slot == net.minecraft.world.entity.EquipmentSlot.HEAD && c.has("head") && !c.get("head").isJsonNull() + ? new ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.withDefaultNamespace(c.get("head").getAsString()))) : ItemStack.EMPTY; + } + @Override public int getTicksFrozen() { return i("ticksFrozen", 0); } + @Override public boolean isScoping() { return b("scoping"); } + @Override public float getEffectBlendFactor(Holder effect, float partial) { + return effect.is(net.minecraft.world.effect.MobEffects.NAUSEA) ? f("nausea", 0) : 0.0F; + } + @Override public int getSleepTimer() { return i("sleepTimer", 0); } @Override public void playSound(net.minecraft.sounds.SoundEvent sound, float volume, float pitch) { } } @@ -306,6 +316,8 @@ public final class VanillaHudOracle { Method overlayMessage = hudMethod("extractOverlayMessage", GuiGraphicsExtractor.class, DeltaTracker.class); Method selectedName = hudMethod("extractSelectedItemName", GuiGraphicsExtractor.class); Method tick = hudMethod("tick"); + Method cameraOverlays = hudMethod("extractCameraOverlays", GuiGraphicsExtractor.class, DeltaTracker.class); + Method sleep = hudMethod("extractSleepOverlay", GuiGraphicsExtractor.class, DeltaTracker.class); Method sidebar = hudMethod("displayScoreboardSidebar", GuiGraphicsExtractor.class, net.minecraft.world.scores.Objective.class); Method level = Class.forName("net.minecraft.client.gui.contextualbar.ContextualBar") .getDeclaredMethod("extractExperienceLevel", GuiGraphicsExtractor.class, Font.class, int.class); @@ -510,6 +522,42 @@ public final class VanillaHudOracle { capture.realDecorations = true; capture.itemDecorations(font, stack, i("x", 0), i("y", 0), c.has("countText") ? c.get("countText").getAsString() : null); } + case "overlays" -> { + put(options, Options.class, "vignette", option(b("vignette"))); + put(options, Options.class, "cameraType", b("firstPerson") ? net.minecraft.client.CameraType.FIRST_PERSON : net.minecraft.client.CameraType.THIRD_PERSON_BACK); + put(options, Options.class, "screenEffectScale", option((double) f("screenEffectScale", 1))); + var border = new net.minecraft.world.level.border.WorldBorder(); + if (c.has("border") && !c.get("border").isJsonNull()) { + var bo = c.getAsJsonObject("border"); + border.setCenter(bo.get("centerX").getAsDouble(), bo.get("centerZ").getAsDouble()); + border.setSize(bo.get("size").getAsDouble()); + border.setWarningBlocks(bo.get("warningBlocks").getAsInt()); + border.setWarningTime(bo.get("warningTime").getAsInt()); + } + put(clientLevel, ClientLevel.class, "worldBorder", border); + put(mc, Minecraft.class, "level", clientLevel); + put(actor, Entity.class, "position", new net.minecraft.world.phys.Vec3(f("camX", 0), 64, f("camZ", 0))); + actor.oPortalEffectIntensity = c.getAsJsonArray("portal").get(0).getAsFloat(); + actor.portalEffectIntensity = c.getAsJsonArray("portal").get(1).getAsFloat(); + put(hud, Hud.class, "vignetteBrightness", f("vignetteBrightness", 1)); + put(hud, Hud.class, "scopeScale", f("scopeScale", 0.5F)); + // The nether portal particle sprite, as the block model set would give it. + var contents = alloc(net.minecraft.client.renderer.texture.SpriteContents.class); + put(contents, net.minecraft.client.renderer.texture.SpriteContents.class, "name", Identifier.withDefaultNamespace("block/nether_portal")); + var sprite = alloc(net.minecraft.client.renderer.texture.TextureAtlasSprite.class); + put(sprite, net.minecraft.client.renderer.texture.TextureAtlasSprite.class, "contents", contents); + var material = new net.minecraft.client.resources.model.sprite.Material.Baked(sprite, false); + var model = (net.minecraft.client.renderer.block.dispatch.BlockStateModel) Proxy.newProxyInstance(Actor.class.getClassLoader(), + new Class[] {net.minecraft.client.renderer.block.dispatch.BlockStateModel.class}, + (proxy, method, a) -> method.getName().equals("particleMaterial") ? material : null); + var models = alloc(net.minecraft.client.resources.model.ModelManager.class); + put(models, net.minecraft.client.resources.model.ModelManager.class, "blockStateModelSet", + new net.minecraft.client.renderer.block.BlockStateModelSet(Map.of(), model)); + put(mc, Minecraft.class, "modelManager", models); + cameraOverlays.invoke(hud, capture, delta); + sleep.invoke(hud, capture, delta); + result.addProperty("scopeScale", (float) field(Hud.class, "scopeScale").get(hud)); + } default -> throw new IllegalArgumentException(c.get("kind").getAsString()); } result.add("draws", capture.draws); diff --git a/tools/hud_parity_cases.py b/tools/hud_parity_cases.py index ec0e1459a..2b04106c5 100644 --- a/tools/hud_parity_cases.py +++ b/tools/hud_parity_cases.py @@ -174,6 +174,28 @@ def decor(rng, n): return case + +def overlays(rng, n): + """Camera overlays (vignette and border warning, spyglass, pumpkin, powder snow, portal, nausea) and sleep.""" + case = {**screen(rng), 'vignette': rng.random() < 0.7, + 'vignetteBrightness': rng.choice([1.0, 0.0, 0.5, round(rng.random(), 4), 1.3, -0.2]), + 'firstPerson': rng.random() < 0.8, 'scoping': rng.random() < 0.2, + 'scopeScale': rng.choice([0.5, 1.125, round(rng.uniform(0.5, 1.125), 4)]), 'partial': round(rng.random(), 3), + 'head': rng.choice([None, None, 'carved_pumpkin', 'diamond_helmet']), + 'ticksFrozen': rng.choice([0, 0, 0, 1, 70, 139, 140, 300]), + 'portal': rng.choice([[0.0, 0.0], [0.0, 0.0], [0.0, 0.0125], [0.5, 0.5125], [1.0, 1.0], [0.05, 0.0], [round(rng.random(), 3)] * 2]), + 'nausea': rng.choice([0.0, 0.0, 1.0, 0.25, round(rng.random(), 3)]), + 'screenEffectScale': rng.choice([1.0, 0.0, 0.5, round(rng.random(), 3)]), + 'sleepTimer': rng.choice([0, 0, 0, 1, 50, 100, 101, 105, 110, 111])} + if rng.random() < 0.4: + size = rng.choice([10.0, 50.0, 200.0, 1000.0]) + case['border'] = {'centerX': rng.choice([0.0, 100.5]), 'centerZ': rng.choice([0.0, -30.25]), 'size': size, + 'warningBlocks': rng.choice([0, 5, 20, 100]), 'warningTime': rng.choice([0, 15])} + case['camX'] = round(rng.uniform(-150, 250), 2) + case['camZ'] = round(rng.uniform(-150, 150), 2) + return case + + # Generators by kind: (rng, index) -> case. Cases are drawn round-robin. KINDS = { 'decorations': decorations, @@ -184,4 +206,5 @@ KINDS = { 'jump': jump, 'sidebar': sidebar, 'decor': decor, + 'overlays': overlays, } diff --git a/tools/test_hud_parity.py b/tools/test_hud_parity.py index d25c5525b..0aceaee10 100644 --- a/tools/test_hud_parity.py +++ b/tools/test_hud_parity.py @@ -118,6 +118,11 @@ def main(): errors.append(v['error']); continue a = [normal(d) for d in v['draws']] b = [normal(d) for d in r['draws']] + # State the case reads back besides the draws. + for key in v.keys() - {'case', 'draws'}: + if key not in r or not close(v[key], r[key]): + a = a + [{'type': 'state', key: v[key]}] + b = b + [{'type': 'state', key: r.get(key)}] if len(a) != len(b) or not all(same(x, y) for x, y in zip(a, b)): first = next((i for i, (x, y) in enumerate(zip(a, b)) if not same(x, y)), min(len(a), len(b))) bad.append((v['case'], first, a[first:first + 2], b[first:first + 2], len(a), len(b)))