Lay out the HUD decorations exactly as vanilla Hud does

Add horizon_client::hud_layout (crosshair and attack indicator, hotbar
with selection, off hand by main arm, item slots with the pop squeeze,
armour, hearts including frozen and absorbing kinds, food, air bubbles,
mount hearts capped at 30, experience bar and level) and the
test_hud_parity harness whose oracle runs vanilla Hud methods on a
stand-in client. The game now draws these through hud_layout; the
experience level is centred with integer division like vanilla,
spectators get no crosshair and mount hearts show in creative too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-10 21:56:23 +02:00
parent 3429de0020
commit 268babc257
8 changed files with 1254 additions and 352 deletions
@@ -0,0 +1,143 @@
//! Headless transport for the HUD parity gate: replays each player state
//! through `horizon_client::hud_layout` (crosshair, hotbar, health, mount
//! hearts, experience bar and level) and writes the draw calls in vanilla's
//! GuiGraphicsExtractor terms.
#![forbid(unsafe_code)]
use horizon_client::{
hud::{HudAtlas, HudBatch},
hud_layout::{self, GuiDraw, HealthHud, HealthInputs, HeartKind, HotbarInputs},
};
use serde_json::{Value, json};
use std::{
fs,
io::{BufWriter, Write},
path::PathBuf,
};
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn main() -> Result<()> {
let args: Vec<PathBuf> = std::env::args_os().skip(1).map(PathBuf::from).collect();
let [root, inputs, output] = args.as_slice() else {
return Err("usage: hud_fixture RESOURCES INPUTS OUTPUT".into());
};
let atlas = HudAtlas::build(root)?;
let mut out = BufWriter::new(fs::File::create(output)?);
for line in fs::read_to_string(inputs)?
.lines()
.filter(|l| !l.is_empty())
{
let c: Value = serde_json::from_str(line)?;
let int = |k: &str, d: i64| c[k].as_i64().unwrap_or(d) as i32;
let float = |k: &str, d: f64| c[k].as_f64().unwrap_or(d) as f32;
let (w, h) = (int("width", 0), int("height", 0));
let mode = c["gameMode"].as_str().unwrap_or("survival");
let survival = mode == "survival" || mode == "adventure";
let indicator = c["attackIndicator"].as_str().unwrap_or("OFF");
let partial = float("partial", 0.0);
let effects: Vec<&str> = c["effects"]
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_str)
.collect();
let has = |e: &str| effects.contains(&e);
let mut draws = Vec::new();
// Spectators only see it over a spectatable target (none here).
if c["crosshair"].as_bool().unwrap_or(false) && mode != "spectator" {
let attack = (indicator == "CROSSHAIR").then(|| float("attackScale", 1.0));
draws.extend(hud_layout::crosshair(w, h, attack, false));
}
if mode != "spectator" {
let pop = |v: &Value| v.as_f64().map(|p| p as f32 - partial);
let slots: [Option<f32>; 9] = std::array::from_fn(|i| pop(&c["slots"][i]));
let inputs = HotbarInputs {
selected: int("selected", 0),
right_handed: c["rightHanded"].as_bool().unwrap_or(true),
offhand: !c["offhand"].is_null(),
slots,
offhand_pop: pop(&c["offhand"]).unwrap_or(0.0),
attack: (indicator == "HOTBAR").then(|| float("attackScale", 1.0)),
};
draws.extend(hud_layout::hotbar(w, h, &inputs));
}
let vehicle_hearts = if c.get("vehicleMaxHealth").is_some() {
hud_layout::vehicle_max_hearts(float("vehicleMaxHealth", 0.0))
} else {
0
};
if survival {
let millis = 1_000_000_000i64;
let mut hud = HealthHud {
last_health: int("lastHealth", 0),
display_health: int("displayHealth", 0),
last_health_time: millis - i64::from(int("lastHealthAgo", 0)),
health_blink_time: i64::from(int("healthBlinkTime", 0)),
};
let kind = if has("minecraft:poison") {
HeartKind::Poisoned
} else if has("minecraft:wither") {
HeartKind::Withered
} else if c["frozen"].as_bool().unwrap_or(false) {
HeartKind::Frozen
} else {
HeartKind::Normal
};
let inputs = HealthInputs {
tick: int("tick", 0),
millis,
health: float("health", 20.0),
max_health: float("maxHealth", 20.0),
absorption: float("absorption", 0.0),
armor: int("armor", 0),
food: int("food", 20),
saturation: float("saturation", 5.0),
kind,
regeneration: has("minecraft:regeneration"),
hunger: has("minecraft:hunger"),
hardcore: c["hardcore"].as_bool().unwrap_or(false),
damage_cooldown: int("damageCooldown", 0) > 0,
air: int("air", 300),
max_air: int("maxAir", 300),
under_water: c["underWater"].as_bool().unwrap_or(false),
vehicle_hearts,
};
draws.extend(hud.layout(&inputs, w, h));
}
if vehicle_hearts > 0 {
draws.extend(hud_layout::vehicle_health(
w,
h,
vehicle_hearts,
float("vehicleHealth", 0.0),
));
}
let width = |s: &str| HudBatch::text_width(&atlas, s) as i32;
let level = if survival { int("xpLevel", 0) } else { 0 };
draws.extend(hud_layout::experience(
w,
h,
float("xpProgress", 0.0),
level,
c["experienceBar"].as_bool().unwrap_or(false),
&width,
));
let draws: Vec<Value> = draws
.iter()
.map(|d| match d {
GuiDraw::Sprite { sprite, x, y, w, h, region } => {
json!({"type": "sprite", "sprite": sprite, "x": x, "y": y, "w": w, "h": h, "region": region})
}
GuiDraw::Text { text, x, y, color, shadow } => {
json!({"type": "text", "text": text, "x": x, "y": y, "color": *color as i32, "shadow": shadow})
}
GuiDraw::Item { slot, x, y, seed, scale, pivot } => {
// translate(pivot) * scale * translate(-pivot) as a 3x2 matrix.
let m = [scale[0], 0.0, 0.0, scale[1], pivot[0] - pivot[0] * scale[0], pivot[1] - pivot[1] * scale[1]];
json!({"type": "item", "slot": slot, "x": x, "y": y, "seed": seed, "matrix": m})
}
})
.collect();
writeln!(out, "{}", json!({ "draws": draws }))?;
}
Ok(())
}
+82 -98
View File
@@ -34,7 +34,6 @@ mod game_mode;
mod ghasts;
mod golems;
mod growth;
mod health_hud;
mod jukebox;
mod lan;
mod lan_actions;
@@ -107,6 +106,7 @@ use horizon_client::{
environment::Environment,
gfx::{Frame, Renderer},
hud::{HudAtlas, HudBatch, rgba},
hud_layout,
items::{ItemStack, Items},
keymapping::KeyState,
light::LightTables,
@@ -585,7 +585,7 @@ struct Game<'a> {
fps_frames: u64,
fps_at: Instant,
ticks: u64,
health_hud: health_hud::HealthHud,
health_hud: hud_layout::HealthHud,
error: Option<String>,
message: Option<(String, Instant)>,
save: Arc<SaveDir>,
@@ -3108,49 +3108,39 @@ impl Game<'_> {
return batch;
}
self.draw_spyglass(&mut batch);
{
let atlas = &self.res.atlas;
// Crosshair (first person only).
if self.camera_type.first_person() {
batch.sprite(
atlas,
"gui/sprites/hud/crosshair",
(w - 15.0) / 2.0,
(h - 15.0) / 2.0,
);
}
}
// Gui: spectators get the (closed) spectator menu instead of the
// hotbar and no player health.
// Hud.extractCrosshair / extractItemHotbar / extractPlayerHealth /
// extractVehicleHealth and the experience bar, laid out by hud_layout.
// Horizon has no attack cooldown yet: the strength is always full.
let spectator = self.spectator();
let (wi, hi) = (w as i32, h as i32);
let indicator = self.settings.attack_indicator;
if self.camera_type.first_person() && !spectator {
let attack = (indicator == 1).then_some(1.0);
let draws = hud_layout::crosshair(wi, hi, attack, false);
hud_layout::paint(&mut batch, &self.res.atlas, &draws);
}
if !spectator {
let atlas = &self.res.atlas;
batch.sprite(atlas, "gui/sprites/hud/hotbar", w / 2.0 - 91.0, h - 22.0);
batch.sprite(
atlas,
"gui/sprites/hud/hotbar_selection",
w / 2.0 - 91.0 - 1.0 + self.selected as f32 * 20.0,
h - 23.0,
);
}
// Hud.extractItemHotbar: the off hand left of the hotbar (right-handed).
if let Some(stack) = self.offhand.clone().filter(|_| !spectator) {
batch.sprite(
&self.res.atlas,
"gui/sprites/hud/hotbar_offhand_left",
w / 2.0 - 91.0 - 29.0,
h - 23.0,
);
self.draw_item(&mut batch, &stack, w / 2.0 - 91.0 - 26.0, h - 19.0);
}
for i in 0..9 {
if let Some(stack) = self.inventory[i].clone().filter(|_| !spectator) {
self.draw_item(
&mut batch,
&stack,
w / 2.0 - 90.0 + i as f32 * 20.0 + 2.0,
h - 19.0,
);
let inputs = hud_layout::HotbarInputs {
selected: self.selected as i32,
right_handed: !self.settings.main_hand_left,
offhand: self.offhand.is_some(),
slots: std::array::from_fn(|i| self.inventory[i].as_ref().map(|_| 0.0)),
offhand_pop: 0.0,
attack: (indicator == 2).then_some(1.0),
};
let draws = hud_layout::hotbar(wi, hi, &inputs);
hud_layout::paint(&mut batch, &self.res.atlas, &draws);
for d in &draws {
if let hud_layout::GuiDraw::Item { slot, x, y, .. } = *d {
let stack = if slot == 40 {
self.offhand.clone()
} else {
self.inventory[slot as usize].clone()
};
if let Some(stack) = stack {
self.draw_item(&mut batch, &stack, x as f32, y as f32);
}
}
}
}
self.draw_effect_icons(&mut batch);
@@ -3160,57 +3150,49 @@ impl Game<'_> {
self.draw_titles(&mut batch);
self.draw_scoreboard(&mut batch);
self.draw_subtitles(&mut batch);
// Gui.renderVehicleHealth / the jump bar while riding a mount.
let mounted = !self.creative && !spectator && self.draw_mount_hud(&mut batch, w, h);
let atlas = &self.res.atlas;
// The mount's hearts (and the jump bar that replaces the experience bar).
let (vehicle_hearts, jump_bar) = if spectator {
(0, false)
} else {
self.draw_mount_hud(&mut batch, wi, hi)
};
if !self.creative
&& !spectator
&& let Some(p) = &mut self.player
{
// Experience bar and hearts/food (Gui.renderPlayerHealth).
let saddled_mount = mounted
&& self
.riding
.and_then(|id| self.mobs.iter().find(|m| m.id == id))
.is_some_and(|m| m.extra.saddled);
if !saddled_mount {
batch.sprite(
atlas,
"gui/sprites/hud/experience_bar_background",
w / 2.0 - 91.0,
h - 29.0,
);
let filled = (self.experience.progress * 183.0).floor() / 182.0;
if filled > 0.0 {
batch.sprite_part(
atlas,
"gui/sprites/hud/experience_bar_progress",
w / 2.0 - 91.0,
h - 29.0,
filled.min(1.0),
);
}
}
if self.experience.level > 0 {
// Gui.renderExperienceLevel: green text with a black outline.
let text = self.experience.level.to_string();
let tw = HudBatch::text_width(atlas, &text);
let (x, y) = ((w - tw) / 2.0, h - 31.0 - 4.0);
for (dx, dy) in [(1.0, 0.0), (-1.0, 0.0), (0.0, 1.0), (0.0, -1.0)] {
batch.text(atlas, &text, x + dx, y + dy, rgba(0, 0, 0, 255), false);
}
batch.text(atlas, &text, x, y, rgba(128, 255, 32, 255), false);
}
let atlas = &self.res.atlas;
let width = |s: &str| HudBatch::text_width(atlas, s) as i32;
let draws = hud_layout::experience(
wi,
hi,
self.experience.progress,
self.experience.level,
!jump_bar,
&width,
);
hud_layout::paint(&mut batch, atlas, &draws);
let effects = &self.potions.effects;
let kind = if effects.get("poison").is_some() {
health_hud::HeartKind::Poisoned
hud_layout::HeartKind::Poisoned
} else if effects.get("wither").is_some() {
health_hud::HeartKind::Withered
hud_layout::HeartKind::Withered
} else {
health_hud::HeartKind::Normal
hud_layout::HeartKind::Normal
};
let inputs = health_hud::HealthInputs {
tick: self.ticks,
let eye = p.position.y + f64::from(p.dimensions.eye_height);
let under_water = self
.res
.facts
.get(self.world.block(
p.position.x.floor() as i32,
eye.floor() as i32,
p.position.z.floor() as i32,
))
.fluid
== horizon_client::blocks::Fluid::Water;
let inputs = hud_layout::HealthInputs {
tick: self.ticks as i32,
millis: self.started.elapsed().as_millis() as i64,
health: p.health.health(),
max_health: p.attribute("minecraft:max_health").unwrap_or(20.0) as f32,
absorption: p.health.absorption(),
@@ -3225,15 +3207,16 @@ impl Game<'_> {
hunger: effects.get("hunger").is_some(),
hardcore: self.level.hardcore,
damage_cooldown: p.health.hurt.cooldown > 0,
show_food: !mounted,
// Horizon does not track the player's air supply yet.
air: 300,
max_air: 300,
under_water,
vehicle_hearts,
};
for (name, x, y) in
self.health_hud
.layout(&inputs, w as i32, h as i32, std::time::Instant::now())
{
batch.sprite(atlas, &name, x as f32, y as f32);
}
let draws = self.health_hud.layout(&inputs, wi, hi);
hud_layout::paint(&mut batch, atlas, &draws);
}
let atlas = &self.res.atlas;
if self.debug {
let p = self
.player
@@ -4483,11 +4466,12 @@ impl Game<'_> {
.unwrap_or((0.0, 0.0));
prev + (cur - prev) * alpha as f32
};
let (view_yaw, view_pitch) = if self.camera_type == perspective::CameraType::ThirdPersonFront {
(self.yaw + 180.0, -self.pitch)
} else {
(self.yaw, self.pitch)
};
let (view_yaw, view_pitch) =
if self.camera_type == perspective::CameraType::ThirdPersonFront {
(self.yaw + 180.0, -self.pitch)
} else {
(self.yaw, self.pitch)
};
let scene = horizon_client::block_entity_render::Scene {
camera,
// Camera.setRotation.
@@ -8504,7 +8488,7 @@ pub fn run() -> Result<()> {
screen: Screen::Playing,
window: None,
renderer: None,
health_hud: health_hud::HealthHud::default(),
health_hud: hud_layout::HealthHud::default(),
started: now,
previous: now,
last_input: now,
@@ -1,226 +0,0 @@
//! `Hud.extractPlayerHealth`: armour, hearts, food. The layout is computed as
//! a list of sprites so it can be tested without drawing.
use std::time::Instant;
/// `java.util.Random`, for the HUD's per-tick jitter.
pub(super) struct JavaRandom(i64);
impl JavaRandom {
pub fn new(seed: i64) -> Self {
Self((seed ^ 0x5_DEEC_E66D) & ((1 << 48) - 1))
}
fn next(&mut self, bits: u32) -> i32 {
self.0 = (self.0.wrapping_mul(0x5_DEEC_E66D).wrapping_add(0xB)) & ((1 << 48) - 1);
(self.0 >> (48 - bits)) as i32
}
pub fn next_int(&mut self, bound: i32) -> i32 {
let mut r = self.next(31);
let m = bound - 1;
if bound & m == 0 {
return ((i64::from(bound) * i64::from(r)) >> 31) as i32;
}
let mut u = r;
loop {
r = u % bound;
if u.wrapping_sub(r).wrapping_add(m) >= 0 {
return r;
}
u = self.next(31);
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum HeartKind {
Normal,
Poisoned,
Withered,
Absorbing,
}
impl HeartKind {
fn prefix(self) -> &'static str {
match self {
Self::Normal => "",
Self::Poisoned => "poisoned_",
Self::Withered => "withered_",
Self::Absorbing => "absorbing_",
}
}
}
/// State kept between frames (`Hud.lastHealth`, `displayHealth`, ...).
pub(super) struct HealthHud {
last_health: i32,
display_health: i32,
last_health_time: Instant,
health_blink_time: i64,
}
impl Default for HealthHud {
fn default() -> Self {
Self {
last_health: 0,
display_health: 0,
last_health_time: Instant::now(),
health_blink_time: 0,
}
}
}
pub(super) struct HealthInputs {
pub tick: u64,
pub health: f32,
pub max_health: f32,
pub absorption: f32,
pub armor: i32,
pub food: i32,
pub saturation: f32,
pub kind: HeartKind,
pub regeneration: bool,
pub hunger: bool,
pub hardcore: bool,
/// `damageCooldownTime > 0`.
pub damage_cooldown: bool,
/// A mount with its own hearts replaces the food bar.
pub show_food: bool,
}
fn heart_sprite(kind: HeartKind, hardcore: bool, half: bool, blink: bool) -> String {
let (hc, h) = (
if hardcore { "hardcore_" } else { "" },
if half { "half" } else { "full" },
);
let b = if blink { "_blinking" } else { "" };
format!("gui/sprites/hud/heart/{}{hc}{h}{b}", kind.prefix())
}
impl HealthHud {
/// Sprites (name, x, y) in draw order for a screen of `w` x `h` GUI pixels.
pub fn layout(
&mut self,
i: &HealthInputs,
w: i32,
h: i32,
now: Instant,
) -> Vec<(String, i32, i32)> {
let mut out = Vec::new();
let tick = i64::try_from(i.tick).unwrap_or(i64::MAX);
let current = i.health.ceil() as i32;
let blink = self.health_blink_time > tick && (self.health_blink_time - tick) / 3 % 2 == 1;
if current < self.last_health && i.damage_cooldown {
self.last_health_time = now;
self.health_blink_time = tick + 20;
} else if current > self.last_health && i.damage_cooldown {
self.last_health_time = now;
self.health_blink_time = tick + 10;
}
if now.duration_since(self.last_health_time).as_millis() > 1000 {
self.display_health = current;
self.last_health_time = now;
}
self.last_health = current;
let old = self.display_health;
let mut random = JavaRandom::new(i64::from((i.tick as i32).wrapping_mul(312_871)));
let (x_left, x_right, y_base) = (w / 2 - 91, w / 2 + 91, h - 39);
let max_health = i.max_health.max(old.max(current) as f32);
let absorption = i.absorption.ceil() as i32;
let rows = ((max_health + absorption as f32) / 2.0 / 10.0).ceil() as i32;
let row_height = (10 - (rows - 2)).max(3);
let offset_index = if i.regeneration {
(i.tick as i32).rem_euclid((max_health + 5.0).ceil() as i32)
} else {
-1
};
if i.armor > 0 {
let y = y_base - (rows - 1) * row_height - 10;
for n in 0..10 {
let name = match (n * 2 + 1).cmp(&i.armor) {
std::cmp::Ordering::Less => "armor_full",
std::cmp::Ordering::Equal => "armor_half",
std::cmp::Ordering::Greater => "armor_empty",
};
out.push((format!("gui/sprites/hud/{name}"), x_left + n * 8, y));
}
}
let containers = (max_health / 2.0).ceil() as i32;
let absorb_containers = (absorption as f32 / 2.0).ceil() as i32;
let container = |hardcore: bool, blink: bool| {
format!(
"gui/sprites/hud/heart/container{}{}",
if hardcore { "_hardcore" } else { "" },
if blink { "_blinking" } else { "" }
)
};
for c in (0..containers + absorb_containers).rev() {
let (row, column) = (c / 10, c % 10);
let x = x_left + column * 8;
let mut y = y_base - row * row_height;
if current + absorption <= 4 {
y += random.next_int(2);
}
if c < containers && c == offset_index {
y -= 2;
}
out.push((container(i.hardcore, blink), x, y));
let halves = c * 2;
if c >= containers {
let ah = halves - containers * 2;
if ah < absorption {
let kind = if i.kind == HeartKind::Withered {
i.kind
} else {
HeartKind::Absorbing
};
out.push((
heart_sprite(kind, i.hardcore, ah + 1 == absorption, false),
x,
y,
));
}
}
if blink && halves < old {
out.push((
heart_sprite(i.kind, i.hardcore, halves + 1 == old, true),
x,
y,
));
}
if halves < current {
out.push((
heart_sprite(i.kind, i.hardcore, halves + 1 == current, false),
x,
y,
));
}
}
if i.show_food {
let suffix = if i.hunger { "_hunger" } else { "" };
for n in 0..10 {
let mut y = y_base;
if i.saturation <= 0.0 && (i.tick as i32).rem_euclid(i.food * 3 + 1) == 0 {
y += random.next_int(3) - 1;
}
let x = x_right - n * 8 - 9;
out.push((format!("gui/sprites/hud/food_empty{suffix}"), x, y));
if n * 2 + 1 < i.food {
out.push((format!("gui/sprites/hud/food_full{suffix}"), x, y));
}
if n * 2 + 1 == i.food {
out.push((format!("gui/sprites/hud/food_half{suffix}"), x, y));
}
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn java_random_matches_reference() {
// new Random(42).nextInt(10) sequence: 0, 3, 8, 4, 0.
let mut r = JavaRandom::new(42);
let v: Vec<i32> = (0..5).map(|_| r.next_int(10)).collect();
assert_eq!(v, [0, 3, 8, 4, 0]);
}
}
+11 -28
View File
@@ -453,38 +453,21 @@ impl Game<'_> {
_ => {}
}
}
/// `Gui.renderVehicleHealth` and the jump bar (`JumpableVehicleBarRenderer`).
pub(super) fn draw_mount_hud(&self, batch: &mut HudBatch, w: f32, h: f32) -> bool {
/// `Hud.extractVehicleHealth` and the jump bar that replaces the
/// experience bar on a saddled jumper. Returns the mount's heart count
/// (`getVehicleMaxHearts`) and whether the jump bar shows.
pub(super) fn draw_mount_hud(&self, batch: &mut HudBatch, w: i32, h: i32) -> (i32, bool) {
let Some(i) = self.mount_index() else {
return false;
return (0, false);
};
let m = &self.mobs[i];
let atlas = &self.res.atlas;
// Hearts in rows of ten, right-aligned where the food bar sits.
let max = (m.attrs.max_health + 0.5) as i32 / 2;
let health = m.health.ceil() as i32;
let right = w / 2.0 + 91.0;
let mut y = h - 39.0;
let mut drawn = 0;
while drawn < max {
let row = (max - drawn).min(10);
for k in 0..row {
let x = right - k as f32 * 8.0 - 9.0;
batch.sprite(atlas, "gui/sprites/hud/heart/vehicle_container", x, y);
let v = health - (drawn + k) * 2;
if v >= 2 {
batch.sprite(atlas, "gui/sprites/hud/heart/vehicle_full", x, y);
} else if v == 1 {
batch.sprite(atlas, "gui/sprites/hud/heart/vehicle_half", x, y);
}
}
drawn += row;
y -= 10.0;
}
// The jump bar replaces the experience bar on a saddled jumper.
let hearts = horizon_client::hud_layout::vehicle_max_hearts(m.attrs.max_health as f32);
let draws = horizon_client::hud_layout::vehicle_health(w, h, hearts, m.health as f32);
horizon_client::hud_layout::paint(batch, atlas, &draws);
if m.extra.saddled {
let x = w / 2.0 - 91.0;
let y = h - 29.0;
let x = (w / 2 - 91) as f32;
let y = (h - 29) as f32;
batch.sprite(atlas, "gui/sprites/hud/jump_bar_background", x, y);
if self.mount.jump_ticks < 0 {
batch.sprite(atlas, "gui/sprites/hud/jump_bar_cooldown", x, y);
@@ -501,6 +484,6 @@ impl Game<'_> {
}
}
}
true
(hearts, m.extra.saddled)
}
}
+599
View File
@@ -0,0 +1,599 @@
//! Layout of vanilla's `Hud` decorations as draw calls (`GuiGraphicsExtractor`
//! blits and text): the hotbar with its selection, off-hand slot, items and
//! attack indicator, the crosshair, armour, hearts, food, air bubbles, mount
//! hearts and the experience bar and level. Computed without drawing so the
//! parity fixture can compare them with the vanilla client.
use horizon_core::random::{LegacyRandom, RandomSource};
/// One `GuiGraphicsExtractor` call.
#[derive(Clone, Debug, PartialEq)]
pub enum GuiDraw {
/// `blitSprite(sprite, x, y, w, h)`; `region` = (spriteW, spriteH, u, v)
/// for the partial overload.
Sprite {
sprite: &'static str,
x: i32,
y: i32,
w: i32,
h: i32,
region: Option<[i32; 4]>,
},
/// `text(font, text, x, y, argb, dropShadow)`.
Text {
text: String,
x: i32,
y: i32,
color: u32,
shadow: bool,
},
/// `item(owner, stack, x, y, seed)` for a hotbar slot (0-8, 40 = off hand)
/// under the pose's x/y scale about (cx, cy) (the pop squeeze).
Item {
slot: u32,
x: i32,
y: i32,
seed: i32,
scale: [f32; 2],
pivot: [f32; 2],
},
}
fn sprite(sprite: &'static str, x: i32, y: i32, w: i32, h: i32) -> GuiDraw {
GuiDraw::Sprite {
sprite,
x,
y,
w,
h,
region: None,
}
}
/// `Hud.extractItemHotbar` inputs.
pub struct HotbarInputs {
pub selected: i32,
/// The main arm is the right one (the off hand sits left of the hotbar).
pub right_handed: bool,
pub offhand: bool,
/// Pop time minus partial tick (`ItemStack.getPopTime`) per hotbar slot
/// that holds an item, then the off hand.
pub slots: [Option<f32>; 9],
pub offhand_pop: f32,
/// `getAttackStrengthScale(0)` when the attack indicator is in HOTBAR mode.
pub attack: Option<f32>,
}
/// `Hud.extractItemHotbar`.
pub fn hotbar(w: i32, h: i32, i: &HotbarInputs) -> Vec<GuiDraw> {
let mut out = Vec::new();
let center = w / 2;
out.push(sprite("hud/hotbar", center - 91, h - 22, 182, 22));
out.push(sprite(
"hud/hotbar_selection",
center - 91 - 1 + i.selected * 20,
h - 22 - 1,
24,
23,
));
// The off hand is opposite the main arm.
let offhand_left = i.right_handed;
if i.offhand {
if offhand_left {
out.push(sprite(
"hud/hotbar_offhand_left",
center - 91 - 29,
h - 23,
29,
24,
));
} else {
out.push(sprite(
"hud/hotbar_offhand_right",
center + 91,
h - 23,
29,
24,
));
}
}
let slot = |slot: u32, x: i32, y: i32, seed: i32, pop: f32, out: &mut Vec<GuiDraw>| {
let (scale, pivot) = if pop > 0.0 {
let squeeze = 1.0 + pop / 5.0;
(
[1.0 / squeeze, (squeeze + 1.0) / 2.0],
[(x + 8) as f32, (y + 12) as f32],
)
} else {
([1.0, 1.0], [0.0, 0.0])
};
out.push(GuiDraw::Item {
slot,
x,
y,
seed,
scale,
pivot,
});
};
let mut seed = 1;
for (n, pop) in i.slots.iter().enumerate() {
if let Some(pop) = pop {
slot(
n as u32,
center - 90 + n as i32 * 20 + 2,
h - 16 - 3,
seed,
*pop,
&mut out,
);
}
seed += 1;
}
if i.offhand {
let x = if offhand_left {
center - 91 - 26
} else {
center + 91 + 10
};
slot(40, x, h - 16 - 3, seed, i.offhand_pop, &mut out);
}
if let Some(scale) = i.attack
&& scale < 1.0
{
let y = h - 20;
let x = if offhand_left {
center + 91 + 6
} else {
center - 91 - 22
};
let progress = (scale * 19.0) as i32;
out.push(sprite(
"hud/hotbar_attack_indicator_background",
x,
y,
18,
18,
));
out.push(GuiDraw::Sprite {
sprite: "hud/hotbar_attack_indicator_progress",
x,
y: y + 18 - progress,
w: 18,
h: progress,
region: Some([18, 18, 0, 18 - progress]),
});
}
out
}
/// `Hud.extractCrosshair` (first person, not hidden for spectators):
/// `attack` is `getAttackStrengthScale(0)` in CROSSHAIR indicator mode and
/// `full` whether the full indicator shows for a target in reach.
pub fn crosshair(w: i32, h: i32, attack: Option<f32>, full: bool) -> Vec<GuiDraw> {
let mut out = vec![sprite("hud/crosshair", (w - 15) / 2, (h - 15) / 2, 15, 15)];
if let Some(scale) = attack {
let (x, y) = (w / 2 - 8, h / 2 - 7 + 16);
if full {
out.push(sprite("hud/crosshair_attack_indicator_full", x, y, 16, 16));
} else if scale < 1.0 {
let progress = (scale * 17.0) as i32;
out.push(sprite(
"hud/crosshair_attack_indicator_background",
x,
y,
16,
4,
));
out.push(GuiDraw::Sprite {
sprite: "hud/crosshair_attack_indicator_progress",
x,
y,
w: progress,
h: 4,
region: Some([16, 4, 0, 0]),
});
}
}
out
}
/// `ExperienceBar.extractBackground` and `ContextualBar.extractExperienceLevel`;
/// `width` measures text with the font.
pub fn experience(
w: i32,
h: i32,
progress: f32,
level: i32,
bar: bool,
width: &dyn Fn(&str) -> i32,
) -> Vec<GuiDraw> {
let mut out = Vec::new();
if bar {
let (left, top) = (w / 2 - 91, h - 32 + 3);
let filled = (progress * 183.0) as i32;
out.push(sprite("hud/experience_bar_background", left, top, 182, 5));
if filled > 0 {
out.push(GuiDraw::Sprite {
sprite: "hud/experience_bar_progress",
x: left,
y: top,
w: filled,
h: 5,
region: Some([182, 5, 0, 0]),
});
}
}
if level > 0 {
let text = level.to_string();
let x = (w - width(&text)) / 2;
let y = h - 24 - 9 - 2;
for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)] {
out.push(GuiDraw::Text {
text: text.clone(),
x: x + dx,
y: y + dy,
color: 0xFF00_0000,
shadow: false,
});
}
out.push(GuiDraw::Text {
text,
x,
y,
color: 0xFF80_FF20,
shadow: false,
});
}
out
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum HeartKind {
Normal,
Poisoned,
Withered,
Frozen,
}
/// State kept between frames (`Hud.lastHealth`, `displayHealth`, ...).
#[derive(Clone, Debug, Default)]
pub struct HealthHud {
pub last_health: i32,
pub display_health: i32,
/// `Util.getMillis()` of the last health change.
pub last_health_time: i64,
pub health_blink_time: i64,
}
pub struct HealthInputs {
/// `Hud.tickCount`.
pub tick: i32,
/// `Util.getMillis()` now.
pub millis: i64,
pub health: f32,
pub max_health: f32,
pub absorption: f32,
pub armor: i32,
pub food: i32,
pub saturation: f32,
pub kind: HeartKind,
pub regeneration: bool,
pub hunger: bool,
pub hardcore: bool,
/// `damageCooldownTime > 0`.
pub damage_cooldown: bool,
/// `getAirSupply`, `getMaxAirSupply`, `isEyeInFluid(WATER)`.
pub air: i32,
pub max_air: i32,
pub under_water: bool,
/// `getVehicleMaxHearts` of the ridden living vehicle (0 = none).
pub vehicle_hearts: i32,
}
/// `Hud.getVehicleMaxHearts` for a vehicle that shows its health.
pub fn vehicle_max_hearts(max_health: f32) -> i32 {
(((max_health + 0.5) as i32) / 2).min(30)
}
/// `Hud.extractVehicleHealth`.
pub fn vehicle_health(w: i32, h: i32, hearts: i32, health: f32) -> Vec<GuiDraw> {
let mut out = Vec::new();
let current = f64::from(health).ceil() as i32;
let x_right = w / 2 + 91;
let mut yo = h - 39;
let mut hearts = hearts;
let mut base = 0;
while hearts > 0 {
let row = hearts.min(10);
hearts -= row;
for i in 0..row {
let xo = x_right - i * 8 - 9;
out.push(sprite("hud/heart/vehicle_container", xo, yo, 9, 9));
if i * 2 + 1 + base < current {
out.push(sprite("hud/heart/vehicle_full", xo, yo, 9, 9));
}
if i * 2 + 1 + base == current {
out.push(sprite("hud/heart/vehicle_half", xo, yo, 9, 9));
}
}
yo -= 10;
base += 20;
}
out
}
fn heart(
kind: Option<HeartKind>,
absorbing: bool,
hardcore: bool,
half: bool,
blink: bool,
) -> &'static str {
// Hud.HeartType sprites: [full, full_blinking, half, half_blinking] x [normal, hardcore].
let table: [&'static str; 8] = match (kind, absorbing) {
(None, _) => [
"hud/heart/container",
"hud/heart/container_blinking",
"hud/heart/container",
"hud/heart/container_blinking",
"hud/heart/container_hardcore",
"hud/heart/container_hardcore_blinking",
"hud/heart/container_hardcore",
"hud/heart/container_hardcore_blinking",
],
(_, true) => [
"hud/heart/absorbing_full",
"hud/heart/absorbing_full_blinking",
"hud/heart/absorbing_half",
"hud/heart/absorbing_half_blinking",
"hud/heart/absorbing_hardcore_full",
"hud/heart/absorbing_hardcore_full_blinking",
"hud/heart/absorbing_hardcore_half",
"hud/heart/absorbing_hardcore_half_blinking",
],
(Some(HeartKind::Normal), _) => [
"hud/heart/full",
"hud/heart/full_blinking",
"hud/heart/half",
"hud/heart/half_blinking",
"hud/heart/hardcore_full",
"hud/heart/hardcore_full_blinking",
"hud/heart/hardcore_half",
"hud/heart/hardcore_half_blinking",
],
(Some(HeartKind::Poisoned), _) => [
"hud/heart/poisoned_full",
"hud/heart/poisoned_full_blinking",
"hud/heart/poisoned_half",
"hud/heart/poisoned_half_blinking",
"hud/heart/poisoned_hardcore_full",
"hud/heart/poisoned_hardcore_full_blinking",
"hud/heart/poisoned_hardcore_half",
"hud/heart/poisoned_hardcore_half_blinking",
],
(Some(HeartKind::Withered), _) => [
"hud/heart/withered_full",
"hud/heart/withered_full_blinking",
"hud/heart/withered_half",
"hud/heart/withered_half_blinking",
"hud/heart/withered_hardcore_full",
"hud/heart/withered_hardcore_full_blinking",
"hud/heart/withered_hardcore_half",
"hud/heart/withered_hardcore_half_blinking",
],
(Some(HeartKind::Frozen), _) => [
"hud/heart/frozen_full",
"hud/heart/frozen_full_blinking",
"hud/heart/frozen_half",
"hud/heart/frozen_half_blinking",
"hud/heart/frozen_hardcore_full",
"hud/heart/frozen_hardcore_full_blinking",
"hud/heart/frozen_hardcore_half",
"hud/heart/frozen_hardcore_half_blinking",
],
};
table[usize::from(hardcore) * 4 + usize::from(half) * 2 + usize::from(blink)]
}
fn ceil(x: f32) -> i32 {
// Mth.ceil.
let i = x as i32;
if x > i as f32 { i + 1 } else { i }
}
impl HealthHud {
/// `Hud.extractPlayerHealth` for a screen of `w` x `h` GUI pixels.
pub fn layout(&mut self, i: &HealthInputs, w: i32, h: i32) -> Vec<GuiDraw> {
let mut out = Vec::new();
let tick = i64::from(i.tick);
let current = ceil(i.health);
let blink = self.health_blink_time > tick && (self.health_blink_time - tick) / 3 % 2 == 1;
if current < self.last_health && i.damage_cooldown {
self.last_health_time = i.millis;
self.health_blink_time = tick + 20;
} else if current > self.last_health && i.damage_cooldown {
self.last_health_time = i.millis;
self.health_blink_time = tick + 10;
}
if i.millis - self.last_health_time > 1000 {
self.display_health = current;
self.last_health_time = i.millis;
}
self.last_health = current;
let old = self.display_health;
let mut random = LegacyRandom::new(i64::from(i.tick.wrapping_mul(312_871)));
let mut next = |bound: i32| random.next_int_bound(bound).unwrap_or(0);
let (x_left, x_right, y_base) = (w / 2 - 91, w / 2 + 91, h - 39);
let max_health = i.max_health.max(old.max(current) as f32);
let absorption = ceil(i.absorption);
let rows = ceil((max_health + absorption as f32) / 2.0 / 10.0);
let row_height = (10 - (rows - 2)).max(3);
let mut y_air = y_base - 10;
let offset_index = if i.regeneration {
i.tick % ceil(max_health + 5.0)
} else {
-1
};
if i.armor > 0 {
let y = y_base - (rows - 1) * row_height - 10;
for n in 0..10 {
let x = x_left + n * 8;
if n * 2 + 1 < i.armor {
out.push(sprite("hud/armor_full", x, y, 9, 9));
}
if n * 2 + 1 == i.armor {
out.push(sprite("hud/armor_half", x, y, 9, 9));
}
if n * 2 + 1 > i.armor {
out.push(sprite("hud/armor_empty", x, y, 9, 9));
}
}
}
let containers = f64::from(max_health / 2.0).ceil() as i32;
let absorb_containers = (f64::from(absorption) / 2.0).ceil() as i32;
for c in (0..containers + absorb_containers).rev() {
let (row, column) = (c / 10, c % 10);
let x = x_left + column * 8;
let mut y = y_base - row * row_height;
if current + absorption <= 4 {
y += next(2);
}
if c < containers && c == offset_index {
y -= 2;
}
out.push(sprite(
heart(None, false, i.hardcore, false, blink),
x,
y,
9,
9,
));
let halves = c * 2;
if c >= containers {
let ah = halves - containers * 2;
if ah < absorption {
let withered = i.kind == HeartKind::Withered;
let name = heart(
Some(i.kind),
!withered,
i.hardcore,
ah + 1 == absorption,
false,
);
out.push(sprite(name, x, y, 9, 9));
}
}
if blink && halves < old {
let name = heart(Some(i.kind), false, i.hardcore, halves + 1 == old, true);
out.push(sprite(name, x, y, 9, 9));
}
if halves < current {
let name = heart(
Some(i.kind),
false,
i.hardcore,
halves + 1 == current,
false,
);
out.push(sprite(name, x, y, 9, 9));
}
}
if i.vehicle_hearts == 0 {
let (empty, half, full) = if i.hunger {
(
"hud/food_empty_hunger",
"hud/food_half_hunger",
"hud/food_full_hunger",
)
} else {
("hud/food_empty", "hud/food_half", "hud/food_full")
};
for n in 0..10 {
let mut y = y_base;
if i.saturation <= 0.0 && i.tick % (i.food * 3 + 1) == 0 {
y += next(3) - 1;
}
let x = x_right - n * 8 - 9;
out.push(sprite(empty, x, y, 9, 9));
if n * 2 + 1 < i.food {
out.push(sprite(full, x, y, 9, 9));
}
if n * 2 + 1 == i.food {
out.push(sprite(half, x, y, 9, 9));
}
}
y_air -= 10;
}
// Hud.extractAirBubbles.
let max_air = i.max_air.max(1);
let air = i.air.clamp(0, max_air);
if i.under_water || air < max_air {
let rows = (f64::from(i.vehicle_hearts) / 10.0).ceil() as i32;
let y = y_air - (rows - 1) * 10;
let bubble = |offset: i32| ceil(((air + offset) * 10) as f32 / max_air as f32);
let full = bubble(-2);
let popping = bubble(0);
let delay = i32::from(air != 0 && i.under_water);
let empty = 10 - bubble(delay);
for b in 1..=10 {
let x = x_right - (b - 1) * 8 - 9;
if b <= full {
out.push(sprite("hud/air", x, y, 9, 9));
} else if full != popping && b == popping && i.under_water {
out.push(sprite("hud/air_bursting", x, y, 9, 9));
} else if b > 10 - empty {
let wobble = if empty == 10 && i.tick % 2 == 0 {
next(2)
} else {
0
};
out.push(sprite("hud/air_empty", x, y + wobble, 9, 9));
}
}
}
out
}
}
/// Draws the sprite and text calls with the HUD batch; items are left to the
/// caller (they need the item renderer).
pub fn paint(batch: &mut crate::hud::HudBatch, atlas: &crate::hud::HudAtlas, draws: &[GuiDraw]) {
for d in draws {
match d {
GuiDraw::Sprite {
sprite,
x,
y,
w,
h,
region,
} => {
let Some(mut r) = atlas.sprites.get(&format!("gui/sprites/{sprite}")).copied()
else {
continue;
};
if let Some([sw, sh, u, v]) = *region {
let (du, dv) = (r.u1 - r.u0, r.v1 - r.v0);
let u0 = r.u0 + du * u as f32 / sw as f32;
let v0 = r.v0 + dv * v as f32 / sh as f32;
r.u1 = u0 + du * *w as f32 / sw as f32;
r.v1 = v0 + dv * *h as f32 / sh as f32;
r.u0 = u0;
r.v0 = v0;
}
batch.rect_uv(*x as f32, *y as f32, *w as f32, *h as f32, r, u32::MAX);
}
GuiDraw::Text {
text,
x,
y,
color,
shadow,
} => {
let [a, r, g, b] = color.to_be_bytes();
let rgba = crate::hud::rgba(r, g, b, a);
batch.text(atlas, text, *x as f32, *y as f32, rgba, *shadow);
}
GuiDraw::Item { .. } => {}
}
}
}
+1
View File
@@ -41,6 +41,7 @@ pub mod gfx;
pub mod gossip;
pub mod health;
pub mod hud;
pub mod hud_layout;
pub mod hunger;
pub mod input;
pub mod item_data;
@@ -0,0 +1,292 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import com.mojang.renderpearl.api.pipeline.RenderPipeline;
import java.lang.reflect.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.client.AttackIndicatorStatus;
import net.minecraft.client.DeltaTracker;
import net.minecraft.client.Minecraft;
import net.minecraft.client.OptionInstance;
import net.minecraft.client.Options;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.Hud;
import net.minecraft.client.gui.contextualbar.ExperienceBar;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.multiplayer.MultiPlayerGameMode;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.core.Holder;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.Identifier;
import net.minecraft.tags.FluidTags;
import net.minecraft.tags.TagKey;
import net.minecraft.util.FormattedCharSequence;
import net.minecraft.util.Util;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityEquipment;
import net.minecraft.world.entity.HumanoidArm;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.food.FoodData;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.GameType;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.material.Fluid;
import org.joml.Matrix3x2f;
import org.joml.Matrix3x2fStack;
/**
* Original oracle for the in-game HUD decorations: runs vanilla's own Hud
* methods (extractItemHotbar, extractPlayerHealth, extractVehicleHealth,
* extractCrosshair) and ExperienceBar / ContextualBar on a stand-in client
* (Unsafe-allocated Minecraft, options, game mode, window and level) and a
* player whose state getters answer from the case, and records every
* GuiGraphicsExtractor blit, text and item call.
*
* Input lines: case JSON. Output lines: {case, draws:[...]} or {case, error}.
*/
public final class VanillaHudOracle {
static Object unsafe;
static Method allocate;
static JsonObject c;
static IdentityHashMap<ItemStack, Integer> slots = new IdentityHashMap<>();
@SuppressWarnings("unchecked")
static <T> T alloc(Class<T> type) throws Exception {
return (T) allocate.invoke(unsafe, type);
}
static Field field(Class<?> type, String name) throws NoSuchFieldException {
for (Class<?> k = type; k != null; k = k.getSuperclass()) {
try {
Field f = k.getDeclaredField(name);
f.setAccessible(true);
return f;
} catch (NoSuchFieldException e) {
}
}
throw new NoSuchFieldException(name + " on " + type);
}
static void put(Object target, Class<?> owner, String name, Object value) throws Exception {
Field f = field(owner, name);
long offset = (long) unsafe.getClass().getMethod("objectFieldOffset", Field.class).invoke(unsafe, f);
Class<?> t = f.getType();
String setter = t == int.class ? "putInt" : t == boolean.class ? "putBoolean" : t == float.class ? "putFloat" : t == long.class ? "putLong" : "putObject";
Class<?> param = t.isPrimitive() ? t : Object.class;
unsafe.getClass().getMethod(setter, Object.class, long.class, param).invoke(unsafe, target, offset, value);
}
static float f(String k, float d) { return c.has(k) && !c.get(k).isJsonNull() ? c.get(k).getAsFloat() : d; }
static int i(String k, int d) { return c.has(k) && !c.get(k).isJsonNull() ? c.get(k).getAsInt() : d; }
static boolean b(String k) { return c.has(k) && c.get(k).getAsBoolean(); }
/** A player whose HUD-facing getters answer from the case. */
public static final class Actor extends LocalPlayer {
Level level;
Entity vehicle;
FoodData food;
ItemStack offhand = ItemStack.EMPTY;
private Actor() { super(null, null, null, null, null, null, false, null, null); }
@Override public float getHealth() { return f("health", 20); }
@Override public double getAttributeValue(Holder<Attribute> a) { return a == Attributes.MAX_HEALTH ? f("maxHealth", 20) : 0.0; }
@Override public float getAbsorptionAmount() { return f("absorption", 0); }
@Override public int getArmorValue() { return i("armor", 0); }
@Override public FoodData getFoodData() { return food; }
@Override public boolean hasEffect(Holder<MobEffect> effect) {
for (var e : c.getAsJsonArray("effects")) if (effect.is(Identifier.parse(e.getAsString()))) return true;
return false;
}
@Override public boolean isFullyFrozen() { return b("frozen"); }
@Override public int getAirSupply() { return i("air", 300); }
@Override public int getMaxAirSupply() { return i("maxAir", 300); }
@Override public boolean isEyeInFluid(TagKey<Fluid> tag) { return tag == FluidTags.WATER && b("underWater"); }
@Override public Entity getVehicle() { return vehicle; }
@Override public ItemStack getOffhandItem() { return offhand; }
@Override public HumanoidArm getMainArm() { return b("rightHanded") ? HumanoidArm.RIGHT : HumanoidArm.LEFT; }
@Override public float getAttackStrengthScale(float a) { return f("attackScale", 1); }
@Override public Level level() { return level; }
@Override public boolean isSpectator() { return false; }
@Override public void playSound(net.minecraft.sounds.SoundEvent sound, float volume, float pitch) { }
}
/** A ridden mount answering health from the case. */
public static final class Mount extends net.minecraft.world.entity.animal.equine.Horse {
private Mount() { super(null, null); }
@Override public float getHealth() { return f("vehicleHealth", 0); }
@Override public double getAttributeValue(Holder<Attribute> a) { return a == Attributes.MAX_HEALTH ? f("vehicleMaxHealth", 0) : 0.0; }
@Override public boolean showVehicleHealth() { return true; }
}
/** Records GuiGraphicsExtractor calls. */
public static final class Capture extends GuiGraphicsExtractor {
JsonArray draws;
Matrix3x2fStack stack;
private Capture() { super(null, null, 0, 0); }
@Override public int guiWidth() { return i("width", 0); }
@Override public int guiHeight() { return i("height", 0); }
@Override public Matrix3x2fStack pose() { return stack; }
@Override public void nextStratum() { }
void sprite(Identifier id, int x, int y, int w, int h, int[] region, int color) {
var o = new JsonObject();
o.addProperty("type", "sprite");
o.addProperty("sprite", id.getPath());
o.addProperty("x", x); o.addProperty("y", y); o.addProperty("w", w); o.addProperty("h", h);
if (region != null) {
var r = new JsonArray();
for (int v : region) r.add(v);
o.add("region", r);
}
o.addProperty("color", color);
draws.add(o);
}
@Override public void blitSprite(RenderPipeline p, Identifier id, int x, int y, int w, int h, int color) { sprite(id, x, y, w, h, null, color); }
@Override public void blitSprite(RenderPipeline p, Identifier id, int sw, int sh, int u, int v, int x, int y, int w, int h, int color) {
sprite(id, x, y, w, h, new int[] {sw, sh, u, v}, color);
}
@Override public void text(Font font, FormattedCharSequence str, int x, int y, int color, boolean shadow) {
var o = new JsonObject();
o.addProperty("type", "text");
var sb = new StringBuilder();
str.accept((index, style, cp) -> { sb.appendCodePoint(cp); return true; });
o.addProperty("text", sb.toString());
o.addProperty("x", x); o.addProperty("y", y); o.addProperty("color", color); o.addProperty("shadow", shadow);
draws.add(o);
}
@Override public void item(LivingEntity owner, ItemStack stack, int x, int y, int seed) {
var o = new JsonObject();
o.addProperty("type", "item");
o.addProperty("slot", slots.getOrDefault(stack, -1));
o.addProperty("x", x); o.addProperty("y", y); o.addProperty("seed", seed);
var m = new Matrix3x2f(stack.isEmpty() ? new Matrix3x2f() : this.stack);
var a = new JsonArray();
for (float v : new float[] {m.m00, m.m01, m.m10, m.m11, m.m20, m.m21}) a.add(v);
o.add("matrix", a);
draws.add(o);
}
@Override public void itemDecorations(Font font, ItemStack stack, int x, int y, String count) { }
}
public static void main(String[] args) throws Exception {
ParityData.init();
var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
unsafe = unsafeField.get(null);
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
Font font = ParityFont.create(ParityFont.resources());
Method hotbar = Hud.class.getDeclaredMethod("extractItemHotbar", GuiGraphicsExtractor.class, DeltaTracker.class);
Method health = Hud.class.getDeclaredMethod("extractPlayerHealth", GuiGraphicsExtractor.class);
Method vehicle = Hud.class.getDeclaredMethod("extractVehicleHealth", GuiGraphicsExtractor.class);
Method crosshair = Hud.class.getDeclaredMethod("extractCrosshair", GuiGraphicsExtractor.class, DeltaTracker.class);
crosshair.setAccessible(true);
for (Method m : new Method[] {hotbar, health, vehicle}) m.setAccessible(true);
Method level = Class.forName("net.minecraft.client.gui.contextualbar.ContextualBar")
.getDeclaredMethod("extractExperienceLevel", GuiGraphicsExtractor.class, Font.class, int.class);
level.setAccessible(true);
var gson = new Gson();
var out = new StringBuilder();
for (String line : Files.readAllLines(Path.of(args[0]))) {
if (line.isBlank()) continue;
c = JsonParser.parseString(line).getAsJsonObject();
var result = new JsonObject();
result.add("case", c);
try {
slots.clear();
var mc = alloc(Minecraft.class);
var actor = alloc(Actor.class);
var clientLevel = alloc(ClientLevel.class);
var levelData = alloc(ClientLevel.ClientLevelData.class);
put(levelData, ClientLevel.ClientLevelData.class, "hardcore", b("hardcore"));
put(clientLevel, ClientLevel.class, "clientLevelData", levelData);
actor.level = clientLevel;
actor.offhand = ItemStack.EMPTY;
actor.food = new FoodData();
actor.food.setFoodLevel(i("food", 20));
actor.food.setSaturation(f("saturation", 5));
actor.damageCooldownTime = i("damageCooldown", 0);
actor.experienceProgress = f("xpProgress", 0);
actor.experienceLevel = i("xpLevel", 0);
var inventory = new Inventory(actor, new EntityEquipment());
put(actor, net.minecraft.world.entity.player.Player.class, "inventory", inventory);
inventory.setSelectedSlot(i("selected", 0));
var stacks = c.getAsJsonArray("slots");
var items = new net.minecraft.world.item.Item[] {Items.STONE, Items.DIAMOND_SWORD, Items.APPLE, Items.TORCH, Items.BOW,
Items.OAK_LOG, Items.BREAD, Items.SHIELD, Items.COMPASS};
for (int n = 0; n < 9; n++) {
if (stacks.get(n).isJsonNull()) continue;
var stack = new ItemStack(items[n]);
stack.setPopTime(stacks.get(n).getAsInt());
inventory.setItem(n, stack);
slots.put(stack, n);
}
if (c.has("offhand") && !c.get("offhand").isJsonNull()) {
actor.offhand = new ItemStack(Items.TOTEM_OF_UNDYING);
actor.offhand.setPopTime(c.get("offhand").getAsInt());
slots.put(actor.offhand, 40);
}
if (c.has("vehicleMaxHealth")) actor.vehicle = alloc(Mount.class);
put(mc, Minecraft.class, "player", actor);
var camera = alloc(net.minecraft.client.Camera.class);
put(camera, net.minecraft.client.Camera.class, "entity", actor);
var renderer = alloc(net.minecraft.client.renderer.GameRenderer.class);
put(renderer, net.minecraft.client.renderer.GameRenderer.class, "mainCamera", camera);
put(mc, Minecraft.class, "gameRenderer", renderer);
put(mc, Minecraft.class, "font", font);
var gameMode = alloc(MultiPlayerGameMode.class);
put(gameMode, MultiPlayerGameMode.class, "localPlayerMode", GameType.byName(c.get("gameMode").getAsString()));
put(mc, Minecraft.class, "gameMode", gameMode);
var options = alloc(Options.class);
var indicator = alloc(OptionInstance.class);
put(indicator, OptionInstance.class, "value", AttackIndicatorStatus.valueOf(c.get("attackIndicator").getAsString()));
put(options, Options.class, "attackIndicator", indicator);
put(mc, Minecraft.class, "options", options);
var window = alloc(com.mojang.blaze3d.platform.Window.class);
put(window, com.mojang.blaze3d.platform.Window.class, "guiScaledWidth", i("width", 0));
put(window, com.mojang.blaze3d.platform.Window.class, "guiScaledHeight", i("height", 0));
put(mc, Minecraft.class, "window", window);
var hud = alloc(Hud.class);
put(hud, Hud.class, "minecraft", mc);
put(hud, Hud.class, "random", net.minecraft.util.RandomSource.create());
put(hud, Hud.class, "tickCount", i("tick", 0));
put(hud, Hud.class, "lastHealth", i("lastHealth", 0));
put(hud, Hud.class, "displayHealth", i("displayHealth", 0));
put(hud, Hud.class, "lastHealthTime", Util.getMillis() - (long) i("lastHealthAgo", 0));
put(hud, Hud.class, "healthBlinkTime", (long) i("healthBlinkTime", 0));
var capture = alloc(Capture.class);
capture.draws = new JsonArray();
capture.stack = new Matrix3x2fStack(16);
float partial = f("partial", 0);
DeltaTracker delta = (DeltaTracker) Proxy.newProxyInstance(DeltaTracker.class.getClassLoader(), new Class<?>[] {DeltaTracker.class},
(proxy, method, a) -> method.getReturnType() == float.class ? partial : null);
var mode = GameType.byName(c.get("gameMode").getAsString());
if (c.has("crosshair") && c.get("crosshair").getAsBoolean()) {
put(options, Options.class, "cameraType", net.minecraft.client.CameraType.FIRST_PERSON);
var debug = alloc(net.minecraft.client.gui.components.debug.DebugScreenEntryList.class);
put(debug, net.minecraft.client.gui.components.debug.DebugScreenEntryList.class, "currentlyEnabled", new ArrayList<Identifier>());
put(mc, Minecraft.class, "debugEntries", debug);
crosshair.invoke(hud, capture, delta);
}
if (mode != GameType.SPECTATOR) hotbar.invoke(hud, capture, delta);
if (mode.isSurvival()) health.invoke(hud, capture);
vehicle.invoke(hud, capture);
if (c.has("experienceBar") && c.get("experienceBar").getAsBoolean()) new ExperienceBar(mc).extractBackground(capture, delta);
if (mode.isSurvival() && actor.experienceLevel > 0) level.invoke(null, capture, font, actor.experienceLevel);
result.add("draws", capture.draws);
} catch (Throwable error) {
var cause = error instanceof InvocationTargetException && error.getCause() != null ? error.getCause() : error;
var sw = new java.io.StringWriter();
cause.printStackTrace(new java.io.PrintWriter(sw));
result.addProperty("error", sw.toString().lines().limit(8).reduce("", (x, y) -> x + y + " | "));
}
out.append(gson.toJson(result)).append('\n');
}
Files.writeString(Path.of(args[1]), out.toString(), StandardCharsets.UTF_8);
}
}
+126
View File
@@ -0,0 +1,126 @@
#!/usr/bin/env python3
"""Compare the in-game HUD decorations with the vanilla 26.3 client's Hud.
The Java oracle (VanillaHudOracle) runs vanilla's own Hud.extractCrosshair,
extractItemHotbar, extractPlayerHealth, extractVehicleHealth, ExperienceBar
and ContextualBar.extractExperienceLevel on a stand-in client whose player
answers from the case, and records every blit (sprite, position, size,
partial region), text call (string, position, colour, shadow) and hotbar
item (slot, position, seed, pose). `examples/hud_fixture` lays out the same
state with `horizon_client::hud_layout`; the ordered call lists must agree.
test_hud_parity.py [--count N] [--detail N]
"""
import argparse
import json
import os
import random
import subprocess
import sys
try:
from . import lab, test_rust_parity as base, test_model_baking_parity as baking
except ImportError:
import lab, test_rust_parity as base, test_model_baking_parity as baking
PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity'
EFFECTS = ['minecraft:poison', 'minecraft:wither', 'minecraft:regeneration', 'minecraft:hunger', 'minecraft:speed']
def cases(count):
rng = random.Random(0x485544)
out = []
for n in range(count):
max_health = rng.choice([20.0, 20.0, 6.0, 40.0, 33.0, 100.0])
health = rng.choice([max_health, round(rng.uniform(0, max_health), 2), 1.0, 0.5, 3.0])
air_max = 300
under = rng.random() < 0.3
air = rng.choice([air_max, rng.randint(-20, air_max), 0, 1, 29, 30, 31, 299]) if under or rng.random() < 0.2 else air_max
case = {
'width': rng.choice([427, 320, 480, 640, 961]), 'height': rng.choice([240, 255, 270, 360, 501]),
'gameMode': rng.choice(['survival'] * 5 + ['adventure', 'creative', 'spectator']),
'crosshair': rng.random() < 0.7,
'attackIndicator': rng.choice(['OFF', 'CROSSHAIR', 'HOTBAR']),
'attackScale': rng.choice([1.0, round(rng.random(), 3), 0.0, 0.999]),
'selected': rng.randint(0, 8), 'rightHanded': rng.random() < 0.7,
'slots': [rng.choice([None, 0, 0, 3, 5]) if rng.random() < 0.6 else None for _ in range(9)],
'offhand': rng.choice([None, None, 0, 4]), 'partial': round(rng.random(), 3),
'health': health, 'maxHealth': max_health,
'absorption': rng.choice([0.0, 0.0, 4.0, 3.5, 17.0, 40.0]),
'armor': rng.choice([0, 0, 1, 7, 20, 13]), 'food': rng.randint(0, 20),
'saturation': rng.choice([0.0, 5.0, 0.0]),
'effects': [e for e in EFFECTS if rng.random() < 0.15], 'frozen': rng.random() < 0.08,
'hardcore': rng.random() < 0.2, 'damageCooldown': rng.choice([0, 0, 10]),
'air': air, 'maxAir': air_max, 'underWater': under,
'tick': rng.randint(0, 100000), 'lastHealth': rng.randint(0, 40), 'displayHealth': rng.randint(0, 40),
'lastHealthAgo': rng.choice([0, 500, 5000]), 'healthBlinkTime': 0,
'xpProgress': rng.choice([0.0, round(rng.random(), 4), 0.999]), 'xpLevel': rng.choice([0, 1, 7, 30, 123, 4000]),
'experienceBar': rng.random() < 0.8,
}
if case['damageCooldown'] and rng.random() < 0.5:
case['healthBlinkTime'] = case['tick'] + rng.randint(1, 20)
if rng.random() < 0.15:
case['vehicleMaxHealth'] = rng.choice([15.0, 30.0, 53.0, 100.0])
case['vehicleHealth'] = round(rng.uniform(0, case['vehicleMaxHealth']), 1)
out.append(case)
return out
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--count', type=int, default=600)
parser.add_argument('--detail', type=int, default=3)
args = parser.parse_args()
lock, jars, _ = base.verify_artifacts()
libraries = baking.client_libraries()
build = lab.LOCAL / 'rust-hud-parity'; build.mkdir(parents=True, exist_ok=True)
resources = lab.LOCAL / 'horizon-client' / '26.3'
chosen = cases(args.count)
inputs = build / 'inputs.jsonl'; inputs.write_text(''.join(json.dumps(c) + '\n' for c in chosen))
classes = build / 'classes'; classes.mkdir(exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['client'], *libraries]))
def run(command, name):
with (build / (name + '.log')).open('w') as log:
result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT)
if result.returncode:
print((build / (name + '.log')).read_text()[-4000:]); sys.exit(f'{name} failed')
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, '-d', classes,
*(PARITY / f'{n}.java' for n in ('ParityData', 'ParityFont', 'VanillaHudOracle'))], 'compile-java')
run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaHudOracle',
inputs, build / 'vanilla.jsonl'], 'vanilla')
run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'hud_fixture', '--',
resources, inputs, build / 'rust.jsonl'], 'rust')
vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()]
rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()]
assert len(vanilla) == len(rust)
errors, bad = [], []
for v, r in zip(vanilla, rust):
if 'error' in v:
errors.append(v['error']); continue
a = [{k: x for k, x in d.items() if k != 'color' or d['type'] == 'text'} for d in v['draws']]
for d in a:
if d['type'] == 'sprite':
d.setdefault('region', None)
b = r['draws']
def same(x, y):
if x.keys() != y.keys():
return False
return all(
(all(abs(p - q) <= 1e-4 * (1 + abs(p)) for p, q in zip(x[k], y[k])) if k == 'matrix' else x[k] == y[k]) for k in x)
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)))
for e in sorted(set(errors))[:5]:
print('ORACLE ERROR', e)
for case, i, a, b, la, lb in bad[:args.detail]:
print('MISMATCH', json.dumps(case))
print(f' at call {i} ({la} vanilla, {lb} Horizon calls)\n vanilla {a}\n horizon {b}')
print(f'{len(vanilla) - len(bad) - len(errors)}/{len(vanilla)} HUD states match; {len(errors)} oracle errors')
if bad or errors:
sys.exit(1)
print('hud parity ok')
if __name__ == '__main__':
main()