From ad4d836f6ff506eaf2d63ca1a4b0ca4eaf94cafb Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:16:28 +0200 Subject: [PATCH 01/28] Resolve sound events exactly as vanilla SoundManager does Add SoundRegistry (sounds.json with replace, subtitles, file validation and event references weighing as much as their event) and a SoundEngine model, with a differential harness resolving every sounds.json event against the real SoundManager.prepare and SimpleSoundInstance.getOrResolve. Co-Authored-By: Claude Opus 5.5 --- .../examples/sound_event_fixture.rs | 78 ++ crates/horizon-client/src/lib.rs | 2 + crates/horizon-client/src/sound_engine.rs | 936 ++++++++++++++++++ crates/horizon-client/src/sound_events.rs | 385 +++++++ .../parity/VanillaSoundEventOracle.java | 111 +++ tools/audio_harness.py | 88 ++ tools/test_sound_event_parity.py | 51 + 7 files changed, 1651 insertions(+) create mode 100644 crates/horizon-client/examples/sound_event_fixture.rs create mode 100644 crates/horizon-client/src/sound_engine.rs create mode 100644 crates/horizon-client/src/sound_events.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundEventOracle.java create mode 100644 tools/audio_harness.py create mode 100644 tools/test_sound_event_parity.py diff --git a/crates/horizon-client/examples/sound_event_fixture.rs b/crates/horizon-client/examples/sound_event_fixture.rs new file mode 100644 index 000000000..57c6dd7be --- /dev/null +++ b/crates/horizon-client/examples/sound_event_fixture.rs @@ -0,0 +1,78 @@ +//! Resolves sound instances through Horizon's sound event registry for +//! `tools/test_sound_event_parity.py`: `sound_event_fixture ROOT INPUT OUTPUT [NAMES]`. +use horizon_client::sound_engine::{Attenuation, MASTER, SoundEngine, SoundInstance}; +use horizon_client::sound_events::{Sentinel, SoundRegistry}; +use horizon_core::random::{LegacyRandom, RandomSource}; +use std::io::Write; + +fn bits(v: f32) -> String { + format!("{:08x}", v.to_bits()) +} + +fn main() { + let args: Vec = std::env::args().collect(); + let registry = SoundRegistry::load(std::path::Path::new(&args[1])); + let mut engine = SoundEngine::new(registry); + let input = std::fs::read_to_string(&args[2]).expect("input"); + let mut out = std::io::BufWriter::new(std::fs::File::create(&args[3]).expect("output")); + let mut names: Vec = engine.registry.names().cloned().collect(); + names.sort(); + for name in names { + writeln!(out, "registered {name}").expect("write"); + } + for line in input.lines() { + let f: Vec<&str> = line.split(' ').collect(); + let seed: i64 = f[1].parse().expect("seed"); + let volume = f32::from_bits(u32::from_str_radix(f[2], 16).expect("volume")); + let pitch = f32::from_bits(u32::from_str_radix(f[3], 16).expect("pitch")); + let event = horizon_client::sound_events::normalize(f[0]); + let instance = SoundInstance::new( + &event, + MASTER, + volume, + pitch, + LegacyRandom::new(seed), + false, + 0, + Attenuation::Linear, + [0.0; 3], + false, + ); + let id = engine.add(instance, true); + engine.resolve(id); + let weight = engine.registry.weight(&event); + let i = engine.instance_mut(id).expect("instance"); + let mut s = line.to_owned(); + match &i.event { + None => s.push_str(" event=none"), + Some(subtitle) => s.push_str(&format!( + " event weight={weight} subtitle={}", + subtitle.as_deref().unwrap_or("-") + )), + } + let v = i.get_volume(); + let p = i.get_pitch(); + let sound = i.sound.clone().expect("resolved"); + let (namespace, path) = sound.path(); + let sentinel = match sound.sentinel { + Sentinel::None => "-", + Sentinel::Empty => "empty", + Sentinel::IntentionallyEmpty => "intentionally_empty", + }; + s.push_str(&format!( + " sound={} path={namespace}:{path} sentinel={sentinel} weight={} type={} stream={} preload={} attenuation={} volume={} pitch={} range={} next={}", + sound.location, + sound.weight, + if sound.event { "SOUND_EVENT" } else { "FILE" }, + sound.stream, + sound.preload, + sound.attenuation_distance, + bits(v), + bits(p), + bits(sound.attenuation_distance(v)), + i.random.next_long() + )); + writeln!(out, "{s}").expect("write"); + engine.release(id); + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index e5080ea4a..01c135262 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -83,6 +83,8 @@ pub mod settings; pub mod shadows; pub mod signs; pub mod snbt; +pub mod sound_engine; +pub mod sound_events; pub mod sprint; pub mod sprites; pub mod stations; diff --git a/crates/horizon-client/src/sound_engine.rs b/crates/horizon-client/src/sound_engine.rs new file mode 100644 index 000000000..f51545595 --- /dev/null +++ b/crates/horizon-client/src/sound_engine.rs @@ -0,0 +1,936 @@ +//! Vanilla's `SoundEngine` bookkeeping, separated from the mixer: sound +//! instances resolved from the registry with their own random, the channel +//! pools (`Library.CountingChannelPool`), `calculateVolume`/`calculatePitch`, +//! the channel parameters a play sets (gain, pitch, linear attenuation, looping, +//! position, relative), the subtitle notifications, tickable instances, +//! delayed and manually looped sounds, the 20-tick minimum channel lifetime, +//! `isActive`, category gains and stopping by sound or source. +//! +//! The executor is modelled as running every channel task immediately (the +//! sound thread keeps up between ticks); a channel's own end is reported by the +//! backend through `stopped`. +use crate::sound_events::{INTENTIONALLY_EMPTY, Sentinel, Sound, SoundRegistry}; +use horizon_core::random::LegacyRandom; +use std::collections::HashMap; + +/// `SoundSource` indices (vanilla order). +pub const MASTER: usize = 0; +pub const MUSIC: usize = 1; +pub const RECORDS: usize = 2; +pub const AMBIENT: usize = 8; +pub const UI: usize = 10; +/// The pool sizes `Library.init` derives from OpenAL Soft's default 255 mono +/// sources: `clamp((int) sqrt(255), 2, 8)` streaming, the rest static. +pub const STATIC_CHANNELS: usize = 247; +pub const STREAMING_CHANNELS: usize = 8; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PlayResult { + Started, + StartedSilently, + NotStarted, +} +/// `SoundInstance.Attenuation`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Attenuation { + None, + Linear, +} +/// The tickable instance kinds Horizon plays (`TickableSoundInstance`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Ticking { + /// Not tickable. + No, + /// `BiomeAmbientSoundsHandler.LoopSoundInstance`. + BiomeLoop { fade: i32, direction: i32 }, + /// `UnderLiquidAmbientSoundInstance`. + UnderLiquidLoop { fade: i32 }, + /// `UnderLiquidSubSound`. + UnderLiquidSub, +} +/// What tickable instances read about the player. +#[derive(Clone, Copy, Debug, Default)] +pub struct TickContext { + pub player_underwater: bool, + pub player_removed: bool, +} +/// `AbstractSoundInstance` and its subclasses' fields. +#[derive(Clone, Debug)] +pub struct SoundInstance { + pub identifier: String, + pub source: usize, + pub volume: f32, + pub pitch: f32, + pub position: [f64; 3], + pub looping: bool, + pub delay: i32, + pub attenuation: Attenuation, + pub relative: bool, + pub random: LegacyRandom, + pub can_start_silent: bool, + pub ticking: Ticking, + /// `AbstractTickableSoundInstance.stopped`. + pub stopped: bool, + /// `sound` after `getOrResolve`. + pub sound: Option, + /// `soundEvent != null` after `getOrResolve`, and its subtitle. + pub event: Option>, +} +impl SoundInstance { + #[allow(clippy::too_many_arguments)] + pub fn new( + identifier: &str, + source: usize, + volume: f32, + pitch: f32, + random: LegacyRandom, + looping: bool, + delay: i32, + attenuation: Attenuation, + position: [f64; 3], + relative: bool, + ) -> Self { + Self { + identifier: identifier.to_owned(), + source, + volume, + pitch, + position, + looping, + delay, + attenuation, + relative, + random, + can_start_silent: false, + ticking: Ticking::No, + stopped: false, + sound: None, + event: None, + } + } + /// `new SimpleSoundInstance(sound, source, volume, pitch, random, x, y, z)`. + pub fn at( + id: &str, + source: usize, + volume: f32, + pitch: f32, + random: LegacyRandom, + at: [f64; 3], + ) -> Self { + Self::new( + id, + source, + volume, + pitch, + random, + false, + 0, + Attenuation::Linear, + at, + false, + ) + } + /// `SimpleSoundInstance.forUI(sound, pitch, volume)`. + pub fn for_ui(id: &str, pitch: f32, volume: f32, random: LegacyRandom) -> Self { + Self::new( + id, + UI, + volume, + pitch, + random, + false, + 0, + Attenuation::None, + [0.0; 3], + true, + ) + } + /// `SimpleSoundInstance.forMusic`. + pub fn for_music(id: &str, random: LegacyRandom) -> Self { + Self::new( + id, + MUSIC, + 1.0, + 1.0, + random, + false, + 0, + Attenuation::None, + [0.0; 3], + true, + ) + } + /// `SimpleSoundInstance.forJukeboxSong`. + pub fn for_jukebox_song(id: &str, at: [f64; 3], random: LegacyRandom) -> Self { + Self::new( + id, + RECORDS, + 4.0, + 1.0, + random, + false, + 0, + Attenuation::Linear, + at, + false, + ) + } + /// `SimpleSoundInstance.forLocalAmbience`. + pub fn for_local_ambience(id: &str, pitch: f32, volume: f32, random: LegacyRandom) -> Self { + Self::new( + id, + AMBIENT, + volume, + pitch, + random, + false, + 0, + Attenuation::None, + [0.0; 3], + true, + ) + } + /// `SimpleSoundInstance.forAmbientAddition`. + pub fn for_ambient_addition(id: &str, random: LegacyRandom) -> Self { + Self::for_local_ambience(id, 1.0, 1.0, random) + } + /// `SimpleSoundInstance.forAmbientMood`. + pub fn for_ambient_mood(id: &str, random: LegacyRandom, at: [f64; 3]) -> Self { + Self::new( + id, + AMBIENT, + 1.0, + 1.0, + random, + false, + 0, + Attenuation::Linear, + at, + false, + ) + } + /// A relative looping ambient instance (the loop sound constructors). + fn ambient_loop(id: &str, random: LegacyRandom, looping: bool, ticking: Ticking) -> Self { + let mut s = Self::new( + id, + AMBIENT, + 1.0, + 1.0, + random, + looping, + 0, + Attenuation::Linear, + [0.0; 3], + true, + ); + s.ticking = ticking; + s + } + /// `new BiomeAmbientSoundsHandler.LoopSoundInstance(event)`. + pub fn biome_loop(id: &str, random: LegacyRandom) -> Self { + Self::ambient_loop( + id, + random, + true, + Ticking::BiomeLoop { + fade: 0, + direction: 0, + }, + ) + } + /// `UnderLiquidAmbientSoundInstance.underwater(player)`. + pub fn under_liquid_loop(id: &str, random: LegacyRandom) -> Self { + Self::ambient_loop(id, random, true, Ticking::UnderLiquidLoop { fade: 0 }) + } + /// `new UnderLiquidSubSound(player, event)`. + pub fn under_liquid_sub(id: &str, random: LegacyRandom) -> Self { + Self::ambient_loop(id, random, false, Ticking::UnderLiquidSub) + } + pub fn tickable(&self) -> bool { + self.ticking != Ticking::No + } + /// `AbstractSoundInstance.getVolume` (after `getOrResolve`). + pub fn get_volume(&mut self) -> f32 { + let sample = match &self.sound { + Some(s) => s.volume.sample(&mut self.random), + None => 1.0, + }; + self.volume * sample + } + /// `AbstractSoundInstance.getPitch`. + pub fn get_pitch(&mut self) -> f32 { + let sample = match &self.sound { + Some(s) => s.pitch.sample(&mut self.random), + None => 1.0, + }; + self.pitch * sample + } + /// `AbstractTickableSoundInstance.stop`. + fn stop(&mut self) { + self.stopped = true; + self.looping = false; + } + /// `TickableSoundInstance.tick`. + pub fn tick(&mut self, ctx: &TickContext) { + match &mut self.ticking { + Ticking::No => {} + Ticking::BiomeLoop { fade, direction } => { + let stop = *fade < 0; + *fade += *direction; + self.volume = (*fade as f32 / 40.0).clamp(0.0, 1.0); + if stop { + self.stop(); + } + } + Ticking::UnderLiquidLoop { fade } => { + if !ctx.player_removed && *fade >= 0 { + if ctx.player_underwater { + *fade += 1; + } else { + *fade -= 2; + } + *fade = (*fade).min(40); + self.volume = 0.0f32.max((*fade as f32 / 40.0).min(1.0)); + } else { + self.stop(); + } + } + Ticking::UnderLiquidSub => { + if ctx.player_removed || !ctx.player_underwater { + self.stop(); + } + } + } + } + /// `LoopSoundInstance.fadeOut`. + pub fn fade_out(&mut self) { + if let Ticking::BiomeLoop { fade, direction } = &mut self.ticking { + *fade = (*fade).min(40); + *direction = -1; + } + } + /// `LoopSoundInstance.fadeIn`. + pub fn fade_in(&mut self) { + if let Ticking::BiomeLoop { fade, direction } = &mut self.ticking { + *fade = 0.max(*fade); + *direction = 1; + } + } +} +/// A sound instance handle. +pub type InstanceId = u64; +/// A backend channel (an OpenAL source). +pub type ChannelId = u64; +/// The OpenAL side: `Channel` operations, all applied immediately. +pub trait Backend { + /// `Channel.create`. + fn create(&mut self, streaming: bool) -> Option; + /// `Channel.destroy`. + fn destroy(&mut self, channel: ChannelId); + fn set_pitch(&mut self, channel: ChannelId, pitch: f32); + fn set_volume(&mut self, channel: ChannelId, volume: f32); + /// `Some(max distance)` for `linearAttenuation`, None for `disableAttenuation`. + fn set_attenuation(&mut self, channel: ChannelId, linear: Option); + fn set_looping(&mut self, channel: ChannelId, looping: bool); + fn set_position(&mut self, channel: ChannelId, position: [f64; 3]); + fn set_relative(&mut self, channel: ChannelId, relative: bool); + /// Attach the sound's buffer or stream (when loaded) and play it. + fn start(&mut self, channel: ChannelId, sound: &Sound, looping: bool); + fn stop(&mut self, channel: ChannelId); + fn pause(&mut self, channel: ChannelId); + fn unpause(&mut self, channel: ChannelId); + /// `Channel.stopped`. + fn stopped(&mut self, channel: ChannelId) -> bool; +} +/// A `SoundEventListener.onPlaySound` call. +#[derive(Clone, Debug, PartialEq)] +pub struct Notification { + pub identifier: String, + pub subtitle: Option, + pub position: [f64; 3], + pub relative: bool, + pub looping: bool, + pub range: f32, +} +/// `ChannelAccess.ChannelHandle`. +#[derive(Clone, Copy, Debug)] +struct Handle { + channel: Option, + streaming: bool, + stopped: bool, +} +pub struct SoundEngine { + pub registry: SoundRegistry, + /// `loaded`: the library opened. + pub loaded: bool, + tick_count: i32, + instances: HashMap, + /// Instances their owner still refers to. + retained: HashMap, + next_instance: InstanceId, + /// `instanceToChannel` (insertion order). + instance_to_channel: Vec<(InstanceId, u64)>, + handles: HashMap, + next_handle: u64, + /// `instanceBySource`. + instance_by_source: Vec<(usize, InstanceId)>, + gain_by_source: [f32; 11], + ticking: Vec, + /// `queuedSounds` (insertion order). + queued: Vec<(InstanceId, i32)>, + delete_time: HashMap, + queued_tickable: Vec, + used: [usize; 2], + pub limits: [usize; 2], + /// `Options.getSoundSourceVolume` per source (index 0 is master). + pub source_volumes: [f32; 11], + /// A `SoundEventListener` is registered. + pub listening: bool, + pub notifications: Vec, +} +fn handle_channel(h: &Handle) -> Option { + h.channel +} +impl SoundEngine { + pub fn new(registry: SoundRegistry) -> Self { + Self { + registry, + loaded: true, + tick_count: 0, + instances: HashMap::new(), + retained: HashMap::new(), + next_instance: 1, + instance_to_channel: Vec::new(), + handles: HashMap::new(), + next_handle: 1, + instance_by_source: Vec::new(), + gain_by_source: [1.0; 11], + ticking: Vec::new(), + queued: Vec::new(), + delete_time: HashMap::new(), + queued_tickable: Vec::new(), + used: [0, 0], + limits: [STATIC_CHANNELS, STREAMING_CHANNELS], + source_volumes: [1.0; 11], + listening: false, + notifications: Vec::new(), + } + } + /// Hand an instance to the engine. A retained instance stays until + /// `release`; others go once the engine no longer refers to them. + pub fn add(&mut self, instance: SoundInstance, retain: bool) -> InstanceId { + let id = self.next_instance; + self.next_instance += 1; + self.instances.insert(id, instance); + if retain { + self.retained.insert(id, ()); + } + id + } + /// The owner drops its reference. + pub fn release(&mut self, id: InstanceId) { + self.retained.remove(&id); + self.collect(id); + } + fn referenced(&self, id: InstanceId) -> bool { + self.retained.contains_key(&id) + || self.instance_to_channel.iter().any(|(i, _)| *i == id) + || self.queued.iter().any(|(i, _)| *i == id) + || self.queued_tickable.contains(&id) + || self.ticking.contains(&id) + } + fn collect(&mut self, id: InstanceId) { + if !self.referenced(id) { + self.instances.remove(&id); + } + } + pub fn instance(&self, id: InstanceId) -> Option<&SoundInstance> { + self.instances.get(&id) + } + pub fn instance_mut(&mut self, id: InstanceId) -> Option<&mut SoundInstance> { + self.instances.get_mut(&id) + } + pub fn tick_count(&self) -> i32 { + self.tick_count + } + /// `Options.getFinalSoundSourceVolume`. + pub fn final_source_volume(&self, source: usize) -> f32 { + if source == MASTER { + self.source_volumes[MASTER] + } else { + self.source_volumes[source] * self.source_volumes[MASTER] + } + } + /// `calculateVolume(volume, source)`. + pub fn calculate_volume(&self, volume: f32, source: usize) -> f32 { + volume.clamp(0.0, 1.0) + * self.final_source_volume(source).clamp(0.0, 1.0) + * self.gain_by_source[source] + } + /// `calculatePitch`. + pub fn calculate_pitch(pitch: f32) -> f32 { + pitch.clamp(0.5, 2.0) + } + fn channel_of(&self, id: InstanceId) -> Option { + self.instance_to_channel + .iter() + .find(|(i, _)| *i == id) + .map(|(_, h)| *h) + } + /// `refreshCategoryVolume`. + pub fn refresh_category_volume(&mut self, source: usize, backend: &mut impl Backend) { + if !self.loaded { + return; + } + for (id, handle) in self.instance_to_channel.clone() { + let Some(instance) = self.instances.get_mut(&id) else { + continue; + }; + if source == instance.source || source == MASTER { + let (v, s) = (instance.get_volume(), instance.source); + let volume = self.calculate_volume(v, s); + if let Some(c) = self.handles.get(&handle).and_then(handle_channel) { + backend.set_volume(c, volume); + } + } + } + } + /// `updateCategoryVolume`. + pub fn update_category_volume(&mut self, source: usize, gain: f32, backend: &mut impl Backend) { + self.gain_by_source[source] = gain.clamp(0.0, 1.0); + self.refresh_category_volume(source, backend); + } + pub fn category_gain(&self, source: usize) -> f32 { + self.gain_by_source[source] + } + /// `stop(SoundInstance)`. + pub fn stop(&mut self, id: InstanceId, backend: &mut impl Backend) { + if !self.loaded { + return; + } + if let Some(handle) = self.channel_of(id) + && let Some(c) = self.handles.get(&handle).and_then(handle_channel) + { + backend.stop(c); + } + } + /// `ChannelHandle.release`. + fn release_handle(&mut self, handle: u64, backend: &mut impl Backend) { + if let Some(h) = self.handles.get_mut(&handle) { + h.stopped = true; + if let Some(c) = h.channel.take() { + self.used[usize::from(h.streaming)] -= 1; + backend.destroy(c); + } + } + } + /// `stopAll`. + pub fn stop_all(&mut self, backend: &mut impl Backend) { + if !self.loaded { + return; + } + let ids: Vec = self.instances.keys().copied().collect(); + self.instance_to_channel.clear(); + let handles: Vec = self.handles.keys().copied().collect(); + for h in handles { + self.release_handle(h, backend); + } + self.handles.clear(); + self.queued.clear(); + self.ticking.clear(); + self.instance_by_source.clear(); + self.delete_time.clear(); + self.queued_tickable.clear(); + self.gain_by_source = [1.0; 11]; + for id in ids { + self.collect(id); + } + } + /// `stop(Identifier sound, SoundSource source)`. + pub fn stop_matching( + &mut self, + sound: Option<&str>, + source: Option, + backend: &mut impl Backend, + ) { + let matches = |engine: &Self, id: InstanceId| { + sound.is_none_or(|s| engine.instances.get(&id).is_some_and(|i| i.identifier == s)) + }; + if let Some(source) = source { + let ids: Vec = self + .instance_by_source + .iter() + .filter(|(s, _)| *s == source) + .map(|(_, i)| *i) + .collect(); + for id in ids { + if matches(self, id) { + self.stop(id, backend); + } + } + } else if sound.is_none() { + self.stop_all(backend); + } else { + let ids: Vec = self.instance_to_channel.iter().map(|(i, _)| *i).collect(); + for id in ids { + if matches(self, id) { + self.stop(id, backend); + } + } + } + } + /// `getRange`. + fn range(relative: bool, attenuation: Attenuation, distance: f32) -> f32 { + if !relative && attenuation != Attenuation::None { + distance + } else { + f32::INFINITY + } + } + fn notify(&mut self, id: InstanceId, subtitle: Option, distance: f32) { + let Some(i) = self.instances.get(&id) else { + return; + }; + self.notifications.push(Notification { + identifier: i.identifier.clone(), + subtitle, + position: i.position, + relative: i.relative, + looping: i.looping, + range: Self::range(i.relative, i.attenuation, distance), + }); + } + /// `getOrResolve`. + pub fn resolve(&mut self, id: InstanceId) { + let Some(instance) = self.instances.get_mut(&id) else { + return; + }; + if instance.identifier == INTENTIONALLY_EMPTY { + instance.sound = Some(Sound::intentionally_empty()); + instance.event = Some(None); + return; + } + match self.registry.get(&instance.identifier) { + None => { + instance.event = None; + instance.sound = Some(Sound::empty()); + } + Some(event) => { + instance.event = Some(event.subtitle.clone()); + instance.sound = self + .registry + .sound(&instance.identifier, &mut instance.random); + } + } + } + /// `play(SoundInstance)`. + pub fn play(&mut self, id: InstanceId, backend: &mut impl Backend) -> PlayResult { + let result = self.play_inner(id, backend); + self.collect(id); + result + } + /// Add and play an instance. + pub fn play_new( + &mut self, + instance: SoundInstance, + retain: bool, + backend: &mut impl Backend, + ) -> (InstanceId, PlayResult) { + let id = self.add(instance, retain); + (id, self.play(id, backend)) + } + fn play_inner(&mut self, id: InstanceId, backend: &mut impl Backend) -> PlayResult { + if !self.loaded || !self.instances.contains_key(&id) { + return PlayResult::NotStarted; + } + self.resolve(id); + let instance = &self.instances[&id]; + let Some(subtitle) = instance.event.clone() else { + return PlayResult::NotStarted; + }; + let sound = instance.sound.clone().unwrap_or_else(Sound::empty); + if sound.sentinel != Sentinel::None { + return PlayResult::NotStarted; + } + let instance = self.instances.get_mut(&id).expect("present"); + let instance_volume = instance.get_volume(); + let attenuation_distance = sound.attenuation_distance(instance_volume); + if self.listening { + self.notify(id, subtitle, attenuation_distance); + } + let instance = &self.instances[&id]; + let source = instance.source; + let volume = self.calculate_volume(instance_volume, source); + let mut silently = false; + if volume == 0.0 { + if !instance.can_start_silent && source != MUSIC { + return PlayResult::NotStarted; + } + silently = true; + } + let position = instance.position; + let looping = instance.looping && instance.delay <= 0; + let streaming = sound.stream; + let pool = usize::from(streaming); + let channel = if self.used[pool] >= self.limits[pool] { + None + } else { + backend.create(streaming) + }; + let Some(channel) = channel else { + return PlayResult::NotStarted; + }; + self.used[pool] += 1; + let handle = self.next_handle; + self.next_handle += 1; + self.handles.insert( + handle, + Handle { + channel: Some(channel), + streaming, + stopped: false, + }, + ); + self.delete_time.insert(id, self.tick_count + 20); + if let Some(entry) = self.instance_to_channel.iter_mut().find(|(i, _)| *i == id) { + entry.1 = handle; + } else { + self.instance_to_channel.push((id, handle)); + } + if !self.instance_by_source.contains(&(source, id)) { + self.instance_by_source.push((source, id)); + } + let instance = self.instances.get_mut(&id).expect("present"); + let pitch = Self::calculate_pitch(instance.get_pitch()); + let (attenuation, relative, tickable) = + (instance.attenuation, instance.relative, instance.tickable()); + backend.set_pitch(channel, pitch); + backend.set_volume(channel, volume); + backend.set_attenuation( + channel, + (attenuation == Attenuation::Linear).then_some(attenuation_distance), + ); + backend.set_looping(channel, looping && !streaming); + backend.set_position(channel, position); + backend.set_relative(channel, relative); + backend.start(channel, &sound, looping); + if tickable { + self.ticking.push(id); + } + if silently { + PlayResult::StartedSilently + } else { + PlayResult::Started + } + } + /// `queueTickingSound`. + pub fn queue_ticking(&mut self, id: InstanceId) { + self.queued_tickable.push(id); + } + /// `playDelayed`. + pub fn play_delayed(&mut self, id: InstanceId, delay: i32) { + let at = self.tick_count + delay; + if let Some(entry) = self.queued.iter_mut().find(|(i, _)| *i == id) { + entry.1 = at; + } else { + self.queued.push((id, at)); + } + } + /// `isActive`. + pub fn is_active(&self, id: InstanceId) -> bool { + self.loaded && self.channel_of(id).is_some() + } + /// `tick(paused)`, then `ChannelAccess.scheduleTick`. + pub fn tick(&mut self, paused: bool, ctx: &TickContext, backend: &mut impl Backend) { + if !paused { + self.tick_in_game(ctx, backend); + } else { + self.tick_music_when_paused(); + } + self.schedule_tick(backend); + } + fn schedule_tick(&mut self, backend: &mut impl Backend) { + let live: Vec<(u64, ChannelId)> = self + .handles + .iter() + .filter_map(|(h, handle)| handle.channel.map(|c| (*h, c))) + .collect(); + for (h, c) in live { + if backend.stopped(c) { + self.release_handle(h, backend); + } + } + // Released handles nobody maps any more. + let mapped: Vec = self.instance_to_channel.iter().map(|(_, h)| *h).collect(); + self.handles + .retain(|h, handle| handle.channel.is_some() || mapped.contains(h)); + } + fn handle_stopped(&self, handle: u64) -> bool { + self.handles.get(&handle).is_none_or(|h| h.stopped) + } + fn tick_in_game(&mut self, ctx: &TickContext, backend: &mut impl Backend) { + self.tick_count += 1; + for id in std::mem::take(&mut self.queued_tickable) { + self.play(id, backend); + } + for id in self.ticking.clone() { + let Some(instance) = self.instances.get_mut(&id) else { + continue; + }; + instance.tick(ctx); + if instance.stopped { + self.stop(id, backend); + continue; + } + let (v, source) = (instance.get_volume(), instance.source); + let pitch = Self::calculate_pitch(instance.get_pitch()); + let position = instance.position; + let volume = self.calculate_volume(v, source); + let Some(handle) = self.channel_of(id) else { + continue; + }; + if let Some(c) = self.handles.get(&handle).and_then(handle_channel) { + backend.set_volume(c, volume); + backend.set_pitch(c, pitch); + backend.set_position(c, position); + } + let instance = self.instances.get_mut(&id).expect("present"); + if instance.looping + && self.tick_count % 10 == 0 + && volume > 0.0 + && self.listening + && let (Some(sound), Some(subtitle)) = + (instance.sound.clone(), instance.event.clone()) + { + let distance = sound.attenuation_distance(instance.get_volume()); + self.notify(id, subtitle, distance); + } + } + let mut removed = Vec::new(); + let mut index = 0; + while index < self.instance_to_channel.len() { + let (id, handle) = self.instance_to_channel[index]; + if self.handle_stopped(handle) + && self.delete_time.get(&id).copied().unwrap_or(0) <= self.tick_count + { + if let Some(i) = self.instances.get(&id) + && i.looping + && i.delay > 0 + { + let at = self.tick_count + i.delay; + if let Some(entry) = self.queued.iter_mut().find(|(q, _)| *q == id) { + entry.1 = at; + } else { + self.queued.push((id, at)); + } + } + self.instance_to_channel.remove(index); + self.handles.remove(&handle); + self.delete_time.remove(&id); + let source = self.instances.get(&id).map(|i| i.source); + self.instance_by_source + .retain(|e| Some(e.0) != source || e.1 != id); + if let Some(p) = self.ticking.iter().position(|t| *t == id) { + self.ticking.remove(p); + } + removed.push(id); + } else { + index += 1; + } + } + let mut index = 0; + while index < self.queued.len() { + let (id, at) = self.queued[index]; + if self.tick_count >= at { + self.queued.remove(index); + if let Some(i) = self.instances.get_mut(&id) + && i.tickable() + { + i.tick(ctx); + } + self.play(id, backend); + } else { + index += 1; + } + } + for id in removed { + self.collect(id); + } + } + fn tick_music_when_paused(&mut self) { + let mut index = 0; + while index < self.instance_to_channel.len() { + let (id, handle) = self.instance_to_channel[index]; + let music = self.instances.get(&id).is_some_and(|i| i.source == MUSIC); + if music && self.handle_stopped(handle) { + self.instance_to_channel.remove(index); + self.handles.remove(&handle); + self.delete_time.remove(&id); + self.instance_by_source + .retain(|e| e.0 != MUSIC || e.1 != id); + self.collect(id); + } else { + index += 1; + } + } + } + /// `pauseAllExcept`. + pub fn pause_all_except(&mut self, sources: &[usize], backend: &mut impl Backend) { + if !self.loaded { + return; + } + for (id, handle) in self.instance_to_channel.clone() { + let source = self.instances.get(&id).map_or(MASTER, |i| i.source); + if !sources.contains(&source) + && let Some(c) = self.handles.get(&handle).and_then(handle_channel) + { + backend.pause(c); + } + } + } + /// `resume`. + pub fn resume(&mut self, backend: &mut impl Backend) { + if !self.loaded { + return; + } + let channels: Vec = self.handles.values().filter_map(handle_channel).collect(); + for c in channels { + backend.unpause(c); + } + } + /// Channels in use (static, streaming). + pub fn used_channels(&self) -> [usize; 2] { + self.used + } + /// The live channel of an instance. + pub fn channel(&self, id: InstanceId) -> Option { + self.channel_of(id) + .and_then(|h| self.handles.get(&h)) + .and_then(handle_channel) + } + /// Instances with a channel, in insertion order. + pub fn active_instances(&self) -> Vec { + self.instance_to_channel.iter().map(|(i, _)| *i).collect() + } + /// A fresh unseeded random (`RandomSource.create()`). + pub fn unseeded() -> LegacyRandom { + LegacyRandom::new(unique_seed()) + } +} +/// `RandomSupport.generateUniqueSeed`. +pub fn unique_seed() -> i64 { + use std::sync::atomic::{AtomicI64, Ordering}; + static UNIQUIFIER: AtomicI64 = AtomicI64::new(8_682_522_807_148_012); + let mut current = UNIQUIFIER.load(Ordering::Relaxed); + let next = loop { + let next = current.wrapping_mul(1_181_783_497_276_652_981); + match UNIQUIFIER.compare_exchange(current, next, Ordering::Relaxed, Ordering::Relaxed) { + Ok(_) => break next, + Err(v) => current = v, + } + }; + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos() as i64); + next ^ nanos +} diff --git a/crates/horizon-client/src/sound_events.rs b/crates/horizon-client/src/sound_events.rs new file mode 100644 index 000000000..6a5e179c2 --- /dev/null +++ b/crates/horizon-client/src/sound_events.rs @@ -0,0 +1,385 @@ +//! `sounds.json` sound events as vanilla's `SoundManager.Preparations` builds +//! them: `WeighedSoundEvents` holding files and references to other events +//! (whose weight is the referenced event's total weight, resolved lazily), the +//! `replace` and `subtitle` fields, files that do not exist being dropped, and +//! `WeighedSoundEvents.getSound` drawing `nextInt(totalWeight)` from the sound +//! instance's random. +use horizon_core::random::RandomSource; +use serde_json::Value; +use std::{collections::HashMap, fs, path::Path}; + +/// `SoundManager.EMPTY_SOUND_LOCATION`. +pub const EMPTY: &str = "minecraft:empty"; +/// `SoundManager.INTENTIONALLY_EMPTY_SOUND_LOCATION`. +pub const INTENTIONALLY_EMPTY: &str = "minecraft:intentionally_empty"; + +/// `SampledFloat` as sounds use it: constants and `MultipliedFloats`. +#[derive(Clone, Debug, PartialEq)] +pub enum Sampled { + Constant(f32), + Product(Vec), +} +impl Sampled { + /// `SampledFloat.sample`: constants draw nothing. + pub fn sample(&self, random: &mut impl RandomSource) -> f32 { + match self { + Self::Constant(v) => *v, + Self::Product(values) => { + let mut result = 1.0f32; + for v in values { + result *= v.sample(random); + } + result + } + } + } +} +/// `Sound`. +#[derive(Clone, Debug, PartialEq)] +pub struct Sound { + /// The file identifier (`namespace:path`, under `sounds/` with `.ogg`). + pub location: String, + pub volume: Sampled, + pub pitch: Sampled, + pub weight: i32, + /// `Sound.Type.SOUND_EVENT` (a reference to another event). + pub event: bool, + pub stream: bool, + pub preload: bool, + pub attenuation_distance: i32, + /// The `EMPTY_SOUND` / `INTENTIONALLY_EMPTY_SOUND` singletons (vanilla + /// compares them by identity). + pub sentinel: Sentinel, +} +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Sentinel { + #[default] + None, + Empty, + IntentionallyEmpty, +} +impl Sound { + fn file(location: &str) -> Self { + Self { + location: location.to_owned(), + volume: Sampled::Constant(1.0), + pitch: Sampled::Constant(1.0), + weight: 1, + event: false, + stream: false, + preload: false, + attenuation_distance: 16, + sentinel: Sentinel::None, + } + } + /// `SoundManager.EMPTY_SOUND`. + pub fn empty() -> Self { + Self { + sentinel: Sentinel::Empty, + ..Self::file(EMPTY) + } + } + /// `SoundManager.INTENTIONALLY_EMPTY_SOUND`. + pub fn intentionally_empty() -> Self { + Self { + sentinel: Sentinel::IntentionallyEmpty, + ..Self::file(INTENTIONALLY_EMPTY) + } + } + /// `Sound.getAttenuationDistance(volume)`. + pub fn attenuation_distance(&self, volume: f32) -> f32 { + volume.max(1.0) * self.attenuation_distance as f32 + } + /// `Sound.getPath`: the resource path (`namespace`, `sounds/.ogg`). + pub fn path(&self) -> (&str, String) { + let (namespace, path) = split(&self.location); + (namespace, format!("sounds/{path}.ogg")) + } +} +/// `WeighedSoundEvents`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct WeighedSoundEvents { + /// Files, or references to events (`Sound.event`). + pub sounds: Vec, + /// The subtitle translation key. + pub subtitle: Option, +} +/// The sound event registry (`SoundManager.registry`). +#[derive(Clone, Debug, Default)] +pub struct SoundRegistry { + events: HashMap, +} +/// `Identifier.parse` with the default namespace. +fn split(id: &str) -> (&str, &str) { + match id.split_once(':') { + Some((namespace, path)) => ( + if namespace.is_empty() { + "minecraft" + } else { + namespace + }, + path, + ), + None => ("minecraft", id), + } +} +pub fn normalize(id: &str) -> String { + let (namespace, path) = split(id); + format!("{namespace}:{path}") +} +/// `GsonHelper.getAsFloat`: Gson parses the number's text as a float. +fn json_float(v: &Value, fallback: f32) -> f32 { + match v { + Value::Number(n) => n.to_string().parse().unwrap_or(fallback), + Value::String(s) => s.parse().unwrap_or(fallback), + _ => fallback, + } +} +fn json_int(v: &Value, fallback: i32) -> i32 { + match v { + Value::Number(n) => n + .as_i64() + .map(|i| i as i32) + .or_else(|| n.as_f64().map(|f| f as i32)) + .unwrap_or(fallback), + Value::String(s) => s.parse().unwrap_or(fallback), + _ => fallback, + } +} +fn json_bool(v: &Value, fallback: bool) -> bool { + match v { + Value::Bool(b) => *b, + Value::String(s) => s == "true", + _ => fallback, + } +} +/// `SoundEventRegistrationSerializer.getSound`; None for an invalid entry +/// (vanilla rejects the whole file). +fn parse_sound(v: &Value) -> Option { + if let Value::String(name) = v { + return Some(Sound::file(&normalize(name))); + } + let name = v.get("name")?.as_str()?; + let event = match v.get("type") { + None => false, + Some(t) => match t.as_str()? { + "file" => false, + "event" => true, + _ => return None, + }, + }; + let volume = json_float(v.get("volume").unwrap_or(&Value::Null), 1.0); + let pitch = json_float(v.get("pitch").unwrap_or(&Value::Null), 1.0); + let weight = json_int(v.get("weight").unwrap_or(&Value::Null), 1); + if !(volume > 0.0 && pitch > 0.0 && weight > 0) { + return None; + } + Some(Sound { + location: normalize(name), + volume: Sampled::Constant(volume), + pitch: Sampled::Constant(pitch), + weight, + event, + stream: json_bool(v.get("stream").unwrap_or(&Value::Null), false), + preload: json_bool(v.get("preload").unwrap_or(&Value::Null), false), + attenuation_distance: json_int(v.get("attenuation_distance").unwrap_or(&Value::Null), 16), + sentinel: Sentinel::None, + }) +} +impl SoundRegistry { + /// Every `assets//sounds.json` under a resource root, files + /// validated against `assets//sounds/`. + pub fn load(root: &Path) -> Self { + let assets = root.join("assets"); + let mut namespaces: Vec = fs::read_dir(&assets) + .into_iter() + .flatten() + .flatten() + .filter_map(|e| e.file_name().to_str().map(str::to_owned)) + .collect(); + namespaces.sort(); + let mut registry = Self::default(); + for namespace in namespaces { + let Ok(text) = fs::read(assets.join(&namespace).join("sounds.json")) else { + continue; + }; + let exists = |ns: &str, path: &str| assets.join(ns).join(path).is_file(); + registry.add_file(&namespace, &text, &exists); + } + registry + } + /// One `sounds.json` (`Preparations.handleRegistration` for each entry). + /// `exists(namespace, path)` says whether a sound file is present. + pub fn add_file(&mut self, namespace: &str, text: &[u8], exists: &dyn Fn(&str, &str) -> bool) { + let Ok(Value::Object(map)) = serde_json::from_slice::(text) else { + return; + }; + // A malformed entry makes Gson reject the whole file. + let mut parsed = Vec::new(); + for (name, def) in &map { + let Value::Object(object) = def else { return }; + let replace = json_bool(object.get("replace").unwrap_or(&Value::Null), false); + let subtitle = match object.get("subtitle") { + None | Some(Value::Null) => None, + Some(Value::String(s)) => Some(s.clone()), + Some(_) => return, + }; + let mut sounds = Vec::new(); + if let Some(list) = object.get("sounds") { + let Value::Array(list) = list else { return }; + for s in list { + let Some(sound) = parse_sound(s) else { return }; + sounds.push(sound); + } + } + parsed.push((format!("{namespace}:{name}"), replace, subtitle, sounds)); + } + for (location, replace, subtitle, sounds) in parsed { + let entry = match self.events.get_mut(&location) { + Some(entry) if !replace => entry, + _ => { + self.events.insert( + location.clone(), + WeighedSoundEvents { + sounds: Vec::new(), + subtitle, + }, + ); + self.events.get_mut(&location).expect("inserted") + } + }; + for sound in sounds { + if !sound.event { + let (ns, path) = sound.path(); + if !exists(ns, &path) { + continue; + } + } + entry.sounds.push(sound); + } + } + } + pub fn get(&self, event: &str) -> Option<&WeighedSoundEvents> { + self.events.get(event) + } + pub fn contains(&self, event: &str) -> bool { + self.events.contains_key(event) + } + /// Every registered event id. + pub fn names(&self) -> impl Iterator { + self.events.keys() + } + /// `Weighted.getWeight` of one entry. + fn entry_weight(&self, sound: &Sound, depth: u32) -> i32 { + if !sound.event { + return sound.weight; + } + if depth > 64 { + return 0; + } + self.events + .get(&sound.location) + .map_or(0, |e| self.total(e, depth + 1)) + } + fn total(&self, event: &WeighedSoundEvents, depth: u32) -> i32 { + event + .sounds + .iter() + .fold(0i32, |sum, s| sum.wrapping_add(self.entry_weight(s, depth))) + } + /// `WeighedSoundEvents.getWeight`. + pub fn weight(&self, event: &str) -> i32 { + self.events.get(event).map_or(0, |e| self.total(e, 0)) + } + /// `WeighedSoundEvents.getSound`: None when the event is not registered. + pub fn sound(&self, event: &str, random: &mut impl RandomSource) -> Option { + let e = self.events.get(event)?; + Some(self.pick(e, random, 0)) + } + fn pick( + &self, + event: &WeighedSoundEvents, + random: &mut impl RandomSource, + depth: u32, + ) -> Sound { + let weight = self.total(event, depth); + if event.sounds.is_empty() || weight == 0 { + return Sound::empty(); + } + let Ok(mut index) = random.next_int_bound(weight) else { + return Sound::empty(); + }; + for sound in &event.sounds { + index -= self.entry_weight(sound, depth); + if index < 0 { + if !sound.event { + return sound.clone(); + } + // The anonymous reference Weighted: the referenced event's + // sound with this entry's volume, pitch and stream folded in. + let Some(inner) = self.events.get(&sound.location) else { + return Sound::empty(); + }; + if depth > 64 { + return Sound::empty(); + } + let wrapped = self.pick(inner, random, depth + 1); + return Sound { + location: wrapped.location, + volume: Sampled::Product(vec![wrapped.volume, sound.volume.clone()]), + pitch: Sampled::Product(vec![wrapped.pitch, sound.pitch.clone()]), + weight: sound.weight, + event: false, + stream: wrapped.stream || sound.stream, + preload: wrapped.preload, + attenuation_distance: wrapped.attenuation_distance, + sentinel: Sentinel::None, + }; + } + } + Sound::empty() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_core::random::LegacyRandom; + + #[test] + fn references_weigh_as_much_as_their_event() { + let mut r = SoundRegistry::default(); + let json = br#"{ + "a": {"sounds": ["x", "y", "z"]}, + "b": {"sounds": [{"name": "a", "type": "event", "weight": 9, "volume": 0.5}, "w"], "subtitle": "s.b"} + }"#; + r.add_file("minecraft", json, &|_, _| true); + assert_eq!(r.weight("minecraft:b"), 4); + let mut random = LegacyRandom::new(1); + let mut seen = std::collections::HashSet::new(); + for _ in 0..64 { + let s = r.sound("minecraft:b", &mut random).unwrap(); + if s.location != "minecraft:w" { + assert_eq!(s.volume.sample(&mut random), 0.5); + } + seen.insert(s.location); + } + assert_eq!(seen.len(), 4); + assert_eq!( + r.get("minecraft:b").unwrap().subtitle.as_deref(), + Some("s.b") + ); + } + + #[test] + fn missing_files_are_dropped_and_empty_events_give_the_empty_sound() { + let mut r = SoundRegistry::default(); + r.add_file("minecraft", br#"{"a": {"sounds": ["gone"]}}"#, &|_, _| { + false + }); + assert_eq!(r.weight("minecraft:a"), 0); + let mut random = LegacyRandom::new(1); + assert_eq!(r.sound("minecraft:a", &mut random).unwrap(), Sound::empty()); + assert!(r.sound("minecraft:b", &mut random).is_none()); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundEventOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundEventOracle.java new file mode 100644 index 000000000..b02ef2783 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundEventOracle.java @@ -0,0 +1,111 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.io.*; +import java.lang.reflect.*; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.Options; +import net.minecraft.client.resources.sounds.*; +import net.minecraft.client.sounds.*; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.contents.TranslatableContents; +import net.minecraft.resources.Identifier; +import net.minecraft.server.packs.*; +import net.minecraft.server.packs.repository.PackSource; +import net.minecraft.server.packs.resources.MultiPackResourceManager; +import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.RandomSource; +import net.minecraft.util.profiling.InactiveProfiler; + +/** + * Builds vanilla's sound event registry with the real SoundManager.prepare + * (sounds.json read through a resource manager over the client asset root, + * files validated against the listed .ogg resources) and Preparations.apply, + * then resolves SimpleSoundInstances: getOrResolve with a seeded random, + * getVolume/getPitch, and the instance random's next draw (to fix the number + * of draws). Lines: "event seed volume pitch". + */ +public final class VanillaSoundEventOracle { + static Field field(Class type, String name) throws Exception { + var f = type.getDeclaredField(name); + f.setAccessible(true); + return f; + } + + static String bits(float v) { + return String.format("%08x", Float.floatToRawIntBits(v)); + } + + static String sentinel(Sound sound) { + if (sound == SoundManager.EMPTY_SOUND) return "empty"; + if (sound == SoundManager.INTENTIONALLY_EMPTY_SOUND) return "intentionally_empty"; + return "-"; + } + + /** The real registry, prepared from an asset root. */ + @SuppressWarnings("unchecked") + static SoundManager load(Path root) throws Exception { + var info = new PackLocationInfo("horizon", Component.literal("horizon"), PackSource.BUILT_IN, Optional.empty()); + ResourceManager resources = new MultiPackResourceManager(PackType.CLIENT_RESOURCES, List.of(new PathPackResources(info, root))); + var u = Class.forName("sun.misc.Unsafe"); + Object unsafe = field(u, "theUnsafe").get(null); + Options options = (Options) u.getMethod("allocateInstance", Class.class).invoke(unsafe, Options.class); + var manager = new SoundManager(options); + Method prepare = SoundManager.class.getDeclaredMethod("prepare", ResourceManager.class, net.minecraft.util.profiling.ProfilerFiller.class); + prepare.setAccessible(true); + Object preparations = prepare.invoke(manager, resources, InactiveProfiler.INSTANCE); + Method apply = preparations.getClass().getDeclaredMethod("apply", Map.class, Map.class, SoundEngine.class); + apply.setAccessible(true); + apply.invoke(preparations, field(SoundManager.class, "registry").get(manager), field(SoundManager.class, "soundCache").get(manager), + field(SoundManager.class, "soundEngine").get(manager)); + return manager; + } + + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + var manager = load(Path.of(args[0])); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2])))) { + var names = new ArrayList(); + for (var id : manager.getAvailableSounds()) names.add(id.toString()); + Collections.sort(names); + for (String name : names) out.println("registered " + name); + for (String line : Files.readAllLines(Path.of(args[1]))) { + String[] f = line.split(" "); + long seed = Long.parseLong(f[1]); + float volume = Float.intBitsToFloat(Integer.parseUnsignedInt(f[2], 16)); + float pitch = Float.intBitsToFloat(Integer.parseUnsignedInt(f[3], 16)); + RandomSource random = RandomSource.create(seed); + var instance = new SimpleSoundInstance(Identifier.parse(f[0]), SoundSource.MASTER, volume, pitch, random, false, 0, + SoundInstance.Attenuation.LINEAR, 0.0, 0.0, 0.0, false); + WeighedSoundEvents event = instance.getOrResolve(manager); + Sound sound = instance.getSound(); + StringBuilder sb = new StringBuilder(line); + if (event == null) { + sb.append(" event=none"); + } else { + String subtitle = "-"; + if (event.getSubtitle() != null && event.getSubtitle().getContents() instanceof TranslatableContents t) subtitle = t.getKey(); + sb.append(" event weight=").append(event.getWeight()).append(" subtitle=").append(subtitle); + } + float v = instance.getVolume(); + float p = instance.getPitch(); + sb.append(" sound=").append(sound.getLocation()).append(" path=").append(sound.getPath()) + .append(" sentinel=").append(sentinel(sound)) + .append(" weight=").append(sound.getWeight()) + .append(" type=").append(sound.getType().name()) + .append(" stream=").append(sound.shouldStream()) + .append(" preload=").append(sound.shouldPreload()) + .append(" attenuation=").append(sound.getAttenuationDistance()) + .append(" volume=").append(bits(v)) + .append(" pitch=").append(bits(p)) + .append(" range=").append(bits(sound.getAttenuationDistance(v))) + .append(" next=").append(random.nextLong()); + out.println(sb); + } + } + System.exit(0); + } +} diff --git a/tools/audio_harness.py b/tools/audio_harness.py new file mode 100644 index 000000000..bfd18e05e --- /dev/null +++ b/tools/audio_harness.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Shared runner for the audio differential harnesses. + +Each harness writes an input file, runs a Java oracle against the pinned +client (the real SoundManager / SoundEngine / MusicManager / ambient handlers; +OpenAL runs on OpenAL Soft's "No Output" device so channel parameters can be +read back from real AL sources) and a Rust example replaying the same inputs +through Horizon's audio code, then requires byte-identical output. +""" +import json +import os +from pathlib import Path +import platform +import subprocess + +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 + +RESOURCES = lab.LOCAL / 'horizon-client/26.3' +COMMON_SOURCES = [ + lab.ROOT / 'tools/audio_harness.py', + lab.ROOT / 'tools/test_rust_parity.py', + lab.ROOT / 'tools/lab.py', + lab.ROOT / 'Cargo.toml', + lab.ROOT / 'Cargo.lock', + lab.ROOT / 'crates/horizon-client/Cargo.toml', + lab.ROOT / 'crates/horizon-client/src/sound_events.rs', + lab.ROOT / 'crates/horizon-client/src/sound_engine.rs', +] + + +def require_sounds(): + if not (RESOURCES / 'assets/minecraft/sounds.json').is_file(): + raise SystemExit('Sound assets missing: run tools/fetch_sounds.py first') + + +def run_harness(name, oracle, example, inputs_text, extra_sources=(), java_args=(), rust_args=(), scope='', timeout=1800): + """Run oracle and example on inputs; returns the number of matched lines.""" + require_sounds() + lock, jars, _ = base.verify_artifacts() + libraries = baking.client_libraries() + build = lab.LOCAL / f'rust-{name}' + build.mkdir(parents=True, exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + oracle_path = lab.ROOT / f'mods/horizon/src/test/java/dev/horizonlab/parity/{oracle}.java' + example_path = lab.ROOT / f'crates/horizon-client/examples/{example}.rs' + sources = [*COMMON_SOURCES, oracle_path, example_path, *[Path(s) for s in extra_sources]] + tested = base.source_hashes(sources) + inputs = build / 'inputs.txt' + inputs.write_text(inputs_text) + input_hash = lab.digest(inputs, 'sha256') + + def run(command, log, env=None): + with (build / (log + '.log')).open('w') as out: + subprocess.run(list(map(str, command)), cwd=lab.ROOT, check=True, timeout=timeout, stdout=out, stderr=subprocess.STDOUT, env=env) + + classes = build / 'classes' + classes.mkdir(exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['client'], *libraries])) + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', lab.ROOT / 'mods/horizon/src/test/java', + '-cp', dependencies, '-d', classes, oracle_path], 'compile-java') + run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', example], 'compile-rust') + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) + binary = Path(metadata['target_directory']) / 'debug/examples' / (example + ('.exe' if os.name == 'nt' else '')) + run([binary, *rust_args, inputs, build / 'rust.txt'], 'rust') + env = dict(os.environ, ALSOFT_DRIVERS='null') + run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, f'dev.horizonlab.parity.{oracle}', *java_args, inputs, build / 'client.txt'], + 'client', env=env) + matched = base.compare(build / 'client.txt', build / 'rust.txt') + base.ensure_sources_unchanged(sources, tested) + if input_hash != lab.digest(inputs, 'sha256'): + raise AssertionError('Input fixtures changed') + lab.write_json(report, dict( + schema=1, minecraft=lock['minecraft']['version'], manifest_sha1=lock['minecraft']['manifest_sha1'], platform=platform.platform(), + rustc=subprocess.check_output(['rustc', '--version'], text=True).strip(), + java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], + sources_sha256=tested, input_sha256=input_hash, client_jar_sha256=lab.digest(jars['client'], 'sha256'), + sounds_json_sha256=lab.digest(RESOURCES / 'assets/minecraft/sounds.json', 'sha256'), + matched_output_lines=matched, output_sha256=lab.digest(build / 'rust.txt', 'sha256'), scope=scope)) + return matched, report + + +def bits(value): + import struct + return struct.pack('>f', value).hex() diff --git a/tools/test_sound_event_parity.py b/tools/test_sound_event_parity.py new file mode 100644 index 000000000..49dc98a96 --- /dev/null +++ b/tools/test_sound_event_parity.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +"""Compare sound event resolution with the vanilla 26.3 client. + +The oracle builds the real `SoundManager` registry from the client asset root +(`SoundManager.prepare` + `Preparations.apply`: sounds.json, `replace`, +subtitles, file validation against the listed .ogg resources, event references +weighing as much as their event) and resolves seeded `SimpleSoundInstance`s: +`getOrResolve`, `getVolume`, `getPitch`, `Sound.getAttenuationDistance`, the +stream/preload/type fields and the instance random's next draw. Horizon's +`SoundRegistry` + `SoundEngine::resolve` replay the same inputs. +""" +import json +import random + +try: + from . import audio_harness as h +except ImportError: + import audio_harness as h + + +def fixtures(): + sounds = json.loads((h.RESOURCES / 'assets/minecraft/sounds.json').read_text()) + rng = random.Random(0x534f554e44) + volumes = [1.0, 0.5, 0.25, 2.0, 4.0, 0.0, 1e-3, 16.0] + pitches = [1.0, 0.5, 2.0, 0.8, 1.2, 3.0, 0.1] + lines = [] + for name in sorted(sounds): + event = 'minecraft:' + name + count = len(sounds[name].get('sounds', [])) + seeds = [0, 1, -1, 42] + [rng.getrandbits(64) - (1 << 63) for _ in range(max(4, 2 * count))] + for seed in seeds: + lines.append(f'{event} {seed} {h.bits(rng.choice(volumes))} {h.bits(rng.choice(pitches))}') + for event in ['minecraft:intentionally_empty', 'minecraft:empty', 'minecraft:not.a.sound', 'horizon:missing', 'block.stone.break', 'music.game']: + for seed in [0, 7, -99]: + lines.append(f'{event} {seed} {h.bits(1.0)} {h.bits(1.0)}') + return lines + + +def main(): + lines = fixtures() + matched, report = h.run_harness( + 'sound-events', 'VanillaSoundEventOracle', 'sound_event_fixture', ''.join(l + '\n' for l in lines), + java_args=[h.RESOURCES], rust_args=[h.RESOURCES], + scope='Real SoundManager.prepare/Preparations.apply over the client asset root and SimpleSoundInstance.getOrResolve/getVolume/getPitch ' + 'for every sounds.json event with seeded randoms (weighted choice, nested event references, MultipliedFloats volume/pitch, ' + 'stream/preload/attenuation fields, EMPTY and INTENTIONALLY_EMPTY sentinels, draw counts) and the full registered event list.') + print(f'{matched:,} sound event lines match the pinned client ({len(lines):,} resolutions): {report}', flush=True) + + +if __name__ == '__main__': + main() From 1d70ca47a82c873f31f684a3540fc989d4defeab Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:20:51 +0200 Subject: [PATCH 02/28] Generate whole chunks block for block as vanilla does The chunk generation harness found 70 differing chunks across three seeds in the overworld, Nether and End. Proto chunks, biomes and decoration now span the dimension type's build range rather than the noise height, so features above y=128 in the Nether and End city upper floors survive; the decoration level reports no sky light, as unlit vanilla chunks do, so mushrooms and crops pass or fail their light checks the same way; beehive decorators store their bees; iceberg ellipses skip NaN distances; double slabs never waterlog; mineshaft spawners save an empty SpawnPotentials list; and the dump example forgets structure starts between rectangles, as the oracle starts each with fresh chunks. The oracle prints absent block entity keys as vanilla loads them from an empty tag, and the harness treats vanilla's save-format equivalences (plain sign text, absent empty banner patterns, unfiltered sign messages) as equal. All 2,352 chunks over 225 structure sites match with zero block, biome or block entity differences. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-world/examples/chunk_dump.rs | 3 + .../horizon-world/src/worldgen/generator.rs | 92 ++++++++++++++----- .../src/worldgen/generator_decoration.rs | 51 ++++++++-- .../src/worldgen/generator_structures.rs | 5 + crates/horizon-world/src/worldgen/iceberg.rs | 3 +- .../horizon-world/src/worldgen/structure.rs | 7 +- .../src/worldgen/structure/legacy.rs | 2 + .../parity/VanillaChunkGenerationOracle.java | 14 ++- tools/test_chunk_generation_parity.py | 20 +++- 9 files changed, 160 insertions(+), 37 deletions(-) diff --git a/crates/horizon-world/examples/chunk_dump.rs b/crates/horizon-world/examples/chunk_dump.rs index 199f7e26f..b72a5e05e 100644 --- a/crates/horizon-world/examples/chunk_dump.rs +++ b/crates/horizon-world/examples/chunk_dump.rs @@ -160,6 +160,9 @@ fn main() -> Result<(), Error> { return Ok(()); } for [x0, z0, x1, z1] in rects { + // Each rectangle starts from scratch, like the oracle's fresh chunks: + // structure pieces keep placement state (a shipwreck's adjusted height). + worker.forget_structure_starts(); let mut chunks: HashMap<(i32, i32), ProtoChunk> = HashMap::new(); for z in z0 - 2..=z1 + 2 { for x in x0 - 2..=x1 + 2 { diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 91a5e0f1d..7a264020f 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -563,10 +563,24 @@ impl ProtoChunk { } } +/// Build range (minimum Y, height) of the vanilla dimension types. +fn dimension_type_height(name: &str) -> Option<(i32, i32)> { + match name { + "minecraft:overworld" | "minecraft:overworld_caves" => Some((-64, 384)), + "minecraft:the_nether" | "minecraft:the_end" => Some((0, 256)), + _ => None, + } +} + /// Per-noise-settings values resolved from the dimension's generator JSON. struct Settings { - min_y: i32, - height: i32, + noise_min_y: i32, + noise_height: i32, + /// The dimension type's build range (LevelHeightAccessor): proto chunks, + /// their heightmaps and the decoration region span it, while the noise + /// only fills `noise_min_y..noise_min_y + noise_height`. + level_min_y: i32, + level_height: i32, sea_level: i32, default_block: BlockStateId, default_fluid: BlockStateId, @@ -635,16 +649,25 @@ where generator: &Value, settings_json: &Value, with_structures: bool, + level: Option<(i32, i32)>, ) -> Result { let registry = data.registry; let noise = &settings_json["noise"]; + let min_y = noise["min_y"] + .as_i64() + .ok_or_else(|| resource("noise min_y"))? as i32; + let height = noise["height"] + .as_i64() + .ok_or_else(|| resource("noise height"))? as i32; + let (level_min_y, level_height) = level.unwrap_or((min_y, height)); + if min_y < level_min_y || min_y + height > level_min_y + level_height { + return Err(resource("noise range outside the dimension's build height")); + } let settings = Settings { - min_y: noise["min_y"] - .as_i64() - .ok_or_else(|| resource("noise min_y"))? as i32, - height: noise["height"] - .as_i64() - .ok_or_else(|| resource("noise height"))? as i32, + noise_min_y: min_y, + noise_height: height, + level_min_y, + level_height, sea_level: settings_json["sea_level"] .as_i64() .ok_or_else(|| resource("sea_level"))? as i32, @@ -777,8 +800,8 @@ where } fn generation(&self) -> WorldGenerationContext { WorldGenerationContext::new( - self.settings.min_y, - self.settings.height, + self.settings.noise_min_y, + self.settings.noise_height, self.settings.sea_level, ) } @@ -790,7 +813,7 @@ where if let Some(chunk) = self.biome_cache.lock().unwrap().get(&(pos.x, pos.z)) { return Ok(chunk.clone()); } - let (min, height) = (self.settings.min_y, self.settings.height); + let (min, height) = (self.settings.level_min_y, self.settings.level_height); let mut chunk = BiomeChunk::new(pos, min, height, BiomeId(0)).map_err(stage("biomes"))?; let mut resolver = self.source.resolver( &self.climate, @@ -856,8 +879,8 @@ where ) -> Result { let data = &self.data; let (min, height, sea) = ( - self.settings.min_y, - self.settings.height, + self.settings.noise_min_y, + self.settings.noise_height, self.settings.sea_level, ); let mut clock = std::time::Instant::now(); @@ -869,8 +892,10 @@ where worker, ChunkPos::new(pos.x.wrapping_add(dx), pos.z.wrapping_add(dz)), )?; - for section in 0..(height / 16) as usize { - possible.extend(chunk.section(section).unwrap().iter().copied()); + let mut section = 0; + while let Some(biomes) = chunk.section(section) { + possible.extend(biomes.iter().copied()); + section += 1; } neighbors.push((*chunk).clone()); } @@ -883,8 +908,14 @@ where .map(|id| data.biome_name(id).to_owned()) .collect(); worker.timings.biomes += lap(&mut clock); - let mut chunk = TerrainChunk::new(pos, min, height, data.registry, data.states.clone()) - .map_err(stage("noise"))?; + let mut chunk = TerrainChunk::new( + pos, + self.settings.level_min_y, + self.settings.level_height, + data.registry, + data.states.clone(), + ) + .map_err(stage("noise"))?; chunk.set_generation_stage(PreLightChunkStage::Biomes); let references = match &self.structures { Some(structures) => structures.references( @@ -1036,7 +1067,7 @@ where /// ChunkGenerator.getBaseHeight: the first free Y above the noise column /// (with aquifers, without terrain adaptation) for a heightmap type. fn base_height(&self, x: i32, z: i32, kind: HeightmapType) -> i32 { - let min = self.settings.min_y; + let min = self.settings.noise_min_y; let mut found = min; self.noise_column(x, z, &mut |y, state| { if kind.is_opaque(self.data.states.get(state)) { @@ -1054,7 +1085,7 @@ where } /// One noise-column pass, as opacities for each heightmap kind. fn base_columns(&self, x: i32, z: i32, kinds: &[HeightmapType]) -> Vec> { - let (min, height) = (self.settings.min_y, self.settings.height); + let (min, height) = (self.settings.noise_min_y, self.settings.noise_height); let mut columns = vec![vec![false; height as usize]; kinds.len()]; self.noise_column(x, z, &mut |y, state| { let state = self.data.states.get(state); @@ -1067,7 +1098,7 @@ where } /// iterateNoiseColumn from the top down until `visit` returns true. fn noise_column(&self, x: i32, z: i32, visit: &mut dyn FnMut(i32, BlockStateId) -> bool) { - let (min, height) = (self.settings.min_y, self.settings.height); + let (min, height) = (self.settings.noise_min_y, self.settings.noise_height); let Ok(volume) = DensityVolume::new([1, height, 1], [x, min, z], [1; 3]) else { return; }; @@ -1131,11 +1162,12 @@ impl super::structure::jigsaw::JigsawContext for StructureQueri where R::Positional: Clone + Send + Sync, { + // Structure.GenerationContext.heightAccessor: the chunk, so the level's range. fn min_y(&self) -> i32 { - self.pipeline.settings.min_y + self.pipeline.settings.level_min_y } fn max_y(&self) -> i32 { - self.pipeline.settings.min_y + self.pipeline.settings.height - 1 + self.pipeline.settings.level_min_y + self.pipeline.settings.level_height - 1 } fn base_height(&mut self, x: i32, z: i32, kind: HeightmapType) -> i32 { if let Some(h) = self.worker.heights.get(&(x, z, kind as u8)) { @@ -1329,6 +1361,7 @@ trait SeededPipeline: Send + Sync { pos: ChunkPos, ) -> Vec>; fn unsupported_features(&self) -> Vec<(String, String)>; + fn forget_structure_starts(&self); fn ring_positions(&self, set: &str) -> Option>; fn locate( &self, @@ -1411,6 +1444,11 @@ where .map(super::generator_decoration::Decoration::unsupported) .unwrap_or_default() } + fn forget_structure_starts(&self) { + if let Some(structures) = &self.structures { + structures.forget_starts(); + } + } fn ring_positions(&self, set: &str) -> Option> { self.structures.as_ref()?.cached_rings(set) } @@ -1485,6 +1523,9 @@ impl OverworldGenerator { .ok_or_else(|| resource(format!("missing world preset {preset}")))?, )?; let generator = preset_json["dimensions"][dimension]["generator"].clone(); + let level = preset_json["dimensions"][dimension]["type"] + .as_str() + .and_then(dimension_type_height); if generator["type"].as_str() != Some("minecraft:noise") { return Err(resource(format!("{dimension} is not a noise generator"))); } @@ -1507,6 +1548,7 @@ impl OverworldGenerator { &generator, &settings_json, with_structures, + level, )?) } else { Arc::new(Pipeline::new( @@ -1516,6 +1558,7 @@ impl OverworldGenerator { &generator, &settings_json, with_structures, + level, )?) }; Ok(Self { pipeline }) @@ -1586,6 +1629,11 @@ impl GeneratorWorker { ) -> Vec> { self.pipeline.structure_starts(&mut self.state, pos) } + /// Forget the cached structure starts: chunks generated afterwards get + /// fresh starts, as in a new level that has not loaded the old chunks. + pub fn forget_structure_starts(&mut self) { + self.pipeline.forget_structure_starts(); + } pub fn stage_timings(&self) -> StageTimings { self.state.timings } diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs index 993872f98..655de6a33 100644 --- a/crates/horizon-world/src/worldgen/generator_decoration.rs +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -329,18 +329,16 @@ impl Decoration { decoration: self, temperatures: &mut worker.temperatures, behaviours: data.behaviours.as_deref(), - build: (generation.min_y, generation.min_y + generation.height), + // WorldGenRegion.isOutsideBuildHeight: the level's range, not the noise's. + build: (min_y, min_y + height), }; let mut stats = DecorateStats::default(); let blocks = self.blocks; let references = region[4].structure_starts.clone(); + // ChunkGenerator.getWritableArea: the chunk's minimum Y + 1 to its maximum Y. let chunk_box = BoundingBox::new( - [center.x * 16, generation.min_y + 1, center.z * 16], - [ - center.x * 16 + 15, - generation.min_y + generation.height - 1, - center.z * 16 + 15, - ], + [center.x * 16, min_y + 1, center.z * 16], + [center.x * 16 + 15, min_y + height - 1, center.z * 16 + 15], ); let mut structure_errors = 0; let result = self.plan.decorate( @@ -497,6 +495,11 @@ impl crate::level::LevelAccess for ShapeLevel<'_, '_> { fn game_time(&self) -> i64 { 0 } + /// Lighting has not run during FEATURES: the light engine has no data for + /// these chunks, so sky light reads zero too (MushroomBlock.canSurvive). + fn sky_light(&self, _: BlockPos) -> i32 { + 0 + } } impl World<'_> { /// `BlockState.updateShape` of the state at `pos` against `neighbor`. @@ -670,6 +673,40 @@ impl PlacementContext for World<'_> { nbt.insert("LootTableSeed".into(), Tag::Long(random.next_long())); self.set_block_entity(position, nbt) } + /// BeehiveDecorator: `getBlockEntity(pos, BEEHIVE)` then + /// `storeBee(Occupant.create(ticks))` for each bee (min ticks in hive 600). + fn store_beehive_occupants( + &mut self, + position: [i32; 3], + ticks_in_hive: &[i32], + ) -> Result<(), PlacementQueryError> { + use crate::nbt::Tag; + let chunk = self.region.chunk(position[0] >> 4, position[2] >> 4)?; + let state = chunk.block(position[0], position[1], position[2]); + let registry = self.decoration.bindings.registry(); + if !matches!( + registry.state(state).map(|s| s.name.as_str()), + Some("minecraft:bee_nest" | "minecraft:beehive") + ) { + return Ok(()); + } + let bees = ticks_in_hive + .iter() + .map(|&ticks| { + let mut entity = crate::nbt::Compound::new(); + entity.insert("id".into(), Tag::String("minecraft:bee".into())); + let mut bee = crate::nbt::Compound::new(); + bee.insert("entity_data".into(), Tag::Compound(entity)); + bee.insert("ticks_in_hive".into(), Tag::Int(ticks)); + bee.insert("min_ticks_in_hive".into(), Tag::Int(600)); + Tag::Compound(bee) + }) + .collect(); + let mut nbt = crate::nbt::Compound::new(); + nbt.insert("id".into(), Tag::String("minecraft:beehive".into())); + nbt.insert("bees".into(), Tag::List(bees)); + self.set_block_entity(position, nbt) + } /// SpawnerBlockEntity.setEntityId: the next spawn data and no potentials. fn configure_spawner( &mut self, diff --git a/crates/horizon-world/src/worldgen/generator_structures.rs b/crates/horizon-world/src/worldgen/generator_structures.rs index ce584eaa4..8a5f15d65 100644 --- a/crates/horizon-world/src/worldgen/generator_structures.rs +++ b/crates/horizon-world/src/worldgen/generator_structures.rs @@ -96,6 +96,11 @@ impl StructureState { pub(super) fn cached_rings(&self, set: &str) -> Option> { self.rings.get().and_then(|rings| rings.get(set).cloned()) } + /// Drop the cached starts, so that later chunks build fresh pieces (the + /// pieces keep per-start placement state such as a shipwreck's height). + pub(super) fn forget_starts(&self) { + self.starts.lock().unwrap().clear(); + } /// The (cached) structure starts owned by a chunk. pub(super) fn starts_at( &self, diff --git a/crates/horizon-world/src/worldgen/iceberg.rs b/crates/horizon-world/src/worldgen/iceberg.rs index e4370e71d..2bfeff29a 100644 --- a/crates/horizon-world/src/worldgen/iceberg.rs +++ b/crates/horizon-world/src/worldgen/iceberg.rs @@ -277,7 +277,8 @@ impl IcebergFeature { let off = 10.0f32 * random.next_float().clamp(0.2, 0.8) / radius as f32; f64::from(off) + pow2(xo) + pow2(zo) - pow2(radius) }; - if signed >= 0.0 { + // `signedDist < 0.0` fails for NaN too (a zero-width ellipse layer at its centre). + if signed.is_nan() || signed >= 0.0 { return Ok(()); } let p = tb::offset(origin, xo, y, zo); diff --git a/crates/horizon-world/src/worldgen/structure.rs b/crates/horizon-world/src/worldgen/structure.rs index 4b4c1cdbb..f15c37dc2 100644 --- a/crates/horizon-world/src/worldgen/structure.rs +++ b/crates/horizon-world/src/worldgen/structure.rs @@ -296,7 +296,12 @@ impl StructureResources { { sources.insert(id); } - if state.properties.get("waterlogged").map(String::as_str) == Some("false") { + // SlabBlock.placeLiquid refuses double slabs. + let double_slab = state.name.ends_with("_slab") + && state.properties.get("type").map(String::as_str) == Some("double"); + if !double_slab + && state.properties.get("waterlogged").map(String::as_str) == Some("false") + { let mut wet = state.clone(); wet.properties.insert("waterlogged".into(), "true".into()); if let Some(wet) = registry.id(&wet) { diff --git a/crates/horizon-world/src/worldgen/structure/legacy.rs b/crates/horizon-world/src/worldgen/structure/legacy.rs index 0d0ccb103..e55209baf 100644 --- a/crates/horizon-world/src/worldgen/structure/legacy.rs +++ b/crates/horizon-world/src/worldgen/structure/legacy.rs @@ -230,6 +230,8 @@ impl PieceContext<'_> { let mut nbt = Compound::new(); nbt.insert("id".into(), Tag::String("minecraft:mob_spawner".into())); nbt.insert("SpawnData".into(), Tag::Compound(data)); + // SpawnerBlockEntity.setEntityId on a fresh spawner: no potentials. + nbt.insert("SpawnPotentials".into(), Tag::List(Vec::new())); self.world.block_entity(pos, nbt) } } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java index a5e6c1402..ea1d4aa23 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java @@ -411,9 +411,17 @@ public final class VanillaChunkGenerationOracle { var tag = target.getBlockEntityNbtForSaving(pos, registry); if (tag == null) continue; var st = target.getBlockState(pos); - var fresh = ((net.minecraft.world.level.block.EntityBlock) st.getBlock()).newBlockEntity(pos, st).saveWithFullMetadata(registry); - if ("DUMMY".equals(tag.getStringOr("id", ""))) tag = fresh; - w.println("be " + pos.getX() + " " + pos.getY() + " " + pos.getZ() + "\t" + canonicalOf(tag) + "\t" + canonicalOf(fresh)); + var block = (net.minecraft.world.level.block.EntityBlock) st.getBlock(); + var fresh = block.newBlockEntity(pos, st).saveWithFullMetadata(registry); + // The value of each key Horizon leaves out: what loading a tag without + // it gives (BrewingStandBlockEntity reads a missing total_brew_time as 400). + var empty = block.newBlockEntity(pos, st); + empty.loadWithComponents(net.minecraft.world.level.storage.TagValueInput.create( + net.minecraft.util.ProblemReporter.DISCARDING, registry, new net.minecraft.nbt.CompoundTag())); + var absent = empty.saveWithFullMetadata(registry); + // A DUMMY pending entry becomes a fresh block entity, not a loaded one. + if ("DUMMY".equals(tag.getStringOr("id", ""))) tag = absent = fresh; + w.println("be " + pos.getX() + " " + pos.getY() + " " + pos.getZ() + "\t" + canonicalOf(tag) + "\t" + canonicalOf(absent)); } } } diff --git a/tools/test_chunk_generation_parity.py b/tools/test_chunk_generation_parity.py index 962780756..8b831d3cd 100644 --- a/tools/test_chunk_generation_parity.py +++ b/tools/test_chunk_generation_parity.py @@ -141,7 +141,8 @@ def parse_nbt(text, i=0): def nbt_matches(vanilla, rust, default): """Horizon stores the placed data only; vanilla saves defaults too. Every key - Horizon sets must match, and every other vanilla key must be the fresh default.""" + Horizon sets must match, and every other vanilla key must be what vanilla + loads for an absent key (the oracle's second form).""" if isinstance(vanilla, dict) and isinstance(rust, dict): default = default if isinstance(default, dict) else {} if 'LootTableSeed' in rust and 'LootTable' not in rust: @@ -154,7 +155,11 @@ def nbt_matches(vanilla, rust, default): return False elif value != default.get(key): return False - return all(key in vanilla or key in ('x', 'y', 'z') or nbt_matches(default.get(key), rust[key], None) or (key, rust[key]) == VAULT_REWARD for key in rust) + return all(key in vanilla or key in ('x', 'y', 'z') or nbt_matches(default.get(key), rust[key], None) or (key, rust[key]) == VAULT_REWARD + or omitted_on_save(key, rust) for key in rust) + if isinstance(vanilla, tuple) and vanilla[0] == 'str' and isinstance(rust, dict) and set(rust) == {'text'}: + # A literal text component saves as its plain string: {text:"a"} is "a". + return vanilla == rust['text'] if isinstance(vanilla, list) and isinstance(rust, list): return len(vanilla) == len(rust) and all(nbt_matches(a, b, None) for a, b in zip(vanilla, rust)) if isinstance(vanilla, tuple) and isinstance(rust, tuple) and vanilla[0] in 'bsil' and rust[0] in 'bsil': @@ -163,6 +168,14 @@ def nbt_matches(vanilla, rust, default): return vanilla == rust +def omitted_on_save(key, rust): + """Template keys that vanilla's codecs leave out when re-saving the loaded block entity.""" + if key == 'patterns' and rust[key] == []: + return True # BannerBlockEntity saves its patterns only when there are some + # SignText saves filtered_messages only when some line differs from messages. + return key == 'filtered_messages' and rust[key] == rust.get('messages') + + def entity_matches(vanilla, rust): if vanilla is None: return False @@ -258,6 +271,7 @@ def pick_structures(starts, per_kind, rng): def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--seeds', type=int, default=3) + parser.add_argument('--seed', type=int, action='append', help='run only this seed (repeatable)') parser.add_argument('--per-structure', type=int, default=2) parser.add_argument('--sites', type=int, default=6, help='terrain sites per overworld seed') parser.add_argument('--radius', type=int, default=1, help='chunk radius around each site') @@ -281,7 +295,7 @@ def main(): biome_seen = set() structure_seen = Counter() started = time.time() - for seed in SEEDS[:args.seeds]: + for seed in args.seed or SEEDS[:args.seeds]: rng = random.Random(seed) for dimension in dimensions: rects, labels = [], [] From fc468a021d9ebcaf19afb46f3538f710380336a4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:21:50 +0200 Subject: [PATCH 03/28] Resolve item models exactly as the vanilla client does The item model harness ran out of memory, so it now streams both outputs and looks Horizon's rows up by offset. With the vanilla side no longer crashing on swap-animation lookups (properties now come from the baked set), on armour (trim sprites are generated by the items atlas's paletted_permutations source once SpriteSources is bootstrapped) or on compasses (item tags are bound from the data pack), 197,000 more stacks were compared and 121,841 differed. Horizon now composes transformations as JOML 1.10.9 does: rotationXYZ and axis-angle quaternions with cosFromSin, and Matrix4f operations that take the identity, translation, affine or generic path by matrix properties, with unfused a * b + c. Float RGB tint constants are scaled by 255, the shulker box renderer always encodes its texture, and a new palette module ports PalettedPermutations and PaletteMapping so trim sprites exist on the Horizon side too. 196,290 resolved stacks match; 2,582 cases are still rejected by vanilla's stand-in client and not compared. Co-Authored-By: Claude Opus 5.5 --- .../examples/item_model_fixture.rs | 55 +++- crates/horizon-assets/src/item_model.rs | 6 +- .../horizon-assets/src/item_model/special.rs | 4 +- crates/horizon-assets/src/lib.rs | 1 + crates/horizon-assets/src/math.rs | 250 +++++++++++++++--- crates/horizon-assets/src/palette.rs | 105 ++++++++ .../parity/VanillaItemModelOracle.java | 59 ++++- tools/test_item_model_parity.py | 71 +++-- 8 files changed, 475 insertions(+), 76 deletions(-) create mode 100644 crates/horizon-assets/src/palette.rs diff --git a/crates/horizon-assets/examples/item_model_fixture.rs b/crates/horizon-assets/examples/item_model_fixture.rs index 559121782..c14ee3866 100644 --- a/crates/horizon-assets/examples/item_model_fixture.rs +++ b/crates/horizon-assets/examples/item_model_fixture.rs @@ -6,6 +6,7 @@ use horizon_assets::{ item_model::*, math::Mat4, model::{CuboidModel, Direction}, + palette::{PalettedPermutations, apply_palette}, resolve::{MISSING_MODEL, ModelLibrary}, }; use serde_json::{Value, json}; @@ -23,6 +24,8 @@ fn bits(v: f32) -> u32 { struct Sprites { root: PathBuf, + /// The items atlas's paletted permutations (armour trim sprites). + permutations: Vec, cache: RefCell>>, } impl SpriteLookup for Sprites { @@ -38,27 +41,48 @@ impl SpriteLookup for Sprites { } } impl Sprites { - fn load(&self, sprite: &str) -> Option { - let (namespace, path) = sprite.split_once(':')?; - let png = self - .root - .join(format!("assets/{namespace}/textures/{path}.png")); - let mut decoder = png::Decoder::new(BufReader::new(File::open(&png).ok()?)); + fn png(&self, sprite: &str, directory: &str) -> PathBuf { + let (namespace, path) = sprite.split_once(':').unwrap_or(("minecraft", sprite)); + self.root + .join(format!("assets/{namespace}/{directory}/{path}.png")) + } + /// The image as ARGB pixels in reading order, with its size. + fn argb(png: &Path) -> Option<(usize, usize, Vec)> { + let mut decoder = png::Decoder::new(BufReader::new(File::open(png).ok()?)); decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16); let mut reader = decoder.read_info().ok()?; let mut bytes = vec![0; reader.output_buffer_size()?]; let info = reader.next_frame(&mut bytes).ok()?; let channels = info.color_type.samples(); - let alpha = |pixel: &[u8]| match info.color_type { - png::ColorType::Rgba => pixel[3], - png::ColorType::GrayscaleAlpha => pixel[1], - _ => 255, - }; - let (iw, ih) = (info.width as usize, info.height as usize); - let pixels: Vec = bytes[..info.buffer_size()] + let pixels = bytes[..info.buffer_size()] .chunks_exact(channels) - .map(alpha) + .map(|p| { + let (r, g, b, a) = match info.color_type { + png::ColorType::Rgba => (p[0], p[1], p[2], p[3]), + png::ColorType::Rgb => (p[0], p[1], p[2], 255), + png::ColorType::GrayscaleAlpha => (p[0], p[0], p[0], p[1]), + _ => (p[0], p[0], p[0], 255), + }; + u32::from_be_bytes([a, r, g, b]) + }) .collect(); + Some((info.width as usize, info.height as usize, pixels)) + } + fn load(&self, sprite: &str) -> Option { + let png = self.png(sprite, "textures"); + let (iw, ih, argb) = match Self::argb(&png) { + Some(image) => image, + None => { + // PalettedPermutations: the base texture through PaletteMapping. + let p = self.permutations.iter().find_map(|s| s.find(sprite))?; + let (w, h, mut pixels) = Self::argb(&self.png(p.base, "textures"))?; + let (_, _, key) = Self::argb(&self.png(p.palette_key, "textures/palettes"))?; + let (_, _, target) = Self::argb(&self.png(p.palette, "textures/palettes"))?; + apply_palette(&mut pixels, &key, &target)?; + (w, h, pixels) + } + }; + let pixels: Vec = argb.iter().map(|p| (p >> 24) as u8).collect(); let meta = fs::read_to_string(png.with_extension("png.mcmeta")).ok(); let animation = meta .and_then(|m| serde_json::from_str::(&m).ok()) @@ -215,6 +239,9 @@ fn main() -> Result<(), Box> { let library = ModelLibrary::with_item_generator(cuboids)?; let sprites = Sprites { root: root.clone(), + permutations: PalettedPermutations::from_atlas( + &fs::read_to_string(root.join("assets/minecraft/atlases/items.json")).unwrap_or_default(), + ), cache: RefCell::default(), }; let grass = { diff --git a/crates/horizon-assets/src/item_model.rs b/crates/horizon-assets/src/item_model.rs index d50140be2..5999805eb 100644 --- a/crates/horizon-assets/src/item_model.rs +++ b/crates/horizon-assets/src/item_model.rs @@ -342,9 +342,11 @@ fn optional_transformation(m: &Map) -> Result> { get(m, "transformation").map(transformation).transpose() } /// `Mth.floor(float)` as `ARGB.as8BitChannel` uses it. +/// `ARGB.as8BitChannel`: `Mth.floor(value * 255.0F)`. fn channel(v: f32) -> i32 { - let i = v as i32; - if (i as f32) > v { i - 1 } else { i } + let scaled = v * 255.0; + let i = scaled as i32; + if (i as f32) > scaled { i - 1 } else { i } } // --------------------------------------------------------------------------- diff --git a/crates/horizon-assets/src/item_model/special.rs b/crates/horizon-assets/src/item_model/special.rs index f62122bf2..a9ec58821 100644 --- a/crates/horizon-assets/src/item_model/special.rs +++ b/crates/horizon-assets/src/item_model/special.rs @@ -207,9 +207,7 @@ impl SpecialModel { } SpecialKind::PlayerHead => "player_head", SpecialKind::ShulkerBox { texture, openness } => { - if texture != "minecraft:shulker" { - put("texture", json!(texture)); - } + put("texture", json!(texture)); if *openness != 0.0 { put("openness", json!(openness)); } diff --git a/crates/horizon-assets/src/lib.rs b/crates/horizon-assets/src/lib.rs index cee09ce5d..629904ee0 100644 --- a/crates/horizon-assets/src/lib.rs +++ b/crates/horizon-assets/src/lib.rs @@ -9,6 +9,7 @@ pub mod item_model; mod json; pub mod math; pub mod model; +pub mod palette; pub mod resolve; pub use json::DecodeError; diff --git a/crates/horizon-assets/src/math.rs b/crates/horizon-assets/src/math.rs index 51a2de0e2..74595c4d2 100644 --- a/crates/horizon-assets/src/math.rs +++ b/crates/horizon-assets/src/math.rs @@ -1,31 +1,88 @@ -//! Column-major `Matrix4f` arithmetic with the operand order of JOML's -//! default (non-FMA) code paths, for composing item-model transformations. +//! Column-major `Matrix4f` arithmetic as JOML 1.10.9 computes it, for composing +//! item-model transformations: each operation takes the path JOML picks from +//! the matrix properties (identity, translation, affine...), and `Math.fma` is +//! `a * b + c` since Minecraft leaves `joml.useMathFma` off. -/// A JOML `Matrix4f`: `m[column][row]`. +/// `Matrix4fc.PROPERTY_*` bits. +const PERSPECTIVE: u8 = 1; +const AFFINE: u8 = 2; +const IDENTITY: u8 = 4; +const TRANSLATION: u8 = 8; +const ORTHONORMAL: u8 = 16; + +/// JOML `Math.fma` without `joml.useMathFma`. +#[inline] +fn fma(a: f32, b: f32, c: f32) -> f32 { + a * b + c +} +/// JOML `Math.absEqualsOne`. +fn abs_equals_one(r: f32) -> bool { + r.to_bits() & 0x7FFF_FFFF == 0x3F80_0000 +} + +/// A JOML `Matrix4f`: `m[column][row]`, with its property bits. #[derive(Clone, Copy, Debug, PartialEq)] -pub struct Mat4(pub [[f32; 4]; 4]); +pub struct Mat4(pub [[f32; 4]; 4], pub u8); impl Mat4 { - pub const IDENTITY: Self = Self([ - [1.0, 0.0, 0.0, 0.0], - [0.0, 1.0, 0.0, 0.0], - [0.0, 0.0, 1.0, 0.0], - [0.0, 0.0, 0.0, 1.0], - ]); + /// `new Matrix4f()`. + pub const IDENTITY: Self = Self( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + IDENTITY | AFFINE | TRANSLATION | ORTHONORMAL, + ); /// `Matrix4f.translation(x, y, z)`. pub fn translation(t: [f32; 3]) -> Self { let mut m = Self::IDENTITY; m.0[3][..3].copy_from_slice(&t); + m.1 = AFFINE | TRANSLATION | ORTHONORMAL; m } - /// `ExtraCodecs.MATRIX4F`: sixteen values in row-major order. + /// `ExtraCodecs.MATRIX4F`: sixteen values in row-major order, then + /// `determineProperties`. pub fn from_row_major(values: [f32; 16]) -> Self { - let mut m = Self([[0.0; 4]; 4]); + let mut m = Self([[0.0; 4]; 4], 0); for (i, v) in values.into_iter().enumerate() { m.0[i & 3][i >> 2] = v; } + m.1 = m.determine_properties(); m } + /// `Matrix4f.determineProperties`. + fn determine_properties(&self) -> u8 { + let m = &self.0; + let mut properties = 0; + if m[0][3] == 0.0 && m[1][3] == 0.0 { + if m[2][3] == 0.0 && m[3][3] == 1.0 { + properties |= AFFINE; + if m[0] == [1.0, 0.0, 0.0, 0.0] && m[1] == [0.0, 1.0, 0.0, 0.0] && m[2] == [0.0, 0.0, 1.0, 0.0] { + properties |= TRANSLATION | ORTHONORMAL; + if m[3][0] == 0.0 && m[3][1] == 0.0 && m[3][2] == 0.0 { + properties |= IDENTITY; + } + } + } else if m[0][1] == 0.0 + && m[0][2] == 0.0 + && m[1][0] == 0.0 + && m[1][2] == 0.0 + && m[2][0] == 0.0 + && m[2][1] == 0.0 + && m[3][0] == 0.0 + && m[3][1] == 0.0 + && m[3][3] == 0.0 + { + properties |= PERSPECTIVE; + } + } + properties + } + fn has(&self, property: u8) -> bool { + self.1 & property != 0 + } /// The matrix as `[row][column]` entries, the order `getRowColumn` reads. pub fn rows(&self) -> [[f32; 4]; 4] { std::array::from_fn(|r| std::array::from_fn(|c| self.0[c][r])) @@ -33,37 +90,106 @@ impl Mat4 { /// `this * right` (`Matrix4f.mul`). pub fn mul(&self, right: &Self) -> Self { let (m, r) = (&self.0, &right.0); + if self.has(IDENTITY) { + return *right; + } + if right.has(IDENTITY) { + return *self; + } let mut out = [[0.0; 4]; 4]; + if self.has(TRANSLATION) && right.has(AFFINE) { + // mulTranslationAffine + for c in 0..4 { + out[c] = [r[c][0], r[c][1], r[c][2], m[c][3]]; + } + for row in 0..3 { + out[3][row] = r[3][row] + m[3][row]; + } + return Self(out, AFFINE | right.1 & ORTHONORMAL); + } + if self.has(AFFINE) && right.has(AFFINE) { + // mulAffine + for c in 0..3 { + for row in 0..3 { + out[c][row] = fma(m[0][row], r[c][0], fma(m[1][row], r[c][1], m[2][row] * r[c][2])); + } + out[c][3] = m[c][3]; + } + for row in 0..3 { + out[3][row] = fma(m[0][row], r[3][0], fma(m[1][row], r[3][1], fma(m[2][row], r[3][2], m[3][row]))); + } + out[3][3] = m[3][3]; + return Self(out, AFFINE | self.1 & right.1 & ORTHONORMAL); + } + if self.has(PERSPECTIVE) && right.has(AFFINE) { + // mulPerspectiveAffine + for c in 0..4 { + out[c] = [m[0][0] * r[c][0], m[1][1] * r[c][1], m[2][2] * r[c][2], m[2][3] * r[c][2]]; + } + out[3][2] = m[2][2] * r[3][2] + m[3][2]; + out[3][3] = m[2][3] * r[3][2]; + return Self(out, 0); + } + if right.has(AFFINE) { + // mulAffineR + for c in 0..3 { + for row in 0..4 { + out[c][row] = fma(m[0][row], r[c][0], fma(m[1][row], r[c][1], m[2][row] * r[c][2])); + } + } + for row in 0..4 { + out[3][row] = fma(m[0][row], r[3][0], fma(m[1][row], r[3][1], fma(m[2][row], r[3][2], m[3][row]))); + } + return Self(out, self.1 & !(PERSPECTIVE | IDENTITY | TRANSLATION | ORTHONORMAL)); + } + // mul0 for c in 0..4 { for row in 0..4 { - out[c][row] = m[0][row] * r[c][0] - + m[1][row] * r[c][1] - + m[2][row] * r[c][2] - + m[3][row] * r[c][3]; + out[c][row] = fma( + m[0][row], + r[c][0], + fma(m[1][row], r[c][1], fma(m[2][row], r[c][2], m[3][row] * r[c][3])), + ); } } - Self(out) + Self(out, 0) } - /// `Matrix4f.translate(x, y, z)` (`translateGeneric`). + /// `Matrix4f.translate(x, y, z)`. pub fn translate(&self, t: [f32; 3]) -> Self { + if self.has(IDENTITY) { + return Self::translation(t); + } + // translateGeneric let mut out = *self; for row in 0..4 { - out.0[3][row] = self.0[0][row] * t[0] - + (self.0[1][row] * t[1] + (self.0[2][row] * t[2] + self.0[3][row])); + out.0[3][row] = fma(self.0[0][row], t[0], fma(self.0[1][row], t[1], fma(self.0[2][row], t[2], self.0[3][row]))); } + out.1 = self.1 & !(PERSPECTIVE | IDENTITY); out } - /// `Matrix4f.scale(x, y, z)`: the first three columns are scaled. + /// `Matrix4f.scale(x, y, z)`. pub fn scale(&self, s: [f32; 3]) -> Self { + let one = s.iter().all(|&v| abs_equals_one(v)); + if self.has(IDENTITY) { + // scaling + let mut out = Self::IDENTITY; + for (c, v) in s.into_iter().enumerate() { + out.0[c][c] = v; + } + out.1 = AFFINE | if one { ORTHONORMAL } else { 0 }; + return out; + } + // scaleGeneric: the first three columns are scaled. let mut out = *self; for c in 0..3 { for row in 0..4 { out.0[c][row] = self.0[c][row] * s[c]; } } + out.1 = self.1 & !(PERSPECTIVE | IDENTITY | TRANSLATION | if one { 0 } else { ORTHONORMAL }); out } - /// `Matrix4f.rotate(Quaternionfc)` (`rotateGeneric`). + /// `Matrix4f.rotate(Quaternionfc)`. pub fn rotate(&self, q: [f32; 4]) -> Self { let [x, y, z, w] = q; let (w2, x2, y2, z2) = (w * w, x * x, y * y, z * z); @@ -71,14 +197,39 @@ impl Mat4 { let (dzw, dxy, dxz, dyw, dyz, dxw) = (zw + zw, xy + xy, xz + xz, yw + yw, yz + yz, xw + xw); let r = [ [w2 + x2 - z2 - y2, dxy + dzw, dxz - dyw], - [dxy - dzw, y2 - z2 + w2 - x2, dyz + dxw], + [-dzw + dxy, y2 - z2 + w2 - x2, dyz + dxw], [dyw + dxz, dyz - dxw, z2 - y2 - x2 + w2], ]; let m = &self.0; let mut out = *self; - for c in 0..3 { - for row in 0..4 { - out.0[c][row] = m[0][row] * r[c][0] + m[1][row] * r[c][1] + m[2][row] * r[c][2]; + if self.has(IDENTITY) { + // rotation + for c in 0..3 { + out.0[c][..3].copy_from_slice(&r[c]); + } + out.1 = AFFINE | ORTHONORMAL; + return out; + } + out.1 = self.1 & !(PERSPECTIVE | IDENTITY | TRANSLATION); + if self.has(TRANSLATION) { + // rotateTranslation + for c in 0..3 { + out.0[c] = [r[c][0], r[c][1], r[c][2], 0.0]; + } + } else if self.has(AFFINE) { + // rotateAffine + for c in 0..3 { + for row in 0..3 { + out.0[c][row] = m[0][row] * r[c][0] + m[1][row] * r[c][1] + m[2][row] * r[c][2]; + } + out.0[c][3] = 0.0; + } + } else { + // rotateGeneric + for c in 0..3 { + for row in 0..4 { + out.0[c][row] = fma(m[0][row], r[c][0], fma(m[1][row], r[c][1], m[2][row] * r[c][2])); + } } } out @@ -94,28 +245,46 @@ pub fn normalize_quaternion(q: [f32; 4]) -> [f32; 4] { let inv = 1.0 / (x * x + (y * y + (z * z + w * w))).sqrt(); [x * inv, y * inv, z * inv, w * inv] } +/// JOML `Math.sin(float)` without fast math. +fn joml_sin(rad: f32) -> f32 { + f64::from(rad).sin() as f32 +} +/// JOML `Math.cosFromSin(float, float)` without fast math: the magnitude from +/// the sine, the sign from the angle's quadrant (exact zeros at right angles). +fn cos_from_sin(sin: f32, angle: f32) -> f32 { + let cos = (1.0 - sin * sin).sqrt(); + let tau = (std::f64::consts::PI * 2.0) as f32; + let a = angle + std::f32::consts::FRAC_PI_2; + let mut b = a - (a / tau) as i32 as f32 * tau; + if b < 0.0 { + b += tau; + } + if b >= std::f32::consts::PI { -cos } else { cos } +} /// `Quaternionf.rotationXYZ` from angles in radians. pub fn quaternion_xyz(x: f32, y: f32, z: f32) -> [f32; 4] { let half = |a: f32| -> (f32, f32) { let h = a * 0.5; - ((f64::from(h).sin()) as f32, (f64::from(h).cos()) as f32) + let s = joml_sin(h); + (s, cos_from_sin(s, h)) }; let ((sx, cx), (sy, cy), (sz, cz)) = (half(x), half(y), half(z)); - let (cx_cy, sx_cy, cx_sy, sx_sy) = (cx * cy, sx * cy, cx * sy, sx * sy); + let (cycz, sysz, sycz, cysz) = (cy * cz, sy * sz, sy * cz, cy * sz); [ - sx_cy * cz + cx_sy * sz, - cx_sy * cz - sx_cy * sz, - cx_cy * sz + sx_sy * cz, - cx_cy * cz - sx_sy * sz, + sx * cycz + cx * sysz, + cx * sycz - sx * cysz, + cx * cysz + sx * sycz, + cx * cycz - sx * sysz, ] } -/// `new Quaternionf(new AxisAngle4f(angle, axis))`. +/// `new Quaternionf(new AxisAngle4f(angle, axis))`: the angle is wrapped into +/// [0, 2Ï€) and the axis is used as given. pub fn quaternion_from_axis_angle(angle: f32, axis: [f32; 3]) -> [f32; 4] { - let half = angle * 0.5; - let (sin, cos) = (half.sin(), half.cos()); - let norm = 1.0 / (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]).sqrt(); - let s = sin * norm; - [axis[0] * s, axis[1] * s, axis[2] * s, cos] + let tau = (std::f64::consts::PI * 2.0) as f32; + let angle = if angle < 0.0 { tau + angle % tau } else { angle } % tau; + let sin = joml_sin(angle * 0.5); + let cos = cos_from_sin(sin, angle * 0.5); + [axis[0] * sin, axis[1] * sin, axis[2] * sin, cos] } #[cfg(test)] @@ -137,4 +306,9 @@ mod tests { let m = Mat4::IDENTITY.rotate(q); assert!((m.0[0][1] - 1.0).abs() < 1e-6 && m.0[0][0].abs() < 1e-6); } + #[test] + fn half_turn_has_exact_zeros_like_joml() { + let half_turn = 180.0 * (std::f64::consts::PI / 180.0) as f32; + assert_eq!(quaternion_xyz(0.0, half_turn, 0.0), [0.0, 1.0, 0.0, 0.0]); + } } diff --git a/crates/horizon-assets/src/palette.rs b/crates/horizon-assets/src/palette.rs new file mode 100644 index 000000000..788d1b17d --- /dev/null +++ b/crates/horizon-assets/src/palette.rs @@ -0,0 +1,105 @@ +//! `PalettedPermutations` atlas sources: sprites such as +//! `trims/items/boots_trim_quartz` are the base texture with its colours +//! swapped through a palette pair (`PaletteMapping`), not files of their own. +use serde_json::Value; +use std::collections::BTreeMap; + +/// One `minecraft:paletted_permutations` source of an atlas definition. +#[derive(Clone, Debug)] +pub struct PalettedPermutations { + /// Base sprite names (`minecraft:trims/items/boots_trim`). + pub textures: Vec, + /// The key palette (`minecraft:trim_base`). + pub palette_key: String, + /// Suffix to target palette (`quartz` → `minecraft:trim/quartz`). + pub permutations: BTreeMap, + pub separator: String, +} + +/// A permuted sprite: its base texture and the palette pair to apply. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Permutation<'a> { + pub base: &'a str, + pub palette_key: &'a str, + pub palette: &'a str, +} + +fn qualified(id: &str) -> String { + if id.contains(':') { id.to_owned() } else { format!("minecraft:{id}") } +} + +impl PalettedPermutations { + /// The `paletted_permutations` sources of an atlas JSON (`atlases/items.json`). + pub fn from_atlas(atlas: &str) -> Vec { + let Ok(json) = serde_json::from_str::(atlas) else { + return Vec::new(); + }; + let sources = json.get("sources").and_then(Value::as_array).cloned().unwrap_or_default(); + sources + .iter() + .filter(|s| s.get("type").and_then(Value::as_str).map(qualified).as_deref() == Some("minecraft:paletted_permutations")) + .filter_map(|s| { + Some(Self { + textures: s.get("textures")?.as_array()?.iter().filter_map(Value::as_str).map(qualified).collect(), + palette_key: qualified(s.get("palette_key")?.as_str()?), + permutations: s + .get("permutations")? + .as_object()? + .iter() + .filter_map(|(k, v)| Some((k.clone(), qualified(v.as_str()?)))) + .collect(), + separator: s.get("separator").and_then(Value::as_str).unwrap_or("_").to_owned(), + }) + }) + .collect() + } + /// The permutation that produces `sprite` (`withSuffix(separator + key)`). + pub fn find(&self, sprite: &str) -> Option> { + let sprite = qualified(sprite); + self.textures.iter().find_map(|base| { + let suffix = sprite.strip_prefix(base.as_str())?.strip_prefix(self.separator.as_str())?; + Some(Permutation { base, palette_key: &self.palette_key, palette: self.permutations.get(suffix)? }) + }) + } +} + +/// `PaletteMapping.create(key, target).apply` over ARGB pixels; the palettes +/// are the pixels of their images in reading order (`Palette.from`). +pub fn apply_palette(pixels: &mut [u32], key: &[u32], target: &[u32]) -> Option<()> { + if key.len() != target.len() { + return None; + } + let mut map = BTreeMap::new(); + for (&k, &t) in key.iter().zip(target) { + if k >> 24 != 0 { + map.insert(k | 0xFF00_0000, t); + } + } + for pixel in pixels { + let alpha = *pixel >> 24; + if alpha == 0 { + continue; + } + let rgb = *pixel | 0xFF00_0000; + let target = map.get(&rgb).copied().unwrap_or(rgb); + *pixel = (alpha * (target >> 24) / 255) << 24 | target & 0x00FF_FFFF; + } + Some(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn finds_trim_permutations_and_maps_colours() { + let atlas = r#"{"sources":[{"type":"minecraft:paletted_permutations","palette_key":"minecraft:trim_base", + "permutations":{"quartz":"minecraft:trim/quartz"},"textures":["minecraft:trims/items/boots_trim"]}]}"#; + let sources = PalettedPermutations::from_atlas(atlas); + let p = sources[0].find("minecraft:trims/items/boots_trim_quartz").unwrap(); + assert_eq!((p.base, p.palette), ("minecraft:trims/items/boots_trim", "minecraft:trim/quartz")); + assert!(sources[0].find("minecraft:trims/items/boots_trim_gold").is_none()); + let mut pixels = [0xFF11_2233, 0x8011_2233, 0x0011_2233, 0xFF44_5566]; + apply_palette(&mut pixels, &[0xFF11_2233], &[0xFFAA_BBCC]).unwrap(); + assert_eq!(pixels, [0xFFAA_BBCC, 0x80AA_BBCC, 0x0011_2233, 0xFF44_5566]); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemModelOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemModelOracle.java index c5d708b0c..cbbcd5e05 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemModelOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemModelOracle.java @@ -84,7 +84,11 @@ public final class VanillaItemModelOracle { static TextureAtlasSprite load(Identifier id, Identifier atlas) { try { var png = root.resolve("assets").resolve(id.getNamespace()).resolve("textures").resolve(id.getPath() + ".png"); - if (!Files.isRegularFile(png)) return null; + if (!Files.isRegularFile(png)) { + // Armour trim textures come from the atlas's paletted_permutations source. + var generated = generatedSprites(atlas).get(id); + return generated == null ? null : new Sprite(atlas, generated.get(null)); + } NativeImage image; try (var in = Files.newInputStream(png)) { image = NativeImage.read(in); } var mcmeta = png.resolveSibling(png.getFileName() + ".mcmeta"); @@ -100,6 +104,40 @@ public final class VanillaItemModelOracle { } catch (IOException e) { throw new UncheckedIOException(e); } } + static final Map> GENERATED = new HashMap<>(); + /** The atlas's paletted_permutations sprites, run by vanilla's own source over the extracted resources. */ + static Map generatedSprites(Identifier atlas) { + return GENERATED.computeIfAbsent(atlas, a -> { + Map out = new HashMap<>(); + var file = "/assets/" + a.getNamespace() + "/atlases/" + a.getPath().replaceFirst("^textures/atlas/", "").replaceFirst("\\.png$", "") + ".json"; + try (var in = VanillaItemModelOracle.class.getResourceAsStream(file)) { + if (in == null) return out; + var json = JsonParser.parseString(new String(in.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8)); + var sources = net.minecraft.client.renderer.texture.atlas.SpriteSources.FILE_CODEC.parse(JsonOps.INSTANCE, json).getOrThrow(); + var output = new net.minecraft.client.renderer.texture.atlas.SpriteSource.Output() { + @Override public void add(Identifier id, net.minecraft.client.renderer.texture.atlas.SpriteSource.DiscardableLoader sprite) { out.put(id, sprite); } + @Override public void removeAll(java.util.function.Predicate predicate) { out.keySet().removeIf(predicate); } + }; + for (var source : sources) + if (source instanceof net.minecraft.client.renderer.texture.atlas.sources.PalettedPermutations) source.run(FILES, output); + } catch (IOException e) { throw new UncheckedIOException(e); } + return out; + }); + } + /** The extracted resources as a single-pack resource manager. */ + static final net.minecraft.server.packs.resources.ResourceManager FILES = new net.minecraft.server.packs.resources.ResourceManager() { + Path path(Identifier id) { return root.resolve("assets").resolve(id.getNamespace()).resolve(id.getPath()); } + @Override public Optional getResource(Identifier id) { + var file = path(id); + return Files.isRegularFile(file) ? Optional.of(new net.minecraft.server.packs.resources.Resource(null, () -> Files.newInputStream(file))) : Optional.empty(); + } + @Override public java.util.Set getNamespaces() { return java.util.Set.of("minecraft"); } + @Override public List getResourceStack(Identifier id) { return getResource(id).stream().toList(); } + @Override public Map listResources(String directory, net.minecraft.server.packs.resources.ResourceManager.Selector selector) { throw new UnsupportedOperationException(); } + @Override public Map> listResourceStacks(String directory, net.minecraft.server.packs.resources.ResourceManager.Selector selector) { throw new UnsupportedOperationException(); } + @Override public java.util.stream.Stream listPacks() { return java.util.stream.Stream.empty(); } + }; + // --- Tagging of special renderers so the layer carries its codec form. --- static final class Tagged implements SpecialModelRenderer.Unbaked { final SpecialModelRenderer.Unbaked delegate; @@ -196,6 +234,15 @@ public final class VanillaItemModelOracle { models.getOrDefault(id, missing).update(output, item, this, context, level instanceof ClientLevel c ? c : null, owner, seed); } } + // ModelManager.getItemProperties, from the same baked properties. + @Override public boolean shouldPlaySwapAnimation(ItemStack stack) { + Identifier id = stack.get(DataComponents.ITEM_MODEL); + return id == null || properties.getOrDefault(id, ClientItem.Properties.DEFAULT).handAnimationOnSwap(); + } + @Override public float swapAnimationScale(ItemStack stack) { + Identifier id = stack.get(DataComponents.ITEM_MODEL); + return id == null ? 1.0F : properties.getOrDefault(id, ClientItem.Properties.DEFAULT).swapAnimationScale(); + } } static Object field(Object target, Class type, String name) throws Exception { @@ -251,12 +298,22 @@ public final class VanillaItemModelOracle { public static void main(String[] args) throws Exception { net.minecraft.SharedConstants.tryDetectVersion(); net.minecraft.server.Bootstrap.bootStrap(); + // Item tags (compasses get the special foil) come from the vanilla data pack. + var repo = net.minecraft.server.packs.repository.ServerPacksSource.createVanillaTrustedRepository(); + repo.reload(); + repo.setSelected(List.of("vanilla")); + try (var data = new net.minecraft.server.packs.resources.MultiPackResourceManager(net.minecraft.server.packs.PackType.SERVER_DATA, repo.openAllSelected())) { + var layers = net.minecraft.server.RegistryLayer.createRegistryAccess(); + net.minecraft.tags.TagLoader.loadTagsForExistingRegistries(data, layers.getLayer(net.minecraft.server.RegistryLayer.STATIC)) + .forEach(net.minecraft.core.Registry.PendingTags::apply); + } ItemModels.bootstrap(); SpecialModelRenderers.bootstrap(); net.minecraft.client.color.item.ItemTintSources.bootstrap(); net.minecraft.client.renderer.item.properties.select.SelectItemModelProperties.bootstrap(); net.minecraft.client.renderer.item.properties.conditional.ConditionalItemModelProperties.bootstrap(); net.minecraft.client.renderer.item.properties.numeric.RangeSelectItemModelProperties.bootstrap(); + net.minecraft.client.renderer.texture.atlas.SpriteSources.bootstrap(); var u = Class.forName("sun.misc.Unsafe"); var uf = u.getDeclaredField("theUnsafe"); uf.setAccessible(true); unsafe = uf.get(null); allocate = u.getMethod("allocateInstance", Class.class); diff --git a/tools/test_item_model_parity.py b/tools/test_item_model_parity.py index 94c34a80e..d25f97c59 100644 --- a/tools/test_item_model_parity.py +++ b/tools/test_item_model_parity.py @@ -26,7 +26,8 @@ TRIM_MATERIALS = ['quartz', 'iron', 'netherite', 'redstone', 'copper', 'gold', ' 'amethyst', 'resin'] NEEDED = ('assets/minecraft/items/', 'assets/minecraft/models/', 'assets/minecraft/textures/item/', 'assets/minecraft/textures/block/', 'assets/minecraft/textures/trims/', - 'assets/minecraft/textures/colormap/') + 'assets/minecraft/textures/colormap/', 'assets/minecraft/textures/palettes/', + 'assets/minecraft/atlases/') def extract(jar, destination): @@ -293,6 +294,12 @@ def matrix(bits): return [0 if b == 0x80000000 else b for b in bits] +def rows_of(path): + with path.open('rb') as rows: + for line in rows: + yield json.loads(line) + + def main(): lock, jars, libraries = base.verify_artifacts() build = lab.LOCAL / 'item-model-parity'; build.mkdir(parents=True, exist_ok=True) @@ -324,8 +331,11 @@ def main(): run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaItemModelOracle', resources, inputs, build / 'client.jsonl', prototypes_path], 'client') # The host inputs vanilla derives from the stack (use duration, charge time). - client = [json.loads(line) for line in (build / 'client.jsonl').read_text().splitlines()] - derived = {r['id']: r['derived'] for r in client if r.get('row') == 'case' and 'derived' in r} + # Both outputs are gigabytes of quads, so rows are streamed one at a time. + derived = {} + for r in rows_of(build / 'client.jsonl'): + if r.get('row') == 'case' and 'derived' in r: + derived[r['id']] = r['derived'] rust_cases = [] for case in cases: case = dict(case) @@ -335,35 +345,60 @@ def main(): rust_inputs.write_text(''.join(json.dumps(c) + '\n' for c in rust_cases)) (build / 'rust-cases.jsonl.definitions').write_text((build / 'cases.jsonl.definitions').read_text()) run([binary, resources, prototypes_path, rust_inputs, build / 'rust.jsonl'], 'rust') - rust = [json.loads(line) for line in (build / 'rust.jsonl').read_text().splitlines()] - mismatches, compared, skipped, decoded = [], 0, 0, 0 - vanilla_by_key = {(r['row'], r.get('id') or r.get('name')): r for r in client if r['row'] in ('case', 'decode', 'components')} - rust_by_key = {(r['row'], r.get('id') or r.get('name')): r for r in rust} - assert vanilla_by_key.keys() == rust_by_key.keys(), 'The two sides produced different rows' - assert vanilla_by_key[('components', None)]['names'] == rust_by_key[('components', None)]['names'], 'Data component registry differs' - unbaked = [r['name'] for r in client if r['row'] == 'unbaked'] - for key, left in vanilla_by_key.items(): - right = rust_by_key[key] - if key[0] == 'components': continue + mismatches, mismatch_count, compared, skipped, decoded = [], 0, 0, 0, 0 + rust_offsets = {} + with (build / 'rust.jsonl').open('rb') as rust_file: + offset = 0 + for line in rust_file: + r = json.loads(line) + rust_offsets[(r['row'], r.get('id') or r.get('name'))] = offset + offset += len(line) + vanilla_keys, unbaked = set(), [] + rust_file = (build / 'rust.jsonl').open('rb') + + def rust_row(key): + rust_file.seek(rust_offsets[key]) + return json.loads(rust_file.readline()) + + for left in rows_of(build / 'client.jsonl'): + if left['row'] == 'unbaked': + unbaked.append(left['name']) + if left['row'] not in ('case', 'decode', 'components'): + continue + key = (left['row'], left.get('id') or left.get('name')) + vanilla_keys.add(key) + assert key in rust_offsets, f'Horizon produced no row for {key}' + right = rust_row(key) + if key[0] == 'components': + assert left['names'] == right['names'], 'Data component registry differs' + continue if key[0] == 'decode': decoded += 1 - if left['ok'] != right['ok']: mismatches.append(('decode', key[1], left, right)) + if left['ok'] != right['ok']: + mismatch_count += 1 + if len(mismatches) < 5: + mismatches.append(('decode', key[1], left, right)) continue if 'error' in left: skipped += 1 continue compared += 1 + left.pop('derived', None) # an input Horizon received, not an output for side in (left, right): for layer in side['layers']: layer['matrix'] = matrix(layer['matrix']) layer.pop('has_transform', None) if layer.get('quads') is not None: layer['quads'] = canonical_quads(layer['quads']) if left != right: - mismatches.append(('case', key[1], left, right)) - if mismatches: - for kind, name, left, right in mismatches[:5]: + mismatch_count += 1 + if len(mismatches) < 5: + mismatches.append(('case', key[1], left, right)) + rust_file.close() + assert vanilla_keys == rust_offsets.keys(), 'The two sides produced different rows' + if mismatch_count: + for kind, name, left, right in mismatches: print(kind, name, '\nvanilla:', json.dumps(left)[:1500], '\nrust: ', json.dumps(right)[:1500]) - raise AssertionError(f'{len(mismatches)} item model mismatches') + raise AssertionError(f'{mismatch_count} item model mismatches') base.ensure_sources_unchanged(sources, tested) assert compared > 1000, 'Too few cases compared' assert skipped * 20 < len(cases), f'Too many cases rejected by vanilla: {skipped}' From f2232c3ed790495ff54a970dfacf5a3b8d6a713a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:22:38 +0200 Subject: [PATCH 04/28] Rescore the Java parity table at 84% World generation and interaction now have every covering harness passing and score 1. The other rows keep 0.75, with their gaps rewritten to name what is still missing now that the block, command, entity model and item model harnesses pass; the next steps follow the open gaps. Co-Authored-By: Claude Opus 5.5 --- README.md | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 9498acab8..863822f8f 100644 --- a/README.md +++ b/README.md @@ -16,41 +16,42 @@ Horizon is a Rust rewrite of Minecraft Java **26.3** targeting one-to-one vanill Parity is **not** complete. Still missing: the warden and the sculk family, the breeze, sniffer, creaking, happy ghast, llamas and a few other mobs, raids and pillager patrols, villager breeding and gossip, the loom, crafter and recipe book, scoreboards, subtitles, and spawned mob gear enchantments. Multiplayer joins vanilla servers but Horizon cannot host one. See [Rust rewrite status](docs/rust-parity.md). -### Java parity: 80% +### Java parity: 84% Each subsystem scores 0 (absent), 0.25 (started, not playable), 0.5 (playable, major vanilla features missing), 0.75 (playable, mostly complete) or 1 (complete and verified against vanilla by differential tests). The percentage is the average; `tests/test_parity.py` keeps it in sync with this table. Last audited -2026-10-10 against the code, not the docs: of the 232 `tools/test_*_parity.py` -differential harnesses, 223 pass, 8 fail and the item model harness runs out of -memory; the failures are new harnesses that still find divergences. +2026-10-10 against the code, not the docs. The harnesses that failed in the +previous audit (block updates, random ticks, redstone, command parsing, menu +clicks, whole chunks, entity models and item models) now pass; the save +round-trip harness has not been rerun. | Subsystem | Score | Main gaps | | --- | ---: | --- | | Window, input and game loop | 0.75 | Game loop and options match vanilla; camera, auto-jump, toggle sprint/sneak and the frame limiter not compared | -| Assets and resources | 0.75 | Item model pipeline not yet used for all GUI icons; item model harness does not finish; no pack screen | +| Assets and resources | 0.75 | Item models match vanilla over 196,290 stacks, but the client does not draw items through that pipeline yet; no pack screen | | Network protocol and multiplayer | 0.75 | Opens worlds to LAN, but hosting is not tested against a vanilla client; no dedicated server mode | | Chunk storage and palettes | 1 | None: client and saves share paletted containers, identical to vanilla over 266 scenarios | | Section meshing | 1 | None: 112 scenes and over a million quads identical to vanilla | -| Rendering | 0.75 | Entity model harness fails; block entity renderers and HUD overlays not compared | +| Rendering | 0.75 | Entity models match over 150 layers; block entity renderers and HUD overlays not compared | | Lighting | 1 | None: saved and relit light matches vanilla, slabs and stairs included | -| World generation | 0.75 | Whole-chunk harness still finds single-block differences near camps, shipwrecks and villages | +| World generation | 1 | None: 2,352 whole chunks over 225 structure sites, in all three dimensions, identical to vanilla | | Region files and saves | 0.75 | Save round-trip harness fails; older DataVersions are not upgraded | | Entities and physics | 0.75 | Attributes and dimensions match; AI, loot and spawn rules not compared; drowned, villagers, traders and the wither unverified | -| Interaction and inventory | 0.75 | Menu click harness fails | -| Menus, HUD and chat | 0.75 | Command parse harness fails; no /item modify, /spectate, /waypoint or /dialog; no tab list or world border rendering | +| Interaction and inventory | 1 | None: menu clicks match over 6,000 click sequences | +| Menus, HUD and chat | 0.75 | Commands parse as vanilla over 39,685 inputs, but /item modify, /spectate, /waypoint and /dialog do not run; no tab list or world border rendering | | Audio | 0.75 | Sound engine, music and ambience not compared with vanilla | -| Block behaviours and ticking | 0.75 | Block update, random tick and redstone harnesses fail; a few dispenser behaviours missing | +| Block behaviours and ticking | 0.75 | Block updates, random ticks and redstone match vanilla; dispensers lack several behaviours | ### Next steps -1. Fix the divergences the failing harnesses report: block updates, random ticks, redstone, command parsing, menu clicks, save round-trip, whole chunks and entity models. -2. Let the item model harness finish, and draw every GUI icon through the item model pipeline. +1. Rerun the save round-trip harness and upgrade saves from older DataVersions. +2. Draw every item through the item model pipeline, and add the resource pack screen. 3. An audio harness: sound engine attenuation, weighted sound events, music and ambience. 4. Mob AI, loot and spawn-rule harnesses, and an oracle for drowned, villagers, traders and the wither. -5. The missing commands, the tab list and world border rendering. -6. Test LAN hosting with a vanilla client, and upgrade saves from older DataVersions. +5. The missing commands and dispenser behaviours, the tab list and world border rendering. +6. Test LAN hosting with a vanilla client, and add a dedicated server mode. ```sh python3 tools/prepare_native_client.py --prepare # needs JDK 25; extracts private vanilla resources From d68efbabfc8b911919a04a776024f0c349514301 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:33:17 +0200 Subject: [PATCH 05/28] Compare the sound engine bookkeeping with the real vanilla SoundEngine The oracle runs vanilla SoundManager/SoundEngine on OpenAL Soft null device (inline executor, silent buffers) and replays scripts of plays, stops, category gains, option volumes, channel ends, pauses, queued, delayed and looping sounds and tickable ambient instances, printing every AL source parameter, isActive, subtitle notification and pool count per step. Co-Authored-By: Claude Opus 5.5 --- .../examples/sound_engine_fixture.rs | 273 ++++++++++++++++++ .../parity/VanillaSoundEngineOracle.java | 112 +++++++ .../horizonlab/parity/VanillaSoundRig.java | 204 +++++++++++++ tools/audio_harness.py | 7 +- tools/test_sound_engine_parity.py | 247 ++++++++++++++++ 5 files changed, 841 insertions(+), 2 deletions(-) create mode 100644 crates/horizon-client/examples/sound_engine_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundEngineOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java create mode 100644 tools/test_sound_engine_parity.py diff --git a/crates/horizon-client/examples/sound_engine_fixture.rs b/crates/horizon-client/examples/sound_engine_fixture.rs new file mode 100644 index 000000000..a9dfbbb02 --- /dev/null +++ b/crates/horizon-client/examples/sound_engine_fixture.rs @@ -0,0 +1,273 @@ +//! Replays `tools/test_sound_engine_parity.py` scripts through Horizon's +//! `SoundEngine` with a backend recording what an OpenAL source would hold: +//! `sound_engine_fixture ROOT INPUT OUTPUT`. +use horizon_client::sound_engine::{ + Attenuation, Backend, ChannelId, InstanceId, SoundEngine, SoundInstance, TickContext, +}; +use horizon_client::sound_events::{Sound, SoundRegistry}; +use horizon_core::random::LegacyRandom; +use std::collections::{BTreeMap, HashMap}; +use std::io::Write; + +const INITIAL: u32 = 0x1011; +const PLAYING: u32 = 0x1012; +const PAUSED: u32 = 0x1013; +const STOPPED: u32 = 0x1014; + +/// An OpenAL source's state as `alGetSource*` reports it. +#[derive(Clone)] +pub struct Source { + pub state: u32, + pub gain: f32, + pub pitch: f32, + pub position: [f32; 3], + pub relative: bool, + pub looping: bool, + pub model: u32, + pub max: f32, + pub rolloff: f32, + pub reference: f32, +} +impl Default for Source { + fn default() -> Self { + Self { + state: INITIAL, + gain: 1.0, + pitch: 1.0, + position: [0.0; 3], + relative: false, + looping: false, + model: 0xD002, + max: f32::MAX, + rolloff: 1.0, + reference: 1.0, + } + } +} +/// Buffers and streams are ready at once (silence in the oracle); stopping an +/// initial source leaves it initial, as in OpenAL Soft. +#[derive(Default)] +pub struct Fake { + pub sources: HashMap, + next: ChannelId, +} +impl Backend for Fake { + fn create(&mut self, _streaming: bool) -> Option { + self.next += 1; + self.sources.insert(self.next, Source::default()); + Some(self.next) + } + fn destroy(&mut self, channel: ChannelId) { + self.sources.remove(&channel); + } + fn set_pitch(&mut self, c: ChannelId, pitch: f32) { + self.sources.get_mut(&c).expect("source").pitch = pitch; + } + fn set_volume(&mut self, c: ChannelId, volume: f32) { + self.sources.get_mut(&c).expect("source").gain = volume; + } + fn set_attenuation(&mut self, c: ChannelId, linear: Option) { + let s = self.sources.get_mut(&c).expect("source"); + match linear { + Some(max) => { + s.model = 0xD003; + s.max = max; + s.rolloff = 1.0; + s.reference = 0.0; + } + None => s.model = 0, + } + } + fn set_looping(&mut self, c: ChannelId, looping: bool) { + self.sources.get_mut(&c).expect("source").looping = looping; + } + fn set_position(&mut self, c: ChannelId, p: [f64; 3]) { + self.sources.get_mut(&c).expect("source").position = + [p[0] as f32, p[1] as f32, p[2] as f32]; + } + fn set_relative(&mut self, c: ChannelId, relative: bool) { + self.sources.get_mut(&c).expect("source").relative = relative; + } + fn start(&mut self, c: ChannelId, _sound: &Sound, _looping: bool) { + self.sources.get_mut(&c).expect("source").state = PLAYING; + } + fn stop(&mut self, c: ChannelId) { + if let Some(s) = self.sources.get_mut(&c) + && s.state != INITIAL + { + s.state = STOPPED; + } + } + fn pause(&mut self, c: ChannelId) { + let s = self.sources.get_mut(&c).expect("source"); + if s.state == PLAYING { + s.state = PAUSED; + } + } + fn unpause(&mut self, c: ChannelId) { + let s = self.sources.get_mut(&c).expect("source"); + if s.state == PAUSED { + s.state = PLAYING; + } + } + fn stopped(&mut self, c: ChannelId) -> bool { + self.sources.get(&c).is_none_or(|s| s.state == STOPPED) + } +} +fn bits(v: f32) -> String { + format!("{:08x}", v.to_bits()) +} +fn f(hex: &str) -> f32 { + f32::from_bits(u32::from_str_radix(hex, 16).expect("float")) +} +fn d(hex: &str) -> f64 { + f64::from_bits(u64::from_str_radix(hex, 16).expect("double")) +} +/// The shared per-step dump (instances, notifications, pool counts). +pub fn describe(engine: &SoundEngine, backend: &Fake, name: &str, id: InstanceId) -> String { + let mut s = format!(" {name} active={}", engine.is_active(id)); + match engine.channel(id).and_then(|c| backend.sources.get(&c)) { + None => s.push_str(" channel=-"), + Some(src) => s.push_str(&format!( + " state={:x} gain={} pitch={} pos={},{},{} rel={} loop={} model={:x} max={} rolloff={} ref={}", + src.state, + bits(src.gain), + bits(src.pitch), + bits(src.position[0]), + bits(src.position[1]), + bits(src.position[2]), + u8::from(src.relative), + u8::from(src.looping), + src.model, + bits(src.max), + bits(src.rolloff), + bits(src.reference) + )), + } + s +} +pub fn flush(engine: &mut SoundEngine, out: &mut impl Write) { + for n in std::mem::take(&mut engine.notifications) { + writeln!( + out, + "notify {} {} {} {} {:016x} {:016x} {:016x}", + n.identifier, + n.subtitle.as_deref().unwrap_or("-"), + bits(n.range), + n.looping, + n.position[0].to_bits(), + n.position[1].to_bits(), + n.position[2].to_bits() + ) + .expect("write"); + } + let [used, streaming] = engine.used_channels(); + writeln!( + out, + " Sounds: {used}/{} + {streaming}/{}", + engine.limits[0], engine.limits[1] + ) + .expect("write"); +} + +fn main() { + let args: Vec = std::env::args().collect(); + let mut engine = SoundEngine::new(SoundRegistry::load(std::path::Path::new(&args[1]))); + engine.listening = true; + let mut backend = Fake::default(); + let mut ctx = TickContext::default(); + let mut instances: BTreeMap = BTreeMap::new(); + let input = std::fs::read_to_string(&args[2]).expect("input"); + let mut out = std::io::BufWriter::new(std::fs::File::create(&args[3]).expect("output")); + for line in input.lines() { + writeln!(out, "{line}").expect("write"); + let a: Vec<&str> = line.split(' ').collect(); + let source = |i: usize| a[i].parse::().expect("source"); + match a[0] { + "play" => { + let event = horizon_client::sound_events::normalize(a[3]); + let random = LegacyRandom::new(a[14].parse().expect("seed")); + let instance = match a[2] { + "simple" => SoundInstance::new( + &event, + source(4), + f(a[5]), + f(a[6]), + random, + a[10] == "1", + a[11].parse().expect("delay"), + if a[12] == "linear" { + Attenuation::Linear + } else { + Attenuation::None + }, + [d(a[7]), d(a[8]), d(a[9])], + a[13] == "1", + ), + "loop" => SoundInstance::biome_loop(&event, random), + "uloop" => SoundInstance::under_liquid_loop(&event, random), + "usub" => SoundInstance::under_liquid_sub(&event, random), + _ => panic!("{line}"), + }; + if let Some(old) = instances.remove(a[1]) { + engine.release(old); + } + let (id, result) = engine.play_new(instance, true, &mut backend); + instances.insert(a[1].to_owned(), id); + writeln!(out, " result {}", result_name(result)).expect("write"); + } + "replay" => { + let result = engine.play(instances[a[1]], &mut backend); + writeln!(out, " result {}", result_name(result)).expect("write"); + } + "queue" => engine.queue_ticking(instances[a[1]]), + "delayed" => engine.play_delayed(instances[a[1]], a[2].parse().expect("delay")), + "fade" => { + let i = engine.instance_mut(instances[a[1]]).expect("instance"); + if a[2] == "in" { + i.fade_in(); + } else { + i.fade_out(); + } + } + "stop" => engine.stop(instances[a[1]], &mut backend), + "stopmatch" => { + let sound = (a[1] != "-").then(|| horizon_client::sound_events::normalize(a[1])); + let src = (a[2] != "-").then(|| source(2)); + engine.stop_matching(sound.as_deref(), src, &mut backend); + } + "finish" => { + if let Some(c) = engine.channel(instances[a[1]]) { + backend.stop(c); + } + } + "gain" => engine.update_category_volume(source(1), f(a[2]), &mut backend), + "volume" => engine.source_volumes[source(1)] = f(a[2]), + "refresh" => engine.refresh_category_volume(source(1), &mut backend), + "pause" => engine.pause_all_except(&[1, 10], &mut backend), + "resume" => engine.resume(&mut backend), + "player" => { + ctx.player_underwater = a[1] == "1"; + ctx.player_removed = a[2] == "1"; + } + "tick" => engine.tick(a[1] == "1", &ctx, &mut backend), + "forget" => { + if let Some(id) = instances.remove(a[1]) { + engine.release(id); + } + } + _ => panic!("{line}"), + } + for (name, id) in &instances { + writeln!(out, "{}", describe(&engine, &backend, name, *id)).expect("write"); + } + flush(&mut engine, &mut out); + } +} +fn result_name(r: horizon_client::sound_engine::PlayResult) -> &'static str { + match r { + horizon_client::sound_engine::PlayResult::Started => "STARTED", + horizon_client::sound_engine::PlayResult::StartedSilently => "STARTED_SILENTLY", + horizon_client::sound_engine::PlayResult::NotStarted => "NOT_STARTED", + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundEngineOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundEngineOracle.java new file mode 100644 index 000000000..317dc177b --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundEngineOracle.java @@ -0,0 +1,112 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.lang.reflect.Constructor; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.resources.sounds.*; +import net.minecraft.resources.Identifier; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.RandomSource; +import net.minecraft.world.entity.Entity; + +/** + * Drives the real SoundEngine (see VanillaSoundRig) with a script of plays, + * stops, category gains, option volumes, channel ends, pauses and ticks, and + * prints after every step each instance's activity and AL source parameters, + * the subtitle notifications and the channel pool counts. + */ +public final class VanillaSoundEngineOracle { + /** The local player the underwater instances look at. */ + public static final class Actor extends LocalPlayer { + boolean underwater; + + Actor() { + super(null, null, null, null, null, null, false, null, null); + } + + @Override + public boolean isUnderWater() { + return underwater; + } + } + + static float f(String hex) { + return Float.intBitsToFloat(Integer.parseUnsignedInt(hex, 16)); + } + + static double d(String hex) { + return Double.longBitsToDouble(Long.parseUnsignedLong(hex, 16)); + } + + static void seed(SoundInstance instance, long seed) throws Exception { + VanillaSoundRig.set(instance, AbstractSoundInstance.class, "random", RandomSource.create(seed)); + } + + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + var rig = new VanillaSoundRig(Path.of(args[0])); + var actor = VanillaSoundRig.make(Actor.class); + Constructor sub = UnderLiquidSubSound.class.getDeclaredConstructor(LocalPlayer.class, SoundEvent.class); + sub.setAccessible(true); + var instances = new TreeMap(); + var manager = rig.manager; + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2])))) { + for (String line : Files.readAllLines(Path.of(args[1]))) { + out.println(line); + String[] a = line.split(" "); + switch (a[0]) { + case "play" -> { + // play name kind event source volume pitch x y z looping delay attenuation relative seed + Identifier id = Identifier.parse(a[3]); + SoundEvent event = SoundEvent.createVariableRangeEvent(id); + long seed = Long.parseLong(a[14]); + SoundInstance instance = switch (a[2]) { + case "simple" -> new SimpleSoundInstance(id, SoundSource.values()[Integer.parseInt(a[4])], f(a[5]), f(a[6]), + RandomSource.create(seed), a[10].equals("1"), Integer.parseInt(a[11]), + a[12].equals("linear") ? SoundInstance.Attenuation.LINEAR : SoundInstance.Attenuation.NONE, d(a[7]), d(a[8]), d(a[9]), + a[13].equals("1")); + case "loop" -> new BiomeAmbientSoundsHandler.LoopSoundInstance(event); + case "uloop" -> new UnderLiquidAmbientSoundInstance(event, actor, LocalPlayer::isUnderWater); + case "usub" -> sub.newInstance(actor, event); + default -> throw new IllegalArgumentException(line); + }; + if (!a[2].equals("simple")) seed(instance, seed); + instances.put(a[1], instance); + out.println(" result " + manager.play(instance)); + } + case "replay" -> out.println(" result " + manager.play(instances.get(a[1]))); + case "queue" -> manager.queueTickingSound((TickableSoundInstance) instances.get(a[1])); + case "delayed" -> manager.playDelayed(instances.get(a[1]), Integer.parseInt(a[2])); + case "fade" -> { + if (instances.get(a[1]) instanceof BiomeAmbientSoundsHandler.LoopSoundInstance loop) { + if (a[2].equals("in")) loop.fadeIn(); else loop.fadeOut(); + } + } + case "stop" -> manager.stop(instances.get(a[1])); + case "stopmatch" -> manager.stop(a[1].equals("-") ? null : Identifier.parse(a[1]), + a[2].equals("-") ? null : SoundSource.values()[Integer.parseInt(a[2])]); + case "finish" -> rig.finish(instances.get(a[1])); + case "gain" -> manager.updateCategoryVolume(SoundSource.values()[Integer.parseInt(a[1])], f(a[2])); + case "volume" -> rig.volume(SoundSource.values()[Integer.parseInt(a[1])], f(a[2])); + case "refresh" -> manager.refreshCategoryVolume(SoundSource.values()[Integer.parseInt(a[1])]); + case "pause" -> manager.pauseAllExcept(SoundSource.MUSIC, SoundSource.UI); + case "resume" -> manager.resume(); + case "player" -> { + actor.underwater = a[1].equals("1"); + VanillaSoundRig.set(actor, Entity.class, "removalReason", a[2].equals("1") ? Entity.RemovalReason.DISCARDED : null); + } + case "tick" -> manager.tick(a[1].equals("1")); + case "forget" -> instances.remove(a[1]); + default -> throw new IllegalArgumentException(line); + } + for (var e : instances.entrySet()) out.println(rig.describe(e.getKey(), e.getValue())); + rig.flush(out); + } + } + System.exit(0); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java new file mode 100644 index 000000000..8edef9325 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java @@ -0,0 +1,204 @@ +package dev.horizonlab.parity; + +import com.mojang.blaze3d.audio.*; +import java.io.PrintWriter; +import java.lang.reflect.*; +import java.nio.ByteBuffer; +import java.nio.file.Path; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import javax.sound.sampled.AudioFormat; +import net.minecraft.client.OptionInstance; +import net.minecraft.client.Options; +import net.minecraft.client.resources.sounds.SoundInstance; +import net.minecraft.client.sounds.*; +import net.minecraft.network.chat.contents.TranslatableContents; +import net.minecraft.resources.Identifier; +import net.minecraft.sounds.SoundSource; +import org.lwjgl.openal.AL10; + +/** + * A real vanilla SoundManager/SoundEngine running on OpenAL Soft's "No Output" + * device (ALSOFT_DRIVERS=null), shared by the audio oracles. + * + * Determinism: the sound executor runs each task inline (the model where the + * sound thread keeps up between client ticks); static sounds get one silent + * hour-long buffer (they play until stopped or "finished" by the script) and + * streams play endless silence. Everything else, the + * channel pools, AL source parameters, lifetimes and bookkeeping, is the real + * code and the real OpenAL implementation. + */ +public final class VanillaSoundRig { + static Object unsafe; + static Method allocate; + + static T make(Class type) throws Exception { + if (unsafe == null) { + var u = Class.forName("sun.misc.Unsafe"); + unsafe = field(u, "theUnsafe").get(null); + allocate = u.getMethod("allocateInstance", Class.class); + } + return type.cast(allocate.invoke(unsafe, type)); + } + + static Field field(Class type, String name) throws Exception { + var f = type.getDeclaredField(name); + f.setAccessible(true); + return f; + } + + static Object get(Object target, Class type, String name) throws Exception { + return field(type, name).get(target); + } + + static void set(Object target, Class type, String name, Object value) throws Exception { + field(type, name).set(target, value); + } + + /** Runs every task on the calling thread. */ + public static final class Inline extends SoundEngineExecutor { + @Override + public void execute(final Runnable command) { + command.run(); + } + + @Override + public void shutDown() { + } + + @Override + public void startUp() { + } + } + + static SoundBuffer silence; + + /** Static sounds: a silent hour; streams: endless silence. */ + public static final class Buffers extends SoundBufferLibrary { + Buffers() { + super(null); + } + + @Override + public CompletableFuture getCompleteBuffer(final Identifier location) { + return CompletableFuture.completedFuture(silence); + } + + @Override + public CompletableFuture getStream(final Identifier location, final boolean looping) { + return CompletableFuture.completedFuture(new Silence()); + } + } + + /** An endless silent stream, a minute per read (it never runs dry between ticks). */ + public static final class Silence implements AudioStream { + static final AudioFormat FORMAT = new AudioFormat(8000.0F, 8, 1, false, false); + + @Override + public AudioFormat getFormat() { + return FORMAT; + } + + @Override + public ByteBuffer read(final int expectedSize) { + ByteBuffer data = ByteBuffer.allocateDirect(8000 * 60); + for (int i = 0; i < data.capacity(); i++) data.put(i, (byte) 0x80); + return data; + } + + @Override + public void close() { + } + } + + public final SoundManager manager; + public final SoundEngine engine; + public final Options options; + public final List heard = new ArrayList<>(); + + public VanillaSoundRig(Path root) throws Exception { + manager = VanillaSoundEventOracle.load(root); + engine = (SoundEngine) get(manager, SoundManager.class, "soundEngine"); + options = (Options) get(engine, SoundEngine.class, "options"); + var inline = make(Inline.class); + set(engine, SoundEngine.class, "executor", inline); + set(get(engine, SoundEngine.class, "channelAccess"), ChannelAccess.class, "executor", inline); + set(engine, SoundEngine.class, "soundBuffers", make(Buffers.class)); + Library library = (Library) get(engine, SoundEngine.class, "library"); + library.init(null, DeviceList.query(), false); + ByteBuffer data = ByteBuffer.allocateDirect(8000 * 3600); + for (int i = 0; i < data.capacity(); i++) data.put(i, (byte) 0x80); + silence = new SoundBuffer(data, new AudioFormat(8000.0F, 8, 1, false, false)); + set(engine, SoundEngine.class, "loaded", true); + Method slider = Options.class.getDeclaredMethod("createSoundSliderOptionInstance", String.class, SoundSource.class); + slider.setAccessible(true); + var volumes = new EnumMap>(SoundSource.class); + for (SoundSource source : SoundSource.values()) { + volumes.put(source, (OptionInstance) slider.invoke(options, "soundCategory." + source.getName(), source)); + } + set(options, Options.class, "soundSourceVolumes", volumes); + manager.addListener((sound, event, range) -> { + String subtitle = "-"; + if (event.getSubtitle() != null && event.getSubtitle().getContents() instanceof TranslatableContents t) subtitle = t.getKey(); + heard.add(String.format("notify %s %s %08x %s %016x %016x %016x", sound.getIdentifier(), subtitle, Float.floatToRawIntBits(range), + sound.isLooping(), Double.doubleToRawLongBits(sound.getX()), Double.doubleToRawLongBits(sound.getY()), + Double.doubleToRawLongBits(sound.getZ()))); + }); + } + + /** Set a sound source volume option without its change callback. */ + public void volume(SoundSource source, double value) throws Exception { + set(options.getSoundSourceOptionInstance(source), OptionInstance.class, "value", value); + } + + /** The channel of an instance, or null. */ + @SuppressWarnings("unchecked") + public Channel channel(SoundInstance instance) throws Exception { + var map = (Map) get(engine, SoundEngine.class, "instanceToChannel"); + var handle = map.get(instance); + return handle == null ? null : (Channel) get(handle, ChannelAccess.ChannelHandle.class, "channel"); + } + + /** The channel's end: what OpenAL does when a non-looping buffer runs out. */ + public void finish(SoundInstance instance) throws Exception { + var channel = channel(instance); + if (channel != null) channel.stop(); + } + + static String fbits(float v) { + return String.format("%08x", Float.floatToRawIntBits(v)); + } + + /** One line describing an instance: activity and its AL source. */ + public String describe(String name, SoundInstance instance) throws Exception { + StringBuilder sb = new StringBuilder(" ").append(name).append(" active=").append(manager.isActive(instance)); + var channel = channel(instance); + if (channel == null) { + sb.append(" channel=-"); + } else { + int source = (int) get(channel, Channel.class, "source"); + boolean initialized = ((java.util.concurrent.atomic.AtomicBoolean) get(channel, Channel.class, "initialized")).get(); + if (!initialized) { + sb.append(" channel=released"); + } else { + float[] pos = new float[3]; + AL10.alGetSourcefv(source, AL10.AL_POSITION, pos); + sb.append(String.format(" state=%x gain=%s pitch=%s pos=%s,%s,%s rel=%d loop=%d model=%x max=%s rolloff=%s ref=%s", + AL10.alGetSourcei(source, AL10.AL_SOURCE_STATE), fbits(AL10.alGetSourcef(source, AL10.AL_GAIN)), + fbits(AL10.alGetSourcef(source, AL10.AL_PITCH)), fbits(pos[0]), fbits(pos[1]), fbits(pos[2]), + AL10.alGetSourcei(source, AL10.AL_SOURCE_RELATIVE), AL10.alGetSourcei(source, AL10.AL_LOOPING), + AL10.alGetSourcei(source, 0xD000), fbits(AL10.alGetSourcef(source, AL10.AL_MAX_DISTANCE)), + fbits(AL10.alGetSourcef(source, AL10.AL_ROLLOFF_FACTOR)), fbits(AL10.alGetSourcef(source, AL10.AL_REFERENCE_DISTANCE)))); + } + } + return sb.toString(); + } + + /** Print and clear the notifications, then the channel counts. */ + public void flush(PrintWriter out) { + for (String h : heard) out.println(h); + heard.clear(); + out.println(" " + manager.getChannelDebugString()); + } +} diff --git a/tools/audio_harness.py b/tools/audio_harness.py index bfd18e05e..41e0fa9dd 100644 --- a/tools/audio_harness.py +++ b/tools/audio_harness.py @@ -54,8 +54,11 @@ def run_harness(name, oracle, example, inputs_text, extra_sources=(), java_args= input_hash = lab.digest(inputs, 'sha256') def run(command, log, env=None): - with (build / (log + '.log')).open('w') as out: - subprocess.run(list(map(str, command)), cwd=lab.ROOT, check=True, timeout=timeout, stdout=out, stderr=subprocess.STDOUT, env=env) + with (build / (log + ".log")).open("w") as out: + try: + subprocess.run(list(map(str, command)), cwd=lab.ROOT, check=True, timeout=timeout, stdout=out, stderr=subprocess.STDOUT, env=env) + except subprocess.CalledProcessError: + raise SystemExit(f"{log} failed: see {build / (log + '.log')}") from None classes = build / 'classes' classes.mkdir(exist_ok=True) diff --git a/tools/test_sound_engine_parity.py b/tools/test_sound_engine_parity.py new file mode 100644 index 000000000..383ca24b2 --- /dev/null +++ b/tools/test_sound_engine_parity.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python3 +"""Compare the sound engine's bookkeeping with the vanilla 26.3 client. + +The oracle runs the real `SoundManager`/`SoundEngine` on OpenAL Soft's "No +Output" device (see VanillaSoundRig) and replays scripts of plays (simple, +biome loop, underwater loop and sub-sound instances), stops (by instance, by +sound and/or source, all), category gains, source volume options and +refreshes, channel ends, delayed and queued sounds, pauses and client ticks. +After every step it prints each instance's `isActive` and the AL source the +engine configured (state, gain, pitch, position, relative, looping, distance +model, max distance, rolloff, reference distance), the subtitle notifications +and the channel pool counts. Horizon's `SoundEngine` replays the scripts +against a backend that records the same AL source fields. +""" +import json +import random + +try: + from . import audio_harness as h +except ImportError: + import audio_harness as h + + +def dbits(v): + import struct + return struct.pack('>d', v).hex() + + +class Script: + def __init__(self, events, streams): + self.lines = [] + self.events, self.streams = events, streams + + def add(self, *parts): + self.lines.append(' '.join(map(str, parts))) + + def play(self, name, event, source=4, volume=1.0, pitch=1.0, at=(0.0, 0.0, 0.0), looping=0, delay=0, linear=True, relative=0, seed=0, kind='simple'): + self.add('play', name, kind, event, source, h.bits(volume), h.bits(pitch), *map(dbits, at), looping, delay, + 'linear' if linear else 'none', relative, seed) + + def tick(self, n=1, paused=0): + for _ in range(n): + self.add('tick', paused) + + def reset(self): + self.add('stopmatch', '-', '-') + for source in range(11): + self.add('volume', source, h.bits(1.0)) + self.tick() + + +def scripted(s): + stone, cave, click = 'minecraft:block.stone.break', 'minecraft:ambient.cave', 'minecraft:ui.button.click' + music, loop, uloop = 'minecraft:music.game', 'minecraft:ambient.crimson_forest.loop', 'minecraft:ambient.underwater.loop' + # Positional and relative sounds, lifetimes and channel ends. + s.play('a', stone, 4, 1.0, 0.8, (10.5, 64.0, -3.25), seed=5) + s.play('b', click, 10, 0.25, 1.0, linear=False, relative=1, seed=6) + s.play('c', cave, 8, 4.0, 1.0, (100.0, 20.0, 100.0), seed=7) + s.play('d', stone, 4, 1.5, 3.0, (0.5, 0.5, 0.5), seed=8) + s.play('e', stone, 4, 0.5, 0.1, (1.0, 2.0, 3.0), seed=9) + s.tick(3) + s.add('finish', 'a') + s.tick(25) + s.add('finish', 'b') + s.add('stop', 'c') + s.tick(2) + s.reset() + # Volumes: options, category gains, refreshes, silent starts. + s.add('volume', 4, h.bits(0.5)) + s.add('volume', 0, h.bits(0.75)) + s.play('a', stone, 4, 1.0, 1.0, (1.0, 1.0, 1.0), seed=1) + s.add('volume', 4, h.bits(0.0)) + s.play('b', stone, 4, 1.0, 1.0, (1.0, 1.0, 1.0), seed=2) + s.add('volume', 1, h.bits(0.0)) + s.play('m', music, 1, 1.0, 1.0, linear=False, relative=1, seed=3) + s.add('refresh', 4) + s.add('volume', 4, h.bits(0.3)) + s.add('refresh', 0) + s.add('gain', 1, h.bits(0.5)) + s.add('gain', 1, h.bits(1.5)) + s.add('gain', 4, h.bits(-0.2)) + s.add('volume', 1, h.bits(1.0)) + s.add('refresh', 1) + s.tick(2) + s.add('volume', 0, h.bits(2.0)) + s.add('refresh', 0) + s.reset() + # Biome loops: fades, crossfade, stopping, removal. + s.play('l1', loop, kind='loop', seed=11) + s.add('fade', 'l1', 'in') + s.tick(45) + s.play('l2', 'minecraft:ambient.warped_forest.loop', kind='loop', seed=12) + s.add('fade', 'l1', 'out') + s.add('fade', 'l2', 'in') + s.tick(50) + s.add('fade', 'l2', 'out') + s.tick(10) + s.add('fade', 'l2', 'in') + s.tick(60) + s.add('volume', 8, h.bits(0.0)) + s.play('l3', loop, kind='loop', seed=13) + s.tick(3) + s.reset() + # Underwater loop and sub-sounds. + s.add('player', 1, 0) + s.play('u', uloop, kind='uloop', seed=21) + s.play('v', 'minecraft:ambient.underwater.loop.additions.rare', kind='usub', seed=22) + s.tick(50) + s.add('player', 0, 0) + s.tick(5) + s.add('player', 1, 0) + s.tick(5) + s.add('player', 0, 0) + s.tick(30) + s.add('player', 1, 1) + s.play('u2', uloop, kind='uloop', seed=23) + s.tick(3) + s.add('player', 0, 0) + s.reset() + # Queued tickables, delayed and manually looped sounds. + s.play('q', loop, kind='loop', seed=31) + s.add('stop', 'q') + s.tick(25) + s.add('queue', 'q') + s.add('fade', 'q', 'in') + s.tick(3) + s.play('w', stone, 4, 1.0, 1.0, (2.0, 2.0, 2.0), seed=32) + s.add('delayed', 'w', 5) + s.tick(7) + s.play('r', stone, 4, 1.0, 1.0, (3.0, 3.0, 3.0), looping=1, delay=4, seed=33) + s.tick(22) + s.add('finish', 'r') + s.tick(8) + s.add('finish', 'r') + s.tick(6) + s.play('n', stone, 4, 1.0, 1.0, (3.0, 3.0, 3.0), looping=1, seed=34) + s.tick(2) + s.reset() + # Stopping by source and sound, pauses. + s.play('a', stone, 4, seed=41) + s.play('b', stone, 5, seed=42) + s.play('c', cave, 8, seed=43) + s.play('m', music, 1, linear=False, relative=1, seed=44) + s.play('u', click, 10, linear=False, relative=1, seed=45) + s.add('pause') + s.tick(1, paused=1) + s.add('stop', 'm') + s.tick(1, paused=1) + s.add('resume') + s.add('stopmatch', stone, '-') + s.tick(25) + s.add('stopmatch', '-', 8) + s.add('stopmatch', click, 4) + s.add('stopmatch', click, 10) + s.tick(2) + s.reset() + # Unknown, empty and intentionally empty events; replaying an instance. + for i, event in enumerate(['minecraft:not.a.sound', 'minecraft:intentionally_empty', 'minecraft:empty', 'minecraft:entity.generic.eat']): + s.play(f'x{i}', event, 6, seed=50 + i) + s.add('replay', 'x3') + s.tick(25) + s.reset() + # Channel pools. + for i in range(252): + s.play('p', stone, 4, 1.0, 1.0, (float(i), 0.0, 0.0), seed=i) + for i in range(10): + s.play('s', music, 1, linear=False, relative=1, seed=i) + s.tick(2) + s.add('stopmatch', '-', '-') + s.tick(1) + + +def fuzz(s, rng, steps): + names = ['f0', 'f1', 'f2', 'f3', 'f4', 'f5'] + live = set() + for _ in range(steps): + op = rng.random() + name = rng.choice(names) + if op < 0.25: + kind = rng.choice(['simple', 'simple', 'simple', 'loop', 'uloop', 'usub']) + event = rng.choice(s.streams if kind != 'simple' and rng.random() < 0.5 else s.events) + at = tuple(rng.choice([0.0, rng.uniform(-200, 200)]) for _ in range(3)) + s.play(name, event, rng.randrange(11), rng.choice([1.0, 0.5, 2.0, 0.0, 4.0, rng.uniform(0, 3)]), rng.choice([1.0, 0.5, 2.5, rng.uniform(0.2, 3)]), + at, int(rng.random() < 0.2), rng.choice([0, 0, 0, 3]), rng.random() < 0.7, int(rng.random() < 0.3), rng.getrandbits(63), kind) + live.add(name) + elif not live: + s.tick() + elif op < 0.32: + s.add('finish', rng.choice(sorted(live))) + elif op < 0.36: + s.add('stop', rng.choice(sorted(live))) + elif op < 0.40: + s.add('fade', rng.choice(sorted(live)), rng.choice(['in', 'out'])) + elif op < 0.42: + s.add('stopmatch', rng.choice(['-', rng.choice(s.events)]), rng.choice(['-', rng.randrange(11)])) + elif op < 0.45: + s.add('volume', rng.randrange(11), h.bits(rng.choice([0.0, 1.0, 0.5, rng.random()]))) + elif op < 0.48: + s.add('refresh', rng.randrange(11)) + elif op < 0.51: + s.add('gain', rng.randrange(11), h.bits(rng.choice([0.0, 1.0, 0.3, 1.2]))) + elif op < 0.53: + s.add('player', int(rng.random() < 0.6), int(rng.random() < 0.05)) + elif op < 0.55: + s.add('replay', rng.choice(sorted(live))) + elif op < 0.56: + s.add('pause') + s.tick(rng.randrange(1, 4), paused=1) + s.add('resume') + elif op < 0.57: + s.add('forget', name) + live.discard(name) + else: + s.tick(rng.randrange(1, 6)) + + +def fixtures(): + sounds = json.loads((h.RESOURCES / 'assets/minecraft/sounds.json').read_text()) + names = sorted(sounds) + streams = sorted('minecraft:' + n for n in names if any(isinstance(e, dict) and e.get('stream') for e in sounds[n].get('sounds', []))) + rng = random.Random(0x454e47494e45) + events = sorted(set(['minecraft:' + rng.choice(names) for _ in range(60)] + ['minecraft:ambient.cave', 'minecraft:block.stone.break'])) + s = Script(events, streams) + scripted(s) + for _ in range(40): + s.reset() + fuzz(s, rng, 150) + return s.lines + + +def main(): + lines = fixtures() + matched, report = h.run_harness( + 'sound-engine', 'VanillaSoundEngineOracle', 'sound_engine_fixture', ''.join(l + '\n' for l in lines), + extra_sources=[h.lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java'], + java_args=[h.RESOURCES], rust_args=[h.RESOURCES], + scope='Real SoundEngine (OpenAL Soft null device, inline executor, silent static buffers, never-ready streams): play results, ' + 'AL source parameters set by play/tickInGameSound/refreshCategoryVolume (gain from calculateVolume, clamped pitch, linear ' + 'attenuation distance, looping, position, relative), isActive, the 20-tick minimum lifetime, channel ends, stop by instance/sound/source/all, ' + 'pauseAllExcept/resume, tickMusicWhenPaused, queued tickables, playDelayed and manual looping, LoopSoundInstance, ' + 'UnderLiquidAmbientSoundInstance and UnderLiquidSubSound ticks, subtitle notifications and ranges, and the 247/8 channel pools. ' + 'Not compared: decoded sample output, OpenAL panning/HRTF and distance gain inside the mixer, asset loading timing.') + print(f'{matched:,} sound engine lines match the pinned client ({len(lines):,} steps): {report}', flush=True) + + +if __name__ == '__main__': + main() From 3429de00203dc99fec0b93c880dd5b583cfb8d32 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:35:45 +0200 Subject: [PATCH 06/28] Compare block entity rendering with vanilla renderers Add a differential harness (test_block_entity_render_parity) whose Java oracle runs each vanilla BlockEntityRenderer on a real block entity and captures the submitted model vertices, textures, light and text calls. Horizon now animates shulker lids, bell shakes, active conduits (cage, wind and the camera-facing eye), skull jaws and ears, pot wobble and sherd sides; signs wrap lines like StringSplitter and measure spaces with the font; books use the Mth sine table and player heads the slim default skin. Co-Authored-By: Claude Opus 5.5 --- .../examples/block_entity_render_fixture.rs | 285 +++++++++++ .../horizon-client/src/block_entity_render.rs | 457 ++++++++++++++---- crates/horizon-client/src/game.rs | 16 +- crates/horizon-client/src/game/minecarts.rs | 5 +- crates/horizon-client/src/hud.rs | 5 + .../dev/horizonlab/parity/ParityFont.java | 94 ++++ .../VanillaBlockEntityRenderOracle.java | 377 +++++++++++++++ tools/test_block_entity_render_parity.py | 305 ++++++++++++ 8 files changed, 1438 insertions(+), 106 deletions(-) create mode 100644 crates/horizon-client/examples/block_entity_render_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/ParityFont.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityRenderOracle.java create mode 100644 tools/test_block_entity_render_parity.py diff --git a/crates/horizon-client/examples/block_entity_render_fixture.rs b/crates/horizon-client/examples/block_entity_render_fixture.rs new file mode 100644 index 000000000..df8a694a6 --- /dev/null +++ b/crates/horizon-client/examples/block_entity_render_fixture.rs @@ -0,0 +1,285 @@ +//! Headless transport for the block-entity render parity gate: replays each +//! case (block state, light, partial tick and ticked block-entity fields) +//! through `BlockEntityRenderer` at the block origin and writes the quads +//! (texture, sprite-local UVs, baked colour, light) and sign text calls. +#![forbid(unsafe_code)] +use glam::{DVec3, Mat4, Quat}; +use horizon_client::{ + assets::Assets, + banner::{self, Banners}, + block_entity_render::{BlockAnim, BlockEntityRenderer, Scene, TextCall}, + chunk::{Chunk, Light}, + hud::{HudAtlas, Rect}, + signs::{DYE_TEXT, SignData, SignText}, + world::World, +}; +use horizon_world::registry::{BlockRegistry, BlockStateId}; +use serde_json::{Value, json}; +use std::{ + cell::RefCell, + collections::HashMap, + fs, + io::{BufWriter, Write}, + path::{Path, PathBuf}, + sync::Arc, +}; +type Result = std::result::Result>; + +/// Every texture the vanilla oracle used gets its own unit square on a small +/// grid (offsets stay small so f32 UVs keep their precision), so a vertex's +/// texture and sprite-local UV can be recovered. +fn fake_sprites(list: &Path) -> Result<(HashMap, Vec, usize)> { + let names: Vec = fs::read_to_string(list)? + .lines() + .filter(|l| !l.is_empty()) + .map(str::to_owned) + .collect(); + let grid = (names.len() as f64).sqrt().ceil().max(1.0) as usize; + let map = names + .iter() + .enumerate() + .map(|(i, n)| { + let (u0, v0) = ((i % grid) as f32 * 2.0, (i / grid) as f32 * 2.0); + ( + n.clone(), + Rect { + u0, + v0, + u1: u0 + 1.0, + v1: v0 + 1.0, + w: 16, + h: 16, + }, + ) + }) + .collect(); + Ok((map, names, grid)) +} + +fn find_state(registry: &BlockRegistry, spec: &str) -> Option { + let (name, props) = match spec.split_once('[') { + Some((n, rest)) => (n, rest.trim_end_matches(']')), + None => (spec, ""), + }; + let wanted: Vec<(&str, &str)> = props + .split(',') + .filter(|p| !p.is_empty()) + .filter_map(|p| p.split_once('=')) + .collect(); + let default = registry.state(registry.default_state(name)?)?.clone(); + (0..registry.len() as u32).find(|&id| { + registry.state(BlockStateId(id)).is_some_and(|s| { + s.name == name + && s.properties.iter().all(|(k, v)| { + wanted + .iter() + .find(|(wk, _)| wk == k) + .map_or(default.properties.get(k) == Some(v), |(_, wv)| wv == v) + }) + }) + }) +} + +fn sign_side(v: &Value) -> SignText { + let mut side = SignText::default(); + for (line, text) in side + .lines + .iter_mut() + .zip(v["lines"].as_array().into_iter().flatten()) + { + *line = text.as_str().unwrap_or_default().to_owned(); + } + let color = v["color"].as_str().unwrap_or("black"); + side.color = DYE_TEXT.iter().position(|(n, _)| *n == color).unwrap_or(15) as u8; + side.glowing = v["glowing"].as_bool().unwrap_or(false); + side +} + +fn intern(s: &str) -> &'static str { + match s { + "north" => "north", + "south" => "south", + "west" => "west", + "east" => "east", + "up" => "up", + _ => "down", + } +} + +fn main() -> Result<()> { + let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); + let [root, inputs, textures, output] = args.as_slice() else { + return Err("usage: block_entity_render_fixture RESOURCES INPUTS TEXTURES OUTPUT".into()); + }; + let assets = Assets::load(root)?; + let registry = assets.registry; + let mut renderer = BlockEntityRenderer::load(root, registry)?; + let atlas = HudAtlas::build(root)?; + let banners = Banners::load(root); + let (sprites, names, grid) = fake_sprites(textures)?; + let air = registry.default_state("minecraft:air").ok_or("no air")?; + let mut out = BufWriter::new(fs::File::create(output)?); + for line in fs::read_to_string(inputs)? + .lines() + .filter(|l| !l.is_empty()) + { + let case: Value = serde_json::from_str(line)?; + let block = case["block"].as_str().unwrap_or_default(); + let Some(state) = find_state(registry, block) else { + writeln!(out, "{}", json!({"skip": "unknown block state"}))?; + continue; + }; + if !renderer.renders(state) { + writeln!(out, "{}", json!({"skip": "no renderer"}))?; + continue; + } + let int = |v: &Value| v.as_i64().unwrap_or(0) as i32; + let float = |v: &Value| v.as_f64().unwrap_or(0.0) as f32; + let pos = [ + int(&case["pos"][0]), + int(&case["pos"][1]), + int(&case["pos"][2]), + ]; + let packed = (int(&case["light"][0]) << 4 | int(&case["light"][1])) as u8; + let mut world = World::new(air, 0); + for dx in -1..=1 { + for dz in -1..=1 { + let (cx, cz) = ((pos[0] >> 4) + dx, (pos[2] >> 4) + dz); + let mut chunk = Chunk::empty(cx, cz); + for section in &mut chunk.sections { + Arc::make_mut(section).light = Light::Uniform(packed); + } + world.chunks.insert((cx, cz), Arc::new(chunk)); + } + } + if let Some(book) = case.get("book") { + renderer.set_book( + pos, + int(&book["time"]), + ["flip", "oFlip", "open", "oOpen", "rot", "oRot"].map(|k| float(&book[k])), + ); + } + let sign = case.get("sign").map(|s| { + let mut data = SignData { + hanging: block.contains("hanging"), + ..SignData::default() + }; + data.front = sign_side(&s["front"]); + data.back = sign_side(&s["back"]); + data + }); + let layers: Vec<(String, u32)> = case["patterns"] + .as_array() + .into_iter() + .flatten() + .map(|p| { + ( + banners.banner_texture(p[0].as_str().unwrap_or_default()), + banner::dye_rgb(p[1].as_str().unwrap_or_default()), + ) + }) + .collect(); + let anim = BlockAnim { + shulker: (float(&case["progress"]), float(&case["progressOld"])), + bell_ticks: int(&case["bellTicks"]), + bell_shake: case["shake"].as_str().map(intern), + conduit: ( + int(&case["conduit"]["tickCount"]), + case["conduit"]["active"].as_bool().unwrap_or(false), + case["conduit"]["hunting"].as_bool().unwrap_or(false), + float(&case["conduit"]["activeRotation"]), + ), + skull: ( + case["skullAnimation"][0].as_bool().unwrap_or(false), + int(&case["skullAnimation"][1]), + ), + sherds: [0, 1, 2, 3].map(|i| { + case["sherds"][i] + .as_str() + .filter(|s| !s.is_empty()) + .map(str::to_owned) + }), + wobble: case["wobble"] + .as_array() + .map(|w| (w[0].as_str() == Some("POSITIVE"), float(&w[1]))), + }; + let open = float(&case["open"]); + let near = case["sign"]["near"].as_bool().unwrap_or(false); + let camera = DVec3::new( + case["camera"][0].as_f64().unwrap_or(0.0), + case["camera"][1].as_f64().unwrap_or(0.0), + case["camera"][2].as_f64().unwrap_or(0.0), + ); + // Signs pick the outline from the camera distance: put the camera where the case says. + let camera = if case.get("sign").is_some() { + let centre = DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])) + 0.5; + centre + + if near { + DVec3::ZERO + } else { + DVec3::new(20.0, 0.0, 0.0) + } + } else { + camera + }; + let (yaw, pitch) = (float(&case["yaw"]), float(&case["pitch"])); + let texts = RefCell::new(Vec::::new()); + let scene = Scene { + camera, + orientation: Quat::from_euler( + glam::EulerRot::YXZ, + std::f32::consts::PI - yaw * (std::f32::consts::PI / 180.0), + -pitch * (std::f32::consts::PI / 180.0), + 0.0, + ), + anim: &|_| anim.clone(), + texts: Some(&texts), + partial: float(&case["partial"]), + game_time: 0, + world: &world, + sprites: &sprites, + nether: false, + lid: &|_| open, + sign: &|_| sign.as_ref(), + banner: &|_| layers.clone(), + glyph: &|c| atlas.glyph_cell(c), + }; + let mut verts = Vec::new(); + renderer.render_block(&scene, pos, state, Mat4::IDENTITY, packed, &mut verts); + let quads: Vec = verts + .chunks(4) + .map(|q| { + let (cu, cv) = ((q[0].uv[0] / 2.0).floor(), (q[0].uv[1] / 2.0).floor()); + let texture = names + .get(cu as usize + cv as usize * grid) + .cloned() + .unwrap_or_default(); + let v: Vec = q + .iter() + .map(|v| { + json!([ + v.pos[0], + v.pos[1], + v.pos[2], + v.uv[0] - cu * 2.0, + v.uv[1] - cv * 2.0 + ]) + }) + .collect(); + json!({"texture": texture, "v": v, "color": q[0].color, "light": q[0].light}) + }) + .collect(); + let texts: Vec = texts + .borrow() + .iter() + .filter(|t| !t.text.is_empty()) + .map(|t| { + json!({"matrix": t.matrix.to_cols_array(), "x": t.x, "y": t.y, "text": t.text, + "color": t.color, "outline": t.outline, + "light": ((t.light & 0xFF) << 16 | (t.light >> 8 & 0xFF))}) + }) + .collect(); + writeln!(out, "{}", json!({"quads": quads, "texts": texts}))?; + } + Ok(()) +} diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 8114542b0..1f6f805ba 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -7,7 +7,10 @@ //! the block plus `minecraft_mix_light` with the level's two diffuse lights. use crate::{hud::Rect, mesher::Vertex, world::World}; use glam::{DVec3, Mat4, Quat, Vec3}; -use horizon_core::random::{LegacyRandom, RandomSource}; +use horizon_core::{ + geometry::trig::Mth, + random::{LegacyRandom, RandomSource}, +}; use horizon_world::registry::{BlockRegistry, BlockStateId}; use serde_json::Value; use std::{collections::HashMap, f32::consts::PI, path::Path}; @@ -582,19 +585,19 @@ fn book_pose(openness: f32, flip1: f32, flip2: f32) -> impl Fn(&str, &mut [f32; "right_lid" => p[4] = -openness, "left_pages" => { p[4] = openness; - p[0] = openness.sin(); + p[0] = openness.msin(); } "right_pages" => { p[4] = -openness; - p[0] = openness.sin(); + p[0] = openness.msin(); } "flip_page1" => { p[4] = openness - openness * 2.0 * flip1; - p[0] = openness.sin(); + p[0] = openness.msin(); } "flip_page2" => { p[4] = openness - openness * 2.0 * flip2; - p[0] = openness.sin(); + p[0] = openness.msin(); } _ => {} } @@ -603,94 +606,163 @@ fn frac(x: f32) -> f32 { x - x.floor() } +/// `StringSplitter.splitLines(...).get(0)` for plain text: the first line, +/// wrapped at the last space that fits or mid-word when none does. +fn first_line(line: &str, max_width: f32, advance: &dyn Fn(char) -> f32) -> String { + let chars: Vec = line.chars().collect(); + let mut width = 0.0; + let mut last_space = None; + for (i, &c) in chars.iter().enumerate() { + if c == '\n' { + return chars[..i].iter().collect(); + } + if c == ' ' { + last_space = Some(i); + } + width += advance(c); + if width > max_width { + let end = match last_space { + Some(s) if s > 0 => s, + _ => i.max(1), + }; + return chars[..end].iter().collect(); + } + } + line.to_owned() +} + /// `AbstractSignRenderer.submitSignText`: four centred lines, glowing text /// full-bright with an 8x outline in the dark colour. -fn sign_text( +fn sign_text_calls( scene: &Scene, data: &crate::signs::SignData, text: &crate::signs::SignText, m: Mat4, packed: u8, near: bool, - out: &mut Vec, -) { +) -> Vec { let line_height = data.line_height(); let midpoint = (4.0 * line_height / 2.0).floor(); - let dark = text.dark_color(); + let dark = 0xFF00_0000 | text.dark_color(); let (color, outline, light) = if text.glowing { let c = text.text_color(); - (c, (c == 0 || near).then_some(dark), 240 | 240 << 8) + ( + 0xFF00_0000 | c, + if c == 0 || near { dark } else { 0 }, + 240 | 240 << 8, + ) } else { - (dark, None, vertex_light(packed)) + (dark, 0, vertex_light(packed)) }; - let width = |s: &str| { - s.chars() - .map(|c| (scene.glyph)(c).map_or(6.0, |g| g.1)) - .sum::() - }; - for (i, line) in text.lines.iter().enumerate() { - // Font.split(line, maxWidth).get(0): keep what fits. - let mut shown = String::new(); - for ch in line.chars() { - shown.push(ch); - if width(&shown) > data.max_line_width() { - shown.pop(); - break; + let advance = |c: char| (scene.glyph)(c).1; + let width = |s: &str| s.chars().map(advance).sum::().ceil(); + text.lines + .iter() + .enumerate() + .map(|(i, line)| { + let shown = first_line(line, data.max_line_width(), &advance); + TextCall { + matrix: m, + x: -((width(&shown) as i32) / 2) as f32, + y: i as f32 * line_height - midpoint, + text: shown, + color, + outline, + light, } - } - let x0 = -(width(&shown) as i32 / 2) as f32; - let y0 = i as f32 * line_height - midpoint; - let mut emit = |dx: f32, dy: f32, rgb: u32| { - let mut x = x0 + dx; - for ch in shown.chars() { - let Some((r, advance)) = (scene.glyph)(ch) else { - x += 6.0; - continue; - }; - if ch != ' ' { - let corners = [ - (x, y0 + dy + 8.0), - (x + 8.0, y0 + dy + 8.0), - (x + 8.0, y0 + dy), - (x, y0 + dy), - ]; - let uvs = [[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]]; - let c = - 0xFF00_0000 | (rgb & 255) << 16 | (rgb >> 8 & 255) << 8 | (rgb >> 16 & 255); - for ((cx, cy), uv) in corners.into_iter().zip(uvs) { - out.push(Vertex { - pos: m.transform_point3(Vec3::new(cx, cy, 0.0)).to_array(), - uv, - layer: 0, - color: c, - light, - }); - } + }) + .collect() +} + +/// Draws a text call with the font atlas: 8x8 glyph cells, the outline as +/// eight one-pixel offsets under the text. +fn draw_text(scene: &Scene, call: &TextCall, out: &mut Vec) { + let mut emit = |dx: f32, dy: f32, argb: u32| { + let mut x = call.x + dx; + let y0 = call.y + dy; + for ch in call.text.chars() { + let (cell, advance) = (scene.glyph)(ch); + if let Some(r) = cell { + let corners = [(x, y0 + 8.0), (x + 8.0, y0 + 8.0), (x + 8.0, y0), (x, y0)]; + let uvs = [[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]]; + let c = + 0xFF00_0000 | (argb & 255) << 16 | (argb >> 8 & 255) << 8 | (argb >> 16 & 255); + for ((cx, cy), uv) in corners.into_iter().zip(uvs) { + out.push(Vertex { + pos: call + .matrix + .transform_point3(Vec3::new(cx, cy, 0.0)) + .to_array(), + uv, + layer: 0, + color: c, + light: call.light, + }); } - x += advance; - } - }; - if let Some(o) = outline { - for (dx, dy) in [ - (-1.0, -1.0), - (0.0, -1.0), - (1.0, -1.0), - (-1.0, 0.0), - (1.0, 0.0), - (-1.0, 1.0), - (0.0, 1.0), - (1.0, 1.0), - ] { - emit(dx, dy, o); } + x += advance; + } + }; + if call.outline != 0 { + for (dx, dy) in [ + (-1.0, -1.0), + (0.0, -1.0), + (1.0, -1.0), + (-1.0, 0.0), + (1.0, 0.0), + (-1.0, 1.0), + (0.0, 1.0), + (1.0, 1.0), + ] { + emit(dx, dy, call.outline); } - emit(0.0, 0.0, color); } + emit(0.0, 0.0, call.color); +} + +/// Block-entity fields the level ticks, at one position (vanilla's own field +/// values; extraction to render state happens here as in each renderer). +#[derive(Clone, Debug, Default)] +pub struct BlockAnim { + /// `ShulkerBoxBlockEntity` progress and progressOld. + pub shulker: (f32, f32), + /// `BellBlockEntity.ticks` and the click direction while `shaking`. + pub bell_ticks: i32, + pub bell_shake: Option<&'static str>, + /// `ConduitBlockEntity` tickCount, isActive, isHunting and activeRotation. + pub conduit: (i32, bool, bool, f32), + /// `SkullBlockEntity` isAnimating and animationTickCount. + pub skull: (bool, i32), + /// `DecoratedPotBlockEntity` decorations as item ids: back, left, right, front. + pub sherds: [Option; 4], + /// `DecoratedPotRenderState` wobble style (positive) and progress. + pub wobble: Option<(bool, f32)>, +} + +/// One `submitText` call (`AbstractSignRenderer.submitSignText`). +#[derive(Clone, Debug, PartialEq)] +pub struct TextCall { + pub matrix: Mat4, + pub x: f32, + pub y: f32, + pub text: String, + /// ARGB. + pub color: u32, + /// ARGB outline colour, 0 for none. + pub outline: u32, + /// Horizon packed light (sky*16 | block*16 << 8). + pub light: u32, } /// Inputs from the game for one frame of block-entity rendering. pub struct Scene<'a> { pub camera: DVec3, + /// `Camera.rotation` (conduit eyes face the camera). + pub orientation: Quat, + /// Ticked block-entity state at a position. + pub anim: &'a dyn Fn([i32; 3]) -> BlockAnim, + /// When set, sign text is recorded here as text calls instead of drawn. + pub texts: Option<&'a std::cell::RefCell>>, pub partial: f32, pub game_time: i64, pub world: &'a World, @@ -702,8 +774,8 @@ pub struct Scene<'a> { pub sign: &'a dyn Fn([i32; 3]) -> Option<&'a crate::signs::SignData>, /// Banner layers at a position: pattern texture and RGB tint, bottom first. pub banner: &'a dyn Fn([i32; 3]) -> Vec<(String, u32)>, - /// Font glyph cell and advance. - pub glyph: &'a dyn Fn(char) -> Option<(Rect, f32)>, + /// Font glyph cell (none for blank glyphs such as the space) and advance. + pub glyph: &'a dyn Fn(char) -> (Option, f32), } pub struct BlockEntityRenderer { @@ -711,8 +783,10 @@ pub struct BlockEntityRenderer { kinds: Vec, books: HashMap<[i32; 3], Book>, random: LegacyRandom, + /// Item id to its `PROVIDES_POTTERY_PATTERN` side texture (`Sheets.DECORATED_POT_MAPPER`). + pot_patterns: HashMap, } -const MODELS: [(&str, &str); 24] = [ +const MODELS: [(&str, &str); 27] = [ ("chest", "minecraft:chest#main"), ("double_chest_left", "minecraft:double_chest_left#main"), ("double_chest_right", "minecraft:double_chest_right#main"), @@ -734,6 +808,9 @@ const MODELS: [(&str, &str); 24] = [ ("bell", "minecraft:bell#main"), ("book", "minecraft:book#main"), ("conduit_shell", "minecraft:conduit#shell"), + ("conduit_cage", "minecraft:conduit#cage"), + ("conduit_wind", "minecraft:conduit#wind"), + ("conduit_eye", "minecraft:conduit#eye"), ("decorated_pot_base", "minecraft:decorated_pot_base#main"), ("decorated_pot_sides", "minecraft:decorated_pot_sides#main"), ("copper_golem", "minecraft:copper_golem#main"), @@ -757,7 +834,30 @@ impl BlockEntityRenderer { .iter() .filter_map(|(key, layer)| all.get(*layer).map(|v| (*key, ModelPart::parse(v)))) .collect(); - Ok(Self::new(models, registry)) + let mut renderer = Self::new(models, registry); + // Sherd items: provides_pottery_pattern -> decorated_pot_pattern asset id. + if let Ok(bytes) = std::fs::read(root.join("items.json")) { + let items: Value = serde_json::from_slice(&bytes)?; + for (item, components) in items.as_object().into_iter().flatten() { + let Some(pattern) = components["minecraft:provides_pottery_pattern"].as_str() + else { + continue; + }; + let name = pattern.strip_prefix("minecraft:").unwrap_or(pattern); + let file = root.join(format!("data/minecraft/decorated_pot_pattern/{name}.json")); + let Ok(def) = std::fs::read(file) else { + continue; + }; + let def: Value = serde_json::from_slice(&def)?; + if let Some(asset) = def["asset_id"].as_str() { + let asset = asset.strip_prefix("minecraft:").unwrap_or(asset); + renderer + .pot_patterns + .insert(item.clone(), format!("entity/decorated_pot/{asset}")); + } + } + } + Ok(renderer) } fn new(models: HashMap<&'static str, ModelPart>, registry: &BlockRegistry) -> Self { let kinds = (0..registry.len() as u32) @@ -773,6 +873,7 @@ impl BlockEntityRenderer { kinds, books: HashMap::new(), random: LegacyRandom::new(0x5EED_B00C), + pot_patterns: HashMap::new(), } } /// The standing banner's pole-and-bar and flag models (`BannerRenderer.submitSpecial`). @@ -831,6 +932,41 @@ impl BlockEntityRenderer { self.render_one(scene, *pos, kind, base, packed, lights, out); } } + /// One block entity at `pos` drawn under `base` with the given packed light + /// (the parity fixture's entry point). + pub fn render_block( + &self, + scene: &Scene, + pos: [i32; 3], + state: u32, + base: Mat4, + packed: u8, + out: &mut Vec, + ) { + let kind = self.kind(state); + let lights = diffuse_lights(scene.nether); + self.render_one(scene, pos, kind, base, packed, lights, out); + } + /// Whether this block state has a block-entity renderer here. + pub fn renders(&self, state: u32) -> bool { + !matches!(self.kind(state), Kind::None) + } + /// Sets an enchanting table's book fields (`EnchantingTableBlockEntity`): + /// time, flip, oFlip, open, oOpen, rot, oRot. + pub fn set_book(&mut self, pos: [i32; 3], time: i32, fields: [f32; 6]) { + let [flip, o_flip, open, o_open, rot, o_rot] = fields; + let book = self.books.entry(pos).or_default(); + *book = Book { + time, + flip, + o_flip, + open, + o_open, + rot, + o_rot, + ..*book + }; + } /// One block entity of `state` drawn under `base` (minecart contents). pub fn render_state( &self, @@ -913,7 +1049,11 @@ impl BlockEntityRenderer { ) .distance_squared(scene.camera) < 256.0; - sign_text(scene, data, text, m, packed, near, out); + let calls = sign_text_calls(scene, data, text, m, packed, near); + match scene.texts { + Some(sink) => sink.borrow_mut().extend(calls), + None => calls.iter().for_each(|c| draw_text(scene, c, out)), + } } } Kind::Chest { @@ -968,8 +1108,18 @@ impl BlockEntityRenderer { * Mat4::from_quat(direction_rotation(facing)) * Mat4::from_scale(Vec3::new(1.0, -1.0, -1.0)) * Mat4::from_translation(Vec3::new(0.0, -1.0, 0.0)); - // ShulkerBoxModel.setupAnim(progress = 0): closed lid. - draw_part(model, "root", m, &none, paint, out); + // ShulkerBoxModel.setupAnim(getProgress(partial)): the lid rises and turns. + let (progress, old) = (scene.anim)(pos).shulker; + let progress = old + scene.partial * (progress - old); + let lid = move |name: &str, p: &mut [f32; 9]| { + if name == "lid" { + p[0] = 0.0; + p[1] = 24.0 - progress * 0.5 * 16.0; + p[2] = 0.0; + p[4] = 270.0 * progress * (PI / 180.0); + } + }; + draw_part(model, "root", m, &lid, paint, out); } Kind::Banner { color, wall, angle } => { let (main, flag) = if *wall { @@ -995,7 +1145,7 @@ impl BlockEntityRenderer { / 100.0; let wave = move |name: &str, p: &mut [f32; 9]| { if name == "flag" { - p[3] = (-0.0125 + 0.01 * (2.0 * PI * phase).cos()) * PI; + p[3] = (-0.0125 + 0.01 * (2.0 * PI * phase).mcos()) * PI; } }; if let Some(paint) = paint("entity/banner/banner_base", 0xFFFFFF, packed) { @@ -1027,7 +1177,7 @@ impl BlockEntityRenderer { SkullType::Creeper => ("creeper_head", "entity/creeper/creeper"), SkullType::Dragon => ("dragon_skull", "entity/enderdragon/dragon"), SkullType::Piglin => ("piglin_head", "entity/piglin/piglin"), - SkullType::Player => ("player_head", "entity/player/wide/steve"), + SkullType::Player => ("player_head", "entity/player/slim/steve"), }; let (Some(model), Some(paint)) = (self.models.get(model), paint(texture, 0xFFFFFF, packed)) @@ -1050,11 +1200,16 @@ impl BlockEntityRenderer { * Mat4::from_scale(Vec3::new(-1.0, -1.0, 1.0)) } }; - // SkullModelBase.State with animationPos 0 (unpowered). - let anim = |name: &str, p: &mut [f32; 9]| match name { - "jaw" => p[3] = (0.0f32.sin() + 1.0) * 0.2, - "left_ear" => p[5] = -(1.0 + 2.5) * 0.2, - "right_ear" => p[5] = (1.0 + 2.5) * 0.2, + // SkullBlockEntity.getAnimation: the dragon jaw and piglin ears + // (DragonHeadModel / PiglinHeadModel use double-precision Math). + let (animating, count) = (scene.anim)(pos).skull; + let t = count as f32 + if animating { scene.partial } else { 0.0 }; + let anim = move |name: &str, p: &mut [f32; 9]| match name { + "jaw" => p[3] = (f64::from(t * PI * 0.2).sin() + 1.0) as f32 * 0.2, + "left_ear" => { + p[5] = -((f64::from(t * PI * 0.2 * 1.2).cos() + 2.5) as f32) * 0.2; + } + "right_ear" => p[5] = (f64::from(t * PI * 0.2).cos() + 2.5) as f32 * 0.2, _ => {} }; draw_part(model, "root", m, &anim, paint, out); @@ -1066,7 +1221,27 @@ impl BlockEntityRenderer { ) else { return; }; - draw_part(model, "root", base, &none, paint, out); + // BellModel.setupAnim(State(ticks + partial, shakeDirection)). + let a = (scene.anim)(pos); + let ticks = a.bell_ticks as f32 + scene.partial; + let (mut x_rot, mut z_rot) = (0.0, 0.0); + if let Some(dir) = a.bell_shake { + let base_rot = (ticks / PI).msin() / (4.0 + ticks / 3.0); + match dir { + "north" => x_rot = -base_rot, + "south" => x_rot = base_rot, + "east" => z_rot = -base_rot, + "west" => z_rot = base_rot, + _ => {} + } + } + let shake = move |name: &str, p: &mut [f32; 9]| { + if name == "bell_body" { + p[3] = x_rot; + p[5] = z_rot; + } + }; + draw_part(model, "root", base, &shake, paint, out); } Kind::DecoratedPot { y_rot } => { let (Some(base_model), Some(sides)) = ( @@ -1075,38 +1250,111 @@ impl BlockEntityRenderer { ) else { return; }; - let m = base + let a = (scene.anim)(pos); + let mut m = base * around( Mat4::from_rotation_y((180.0 - y_rot).to_radians()), Vec3::splat(0.5), ); + // DecoratedPotRenderer.submit: the wobble tilts around the base centre. + let pivot = Vec3::new(0.5, 0.0, 0.5); + if let Some((positive, progress)) = a.wobble + && (0.0..=1.0).contains(&progress) + { + if positive { + let delta = progress * (PI * 2.0); + let tilt_x = -1.5 * (delta.mcos() + 0.5) * (delta / 2.0).msin(); + m *= around(Mat4::from_rotation_x(tilt_x * 0.015_625), pivot); + let tilt_z = delta.msin(); + m *= around(Mat4::from_rotation_z(tilt_z * 0.015_625), pivot); + } else { + let turn = (-progress * 3.0 * PI).msin() * 0.125; + let decay = 1.0 - progress; + m *= around(Mat4::from_rotation_y(turn * decay), pivot); + } + } if let Some(paint) = paint("entity/decorated_pot/decorated_pot_base", 0xFFFFFF, packed) { draw_part(base_model, "root", m, &none, paint, out); } - if let Some(paint) = - paint("entity/decorated_pot/decorated_pot_side", 0xFFFFFF, packed) - { - draw_part(sides, "root", m, &none, paint, out); + // PotDecorations (back, left, right, front); items without a pattern use the blank side. + for (side, item) in ["back", "left", "right", "front"].iter().zip(&a.sherds) { + let texture = item + .as_ref() + .and_then(|i| self.pot_patterns.get(i)) + .map_or("entity/decorated_pot/decorated_pot_side", String::as_str); + if let (Some(part), Some(paint)) = + (sides.child(side), paint(texture, 0xFFFFFF, packed)) + { + draw_part(part, side, m, &none, paint, out); + } } } Kind::Conduit => { - // Inactive conduit (no frame scan yet): the shell at activeRotation 0. - let (Some(model), Some(paint)) = ( - self.models.get("conduit_shell"), - paint("entity/conduit/base", 0xFFFFFF, packed), - ) else { + let (ticks, active, hunting, raw_rotation) = (scene.anim)(pos).conduit; + // ConduitRenderer.extractRenderState. + let rotation = (raw_rotation + if active { scene.partial } else { 0.0 }) * -0.0375; + let tex = |name: &str| paint(name, 0xFFFFFF, packed); + if !active { + let (Some(model), Some(paint)) = + (self.models.get("conduit_shell"), tex("entity/conduit/base")) + else { + return; + }; + let m = base + * Mat4::from_translation(Vec3::splat(0.5)) + * Mat4::from_rotation_y(rotation.to_radians()); + draw_part(model, "root", m, &none, paint, out); return; + } + let anim_time = ticks as f32 + scene.partial; + let phase = ticks / 66 % 3; + let degrees = rotation * (180.0 / PI); + let hh = (anim_time * 0.1).msin() / 2.0 + 0.5; + let hh = hh * hh + hh; + let lift = Vec3::new(0.5, 0.3 + hh * 0.2, 0.5); + if let (Some(model), Some(paint)) = + (self.models.get("conduit_cage"), tex("entity/conduit/cage")) + { + let axis = Vec3::new(0.5, 1.0, 0.5).normalize(); + let m = base + * Mat4::from_translation(lift) + * Mat4::from_quat(Quat::from_axis_angle(axis, degrees * (PI / 180.0))); + draw_part(model, "root", m, &none, paint, out); + } + let wind = if phase == 1 { + "entity/conduit/wind_vertical" + } else { + "entity/conduit/wind" }; - draw_part( - model, - "root", - base * Mat4::from_translation(Vec3::splat(0.5)), - &none, - paint, - out, - ); + if let (Some(model), Some(paint)) = (self.models.get("conduit_wind"), tex(wind)) { + let turn = match phase { + 1 => Mat4::from_rotation_x(PI / 2.0), + 2 => Mat4::from_rotation_z(PI / 2.0), + _ => Mat4::IDENTITY, + }; + let center = base * Mat4::from_translation(Vec3::splat(0.5)); + draw_part(model, "root", center * turn, &none, paint, out); + let inner = center + * Mat4::from_scale(Vec3::splat(0.875)) + * Mat4::from_quat(Quat::from_euler(glam::EulerRot::XYZ, PI, 0.0, PI)); + draw_part(model, "root", inner, &none, paint, out); + } + let eye = if hunting { + "entity/conduit/open_eye" + } else { + "entity/conduit/closed_eye" + }; + if let (Some(model), Some(paint)) = (self.models.get("conduit_eye"), tex(eye)) { + let m = base + * Mat4::from_translation(lift) + * Mat4::from_scale(Vec3::splat(0.5)) + * Mat4::from_quat(scene.orientation) + * Mat4::from_quat(Quat::from_rotation_z(PI) * Quat::from_rotation_y(PI)) + * Mat4::from_scale(Vec3::splat(1.333_333_4)); + draw_part(model, "root", m, &none, paint, out); + } } Kind::EnchantingTable => { let (Some(model), Some(paint)) = ( @@ -1123,12 +1371,13 @@ impl BlockEntityRenderer { let y_rot = b.o_rot + wrap(b.rot - b.o_rot) * a; let m = base * Mat4::from_translation(Vec3::new(0.5, 0.75, 0.5)) - * Mat4::from_translation(Vec3::new(0.0, 0.1 + (time * 0.1).sin() * 0.01, 0.0)) + * Mat4::from_translation(Vec3::new(0.0, 0.1 + (time * 0.1).msin() * 0.01, 0.0)) * Mat4::from_rotation_y(-y_rot) * Mat4::from_rotation_z(80f32.to_radians()); let ff1 = (frac(flip + 0.25) * 1.6 - 0.3).clamp(0.0, 1.0); let ff2 = (frac(flip + 0.75) * 1.6 - 0.3).clamp(0.0, 1.0); - let openness = ((time * 0.02).sin() * 0.1 + 1.25) * open; + // BookModel.State.forAnimation. + let openness = ((time * 0.02).msin() * 0.1 + 1.25) * open; draw_part(model, "root", m, &book_pose(openness, ff1, ff2), paint, out); } Kind::Lectern { y_rot } => { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b81c403fd..64eb9ec65 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4483,8 +4483,22 @@ 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 scene = horizon_client::block_entity_render::Scene { camera, + // Camera.setRotation. + orientation: glam::Quat::from_euler( + glam::EulerRot::YXZ, + std::f32::consts::PI - view_yaw.to_radians(), + -view_pitch.to_radians(), + 0.0, + ), + anim: &|_| horizon_client::block_entity_render::BlockAnim::default(), + texts: None, partial: alpha as f32, game_time: self.world.game_time, world: &self.world, @@ -4496,7 +4510,7 @@ impl Game<'_> { _ => None, }, banner: &|p| self.banner_layers_at(p), - glyph: &|c| self.res.atlas.glyph(c), + glyph: &|c| self.res.atlas.glyph_cell(c), }; self.res .block_entity_render diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 6f2b00da7..967bef7e4 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -1231,6 +1231,9 @@ impl Game<'_> { let lid = |_: [i32; 3]| 0.0; let scene = horizon_client::block_entity_render::Scene { camera: glam::DVec3::ZERO, + orientation: glam::Quat::IDENTITY, + anim: &|_| horizon_client::block_entity_render::BlockAnim::default(), + texts: None, partial: 0.0, game_time: self.world.game_time, world: &self.world, @@ -1239,7 +1242,7 @@ impl Game<'_> { lid: &lid, sign: &|_| None, banner: &|_| Vec::new(), - glyph: &|c| self.res.atlas.glyph(c), + glyph: &|c| self.res.atlas.glyph_cell(c), }; self.res .block_entity_render diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index ed1a91c15..ea3beb3e3 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -68,6 +68,11 @@ impl HudAtlas { let g = self.font.glyph(ch); g.rect.map(|rect| (rect, g.advance)) } + /// A font glyph's atlas cell (none for blank glyphs such as the space) and advance. + pub fn glyph_cell(&self, ch: char) -> (Option, f32) { + let g = self.font.glyph(ch); + (g.rect, g.advance) + } pub fn build(root: &Path) -> Result { let textures = root.join("assets/minecraft/textures"); let mut files = Vec::new(); diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/ParityFont.java b/mods/horizon/src/test/java/dev/horizonlab/parity/ParityFont.java new file mode 100644 index 000000000..09e9911d6 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/ParityFont.java @@ -0,0 +1,94 @@ +package dev.horizonlab.parity; + +import com.google.gson.JsonParser; +import com.mojang.blaze3d.font.GlyphInfo; +import com.mojang.blaze3d.font.GlyphProvider; +import com.mojang.blaze3d.font.UnbakedGlyph; +import com.mojang.serialization.JsonOps; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GlyphSource; +import net.minecraft.client.gui.font.glyphs.BakedGlyph; +import net.minecraft.client.gui.font.providers.GlyphProviderDefinition; +import net.minecraft.client.gui.font.TextRenderable; +import net.minecraft.network.chat.FontDescription; +import net.minecraft.network.chat.Style; +import net.minecraft.resources.Identifier; +import net.minecraft.server.packs.PackType; +import net.minecraft.server.packs.resources.MultiPackResourceManager; +import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.util.RandomSource; + +/** + * The vanilla default font's glyph metrics without a GPU: the `space` and + * `include/default` providers of the client jar loaded by vanilla's own + * provider definitions (BitmapProvider scans ascii.png etc. for advances). + * Glyphs carry metrics only; nothing is stitched. + */ +public final class ParityFont { + public static ResourceManager resources() throws Exception { + var method = net.minecraft.client.resources.ClientPackSource.class.getDeclaredMethod("createVanillaPackSource", Path.class); + method.setAccessible(true); + var pack = (net.minecraft.server.packs.VanillaPackResources) method.invoke(null, Path.of("/nonexistent-horizon-assets")); + return pack.asResourceManager(); + } + + public static Font create(ResourceManager resources) throws Exception { + List providers = new ArrayList<>(); + for (String include : new String[] {"space", "default"}) { + var id = Identifier.withDefaultNamespace("font/include/" + include + ".json"); + try (var reader = new InputStreamReader(resources.open(id), StandardCharsets.UTF_8)) { + var json = JsonParser.parseReader(reader).getAsJsonObject(); + for (var element : json.getAsJsonArray("providers")) { + var conditional = GlyphProviderDefinition.Conditional.CODEC.parse(JsonOps.INSTANCE, element).getOrThrow(); + var loader = conditional.definition().unpack().left().orElseThrow(); + providers.add(loader.load(resources)); + } + } + } + GlyphSource source = new GlyphSource() { + @Override + public BakedGlyph getGlyph(int codepoint) { + for (GlyphProvider provider : providers) { + UnbakedGlyph glyph = provider.getGlyph(codepoint); + if (glyph != null) return baked(glyph.info()); + } + return baked(GlyphInfo.simple(6.0F)); + } + + @Override + public BakedGlyph getRandomGlyph(RandomSource random, int width) { + return getGlyph('?'); + } + }; + return new Font(new Font.Provider() { + @Override + public GlyphSource glyphs(FontDescription font) { + return source; + } + + @Override + public net.minecraft.client.gui.font.glyphs.EffectGlyph effect() { + return null; + } + }); + } + + private static BakedGlyph baked(GlyphInfo info) { + return new BakedGlyph() { + @Override + public GlyphInfo info() { + return info; + } + + @Override + public TextRenderable.Styled createGlyph(float x, float y, int color, int shadowColor, Style style, float boldOffset, float shadowOffset) { + return null; + } + }; + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityRenderOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityRenderOracle.java new file mode 100644 index 000000000..5f42922af --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityRenderOracle.java @@ -0,0 +1,377 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.gui.Font; +import net.minecraft.client.model.Model; +import net.minecraft.client.model.geom.EntityModelSet; +import net.minecraft.client.model.geom.LayerDefinitions; +import net.minecraft.client.renderer.SubmitNodeCollector; +import net.minecraft.client.renderer.blockentity.*; +import net.minecraft.client.renderer.blockentity.state.*; +import net.minecraft.client.renderer.rendertype.RenderType; +import net.minecraft.client.renderer.state.level.CameraRenderState; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.renderer.texture.UvMapping; +import net.minecraft.client.resources.model.sprite.SpriteGetter; +import net.minecraft.client.resources.model.sprite.SpriteId; +import net.minecraft.commands.arguments.blocks.BlockStateParser; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.util.FormattedCharSequence; +import net.minecraft.world.item.DyeColor; +import net.minecraft.world.item.ItemStackTemplate; +import net.minecraft.world.level.block.EntityBlock; +import net.minecraft.world.level.block.entity.*; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.ChestType; +import net.minecraft.world.phys.Vec3; +import org.joml.Matrix4f; +import org.joml.Quaternionf; + +/** + * Original oracle for block-entity rendering: each case builds a vanilla block + * entity for a block state, sets its animation fields, runs the real + * renderer's extractRenderState and submit, and captures every submitted + * model (vertices after setupAnim and the pose stack, sprite-local UVs, tint, + * light), text call and item. Level-backed inputs (light, chest lid + * openness, pot wobble) come from the case because the entity has no level. + * + * Input lines: case JSON. Output lines: {case, submits:[...]} or {case, error}. + */ +public final class VanillaBlockEntityRenderOracle { + private static final Map SPRITES = new IdentityHashMap<>(); + private static Object unsafe; + private static Method allocate; + + static String textureName(Identifier id) { + String path = id.getPath(); + if (path.startsWith("textures/")) path = path.substring(9); + if (path.endsWith(".png")) path = path.substring(0, path.length() - 4); + return id.getNamespace().equals("minecraft") ? path : id.getNamespace() + ":" + path; + } + + @SuppressWarnings("unchecked") + static Identifier renderTypeTexture(RenderType type) throws Exception { + Field state = RenderType.class.getDeclaredField("state"); + state.setAccessible(true); + Object setup = state.get(type); + Field textures = setup.getClass().getDeclaredField("textures"); + textures.setAccessible(true); + var map = (Map) textures.get(setup); + Object binding = map.get("Sampler0"); + if (binding == null) return null; + Method location = binding.getClass().getDeclaredMethod("location"); + location.setAccessible(true); + return (Identifier) location.invoke(binding); + } + + static JsonArray matrix(Matrix4f m) { + var a = new JsonArray(); + float[] f = new float[16]; + m.get(f); + for (float x : f) a.add(x); + return a; + } + + /** A vertex consumer recording [x,y,z,color,u,v,overlay,light,nx,ny,nz]. */ + static VertexConsumer recorder(List out) { + InvocationHandler handler = new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + if (method.isDefault()) return InvocationHandler.invokeDefault(proxy, method, args); + float[] v = out.isEmpty() ? null : out.get(out.size() - 1); + switch (method.getName()) { + case "addVertex" -> out.add(new float[] {(float) args[0], (float) args[1], (float) args[2], 0, 0, 0, 0, 0, 0, 0, 0}); + case "setColor" -> v[3] = Float.intBitsToFloat(args.length == 1 ? (int) args[0] + : ((int) args[3] << 24) | ((int) args[0] << 16) | ((int) args[1] << 8) | (int) args[2]); + case "setUv" -> { v[4] = (float) args[0]; v[5] = (float) args[1]; } + case "setUv1" -> v[6] = Float.intBitsToFloat(((int) args[0]) | ((int) args[1] << 16)); + case "setUv2" -> v[7] = Float.intBitsToFloat(((int) args[0]) | ((int) args[1] << 16)); + case "setNormal" -> { v[8] = (float) args[0]; v[9] = (float) args[1]; v[10] = (float) args[2]; } + default -> { } + } + return proxy; + } + }; + return (VertexConsumer) Proxy.newProxyInstance(VertexConsumer.class.getClassLoader(), new Class[] {VertexConsumer.class}, handler); + } + + static JsonArray vertices(List verts) { + var out = new JsonArray(); + for (float[] v : verts) { + var a = new JsonArray(); + a.add(v[0]); a.add(v[1]); a.add(v[2]); + a.add(Float.floatToRawIntBits(v[3])); + a.add(v[4]); a.add(v[5]); + a.add(Float.floatToRawIntBits(v[6])); a.add(Float.floatToRawIntBits(v[7])); + a.add(v[8]); a.add(v[9]); a.add(v[10]); + out.add(a); + } + return out; + } + + static String text(FormattedCharSequence sequence) { + var sb = new StringBuilder(); + sequence.accept((index, style, codepoint) -> { + sb.appendCodePoint(codepoint); + return true; + }); + return sb.toString(); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + static SubmitNodeCollector collector(JsonArray submits) { + InvocationHandler handler = new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + String name = method.getName(); + if (name.equals("order")) return proxy; + if (method.isDefault()) return InvocationHandler.invokeDefault(proxy, method, args); + var submit = new JsonObject(); + submit.addProperty("type", name); + switch (name) { + case "submitModel" -> { + var model = (Model) args[0]; + var pose = (PoseStack) args[2]; + var renderType = (RenderType) args[3]; + var uv = (UvMapping) args[7]; + String texture; + if (uv instanceof TextureAtlasSprite sprite && SPRITES.containsKey(sprite)) + texture = textureName(SPRITES.get(sprite).texture()); + else { + Identifier t = renderTypeTexture(renderType); + texture = t == null ? "?" : textureName(t); + } + submit.addProperty("texture", texture); + submit.addProperty("renderType", renderType.toString().split("\\[")[0]); + submit.addProperty("light", (int) args[4]); + submit.addProperty("overlay", (int) args[5]); + submit.addProperty("tint", (int) args[6]); + model.setupAnim(args[1]); + List verts = new ArrayList<>(); + model.renderToBuffer(pose, recorder(verts), (int) args[4], (int) args[5], (int) args[6]); + submit.add("vertices", vertices(verts)); + } + case "submitText" -> { + var pose = (PoseStack) args[0]; + submit.add("matrix", matrix(pose.last().pose())); + submit.addProperty("x", (float) args[1]); + submit.addProperty("y", (float) args[2]); + submit.addProperty("text", text((FormattedCharSequence) args[3])); + submit.addProperty("shadow", (boolean) args[4]); + submit.addProperty("mode", args[5].toString()); + submit.addProperty("light", (int) args[6]); + submit.addProperty("color", (int) args[7]); + submit.addProperty("background", (int) args[8]); + submit.addProperty("outline", (int) args[9]); + } + case "submitCustomGeometry" -> { + var pose = (PoseStack) args[0]; + var renderType = (RenderType) args[1]; + Identifier t = renderTypeTexture(renderType); + submit.addProperty("texture", t == null ? "?" : textureName(t)); + submit.addProperty("renderType", renderType.toString().split("\\[")[0]); + List verts = new ArrayList<>(); + ((SubmitNodeCollector.CustomGeometryRenderer) args[2]).render(pose.last(), recorder(verts)); + submit.add("vertices", vertices(verts)); + } + case "submitItem" -> { + var pose = (PoseStack) args[0]; + submit.add("matrix", matrix(pose.last().pose())); + submit.addProperty("context", args[1].toString()); + submit.addProperty("light", (int) args[2]); + } + case "submitMovingBlock", "submitBlockModel" -> { + var pose = (PoseStack) args[0]; + submit.add("matrix", matrix(pose.last().pose())); + } + case "submitCrumblingOverlay" -> { return null; } + default -> { } + } + submits.add(submit); + return null; + } + }; + return (SubmitNodeCollector) Proxy.newProxyInstance(SubmitNodeCollector.class.getClassLoader(), new Class[] {SubmitNodeCollector.class}, handler); + } + + static Field field(Class type, String name) throws NoSuchFieldException { + for (Class c = type; c != null; c = c.getSuperclass()) { + try { + Field f = c.getDeclaredField(name); + f.setAccessible(true); + return f; + } catch (NoSuchFieldException e) { + } + } + throw new NoSuchFieldException(name + " on " + type); + } + + static DyeColor dye(String name) { + return DyeColor.byName(name, DyeColor.BLACK); + } + + static SignText signText(JsonObject side) { + var lines = side.getAsJsonArray("lines"); + var messages = new ArrayList(); + for (int i = 0; i < 4; i++) messages.add(Component.literal(i < lines.size() ? lines.get(i).getAsString() : "")); + return new SignText(messages, messages, dye(side.get("color").getAsString()), side.get("glowing").getAsBoolean()); + } + + /** Block-entity fields that vanilla ticks; set from the case before extraction. */ + static void apply(BlockEntity be, JsonObject c) throws Exception { + if (be instanceof BellBlockEntity bell) { + bell.ticks = c.has("bellTicks") ? c.get("bellTicks").getAsInt() : 0; + bell.shaking = c.has("shake"); + if (bell.shaking) bell.clickDirection = Direction.byName(c.get("shake").getAsString()); + } else if (be instanceof ShulkerBoxBlockEntity) { + field(ShulkerBoxBlockEntity.class, "progressOld").setFloat(be, c.has("progressOld") ? c.get("progressOld").getAsFloat() : 0.0F); + field(ShulkerBoxBlockEntity.class, "progress").setFloat(be, c.has("progress") ? c.get("progress").getAsFloat() : 0.0F); + } else if (be instanceof ConduitBlockEntity conduit && c.has("conduit")) { + var k = c.getAsJsonObject("conduit"); + conduit.tickCount = k.get("tickCount").getAsInt(); + field(ConduitBlockEntity.class, "isActive").setBoolean(be, k.get("active").getAsBoolean()); + field(ConduitBlockEntity.class, "isHunting").setBoolean(be, k.get("hunting").getAsBoolean()); + field(ConduitBlockEntity.class, "activeRotation").setFloat(be, k.get("activeRotation").getAsFloat()); + } else if (be instanceof EnchantingTableBlockEntity table && c.has("book")) { + var b = c.getAsJsonObject("book"); + table.time = b.get("time").getAsInt(); + table.flip = b.get("flip").getAsFloat(); table.oFlip = b.get("oFlip").getAsFloat(); + table.open = b.get("open").getAsFloat(); table.oOpen = b.get("oOpen").getAsFloat(); + table.rot = b.get("rot").getAsFloat(); table.oRot = b.get("oRot").getAsFloat(); + } else if (be instanceof SkullBlockEntity && c.has("skullAnimation")) { + var a = c.getAsJsonArray("skullAnimation"); + field(SkullBlockEntity.class, "isAnimating").setBoolean(be, a.get(0).getAsBoolean()); + field(SkullBlockEntity.class, "animationTickCount").setInt(be, a.get(1).getAsInt()); + } else if (be instanceof DecoratedPotBlockEntity && c.has("sherds")) { + var s = c.getAsJsonArray("sherds"); + var items = new ArrayList>(); + for (var e : s) { + var id = e.getAsString(); + items.add(id.isEmpty() ? Optional.empty() + : Optional.of(new ItemStackTemplate(BuiltInRegistries.ITEM.getValue(Identifier.parse(id))))); + } + field(DecoratedPotBlockEntity.class, "decorations").set(be, new PotDecorations(items.get(0), items.get(1), items.get(2), items.get(3))); + } else if (be instanceof BannerBlockEntity && c.has("patterns")) { + var builder = new net.minecraft.world.level.block.entity.BannerPatternLayers.Builder(); + var registry = ParityData.access.lookupOrThrow(Registries.BANNER_PATTERN); + for (var e : c.getAsJsonArray("patterns")) { + var p = e.getAsJsonArray(); + var holder = registry.getOrThrow(ResourceKey.create(Registries.BANNER_PATTERN, Identifier.parse(p.get(0).getAsString()))); + builder.add(holder, dye(p.get(1).getAsString())); + } + field(BannerBlockEntity.class, "patterns").set(be, builder.build()); + } + } + + /** Render-state values vanilla reads from the level (absent here). */ + static void patch(BlockEntityRenderState rs, BlockState state, JsonObject c) { + if (rs instanceof ChestRenderState chest) { + chest.type = state.hasProperty(net.minecraft.world.level.block.ChestBlock.TYPE) + ? state.getValue(net.minecraft.world.level.block.ChestBlock.TYPE) : ChestType.SINGLE; + chest.facing = state.getValue(net.minecraft.world.level.block.ChestBlock.FACING); + chest.open = c.has("open") ? c.get("open").getAsFloat() : 0.0F; + } else if (rs instanceof DecoratedPotRenderState pot && c.has("wobble")) { + var w = c.getAsJsonArray("wobble"); + pot.wobbleStyle = DecoratedPotBlockEntity.WobbleStyle.valueOf(w.get(0).getAsString()); + pot.wobbleProgress = w.get(1).getAsFloat(); + } + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + 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()); + var models = new EntityModelSet(LayerDefinitions.createRoots()); + SpriteGetter sprites = id -> { + try { + var sprite = (TextureAtlasSprite) allocate.invoke(unsafe, TextureAtlasSprite.class); + SPRITES.put(sprite, id); + return sprite; + } catch (Exception e) { + throw new RuntimeException(e); + } + }; + var context = new BlockEntityRendererProvider.Context(null, null, null, null, models, font, sprites, null); + Map renderers = (Map) BlockEntityRenderers.createEntityRenderers(context); + var gson = new Gson(); + var out = new StringBuilder(); + for (String line : Files.readAllLines(Path.of(args[0]))) { + if (line.isBlank()) continue; + var c = JsonParser.parseString(line).getAsJsonObject(); + var result = new JsonObject(); + result.add("case", c); + try { + BlockState state = BlockStateParser.parseForBlock(BuiltInRegistries.BLOCK, c.get("block").getAsString(), false).blockState(); + var p = c.getAsJsonArray("pos"); + var pos = new BlockPos(p.get(0).getAsInt(), p.get(1).getAsInt(), p.get(2).getAsInt()); + var be = ((EntityBlock) state.getBlock()).newBlockEntity(pos, state); + if (be == null) throw new IllegalStateException("no block entity"); + apply(be, c); + var renderer = renderers.get(be.getType()); + if (renderer == null) throw new IllegalStateException("no renderer"); + float partial = c.get("partial").getAsFloat(); + var cam = c.getAsJsonArray("camera"); + var cameraPos = new Vec3(cam.get(0).getAsDouble(), cam.get(1).getAsDouble(), cam.get(2).getAsDouble()); + var rs = (BlockEntityRenderState) renderer.createRenderState(); + if (rs instanceof SignRenderState sign) { + // AbstractSignRenderer.extractRenderState reads Minecraft.getInstance(); its level-free part: + var signBe = (SignBlockEntity) be; + BlockEntityRenderState.extractBase(be, rs, null); + sign.maxTextLineWidth = signBe.getMaxTextLineWidth(); + sign.textLineHeight = signBe.getTextLineHeight(); + var s = c.getAsJsonObject("sign"); + sign.frontText = signText(s.getAsJsonObject("front")); + sign.backText = signText(s.getAsJsonObject("back")); + sign.drawOutline = s.get("near").getAsBoolean(); + if (rs instanceof StandingSignRenderState standing) { + standing.attachmentType = net.minecraft.world.level.block.PlainSignBlock.getAttachmentPoint(state); + sign.transformations = state.getBlock() instanceof net.minecraft.world.level.block.WallSignBlock + ? StandingSignRenderer.TRANSFORMATIONS.wallTransformation(state.getValue(net.minecraft.world.level.block.WallSignBlock.FACING)) + : StandingSignRenderer.TRANSFORMATIONS.freeTransformations(state.getValue(net.minecraft.world.level.block.StandingSignBlock.ROTATION)); + } else { + ((HangingSignRenderState) rs).attachmentType = net.minecraft.world.level.block.HangingSignBlock.getAttachmentPoint(state); + sign.transformations = state.getBlock() instanceof net.minecraft.world.level.block.WallHangingSignBlock + ? HangingSignRenderer.TRANSFORMATIONS.wallTransformation(state.getValue(net.minecraft.world.level.block.WallHangingSignBlock.FACING)) + : HangingSignRenderer.TRANSFORMATIONS.freeTransformations(state.getValue(net.minecraft.world.level.block.CeilingHangingSignBlock.ROTATION)); + } + } else { + renderer.extractRenderState(be, rs, partial, cameraPos, null); + } + var light = c.getAsJsonArray("light"); + rs.lightCoords = light.get(1).getAsInt() << 4 | light.get(0).getAsInt() << 20; + patch(rs, state, c); + var camera = new CameraRenderState(); + camera.pos = cameraPos; + float yaw = c.has("yaw") ? c.get("yaw").getAsFloat() : 0.0F, pitch = c.has("pitch") ? c.get("pitch").getAsFloat() : 0.0F; + // Camera.setRotation. + camera.orientation = new Quaternionf().rotationYXZ((float) Math.PI - yaw * (float) (Math.PI / 180.0), -pitch * (float) (Math.PI / 180.0), 0.0F); + var submits = new JsonArray(); + renderer.submit(rs, new PoseStack(), collector(submits), camera); + result.add("submits", submits); + } 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(6).reduce("", (a, b) -> a + b + " | ")); + } + out.append(gson.toJson(result)).append('\n'); + } + Files.writeString(Path.of(args[1]), out.toString(), StandardCharsets.UTF_8); + } +} diff --git a/tools/test_block_entity_render_parity.py b/tools/test_block_entity_render_parity.py new file mode 100644 index 000000000..672138543 --- /dev/null +++ b/tools/test_block_entity_render_parity.py @@ -0,0 +1,305 @@ +#!/usr/bin/env python3 +"""Compare block-entity rendering with the vanilla 26.3 client renderers. + +The Java oracle (VanillaBlockEntityRenderOracle) builds each case's vanilla +block entity, sets its animation fields, runs the real BlockEntityRenderer's +extractRenderState and submit, and captures what it submits: model vertices +after setupAnim and the pose stack (sprite-local UVs, tint, normal, light), +text calls and items. `examples/block_entity_render_fixture` replays the case +through Horizon's BlockEntityRenderer. Quads are matched by texture and +position; colours compare vanilla's tint times the entity shader's +`minecraft_mix_light` for the vanilla normal with Horizon's baked colour. + + test_block_entity_render_parity.py [--filter SUBSTRING] [--detail N] [--tolerance EPS] +""" +import argparse +import json +import math +import os +from pathlib import Path +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' +DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', + 'blue', 'brown', 'green', 'red', 'black'] +HORIZONTAL = ['north', 'south', 'west', 'east'] +ALL = HORIZONTAL + ['up', 'down'] +NO_OVERLAY = 10 << 16 + + +def cases(): + rng = random.Random(0x42454e44) + out = [] + + def add(block, **extra): + case = {'block': block, 'pos': [rng.randint(-40, 40), rng.randint(-20, 90), rng.randint(-40, 40)], + 'light': [rng.randint(0, 15), rng.randint(0, 15)], 'partial': round(rng.random(), 4), + 'camera': [0.5, 70.0, 0.5]} + case.update(extra) + out.append(case) + + for block in ['chest', 'trapped_chest', 'copper_chest', 'exposed_copper_chest', 'weathered_copper_chest', + 'oxidized_copper_chest', 'waxed_copper_chest', 'waxed_oxidized_copper_chest']: + for facing in HORIZONTAL: + for kind in ['single', 'left', 'right']: + add(f'minecraft:{block}[facing={facing},type={kind}]', open=rng.choice([0.0, 0.25, 0.7, 1.0])) + for facing in HORIZONTAL: + add(f'minecraft:ender_chest[facing={facing}]', open=rng.choice([0.0, 0.5, 1.0])) + texts = [['Hello', '', 'World', ''], ['A much longer line that cannot fit', 'mid', 'iii', 'WWWWWWWWWWWWWWW'], + ['', '', '', ''], ['x', 'Sign text', '#1 (test)', '!']] + for wood in ['oak', 'spruce', 'cherry', 'crimson', 'bamboo', 'pale_oak']: + signs = [f'minecraft:{wood}_sign[rotation={r}]' for r in (0, 3, 8, 13)] + \ + [f'minecraft:{wood}_wall_sign[facing={f}]' for f in HORIZONTAL] + \ + [f'minecraft:{wood}_hanging_sign[rotation={r},attached={a}]' for r, a in ((0, 'false'), (6, 'true'), (11, 'false'))] + \ + [f'minecraft:{wood}_wall_hanging_sign[facing={f}]' for f in HORIZONTAL] + for block in signs: + side = lambda: {'lines': rng.choice(texts), 'color': rng.choice(DYES), 'glowing': rng.random() < 0.4} + add(block, sign={'front': side(), 'back': side(), 'near': rng.random() < 0.5}) + patterns = ['minecraft:stripe_bottom', 'minecraft:creeper', 'minecraft:gradient', 'minecraft:flower', + 'minecraft:border', 'minecraft:skull', 'minecraft:globe', 'minecraft:piglin'] + for color in ['white', 'red', 'light_gray', 'black']: + for r in (0, 5, 12): + add(f'minecraft:{color}_banner[rotation={r}]', + patterns=[[rng.choice(patterns), rng.choice(DYES)] for _ in range(rng.randint(0, 3))]) + for f in HORIZONTAL: + add(f'minecraft:{color}_wall_banner[facing={f}]', + patterns=[[rng.choice(patterns), rng.choice(DYES)] for _ in range(rng.randint(0, 2))]) + add('minecraft:blue_banner[rotation=2]', patterns=[[rng.choice(patterns), rng.choice(DYES)] for _ in range(17)]) + for skull in ['skeleton_skull', 'wither_skeleton_skull', 'zombie_head', 'creeper_head', 'dragon_head', + 'piglin_head', 'player_head']: + wall = skull.replace('_skull', '_wall_skull').replace('_head', '_wall_head') + for r in (0, 4, 9): + add(f'minecraft:{skull}[rotation={r}]', skullAnimation=[rng.random() < 0.5, rng.randint(0, 80)]) + for f in HORIZONTAL: + add(f'minecraft:{wall}[facing={f}]', skullAnimation=[rng.random() < 0.5, rng.randint(0, 80)]) + for color in [None, 'white', 'light_gray', 'purple', 'black']: + name = 'shulker_box' if color is None else f'{color}_shulker_box' + for f in ALL: + p = rng.choice([0.0, 0.0, 0.3, 1.0]) + add(f'minecraft:{name}[facing={f}]', progress=p, progressOld=max(0.0, p - 0.1)) + for attach in ['floor', 'ceiling', 'single_wall', 'double_wall']: + for f in HORIZONTAL: + shake = rng.choice([None] + HORIZONTAL) + extra = {'bellTicks': rng.randint(0, 50)} + if shake: + extra['shake'] = shake + add(f'minecraft:bell[attachment={attach},facing={f}]', **extra) + sherds = ['', 'minecraft:brick', 'minecraft:angler_pottery_sherd', 'minecraft:skull_pottery_sherd', + 'minecraft:heart_pottery_sherd', 'minecraft:flow_pottery_sherd'] + for f in HORIZONTAL: + for wobble in [None, ['POSITIVE', 0.3], ['NEGATIVE', 0.6], ['POSITIVE', 1.2]]: + extra = {'sherds': [rng.choice(sherds) for _ in range(4)]} + if wobble: + extra['wobble'] = wobble + add(f'minecraft:decorated_pot[facing={f}]', **extra) + for active in (False, True): + for _ in range(4): + add('minecraft:conduit', conduit={'tickCount': rng.randint(0, 400), 'active': active, + 'hunting': rng.random() < 0.5, 'activeRotation': rng.uniform(0, 300)}, + yaw=round(rng.uniform(-180, 180), 2), pitch=round(rng.uniform(-90, 90), 2)) + for _ in range(6): + o = rng.random() + add('minecraft:enchanting_table', book={'time': rng.randint(0, 2000), 'flip': rng.uniform(-3, 3), + 'oFlip': rng.uniform(-3, 3), 'open': o, 'oOpen': max(0.0, o - 0.1), + 'rot': rng.uniform(-3.1, 3.1), 'oRot': rng.uniform(-3.1, 3.1)}) + for f in HORIZONTAL: + add(f'minecraft:lectern[facing={f},has_book=true]') + add(f'minecraft:lectern[facing={f},has_book=false]') + for prefix in ['', 'exposed_', 'weathered_', 'oxidized_', 'waxed_']: + for pose in ['standing', 'running', 'sitting', 'star']: + add(f'minecraft:{prefix}copper_golem_statue[facing={rng.choice(HORIZONTAL)},copper_golem_pose={pose}]') + for block in ['end_portal', 'end_gateway', 'beacon', 'campfire[facing=north]', 'spawner', + 'trial_spawner', 'vault', 'suspicious_sand', 'oak_shelf[facing=east]']: + add('minecraft:' + block) + return out + + +def light_coords(light): + """Horizon light (sky*16 low byte, block*16 next) as vanilla light coords.""" + return ((light & 0xFF) << 16) | ((light >> 8) & 0xFF) + + +def lights(): + def norm(v): + n = math.sqrt(sum(x * x for x in v)) + return [x / n for x in v] + return norm([0.2, 1.0, -0.7]), norm([-0.2, 1.0, 0.7]) + + +L0, L1 = lights() + + +def mix(normal): + d = lambda l: max(0.0, sum(a * b for a, b in zip(l, normal))) + return min(1.0, (d(L0) + d(L1)) * 0.6 + 0.4) + + +def vanilla_quads(submits): + quads, other = [], [] + for s in submits: + if s['type'] != 'submitModel': + other.append(s) + continue + verts = s['vertices'] + for i in range(0, len(verts), 4): + q = verts[i:i + 4] + tint = q[0][3] & 0xFFFFFFFF + b = mix(q[0][8:11]) + ch = lambda shift: int(((tint >> shift) & 255) * b) + quads.append({'texture': s['texture'], 'v': [v[:3] + v[4:6] for v in q], + 'rgb': [ch(16), ch(8), ch(0)], 'alpha': tint >> 24, 'light': q[0][7], + 'overlay': q[0][6], 'type': s['renderType']}) + return quads, other + + +def area(q): + import itertools + p = [v[:3] for v in q] + a = [p[1][i] - p[0][i] for i in range(3)] + b = [p[2][i] - p[0][i] for i in range(3)] + c = [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] + a2 = [p[3][i] - p[0][i] for i in range(3)] + d = [b[1] * a2[2] - b[2] * a2[1], b[2] * a2[0] - b[0] * a2[2], b[0] * a2[1] - b[1] * a2[0]] + return math.sqrt(sum(x * x for x in c)) + math.sqrt(sum(x * x for x in d)) + + +def pair(vq, rq): + """Matches quads of the same texture globally by ascending vertex distance.""" + candidates = [] + for i, a in enumerate(vq): + for j, b in enumerate(rq): + if a['texture'] == b['texture']: + d = sum((a['v'][k][c] - b['v'][k][c]) ** 2 for k in range(4) for c in range(5)) + candidates.append((d, i, j)) + candidates.sort() + match, used = {}, set() + for d, i, j in candidates: + if i not in match and j not in used: + match[i] = j + used.add(j) + return [(a, rq[match[i]] if i in match else None) for i, a in enumerate(vq)], \ + [b for j, b in enumerate(rq) if j not in used] + + +def compare_case(v, r, tol): + problems = [] + vq, other = vanilla_quads(v['submits']) + for s in other: + if s['type'] == 'submitText': + continue + problems.append(f'unsupported vanilla submit {s["type"]}') + rq = r.get('quads', []) + if len(vq) != len(rq): + tex = lambda qs: sorted({q['texture'] for q in qs}) + problems.append(f'{len(vq)} vanilla quads {tex(vq)} vs {len(rq)} Horizon quads {tex(rq)}') + pairs, extra = pair(vq, rq) + for b in extra[:1]: + problems.append(f'extra Horizon quad {b["texture"]} {b["v"]}') + for a, b in pairs: + if b is None: + problems.append(f'missing {a["texture"]} quad {a["v"]}') + break + bad = [(i, j) for i in range(4) for j in range(5) if abs(a['v'][i][j] - b['v'][i][j]) > tol * (1 + abs(a['v'][i][j]))] + if bad: + problems.append(f'{a["texture"]} vertices {a["v"]} != {b["v"]}') + break + if a['overlay'] != NO_OVERLAY: + problems.append(f'overlay {a["overlay"]}') + got = b['color'] + rgb = [got & 255, (got >> 8) & 255, (got >> 16) & 255] + # A zero-area quad shows nothing: vanilla shades it by its face normal, Horizon cannot derive one. + if area(a['v']) > 1e-9 and (any(abs(x - y) > 1 for x, y in zip(a['rgb'], rgb)) or (got >> 24) != a['alpha']): + problems.append(f'{a["texture"]} colour {a["rgb"]}/{a["alpha"]} != {rgb}/{got >> 24} at {a["v"]}') + break + if a['light'] != light_coords(b['light']): + problems.append(f'{a["texture"]} light {a["light"]:#x} != {light_coords(b["light"]):#x}') + break + vt = [s for s in v['submits'] if s['type'] == 'submitText' and s['text']] + rt = r.get('texts', []) + if len(vt) != len(rt): + problems.append(f'{len(vt)} vanilla texts {[t["text"] for t in vt]} vs {len(rt)} Horizon texts {[t["text"] for t in rt]}') + for a, b in zip(vt, rt): + for k in ('text', 'x', 'y', 'color', 'outline', 'light'): + av, bv = a[k], b[k] + if k in ('color', 'outline'): + av &= 0xFFFFFFFF + if (abs(av - bv) > 1e-4) if isinstance(av, float) else av != bv: + problems.append(f'text {a["text"]!r} {k} {av!r} != {bv!r}') + if any(abs(x - y) > tol * (1 + abs(x)) for x, y in zip(a['matrix'], b['matrix'])): + problems.append(f'text {a["text"]!r} matrix {a["matrix"]} != {b["matrix"]}') + return problems + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--filter', default='') + parser.add_argument('--detail', type=int, default=2) + parser.add_argument('--tolerance', type=float, default=2e-5) + args = parser.parse_args() + lock, jars, _ = base.verify_artifacts() + libraries = baking.client_libraries() + build = lab.LOCAL / 'rust-block-entity-render-parity'; build.mkdir(parents=True, exist_ok=True) + resources = lab.LOCAL / 'horizon-client' / '26.3' + chosen = [c for c in cases() if args.filter in c['block']] + 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', 'VanillaBlockEntityRenderOracle'))], 'compile-java') + run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockEntityRenderOracle', + inputs, build / 'vanilla.jsonl'], 'vanilla') + vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] + textures = sorted({s['texture'] for v in vanilla for s in v.get('submits', []) if 'texture' in s}) + (build / 'textures.txt').write_text(''.join(t + '\n' for t in textures)) + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'block_entity_render_fixture', '--', + resources, inputs, build / 'textures.txt', build / 'rust.jsonl'], 'rust') + rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] + assert len(vanilla) == len(rust), (len(vanilla), len(rust)) + groups, errors, skipped, passed = {}, {}, {}, 0 + for v, r in zip(vanilla, rust): + block = v['case']['block'].split('[')[0] + if 'error' in v: + errors.setdefault(block, v['error']); continue + if 'skip' in r: + if not v['submits']: + passed += 1 # vanilla submits nothing either (e.g. a lectern without a book) + else: + skipped.setdefault(r['skip'], set()).add(block) + continue + problems = compare_case(v, r, args.tolerance) + if problems: + groups.setdefault(block, []).append((v['case'], problems)) + else: + passed += 1 + for reason, blocks in sorted(skipped.items()): + print(f'NOT RENDERED by Horizon ({reason}): {", ".join(sorted(blocks))}') + for block, error in sorted(errors.items()): + print(f'ORACLE ERROR {block}: {error}') + for block, items in sorted(groups.items()): + print(f'MISMATCH {block}: {len(items)} cases') + for case, problems in items[:args.detail]: + print(' ', json.dumps(case)) + for p in problems[:4]: + print(' ', p[:600]) + total = len(vanilla) + print(f'{passed}/{total} cases match; {sum(len(b) for b in skipped.values())} not rendered; {len(errors)} oracle errors') + if groups or errors or skipped: + sys.exit(1) + print('block entity render parity ok') + + +if __name__ == '__main__': + main() From ccdf49d3e5aad447d3f987138115afaede2d7b41 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:44:58 +0200 Subject: [PATCH 07/28] Play every sound through the vanilla SoundEngine model Audio now keeps vanilla SoundEngine bookkeeping over a mixer that stands in for OpenAL sources (gain, pitch, linear distance attenuation, looping, relative, source states, the 247/8 channel pools), ticks once per client tick with pauseAllExcept/resume and stops everything when the world closes. MusicManager holds a forMusic instance and checks isActive as vanilla does; the ambient handlers play LoopSoundInstance, UnderLiquid* and mood instances, the enter/exit sounds seeded from the level random; jukebox songs use forJukeboxSong instead of a hand-made volume ramp. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/ambience.rs | 430 +++++------ crates/horizon-client/src/audio.rs | 847 +++++++++++----------- crates/horizon-client/src/game.rs | 12 +- crates/horizon-client/src/game/control.rs | 2 +- crates/horizon-client/src/game/jukebox.rs | 27 +- crates/horizon-client/src/game/music.rs | 104 +-- crates/horizon-client/src/music.rs | 254 ++++--- crates/horizon-client/src/sound_engine.rs | 83 +++ 8 files changed, 892 insertions(+), 867 deletions(-) diff --git a/crates/horizon-client/src/ambience.rs b/crates/horizon-client/src/ambience.rs index c447d1450..860a080a6 100644 --- a/crates/horizon-client/src/ambience.rs +++ b/crates/horizon-client/src/ambience.rs @@ -1,7 +1,9 @@ //! The player's ambient sound handlers: `BiomeAmbientSoundsHandler` (biome //! loops with 40-tick cross-fades, random additions, cave mood) driven by the //! `minecraft:audio/ambient_sounds` attribute, `UnderwaterAmbientSoundHandler` -//! and the underwater loop (`UnderLiquidAmbientSoundInstance`). +//! and `LocalPlayer.updateIsUnderwater` (enter/exit sounds and the +//! `UnderLiquidAmbientSoundInstance` loop), played through the sound engine. +use crate::sound_engine::{AMBIENT, InstanceId, SoundEngine, SoundInstance, Sounds}; use horizon_core::random::{LegacyRandom, RandomSource}; use serde_json::Value; use std::{collections::HashMap, fs, path::Path}; @@ -80,87 +82,35 @@ impl AmbientTables { .unwrap_or_default() } } -/// The sound engine side of the handlers. -pub trait AmbientOutput { - /// A relative tickable instance; None when it could not start. - fn play_tracked(&mut self, event: &str, volume: f32, looping: bool) -> Option; - fn set_volume(&mut self, id: u64, volume: f32); - fn stop(&mut self, id: u64); - fn is_active(&self, id: u64) -> bool; - /// A positional one-shot (`SimpleSoundInstance`, linear attenuation). - fn play_at(&mut self, event: &str, at: [f64; 3]); -} -impl AmbientOutput for crate::audio::Audio { - fn play_tracked(&mut self, event: &str, volume: f32, looping: bool) -> Option { - crate::audio::Audio::play_tracked(self, event, volume, looping) - } - fn set_volume(&mut self, id: u64, volume: f32) { - self.set_tracked_volume(id, volume); - } - fn stop(&mut self, id: u64) { - self.stop_tracked(id); - } - fn is_active(&self, id: u64) -> bool { - self.tracked_active(id) - } - fn play_at(&mut self, event: &str, at: [f64; 3]) { - self.play(event, Some(at), 1.0, 1.0); - } -} -/// `BiomeAmbientSoundsHandler.LoopSoundInstance`. -struct LoopSound { - id: Option, - fade: i32, - direction: i32, - stopped: bool, -} -impl LoopSound { - fn tick(&mut self) -> f32 { - if self.fade < 0 { - self.stopped = true; - } - self.fade += self.direction; - (self.fade as f32 / 40.0).clamp(0.0, 1.0) - } - fn fade_out(&mut self) { - self.fade = self.fade.min(40); - self.direction = -1; - } - fn fade_in(&mut self) { - self.fade = self.fade.max(0); - self.direction = 1; - } -} /// What the handlers read about the player and level each tick. pub struct AmbientContext<'a> { + /// `AMBIENT_SOUNDS` at the player's position. pub sounds: &'a AmbientSounds, - /// Feet and eye position. + /// The player's position (feet) and eye height. pub position: [f64; 3], pub eye_y: f64, + /// `isEyeInFluid(WATER)` this tick (`Entity.updateIsUnderwater`). pub underwater: bool, - /// Raw (sky, block) light at a block. + pub spectator: bool, + /// `Level.getBrightness` (sky, block) at a block. pub light: &'a dyn Fn([i32; 3]) -> (u8, u8), } /// The local player's ambient sound handlers. pub struct Ambience { /// The client level's random. - random: LegacyRandom, - loops: Vec<(String, LoopSound)>, + pub random: LegacyRandom, + /// `BiomeAmbientSoundsHandler.loopSounds` (insertion order). + loops: Vec<(String, InstanceId)>, previous_loop: Option, pub moodiness: f32, + /// `UnderwaterAmbientSoundHandler.tickDelay`. underwater_delay: i32, - /// The underwater loop instance and its fade. - underwater_loop: Option<(u64, i32)>, - /// UnderLiquidSubSound instances (stop when the player leaves the water). - sub_sounds: Vec, + /// `LocalPlayer.wasUnderwater`. was_underwater: bool, } impl Default for Ambience { fn default() -> Self { - let seed = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |d| d.as_nanos() as i64); - Self::new(seed) + Self::new(crate::sound_engine::unique_seed()) } } impl Ambience { @@ -171,53 +121,54 @@ impl Ambience { previous_loop: None, moodiness: 0.0, underwater_delay: 0, - underwater_loop: None, - sub_sounds: Vec::new(), was_underwater: false, } } - /// Stop everything (leaving the world). - pub fn clear(&mut self, out: &mut impl AmbientOutput) { - for (_, l) in self.loops.drain(..) { - if let Some(id) = l.id { - out.stop(id); - } - } - if let Some((id, _)) = self.underwater_loop.take() { - out.stop(id); - } - for id in self.sub_sounds.drain(..) { - out.stop(id); + /// `LocalPlayer.isUnderWater`. + pub fn was_underwater(&self) -> bool { + self.was_underwater + } + /// A new player (leaving or changing worlds): fresh handlers. + pub fn clear(&mut self, sounds: &mut impl Sounds) { + for (_, id) in self.loops.drain(..) { + sounds.release(id); } self.previous_loop = None; self.moodiness = 0.0; + self.underwater_delay = 0; self.was_underwater = false; } - /// `LocalPlayer.updateIsUnderwater` enter/exit sounds and loop, then - /// `UnderwaterAmbientSoundHandler`, `BubbleColumn` (absent) and - /// `BiomeAmbientSoundsHandler` ticks, then the tickable instances. - pub fn tick(&mut self, ctx: &AmbientContext, out: &mut impl AmbientOutput) { - let feet = ctx.position; - if !self.was_underwater && ctx.underwater { - out.play_at("minecraft:ambient.underwater.enter", feet); - if let Some((id, _)) = self.underwater_loop.take() { - out.stop(id); - } - self.underwater_loop = out - .play_tracked("minecraft:ambient.underwater.loop", 0.0, true) - .map(|id| (id, 0)); - } - if self.was_underwater && !ctx.underwater { - out.play_at("minecraft:ambient.underwater.exit", feet); - } - self.was_underwater = ctx.underwater; - self.tick_underwater(ctx, out); - self.tick_biome(ctx, out); - self.tick_instances(ctx, out); + /// `ClientLevel.playLocalSound(x, y, z, sound, AMBIENT, 1, 1, false)`. + fn play_local(&mut self, event: &str, at: [f64; 3], sounds: &mut impl Sounds) { + let seed = self.random.next_long(); + let instance = SoundInstance::at(event, AMBIENT, 1.0, 1.0, LegacyRandom::new(seed), at); + sounds.play_instance(instance, false); } - fn tick_underwater(&mut self, ctx: &AmbientContext, out: &mut impl AmbientOutput) { + /// `LocalPlayer.updateIsUnderwater`, then the `ambientSoundHandlers` + /// (underwater, bubble column, biome) as `LocalPlayer.tick` runs them. + pub fn tick(&mut self, ctx: &AmbientContext, sounds: &mut impl Sounds) { + let old = self.was_underwater; + self.was_underwater = ctx.underwater; + if !ctx.spectator { + if !old && ctx.underwater { + self.play_local("minecraft:ambient.underwater.enter", ctx.position, sounds); + let instance = SoundInstance::under_liquid_loop( + "minecraft:ambient.underwater.loop", + SoundEngine::unseeded(), + ); + sounds.play_instance(instance, false); + } + if old && !ctx.underwater { + self.play_local("minecraft:ambient.underwater.exit", ctx.position, sounds); + } + } + self.tick_underwater(sounds); + self.tick_biome(ctx, sounds); + } + /// `UnderwaterAmbientSoundHandler.tick`. + fn tick_underwater(&mut self, sounds: &mut impl Sounds) { self.underwater_delay -= 1; - if self.underwater_delay <= 0 && ctx.underwater { + if self.underwater_delay <= 0 && self.was_underwater { let rand = self.random.next_float(); let sound = if rand < 1.0E-4 { Some("minecraft:ambient.underwater.loop.additions.ultra_rare") @@ -230,147 +181,121 @@ impl Ambience { }; if let Some(sound) = sound { self.underwater_delay = 0; - if let Some(id) = out.play_tracked(sound, 1.0, false) { - self.sub_sounds.push(id); - } + let instance = SoundInstance::under_liquid_sub(sound, SoundEngine::unseeded()); + sounds.play_instance(instance, false); } } } - fn tick_biome(&mut self, ctx: &AmbientContext, out: &mut impl AmbientOutput) { - self.loops.retain(|(_, l)| !l.stopped); - let sounds = ctx.sounds; - if sounds.r#loop != self.previous_loop { - self.previous_loop = sounds.r#loop.clone(); - for (_, l) in &mut self.loops { - l.fade_out(); + /// `BiomeAmbientSoundsHandler.tick`. + fn tick_biome(&mut self, ctx: &AmbientContext, sounds: &mut impl Sounds) { + let mut kept = Vec::new(); + for (event, id) in std::mem::take(&mut self.loops) { + if sounds.engine().instance(id).is_some_and(|i| i.stopped) { + sounds.release(id); + } else { + kept.push((event, id)); } - if let Some(event) = &sounds.r#loop { - if !self.loops.iter().any(|(e, _)| e == event) { - let id = out.play_tracked(event, 0.0, true); - self.loops.push(( - event.clone(), - LoopSound { - id, - fade: 0, - direction: 0, - stopped: false, - }, - )); + } + self.loops = kept; + let current = ctx + .sounds + .r#loop + .as_deref() + .map(crate::sound_events::normalize); + if current != self.previous_loop { + self.previous_loop = current.clone(); + for (_, id) in &self.loops { + if let Some(i) = sounds.engine().instance_mut(*id) { + i.fade_out(); } - if let Some((_, l)) = self.loops.iter_mut().find(|(e, _)| e == event) { - l.fade_in(); + } + if let Some(event) = current { + let id = match self.loops.iter().find(|(e, _)| *e == event) { + Some((_, id)) => *id, + None => { + let instance = SoundInstance::biome_loop(&event, SoundEngine::unseeded()); + let id = sounds.engine().add(instance, true); + sounds.play_id(id); + self.loops.push((event, id)); + id + } + }; + if let Some(i) = sounds.engine().instance_mut(id) { + i.fade_in(); } } } - for (sound, chance) in &sounds.additions { - if self.random.next_double() < *chance - && let Some(id) = out.play_tracked(sound, 1.0, false) - { - // forAmbientAddition: a one-shot nobody ticks. - let _ = id; + for (sound, chance) in &ctx.sounds.additions { + if self.random.next_double() < *chance { + let event = crate::sound_events::normalize(sound); + let instance = SoundInstance::for_ambient_addition(&event, SoundEngine::unseeded()); + sounds.play_instance(instance, false); } } - let Some(mood) = &sounds.mood else { return }; + let Some(mood) = &ctx.sounds.mood else { return }; let extent = mood.block_search_extent; let span = extent * 2 + 1; - let mut offset = || self.random.next_int_bound(span).unwrap_or(0) - extent; - let (dx, dy, dz) = (offset(), offset(), offset()); - let sample = [ - (ctx.position[0] + f64::from(dx)).floor() as i32, - (ctx.eye_y + f64::from(dy)).floor() as i32, - (ctx.position[2] + f64::from(dz)).floor() as i32, - ]; + let x = ctx.position[0] + f64::from(self.random.next_int_bound(span).unwrap_or(0)) + - f64::from(extent); + let y = ctx.eye_y + f64::from(self.random.next_int_bound(span).unwrap_or(0)) + - f64::from(extent); + let z = ctx.position[2] + f64::from(self.random.next_int_bound(span).unwrap_or(0)) + - f64::from(extent); + let sample = [x.floor() as i32, y.floor() as i32, z.floor() as i32]; let (sky, block) = (ctx.light)(sample); if sky > 0 { self.moodiness -= f32::from(sky) / 15.0 * 0.001; } else { - self.moodiness -= (f32::from(block) - 1.0) / mood.tick_delay as f32; + self.moodiness -= (i32::from(block) - 1) as f32 / mood.tick_delay as f32; } if self.moodiness >= 1.0 { - let d = [ - f64::from(sample[0]) + 0.5 - ctx.position[0], - f64::from(sample[1]) + 0.5 - ctx.eye_y, - f64::from(sample[2]) + 0.5 - ctx.position[2], - ]; - let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); + let sample_x = f64::from(sample[0]) + 0.5; + let sample_y = f64::from(sample[1]) + 0.5; + let sample_z = f64::from(sample[2]) + 0.5; + let dx = sample_x - ctx.position[0]; + let dy = sample_y - ctx.eye_y; + let dz = sample_z - ctx.position[2]; + let distance = (dx * dx + dy * dy + dz * dz).sqrt(); let source = distance + mood.offset; - out.play_at( - &mood.sound, - [ - ctx.position[0] + d[0] / distance * source, - ctx.eye_y + d[1] / distance * source, - ctx.position[2] + d[2] / distance * source, - ], - ); + let at = [ + ctx.position[0] + dx / distance * source, + ctx.eye_y + dy / distance * source, + ctx.position[2] + dz / distance * source, + ]; + // The mood sound draws from the level random itself. + let event = crate::sound_events::normalize(&mood.sound); + let instance = SoundInstance::for_ambient_mood(&event, self.random.clone(), at); + let id = sounds.engine().add(instance, true); + sounds.play_id(id); + if let Some(i) = sounds.engine().instance(id) { + self.random = i.random.clone(); + } + sounds.release(id); self.moodiness = 0.0; } else { self.moodiness = self.moodiness.max(0.0); } } - /// The tickable instances' own ticks (SoundEngine.tickInGameSound). - fn tick_instances(&mut self, ctx: &AmbientContext, out: &mut impl AmbientOutput) { - for (_, l) in &mut self.loops { - let volume = l.tick(); - if let Some(id) = l.id { - if l.stopped { - out.stop(id); - } else { - out.set_volume(id, volume); - } - } - } - // UnderLiquidAmbientSoundInstance: +1 per tick under water, -2 out of it. - if let Some((id, fade)) = self.underwater_loop.as_mut() { - if *fade >= 0 { - *fade += if ctx.underwater { 1 } else { -2 }; - *fade = (*fade).min(40); - out.set_volume(*id, (*fade as f32 / 40.0).clamp(0.0, 1.0)); - } else { - out.stop(*id); - self.underwater_loop = None; - } - } - // UnderLiquidSubSound: stops when the player leaves the water. - self.sub_sounds.retain(|&id| { - let keep = ctx.underwater && out.is_active(id); - if !keep { - out.stop(id); - } - keep - }); - } } #[cfg(test)] mod tests { use super::*; + use crate::sound_engine::{Bound, TickContext, test_backend::Null}; + use crate::sound_events::SoundRegistry; - #[derive(Default)] - struct Fake { - next: u64, - live: HashMap, - at: Vec, - } - impl AmbientOutput for Fake { - fn play_tracked(&mut self, event: &str, volume: f32, _looping: bool) -> Option { - self.next += 1; - self.live.insert(self.next, (event.to_owned(), volume)); - Some(self.next) - } - fn set_volume(&mut self, id: u64, volume: f32) { - if let Some(v) = self.live.get_mut(&id) { - v.1 = volume; - } - } - fn stop(&mut self, id: u64) { - self.live.remove(&id); - } - fn is_active(&self, id: u64) -> bool { - self.live.contains_key(&id) - } - fn play_at(&mut self, event: &str, _at: [f64; 3]) { - self.at.push(event.to_owned()); - } + fn engine() -> SoundEngine { + let mut registry = SoundRegistry::default(); + registry.add_file( + "minecraft", + br#"{"crimson": {"sounds": ["c"]}, "warped": {"sounds": ["w"]}, + "ambient.cave": {"sounds": ["a", "b"]}, + "ambient.underwater.loop": {"sounds": ["u"]}, + "ambient.underwater.enter": {"sounds": ["e"]}, + "ambient.underwater.exit": {"sounds": ["x"]}}"#, + &|_, _| true, + ); + SoundEngine::new(registry) } fn ctx<'a>( sounds: &'a AmbientSounds, @@ -382,49 +307,58 @@ mod tests { position: [0.5, 10.0, 0.5], eye_y: 11.62, underwater, + spectator: false, light, } } #[test] fn loops_cross_fade_over_forty_ticks() { + let (mut engine, mut backend) = (engine(), Null::default()); let mut a = Ambience::new(1); - let mut out = Fake::default(); - let dark = |_: [i32; 3]| (15u8, 0u8); + let lit = |_: [i32; 3]| (15u8, 0u8); let crimson = AmbientSounds { - r#loop: Some("crimson".into()), + r#loop: Some("minecraft:crimson".into()), ..Default::default() }; - for _ in 0..40 { - a.tick(&ctx(&crimson, false, &dark), &mut out); - } - assert_eq!(out.live.values().map(|v| v.1).collect::>(), [1.0]); let warped = AmbientSounds { - r#loop: Some("warped".into()), + r#loop: Some("minecraft:warped".into()), ..Default::default() }; + let tick = + |a: &mut Ambience, s: &AmbientSounds, engine: &mut SoundEngine, backend: &mut Null| { + a.tick( + &ctx(s, false, &lit), + &mut Bound { + engine: &mut *engine, + backend: &mut *backend, + }, + ); + engine.tick(false, &TickContext::default(), backend); + }; + for _ in 0..40 { + tick(&mut a, &crimson, &mut engine, &mut backend); + } for _ in 0..20 { - a.tick(&ctx(&warped, false, &dark), &mut out); + tick(&mut a, &warped, &mut engine, &mut backend); } - let mut volumes: Vec<_> = out.live.values().map(|v| (v.0.clone(), v.1)).collect(); - volumes.sort_by(|x, y| x.0.cmp(&y.0)); - assert_eq!( - volumes, - [("crimson".to_owned(), 0.5), ("warped".to_owned(), 0.5)] - ); + let volumes: Vec = a + .loops + .iter() + .map(|(_, id)| engine.instance(*id).unwrap().volume) + .collect(); + assert_eq!(volumes, [0.5, 0.5]); for _ in 0..30 { - a.tick(&ctx(&warped, false, &dark), &mut out); + tick(&mut a, &warped, &mut engine, &mut backend); } - assert_eq!( - out.live.values().map(|v| v.0.as_str()).collect::>(), - ["warped"] - ); + assert_eq!(a.loops.len(), 1); } #[test] fn mood_builds_in_the_dark_and_plays_a_cave_sound() { + let (mut engine, mut backend) = (engine(), Null::default()); + engine.listening = true; let mut a = Ambience::new(2); - let mut out = Fake::default(); let cave = |_: [i32; 3]| (0u8, 0u8); let sounds = AmbientSounds { mood: Some(Mood { @@ -435,31 +369,19 @@ mod tests { }), ..Default::default() }; - // Block light 0: +1/6000 per tick (float), so the sound plays around tick 6000. let mut ticks = 0; - while out.at.is_empty() && ticks < 7000 { - a.tick(&ctx(&sounds, false, &cave), &mut out); + while engine.notifications.is_empty() && ticks < 7000 { + a.tick( + &ctx(&sounds, false, &cave), + &mut Bound { + engine: &mut engine, + backend: &mut backend, + }, + ); ticks += 1; } assert!((5990..=6010).contains(&ticks), "{ticks}"); - assert_eq!(out.at, ["minecraft:ambient.cave"]); + assert_eq!(engine.notifications[0].identifier, "minecraft:ambient.cave"); assert_eq!(a.moodiness, 0.0); } - - #[test] - fn entering_water_plays_enter_and_fades_the_loop_in() { - let mut a = Ambience::new(3); - let mut out = Fake::default(); - let lit = |_: [i32; 3]| (15u8, 0u8); - let none = AmbientSounds::default(); - a.tick(&ctx(&none, true, &lit), &mut out); - assert_eq!(out.at, ["minecraft:ambient.underwater.enter"]); - let id = a.underwater_loop.unwrap().0; - assert_eq!(out.live[&id].1, 1.0 / 40.0); - a.tick(&ctx(&none, false, &lit), &mut out); - assert_eq!(out.at.last().unwrap(), "minecraft:ambient.underwater.exit"); - // Fade 1 -> -1 stops on the next tick. - a.tick(&ctx(&none, false, &lit), &mut out); - assert!(!out.live.contains_key(&id)); - } } diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index d673d4031..773bf064d 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -1,9 +1,16 @@ -//! Sound playback: `sounds.json` events with weighted variants, Ogg/Vorbis -//! decoding, and a small mixer with vanilla's linear distance attenuation -//! (`SoundInstance.Attenuation.LINEAR`, default range 16 blocks) and stereo panning. +//! Sound playback: vanilla's `SoundEngine` bookkeeping (`sound_engine`) over a +//! small mixer standing in for OpenAL: one channel per source with its gain, +//! pitch, linear distance attenuation (`AL_LINEAR_DISTANCE`, reference 0, +//! rolloff 1), looping, relative flag and source state, Ogg/Vorbis decoding +//! (streams on a worker thread) and stereo panning. use crate::Result; +use crate::sound_engine::{ + Attenuation, Backend, Bound, ChannelId, InstanceId, PlayResult, SoundEngine, SoundInstance, + Sounds, TickContext, +}; +use crate::sound_events::{Sound, SoundRegistry}; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; -use serde_json::Value; +use horizon_core::random::{LegacyRandom, RandomSource}; use std::{ collections::HashMap, fs, @@ -11,46 +18,32 @@ use std::{ sync::{Arc, Mutex}, }; -#[derive(Clone, Debug)] -struct Variant { - name: String, - volume: f32, - pitch: f32, - weight: u32, - attenuation: f32, - is_event: bool, +/// An OpenAL source's state. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum State { + Initial, + Playing, + Paused, + Stopped, } -struct Voice { - samples: Arc>, +/// An OpenAL source. +struct Channel { + samples: Option<(Arc>, u32)>, position: f64, - step: f64, - left: f32, - right: f32, - /// The sound event and `SoundSource` index (what `/stopsound` matches). - event: Arc, - source: usize, + state: State, + gain: f32, + pitch: f32, + /// `AL_LINEAR_DISTANCE` max distance, or no attenuation. + linear: Option, + looping: bool, + at: [f32; 3], + relative: bool, } #[derive(Default)] struct Mixer { - voices: Vec, - /// The streaming music track (`SoundSource.MUSIC`), kept apart from the - /// voice cap and scaled by `music_gain` (MusicManager's fade). - music: Option, - music_gain: f32, - /// Tickable sound instances the game keeps a handle to (ambient loops). - tracked: Vec, -} -struct Tracked { - id: u64, - voice: Voice, - looping: bool, - volume: f32, -} -/// The current music track: decoding on a worker until the voice exists. -struct MusicTrack { - event: String, - /// Set by the decoder thread once the voice is in the mixer (or failed). - ready: Arc, + channels: HashMap, + listener: [f64; 3], + listener_yaw: f32, } /// A sound the player could have heard (`SoundEventListener.onPlaySound`): /// what the subtitle overlay needs. @@ -58,30 +51,31 @@ struct MusicTrack { pub struct Heard { /// The `subtitle` translation key of the sound event. pub subtitle: String, - /// Where it played (None = relative to the listener, e.g. UI sounds). + /// The instance's position (relative sounds report their raw coordinates). pub at: Option<[f64; 3]>, /// `SoundEngine.getRange`: infinite for relative and non-attenuated sounds. pub range: f32, pub looping: bool, } +/// The mixer side of the engine (`Backend`). +pub struct MixerBackend { + mixer: Arc>, + root: PathBuf, + cache: HashMap>, u32)>>, + next: ChannelId, + live: bool, +} pub struct Audio { _stream: Option, - /// `subtitle` keys of `sounds.json` events. - subtitles: HashMap, + pub engine: SoundEngine, + backend: MixerBackend, /// Record `Heard` sounds (the subtitle overlay is listening). pub record_heard: bool, - heard: Vec, - mixer: Arc>, - rate: u32, - root: PathBuf, - events: HashMap>, - cache: HashMap>, u32)>>, - seed: u64, pub listener: [f64; 3], pub listener_yaw: f32, pub master: f32, - music: Option, - next_tracked: u64, + /// Seeds of positional plays (the client level random's `nextLong`). + random: LegacyRandom, /// A `SoundSource` index the next sound plays on (`/playsound`). source_override: Option, /// Positional sounds played since the last drain, kept while the world @@ -130,75 +124,242 @@ fn decode(path: &Path) -> Option<(Vec, u32)> { } Some((mono, rate)) } -impl Audio { - pub fn new(root: &Path) -> Self { - let mut events = HashMap::new(); - let mut subtitles = HashMap::new(); - if let Ok(text) = fs::read(root.join("assets/minecraft/sounds.json")) - && let Ok(Value::Object(map)) = serde_json::from_slice::(&text) +impl MixerBackend { + fn with(&self, channel: ChannelId, f: impl FnOnce(&mut Channel)) { + if let Ok(mut m) = self.mixer.lock() + && let Some(c) = m.channels.get_mut(&channel) { - for (name, def) in map { - let variants = def["sounds"] - .as_array() - .into_iter() - .flatten() - .map(|s| match s { - Value::String(n) => Variant { - name: n.clone(), - volume: 1.0, - pitch: 1.0, - weight: 1, - attenuation: 16.0, - is_event: false, - }, - _ => Variant { - name: s["name"].as_str().unwrap_or("").to_owned(), - volume: s["volume"].as_f64().unwrap_or(1.0) as f32, - pitch: s["pitch"].as_f64().unwrap_or(1.0) as f32, - weight: s["weight"].as_u64().unwrap_or(1) as u32, - attenuation: s["attenuation_distance"].as_f64().unwrap_or(16.0) as f32, - is_event: s["type"].as_str() == Some("event"), - }, - }) - .collect::>(); - if let Some(key) = def["subtitle"].as_str() { - subtitles.insert(format!("minecraft:{name}"), key.to_owned()); - } - events.insert(format!("minecraft:{name}"), variants); - } + f(c); } - let mixer = Arc::new(Mutex::new(Mixer { - music_gain: 1.0, - ..Mixer::default() - })); - let (stream, rate) = match Self::open(mixer.clone()) { - Ok(v) => (Some(v.0), v.1), - Err(e) => { - eprintln!("Horizon: audio unavailable: {e}"); - (None, 48_000) + } +} +impl Backend for MixerBackend { + fn create(&mut self, _streaming: bool) -> Option { + self.next += 1; + let id = self.next; + self.mixer.lock().ok()?.channels.insert( + id, + Channel { + samples: None, + position: 0.0, + state: State::Initial, + gain: 1.0, + pitch: 1.0, + linear: None, + looping: false, + at: [0.0; 3], + relative: false, + }, + ); + Some(id) + } + fn destroy(&mut self, channel: ChannelId) { + if let Ok(mut m) = self.mixer.lock() { + m.channels.remove(&channel); + } + } + fn set_pitch(&mut self, channel: ChannelId, pitch: f32) { + self.with(channel, |c| c.pitch = pitch); + } + fn set_volume(&mut self, channel: ChannelId, volume: f32) { + self.with(channel, |c| c.gain = volume); + } + fn set_attenuation(&mut self, channel: ChannelId, linear: Option) { + self.with(channel, |c| c.linear = linear); + } + fn set_looping(&mut self, channel: ChannelId, looping: bool) { + self.with(channel, |c| c.looping = looping); + } + fn set_position(&mut self, channel: ChannelId, p: [f64; 3]) { + self.with(channel, |c| c.at = [p[0] as f32, p[1] as f32, p[2] as f32]); + } + fn set_relative(&mut self, channel: ChannelId, relative: bool) { + self.with(channel, |c| c.relative = relative); + } + /// `getCompleteBuffer` (decoded now, cached) or `getStream` (decoded on a + /// worker), then attach and `alSourcePlay`. A sound that cannot load + /// leaves its source initial, as a failed buffer future does in vanilla. + fn start(&mut self, channel: ChannelId, sound: &Sound, looping: bool) { + if !self.live { + return; + } + let (namespace, path) = sound.path(); + let file = self.root.join("assets").join(namespace).join(&path); + let attach = move |mixer: &Mutex, samples: Option<(Arc>, u32)>| { + if let Some(samples) = samples + && let Ok(mut m) = mixer.lock() + && let Some(c) = m.channels.get_mut(&channel) + { + c.samples = Some(samples); + c.position = 0.0; + c.state = State::Playing; } }; + if sound.stream { + // A streamed sound loops by restarting its stream. + let mixer = self.mixer.clone(); + std::thread::spawn(move || { + let samples = decode(&file).map(|(s, r)| (Arc::new(s), r)); + if looping + && let Ok(mut m) = mixer.lock() + && let Some(c) = m.channels.get_mut(&channel) + { + c.looping = true; + } + attach(&mixer, samples); + }); + } else { + let samples = self + .cache + .entry(format!("{namespace}:{path}")) + .or_insert_with(|| decode(&file).map(|(s, r)| (Arc::new(s), r))) + .clone(); + attach(&self.mixer, samples); + } + } + fn stop(&mut self, channel: ChannelId) { + self.with(channel, |c| { + if c.state != State::Initial { + c.state = State::Stopped; + } + }); + } + fn pause(&mut self, channel: ChannelId) { + self.with(channel, |c| { + if c.state == State::Playing { + c.state = State::Paused; + } + }); + } + fn unpause(&mut self, channel: ChannelId) { + self.with(channel, |c| { + if c.state == State::Paused { + c.state = State::Playing; + } + }); + } + fn stopped(&mut self, channel: ChannelId) -> bool { + self.mixer + .lock() + .map(|m| { + m.channels + .get(&channel) + .is_none_or(|c| c.state == State::Stopped) + }) + .unwrap_or(true) + } +} +/// The gain OpenAL applies for distance (`AL_LINEAR_DISTANCE` with reference +/// distance 0 and rolloff 1: the distance clamps to the max distance). +fn distance_gain(linear: Option, distance: f32) -> f32 { + match linear { + None => 1.0, + Some(max) if max > 0.0 => (1.0 - distance.min(max) / max).clamp(0.0, 1.0), + Some(_) => 0.0, + } +} +fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { + data.fill(0.0); + let listener = mixer.listener; + let yaw = mixer.listener_yaw.to_radians(); + // Gains and pans per source for this buffer. + let mut voices: Vec<(ChannelId, f32, f32, f64)> = Vec::new(); + for (id, c) in &mixer.channels { + let Some((_, source_rate)) = &c.samples else { + continue; + }; + if c.state != State::Playing { + continue; + } + let d = if c.relative { + [f64::from(c.at[0]), f64::from(c.at[1]), f64::from(c.at[2])] + } else { + [ + f64::from(c.at[0]) - listener[0], + f64::from(c.at[1]) - listener[1], + f64::from(c.at[2]) - listener[2], + ] + }; + let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() as f32; + let gain = c.gain.clamp(0.0, 1.0) * distance_gain(c.linear, distance); + // The listener's right vector for a Minecraft yaw. + let side = if c.relative { + (d[0] as f32) / distance.max(0.001) + } else { + (-(yaw.cos()) as f64 * d[0] - (yaw.sin()) as f64 * d[2]) as f32 / distance.max(0.001) + }; + let pan = side.clamp(-1.0, 1.0); + let left = gain * (1.0 - pan.max(0.0) * 0.6); + let right = gain * (1.0 + pan.min(0.0) * 0.6); + let step = f64::from(*source_rate) / f64::from(rate) * f64::from(c.pitch.max(0.0)); + voices.push((*id, left, right, step)); + } + for (id, left, right, step) in voices { + let Some(c) = mixer.channels.get_mut(&id) else { + continue; + }; + let Some((samples, _)) = c.samples.clone() else { + continue; + }; + for frame in data.chunks_mut(channels) { + let mut i = c.position as usize; + if i + 1 >= samples.len() { + if c.looping && samples.len() > 1 { + c.position = 0.0; + i = 0; + } else { + c.state = State::Stopped; + break; + } + } + let t = (c.position - i as f64) as f32; + let s = samples[i] * (1.0 - t) + samples[i + 1] * t; + if channels >= 2 { + frame[0] += s * left; + frame[1] += s * right; + } else { + frame[0] += s * (left + right) / 2.0; + } + c.position += step; + } + } + for s in data.iter_mut() { + *s = s.clamp(-1.0, 1.0); + } +} +impl Audio { + pub fn new(root: &Path) -> Self { + let registry = SoundRegistry::load(root); + let mixer = Arc::new(Mutex::new(Mixer::default())); + let (stream, live) = match Self::open(mixer.clone()) { + Ok(v) => (Some(v), true), + Err(e) => { + eprintln!("Horizon: audio unavailable: {e}"); + (None, false) + } + }; + let mut engine = SoundEngine::new(registry); + engine.loaded = live; Self { _stream: stream, - subtitles, + engine, + backend: MixerBackend { + mixer, + root: root.to_owned(), + cache: HashMap::new(), + next: 0, + live, + }, record_heard: false, - heard: Vec::new(), - mixer, - rate, - root: root.to_owned(), - events, - cache: HashMap::new(), - seed: 0x5DEE_CE66, listener: [0.0; 3], listener_yaw: 0.0, master: 1.0, - music: None, - next_tracked: 0, + random: LegacyRandom::new(crate::sound_engine::unique_seed()), source_override: None, capture: None, } } - fn open(mixer: Arc>) -> Result<(cpal::Stream, u32)> { + fn open(mixer: Arc>) -> Result { let host = cpal::default_host(); let device = host .default_output_device() @@ -209,269 +370,110 @@ impl Audio { let stream = device.build_output_stream( &config.into(), move |data: &mut [f32], _| { - data.fill(0.0); - let Ok(mut mixer) = mixer.lock() else { return }; - for frame in data.chunks_mut(channels) { - let (mut l, mut r) = (0.0f32, 0.0f32); - for v in mixer.voices.iter_mut() { - let i = v.position as usize; - if i + 1 >= v.samples.len() { - continue; - } - let t = (v.position - i as f64) as f32; - let s = v.samples[i] * (1.0 - t) + v.samples[i + 1] * t; - l += s * v.left; - r += s * v.right; - v.position += v.step; - } - for t in mixer.tracked.iter_mut() { - let v = &mut t.voice; - let mut i = v.position as usize; - if t.looping && i + 1 >= v.samples.len() { - v.position = 0.0; - i = 0; - } - if i + 1 < v.samples.len() { - let f = (v.position - i as f64) as f32; - let s = (v.samples[i] * (1.0 - f) + v.samples[i + 1] * f) * t.volume; - l += s * v.left; - r += s * v.right; - v.position += v.step; - } - } - let gain = mixer.music_gain; - if let Some(v) = mixer.music.as_mut() { - let i = v.position as usize; - if i + 1 < v.samples.len() { - let t = (v.position - i as f64) as f32; - let s = (v.samples[i] * (1.0 - t) + v.samples[i + 1] * t) * gain; - l += s * v.left; - r += s * v.right; - v.position += v.step; - } - } - if channels >= 2 { - frame[0] = l.clamp(-1.0, 1.0); - frame[1] = r.clamp(-1.0, 1.0); - } else { - frame[0] = ((l + r) / 2.0).clamp(-1.0, 1.0); - } - } - mixer - .voices - .retain(|v| (v.position as usize) + 1 < v.samples.len()); - mixer.tracked.retain(|t| { - t.looping || (t.voice.position as usize) + 1 < t.voice.samples.len() - }); - if mixer - .music - .as_ref() - .is_some_and(|v| (v.position as usize) + 1 >= v.samples.len()) - { - mixer.music = None; + if let Ok(mut m) = mixer.lock() { + mix(&mut m, data, channels, rate); + } else { + data.fill(0.0); } }, |e| eprintln!("Horizon: audio stream error: {e}"), None, )?; stream.play()?; - Ok((stream, rate)) + Ok(stream) } - fn random(&mut self) -> u64 { - self.seed ^= self.seed << 13; - self.seed ^= self.seed >> 7; - self.seed ^= self.seed << 17; - self.seed - } - fn resolve(&mut self, event: &str, depth: u32) -> Option { - let variants = self.events.get(event)?.clone(); - let total: u32 = variants.iter().map(|v| v.weight).sum(); - if total == 0 { - return None; + fn bound(&mut self) -> Bound<'_, MixerBackend> { + Bound { + engine: &mut self.engine, + backend: &mut self.backend, } - let mut pick = (self.random() % u64::from(total)) as u32; - let chosen = variants.into_iter().find(|v| { - if pick < v.weight { - true - } else { - pick -= v.weight; - false + } + /// `SoundManager.updateSource`: the camera position and yaw. + pub fn set_listener(&mut self, position: [f64; 3], yaw: f32) { + self.listener = position; + self.listener_yaw = yaw; + if let Ok(mut m) = self.backend.mixer.lock() { + m.listener = position; + m.listener_yaw = yaw; + } + } + /// Sync the volume options, refreshing the categories that changed + /// (the option sliders' `refreshCategoryVolume`). + fn sync_volumes(&mut self) { + let mut volumes = [self.master; 11]; + for (i, v) in volumes.iter_mut().enumerate().skip(1) { + *v = crate::settings::source_volume(i); + } + for source in 0..11 { + if self.engine.source_volumes[source] != volumes[source] { + self.engine.source_volumes[source] = volumes[source]; + self.engine + .refresh_category_volume(source, &mut self.backend); } - })?; - if chosen.is_event && depth < 4 { - let name = if chosen.name.contains(':') { - chosen.name.clone() - } else { - format!("minecraft:{}", chosen.name) - }; - let mut inner = self.resolve(&name, depth + 1)?; - inner.volume *= chosen.volume; - inner.pitch *= chosen.pitch; - return Some(inner); } - Some(chosen) + self.engine.listening = self.record_heard; } - /// Play a sound event at a world position (None = non-positional UI sound). + /// `SoundManager.tick(paused)`, once per client tick. + pub fn tick(&mut self, paused: bool, ctx: &TickContext) { + self.sync_volumes(); + self.engine.tick(paused, ctx, &mut self.backend); + } + /// `SoundManager.pauseAllExcept(MUSIC, UI)`. + pub fn pause(&mut self) { + self.engine.pause_all_except( + &[crate::sound_engine::MUSIC, crate::sound_engine::UI], + &mut self.backend, + ); + } + /// `SoundManager.resume`. + pub fn resume(&mut self) { + self.engine.resume(&mut self.backend); + } + /// `SoundManager.stop()`: every sound. + pub fn stop_all(&mut self) { + self.engine.stop_all(&mut self.backend); + } + /// Play a sound event at a world position, as `ClientLevel.playLocalSound` + /// (a `SimpleSoundInstance` seeded from the level random), or relative to + /// the listener without attenuation (`None`). pub fn play(&mut self, event: &str, at: Option<[f64; 3]>, volume: f32, pitch: f32) { + let seed = self.random.next_long(); + self.play_seeded(event, at, volume, pitch, seed); + } + /// `play` with the seed a sound packet carries. + pub fn play_seeded( + &mut self, + event: &str, + at: Option<[f64; 3]>, + volume: f32, + pitch: f32, + seed: i64, + ) { if let (Some(capture), Some(at)) = (self.capture.as_mut(), at) { capture.push((event.to_owned(), at, volume, pitch)); } - let Some(variant) = self.resolve(event, 0) else { - return; - }; - if self.record_heard - && let Some(key) = self.subtitles.get(event) - { - let range = if at.is_some() { - variant.attenuation * volume.max(1.0) - } else { - f32::INFINITY - }; - self.heard.push(Heard { - subtitle: key.clone(), - at, - range, - looping: false, - }); - } - if self._stream.is_none() { - return; - } - let file = variant.name.trim_start_matches("minecraft:").to_owned(); - let entry = self.cache.entry(file.clone()).or_insert_with(|| { - decode( - &self - .root - .join(format!("assets/minecraft/sounds/{file}.ogg")), - ) - .map(|(s, r)| (Arc::new(s), r)) - }); - let Some((samples, rate)) = entry.clone() else { - return; - }; + self.sync_volumes(); + let event = crate::sound_events::normalize(event); let source = self .source_override - .unwrap_or_else(|| crate::settings::sound_source(event)); - let volume = (volume * variant.volume).clamp(0.0, 1.0) - * self.master - * crate::settings::source_volume(source); - let pitch = (pitch * variant.pitch).clamp(0.5, 2.0); - let (mut left, mut right) = (volume, volume); - if let Some(p) = at { - let d = [ - p[0] - self.listener[0], - p[1] - self.listener[1], - p[2] - self.listener[2], - ]; - let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() as f32; - let range = variant.attenuation * volume.max(1.0); - let gain = (1.0 - distance / range).clamp(0.0, 1.0); - if gain <= 0.0 { - return; - } - let yaw = self.listener_yaw.to_radians(); - // Right vector of a Minecraft yaw. - let side = (-(yaw.cos()) as f64 * d[0] - (yaw.sin()) as f64 * d[2]) as f32 - / distance.max(0.001); - let pan = side.clamp(-1.0, 1.0); - left = volume * gain * (1.0 - pan.max(0.0) * 0.6); - right = volume * gain * (1.0 + pan.min(0.0) * 0.6); - } - let step = f64::from(rate) / f64::from(self.rate) * f64::from(pitch); - if let Ok(mut m) = self.mixer.lock() { - if m.voices.len() > 64 { - m.voices.remove(0); - } - m.voices.push(Voice { - samples, - position: 0.0, - step, - left, - right, - event: event.into(), + .unwrap_or_else(|| crate::settings::sound_source(&event)); + let random = LegacyRandom::new(seed); + let instance = match at { + Some(at) => SoundInstance::at(&event, source, volume, pitch, random, at), + None => SoundInstance::new( + &event, source, - }); - } - } - /// `SoundManager.play` of a music instance (`SimpleSoundInstance.forMusic`: - /// non-positional, streamed). Decoding runs on a worker thread; the track - /// counts as active from now on. Returns false when nothing can play. - pub fn play_music(&mut self, event: &str) -> bool { - self.stop_music(); - if self._stream.is_none() { - return false; - } - let Some(variant) = self.resolve(event, 0) else { - return false; + volume, + pitch, + random, + false, + 0, + Attenuation::None, + [0.0; 3], + true, + ), }; - let path = self.root.join(format!( - "assets/minecraft/sounds/{}.ogg", - variant.name.trim_start_matches("minecraft:") - )); - let volume = - variant.volume.clamp(0.0, 1.0) * self.master * crate::settings::event_volume(event); - let step_scale = f64::from(variant.pitch.clamp(0.5, 2.0)) / f64::from(self.rate); - let ready = Arc::new(std::sync::atomic::AtomicBool::new(false)); - let (mixer, done) = (self.mixer.clone(), ready.clone()); - let music_event = event.to_owned(); - std::thread::spawn(move || { - if let Some((samples, rate)) = decode(&path) - && let Ok(mut m) = mixer.lock() - && !done.load(std::sync::atomic::Ordering::Acquire) - { - m.music = Some(Voice { - samples: Arc::new(samples), - position: 0.0, - step: f64::from(rate) * step_scale, - left: volume, - right: volume, - event: music_event.as_str().into(), - source: 1, - }); - } - done.store(true, std::sync::atomic::Ordering::Release); - }); - self.music = Some(MusicTrack { - event: event.to_owned(), - ready, - }); - true - } - /// `SoundManager.stop` of the music instance. - pub fn stop_music(&mut self) { - if let Some(track) = self.music.take() { - // A decoder still running sees the flag and drops its result. - track - .ready - .store(true, std::sync::atomic::Ordering::Release); - } - if let Ok(mut m) = self.mixer.lock() { - m.music = None; - } - } - /// `SoundManager.isActive`: decoding or still sounding. - pub fn music_active(&mut self) -> bool { - let Some(track) = &self.music else { - return false; - }; - if !track.ready.load(std::sync::atomic::Ordering::Acquire) { - return true; - } - let playing = self.mixer.lock().is_ok_and(|m| m.music.is_some()); - if !playing { - self.music = None; - } - playing - } - /// The event of the current music track. - pub fn music_event(&self) -> Option<&str> { - self.music.as_ref().map(|t| t.event.as_str()) - } - /// Every sound event id (for command completion). - pub fn event_names(&self) -> Vec { - let mut v: Vec = self.events.keys().cloned().collect(); - v.sort(); - v + self.play_instance(instance, false); } /// Play a sound on a given `SoundSource` index (`/playsound`). pub fn play_on( @@ -486,102 +488,67 @@ impl Audio { self.play(event, at, volume, pitch); self.source_override = None; } + /// `SimpleSoundInstance.forJukeboxSong` at a jukebox; the handle stays + /// until `release`. + pub fn play_jukebox_song(&mut self, event: &str, pos: [i32; 3]) -> InstanceId { + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + let event = crate::sound_events::normalize(event); + let instance = SoundInstance::for_jukebox_song(&event, at, SoundEngine::unseeded()); + self.play_instance(instance, true).0 + } + /// Stop and drop a held instance. + pub fn stop_and_release(&mut self, id: InstanceId) { + self.stop_instance(id); + self.release(id); + } + /// Every sound event id (for command completion). + pub fn event_names(&self) -> Vec { + let mut v: Vec = self.engine.registry.names().cloned().collect(); + v.sort(); + v + } /// `ClientboundStopSoundPacket`: stop the playing sounds of an event /// and/or a source. pub fn stop_sounds(&mut self, event: Option<&str>, source: Option) { - let matches = |v: &Voice| { - event.is_none_or(|e| &*v.event == e) && source.is_none_or(|s| v.source == s) - }; - if let Ok(mut m) = self.mixer.lock() { - m.voices.retain(|v| !matches(v)); - m.tracked.retain(|t| !matches(&t.voice)); - if m.music.as_ref().is_some_and(matches) { - m.music = None; - } - } - if self - .music - .as_ref() - .is_some_and(|t| event.is_none_or(|e| t.event == e) && source.is_none_or(|s| s == 1)) - { - self.music = None; - } + let event = event.map(crate::sound_events::normalize); + self.engine + .stop_matching(event.as_deref(), source, &mut self.backend); } /// The sounds played since the last call, for the subtitle overlay. pub fn take_heard(&mut self) -> Vec { - std::mem::take(&mut self.heard) - } - /// `SoundManager.updateCategoryVolume(MUSIC, gain)`. - pub fn set_music_gain(&mut self, gain: f32) { - if let Ok(mut m) = self.mixer.lock() { - m.music_gain = gain; - } - } - /// Play a relative (non-positional) tickable sound instance the caller - /// keeps a handle to: ambient loops (`looping`) and sub-sounds. - pub fn play_tracked(&mut self, event: &str, volume: f32, looping: bool) -> Option { - let variant = self.resolve(event, 0)?; - if self.record_heard - && let Some(key) = self.subtitles.get(event) - { - self.heard.push(Heard { - subtitle: key.clone(), - at: None, - range: f32::INFINITY, - looping, - }); - } - self._stream.as_ref()?; - let file = variant.name.trim_start_matches("minecraft:").to_owned(); - let root = &self.root; - let (samples, rate) = self - .cache - .entry(file.clone()) - .or_insert_with(|| { - decode(&root.join(format!("assets/minecraft/sounds/{file}.ogg"))) - .map(|(s, r)| (Arc::new(s), r)) + std::mem::take(&mut self.engine.notifications) + .into_iter() + .filter_map(|n| { + Some(Heard { + subtitle: n.subtitle?, + at: Some(n.position), + range: n.range, + looping: n.looping, + }) }) - .clone()?; - let gain = - variant.volume.clamp(0.0, 1.0) * self.master * crate::settings::event_volume(event); - let step = - f64::from(rate) / f64::from(self.rate) * f64::from(variant.pitch.clamp(0.5, 2.0)); - self.next_tracked += 1; - let id = self.next_tracked; - let mut m = self.mixer.lock().ok()?; - m.tracked.push(Tracked { - id, - voice: Voice { - samples, - position: 0.0, - step, - left: gain, - right: gain, - event: event.into(), - source: crate::settings::sound_source(event), - }, - looping, - volume: volume.clamp(0.0, 1.0), - }); - Some(id) - } - /// A tracked instance's volume (`AbstractTickableSoundInstance.volume`). - pub fn set_tracked_volume(&mut self, id: u64, volume: f32) { - if let Ok(mut m) = self.mixer.lock() - && let Some(t) = m.tracked.iter_mut().find(|t| t.id == id) - { - t.volume = volume.clamp(0.0, 1.0); - } - } - pub fn stop_tracked(&mut self, id: u64) { - if let Ok(mut m) = self.mixer.lock() { - m.tracked.retain(|t| t.id != id); - } - } - /// Still sounding (a finished one-shot is gone). - pub fn tracked_active(&self, id: u64) -> bool { - self.mixer - .lock() - .is_ok_and(|m| m.tracked.iter().any(|t| t.id == id)) + .collect() + } +} +impl Sounds for Audio { + fn engine(&mut self) -> &mut SoundEngine { + &mut self.engine + } + fn play_instance(&mut self, instance: SoundInstance, retain: bool) -> (InstanceId, PlayResult) { + self.sync_volumes(); + self.bound().play_instance(instance, retain) + } + fn play_id(&mut self, id: InstanceId) -> PlayResult { + self.sync_volumes(); + self.bound().play_id(id) + } + fn stop_instance(&mut self, id: InstanceId) { + self.bound().stop_instance(id); + } + fn update_category_volume(&mut self, source: usize, gain: f32) { + self.bound().update_category_volume(source, gain); } } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b81c403fd..2fdaa712c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -594,6 +594,8 @@ struct Game<'a> { audio: Audio, music: horizon_client::music::MusicManager, ambience: horizon_client::ambience::Ambience, + /// The sound engine was told the game paused (pauseAllExcept). + sound_paused: bool, dropped: Vec, next_entity: u32, particles: horizon_client::particles::ParticleEngine, @@ -5706,6 +5708,10 @@ impl Game<'_> { } fn close_world(&mut self) -> Result<()> { self.ambience.clear(&mut self.audio); + // updateLevelInEngines(null): every sound stops; the music manager + // lets go of its track. + self.music.stop_playing(None, &mut self.audio); + self.audio.stop_all(); if self.remote.is_some() { return self.leave_server(None); } @@ -7409,8 +7415,8 @@ impl Game<'_> { self.pitch, ), }; - self.audio.listener = [camera.x, camera.y, camera.z]; - self.audio.listener_yaw = view_yaw; + self.audio + .set_listener([camera.x, camera.y, camera.z], view_yaw); let block = [ camera.x.floor() as i32, camera.y.floor() as i32, @@ -8209,6 +8215,7 @@ impl ApplicationHandler for Game<'_> { self.tick_fov(); } self.tick_music(); + self.tick_sound_engine(); self.clock.record(started.elapsed()); if let Some(report) = self.clock.take_sprint_report() { self.sprint_report(&report); @@ -8507,6 +8514,7 @@ pub fn run() -> Result<()> { audio, music: Default::default(), ambience: Default::default(), + sound_paused: false, dropped: Vec::new(), next_entity: 0, particles, diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index b6f8c157d..60fbc737c 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -509,7 +509,7 @@ impl Game<'_> { "frames": self.frames, "ticks": self.ticks, "day_time": self.world.day_time, - "music": self.music.current(), + "music": self.music.current(&self.audio.engine), "fishing": self.hook_status(), "tridents": self.tridents.len(), "rockets": self.rockets.len(), diff --git a/crates/horizon-client/src/game/jukebox.rs b/crates/horizon-client/src/game/jukebox.rs index e321a599b..f721e2352 100644 --- a/crates/horizon-client/src/game/jukebox.rs +++ b/crates/horizon-client/src/game/jukebox.rs @@ -12,9 +12,6 @@ use horizon_client::{ use horizon_core::{position::BlockPos, random::RandomSource}; use horizon_world::level::flags as level_flags; -/// Linear attenuation range of a song (`SimpleSoundInstance.forJukeboxSong`: volume 4). -const RANGE: f64 = 64.0; - impl Game<'_> { fn jukebox(&self, pos: [i32; 3]) -> Option<&Jukebox> { match self.world.block_entities.get(&(pos[0], pos[1], pos[2])) { @@ -101,9 +98,9 @@ impl Game<'_> { let Some(s) = self.res.items.songs.get(song).cloned() else { return; }; - if let Some(id) = self.audio.play_tracked(&s.sound, 0.0, false) { - self.jukebox_sounds.insert((pos[0], pos[1], pos[2]), id); - } + // LevelRenderer.playJukeboxSong: SimpleSoundInstance.forJukeboxSong. + let id = self.audio.play_jukebox_song(&s.sound, pos); + self.jukebox_sounds.insert((pos[0], pos[1], pos[2]), id); let description = horizon_client::component::to_text(&s.description, &mut |k| Text::literal(k)); self.titles @@ -113,7 +110,7 @@ impl Game<'_> { } fn stop_song(&mut self, pos: [i32; 3]) { if let Some(id) = self.jukebox_sounds.remove(&(pos[0], pos[1], pos[2])) { - self.audio.stop_tracked(id); + self.audio.stop_and_release(id); } } /// `popOutTheItem`: the disc above the jukebox, and the song stops. @@ -202,30 +199,20 @@ impl Game<'_> { } self.update_song_volumes(); } - /// Linear distance attenuation of each song at the listener. + /// Let go of songs that ended or whose jukebox stopped. fn update_song_volumes(&mut self) { - let Some(eye) = self.eye_position() else { - return; - }; let sounds: Vec<_> = self .jukebox_sounds .iter() .map(|(k, id)| (*k, *id)) .collect(); for (k, id) in sounds { - if !self.audio.tracked_active(id) + if !self.audio.engine.is_active(id) || !matches!(self.world.block_entities.get(&k), Some(BlockEntity::Jukebox(j)) if j.playing) { - self.audio.stop_tracked(id); + self.audio.stop_and_release(id); self.jukebox_sounds.remove(&k); - continue; } - let d = ((f64::from(k.0) + 0.5 - eye[0]).powi(2) - + (f64::from(k.1) + 0.5 - eye[1]).powi(2) - + (f64::from(k.2) + 0.5 - eye[2]).powi(2)) - .sqrt(); - self.audio - .set_tracked_volume(id, (1.0 - d / RANGE).clamp(0.0, 1.0) as f32); } } } diff --git a/crates/horizon-client/src/game/music.rs b/crates/horizon-client/src/game/music.rs index 6ac336780..a7e054fdb 100644 --- a/crates/horizon-client/src/game/music.rs +++ b/crates/horizon-client/src/game/music.rs @@ -1,6 +1,11 @@ -//! `Minecraft.getSituationalMusic` and `getMusicVolume` for the music manager. +//! `Minecraft.getSituationalMusic` and `getMusicVolume` for the music manager, +//! the local player's ambient sound handlers and the sound engine tick. use super::Game; -use horizon_client::{blocks::Fluid, music::Music}; +use horizon_client::{ + blocks::Fluid, + music::Music, + sound_engine::TickContext, +}; impl Game<'_> { /// `Minecraft.tick` -> `MusicManager.tick`, once per client tick. @@ -11,6 +16,25 @@ impl Game<'_> { self.music .tick(music.as_ref(), volume, loading, &mut self.audio); } + /// `Minecraft.tick` -> `SoundManager.tick(pause)`, after the music, with + /// `pauseAllExcept(MUSIC, UI)` when the game pauses and `resume` when it + /// carries on. + pub(super) fn tick_sound_engine(&mut self) { + if self.pause != self.sound_paused { + if self.pause { + self.audio.pause(); + } else { + self.audio.resume(); + } + self.sound_paused = self.pause; + } + let ctx = TickContext { + player_underwater: self.ambience.was_underwater(), + player_removed: self.player.is_none(), + }; + self.audio.tick(self.pause, &ctx); + } + /// `getSituationalMusic` and `getMusicVolume`. fn situational_music(&self) -> (Option, f32) { // Title screen: no player, Musics.MENU at full volume. if self.title.is_some() { @@ -19,33 +43,44 @@ impl Game<'_> { let Some(eye) = self.eye_position() else { return (Some(Music::menu()), 1.0); }; - let (x, y, z) = ( - eye[0].floor() as i32, - eye[1].floor() as i32, - eye[2].floor() as i32, - ); - let biome = self - .world + let biome = self.biome_at(eye); + let dimension = self.dim.id(); + let tables = &self.res.music; + let volume = tables.volume(dimension, biome); + // Minecraft.getSituationalMusic: the boss overlay's music in the End. + if self.dim == super::Dim::End && self.boss_music() { + return (Some(Music::end_boss()), volume); + } + let music = tables + .background(dimension, biome) + .select(self.creative, self.ambience.was_underwater()) + .cloned(); + (music, volume) + } + /// `BiomeManager.getNoiseBiomeAtPosition`: the quart cell holding a position. + fn biome_at(&self, p: [f64; 3]) -> &str { + let (x, y, z) = (p[0].floor() as i32, p[1].floor() as i32, p[2].floor() as i32); + self.world .chunks .get(&(x >> 4, z >> 4)) .map_or("minecraft:plains", |c| { - self.res.biomes.list[c.biome(x, y, z) as usize] - .name - .as_str() - }); - // Minecraft.getSituationalMusic: the boss bar's music in the End. - if self.boss_music() { - return (Some(Music::end_boss()), 1.0); + self.res.biomes.list[c.biome(x, y, z) as usize].name.as_str() + }) + } + /// `isEyeInFluid(WATER)`: the eye inside the water of its block column. + fn eye_in_water(&self, x: f64, eye_y: f64, z: f64) -> bool { + let (bx, by, bz) = (x.floor() as i32, eye_y.floor() as i32, z.floor() as i32); + let f = self.res.facts.get(self.world.block(bx, by, bz)); + if f.fluid != Fluid::Water { + return false; } - let dimension = self.dim.id(); - let tables = &self.res.music; - // Player.isUnderWater: eyes in water. - let underwater = self.res.facts.get(self.world.block(x, y, z)).fluid == Fluid::Water; - let music = tables - .background(dimension, biome) - .select(self.creative, underwater) - .cloned(); - (music, tables.volume(dimension, biome)) + let above = self.res.facts.get(self.world.block(bx, by + 1, bz)); + let height = if above.fluid == Fluid::Water { + 1.0 + } else { + f64::from(f.fluid_level) / 9.0 + }; + eye_y <= f64::from(by) + height } } @@ -57,23 +92,9 @@ impl Game<'_> { }; let feet = [p.position.x, p.position.y, p.position.z]; let eye_y = feet[1] + f64::from(p.dimensions.eye_height); - let (x, z) = (feet[0].floor() as i32, feet[2].floor() as i32); + let sounds = self.res.ambient.get(self.dim.id(), self.biome_at(feet)); + let underwater = self.eye_in_water(feet[0], eye_y, feet[2]); let world = &self.world; - let biome = world - .chunks - .get(&(x >> 4, z >> 4)) - .map_or("minecraft:plains", |c| { - self.res.biomes.list[c.biome(x, feet[1].floor() as i32, z) as usize] - .name - .as_str() - }); - let sounds = self.res.ambient.get(self.dim.id(), biome); - let underwater = self - .res - .facts - .get(world.block(x, eye_y.floor() as i32, z)) - .fluid - == Fluid::Water; let light = |b: [i32; 3]| { let l = world.light(b[0], b[1], b[2]); (l >> 4, l & 15) @@ -83,6 +104,7 @@ impl Game<'_> { position: feet, eye_y, underwater, + spectator: self.spectator(), light: &light, }; self.ambience.tick(&ctx, &mut self.audio); diff --git a/crates/horizon-client/src/music.rs b/crates/horizon-client/src/music.rs index ebc86ac44..94a7f87a0 100644 --- a/crates/horizon-client/src/music.rs +++ b/crates/horizon-client/src/music.rs @@ -2,6 +2,7 @@ //! `Minecraft.getSituationalMusic`, with the `minecraft:audio/background_music` //! and `minecraft:audio/music_volume` environment attributes of dimension //! types and biomes (a biome value overrides its dimension's). +use crate::sound_engine::{InstanceId, MUSIC, PlayResult, SoundEngine, SoundInstance, Sounds}; use horizon_core::random::{LegacyRandom, RandomSource}; use serde_json::Value; use std::{collections::HashMap, fs, path::Path}; @@ -15,7 +16,7 @@ pub struct Music { pub replace_current_music: bool, } impl Music { - fn new(sound: &str, min_delay: i32, max_delay: i32, replace_current_music: bool) -> Self { + pub fn new(sound: &str, min_delay: i32, max_delay: i32, replace_current_music: bool) -> Self { Self { sound: sound.to_owned(), min_delay, @@ -177,45 +178,23 @@ fn next_int(random: &mut LegacyRandom, min: i32, max: i32) -> i32 { random.next_int_bound(max - min + 1).unwrap_or(0) + min } } -/// What the music manager drives (the sound engine's music channel). -pub trait MusicOutput { - /// Start a track; false when nothing can play. - fn play(&mut self, event: &str) -> bool; - fn stop(&mut self); - fn is_active(&mut self) -> bool; - /// `SoundManager.updateCategoryVolume(MUSIC, gain)`. - fn set_gain(&mut self, gain: f32); -} -impl MusicOutput for crate::audio::Audio { - fn play(&mut self, event: &str) -> bool { - self.play_music(event) - } - fn stop(&mut self) { - self.stop_music(); - } - fn is_active(&mut self) -> bool { - self.music_active() - } - fn set_gain(&mut self, gain: f32) { - self.set_music_gain(gain); - } -} /// `MusicManager`. pub struct MusicManager { random: LegacyRandom, - /// The sound event of the current track. - current: Option, + /// `currentMusic`: the instance the manager holds. + current: Option, current_gain: f32, next_song_delay: i32, + toast_shown: bool, pub frequency: MusicFrequency, + /// `ToastManager.showNowPlayingToast` (true) / `hideNowPlayingToast` + /// (false) calls since the last drain. + pub toast_requests: Vec, } impl Default for MusicManager { fn default() -> Self { // RandomSource.create(): seeded from the clock, not the world. - let seed = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |d| d.as_nanos() as i64); - Self::new(seed) + Self::new(crate::sound_engine::unique_seed()) } } impl MusicManager { @@ -225,35 +204,68 @@ impl MusicManager { current: None, current_gain: 1.0, next_song_delay: 100, + toast_shown: false, frequency: MusicFrequency::Default, + toast_requests: Vec::new(), } } - pub fn current(&self) -> Option<&str> { - self.current.as_deref() + /// The sound event of the current track. + pub fn current<'a>(&self, sounds: &'a SoundEngine) -> Option<&'a str> { + self.current + .and_then(|id| sounds.instance(id)) + .map(|i| i.identifier.as_str()) } - /// `MusicManager.tick` with the situational music and music volume; - /// `loading` holds back a new track (`LevelLoadingScreen`). + pub fn current_instance(&self) -> Option { + self.current + } + pub fn next_song_delay(&self) -> i32 { + self.next_song_delay + } + pub fn current_gain(&self) -> f32 { + self.current_gain + } + pub fn toast_shown(&self) -> bool { + self.toast_shown + } + fn set_current(&mut self, id: Option, sounds: &mut impl Sounds) { + if let Some(old) = self.current + && Some(old) != id + { + sounds.release(old); + } + self.current = id; + } + /// `MusicManager.tick` with `Minecraft.getMusicVolume` and + /// `getSituationalMusic`; `loading` is a `LevelLoadingScreen`. pub fn tick( &mut self, music: Option<&Music>, volume: f32, loading: bool, - out: &mut impl MusicOutput, + sounds: &mut impl Sounds, ) { - if self.current.is_some() && self.current_gain != volume && !self.fade(volume, music, out) { + if self.current.is_some() + && self.current_gain != volume + && !self.fade(volume, music, sounds) + { return; } let Some(music) = music else { self.next_song_delay = self.next_song_delay.max(100); return; }; - if let Some(current) = &self.current { - if music.replace_current_music && music.sound != *current { - out.stop(); + if let Some(current) = self.current { + // canReplace + let playing = sounds + .engine() + .instance(current) + .map(|i| i.identifier.clone()); + if music.replace_current_music && playing.as_deref() != Some(music.sound.as_str()) { + sounds.stop_instance(current); self.next_song_delay = next_int(&mut self.random, 0, music.min_delay / 2); } - if !out.is_active() { - self.current = None; + if !sounds.is_active(current) { + self.set_current(None, sounds); let delay = self .frequency .next_song_delay(Some(music), &mut self.random); @@ -264,35 +276,68 @@ impl MusicManager { if self.current.is_none() && !loading { self.next_song_delay -= 1; if self.next_song_delay <= 0 { - self.start(music, out); + self.start_playing(music, sounds); } } } /// `MusicManager.startPlaying`. - fn start(&mut self, music: &Music, out: &mut impl MusicOutput) { - // The instance is current even if it could not start; the next tick - // finds it inactive and schedules another. - out.play(&music.sound); - self.current = Some(music.sound.clone()); + pub fn start_playing(&mut self, music: &Music, sounds: &mut impl Sounds) { + let instance = SoundInstance::for_music(&music.sound, SoundEngine::unseeded()); + let (id, result) = sounds.play_instance(instance, true); + self.set_current(Some(id), sounds); + match result { + PlayResult::Started => { + self.toast_requests.push(true); + self.toast_shown = true; + } + PlayResult::StartedSilently => self.toast_shown = false, + PlayResult::NotStarted => {} + } self.next_song_delay = i32::MAX; } - /// `MusicManager.stopPlaying`. - pub fn stop(&mut self, situational: Option<&Music>, out: &mut impl MusicOutput) { - if self.current.take().is_some() { - out.stop(); + /// `MusicManager.showNowPlayingToastIfNeeded`. + pub fn show_now_playing_toast_if_needed(&mut self) { + if !self.toast_shown { + self.toast_requests.push(true); + self.toast_shown = true; + } + } + /// `MusicManager.stopPlaying(Music)`. + pub fn stop_playing_music( + &mut self, + music: &Music, + situational: Option<&Music>, + sounds: &mut impl Sounds, + ) { + if self.is_playing_music(music, sounds.engine()) { + self.stop_playing(situational, sounds); + } + } + /// `MusicManager.stopPlaying()`. + pub fn stop_playing(&mut self, situational: Option<&Music>, sounds: &mut impl Sounds) { + if let Some(current) = self.current { + sounds.stop_instance(current); + self.set_current(None, sounds); + self.toast_requests.push(false); } self.next_song_delay = self .frequency .next_song_delay(situational, &mut self.random) + 100; } + /// `MusicManager.isPlayingMusic`. + pub fn is_playing_music(&self, music: &Music, sounds: &SoundEngine) -> bool { + self.current(sounds) == Some(music.sound.as_str()) + } + /// `MusicManager.setMinutesBetweenSongs`. + pub fn set_frequency(&mut self, frequency: MusicFrequency, situational: Option<&Music>) { + self.frequency = frequency; + self.next_song_delay = self + .frequency + .next_song_delay(situational, &mut self.random); + } /// `MusicManager.fadePlaying`: false once the track faded out and stopped. - fn fade( - &mut self, - volume: f32, - situational: Option<&Music>, - out: &mut impl MusicOutput, - ) -> bool { + fn fade(&mut self, volume: f32, situational: Option<&Music>, sounds: &mut impl Sounds) -> bool { if self.current.is_none() { return false; } @@ -312,10 +357,10 @@ impl MusicManager { } self.current_gain = self.current_gain.clamp(0.0, 1.0); if self.current_gain <= 1.0E-4 { - self.stop(situational, out); + self.stop_playing(situational, sounds); false } else { - out.set_gain(self.current_gain); + sounds.update_category_volume(MUSIC, self.current_gain); true } } @@ -324,79 +369,70 @@ impl MusicManager { #[cfg(test)] mod tests { use super::*; + use crate::sound_engine::{Bound, test_backend::Null}; + use crate::sound_events::SoundRegistry; - #[derive(Default)] - struct Fake { - playing: Option, - started: Vec, - gain: f32, - } - impl MusicOutput for Fake { - fn play(&mut self, event: &str) -> bool { - self.playing = Some(event.to_owned()); - self.started.push(event.to_owned()); - true - } - fn stop(&mut self) { - self.playing = None; - } - fn is_active(&mut self) -> bool { - self.playing.is_some() - } - fn set_gain(&mut self, gain: f32) { - self.gain = gain; - } + fn engine() -> SoundEngine { + let mut registry = SoundRegistry::default(); + registry.add_file( + "minecraft", + br#"{"music.menu": {"sounds": [{"name": "m", "stream": true}]}, + "music.game": {"sounds": [{"name": "g", "stream": true}]}, + "music.end": {"sounds": [{"name": "e", "stream": true}]}}"#, + &|_, _| true, + ); + SoundEngine::new(registry) } #[test] fn menu_music_starts_within_its_delay_and_game_music_replaces_nothing() { + let (mut engine, mut backend) = (engine(), Null::default()); let mut m = MusicManager::new(1); - let mut out = Fake::default(); let menu = Music::menu(); + let tick = + |m: &mut MusicManager, music: &Music, engine: &mut SoundEngine, backend: &mut Null| { + m.tick(Some(music), 1.0, false, &mut Bound { engine, backend }); + }; // nextSongDelay starts at 100, capped to MENU's max delay 600: starts on tick 100. for _ in 0..99 { - m.tick(Some(&menu), 1.0, false, &mut out); + tick(&mut m, &menu, &mut engine, &mut backend); } - assert!(out.started.is_empty()); - m.tick(Some(&menu), 1.0, false, &mut out); - assert_eq!(out.started, ["minecraft:music.menu"]); + assert!(m.current(&engine).is_none()); + tick(&mut m, &menu, &mut engine, &mut backend); + assert_eq!(m.current(&engine), Some("minecraft:music.menu")); // Game music does not replace the current track. let game = Music::new("minecraft:music.game", 12000, 24000, false); - m.tick(Some(&game), 1.0, false, &mut out); - assert_eq!(m.current(), Some("minecraft:music.menu")); - // When the menu track ends, the next delay comes from the game music range. - out.playing = None; - m.tick(Some(&game), 1.0, false, &mut out); - assert!(m.current().is_none()); - assert!((12000..=24000).contains(&m.next_song_delay)); - } - - #[test] - fn replacing_music_stops_the_current_track() { - let mut m = MusicManager::new(2); - let mut out = Fake::default(); - m.start(&Music::menu(), &mut out); - let end = Music::new("minecraft:music.end", 6000, 24000, true); - m.tick(Some(&end), 1.0, false, &mut out); - assert!(out.playing.is_none()); - assert!(m.current().is_none()); - assert!(m.next_song_delay <= 3000); + tick(&mut m, &game, &mut engine, &mut backend); + assert_eq!(m.current(&engine), Some("minecraft:music.menu")); } #[test] fn zero_music_volume_fades_out_and_stops() { + let (mut engine, mut backend) = (engine(), Null::default()); let mut m = MusicManager::new(3); - let mut out = Fake::default(); let game = Music::new("minecraft:music.game", 12000, 24000, false); - m.start(&game, &mut out); + m.start_playing( + &game, + &mut Bound { + engine: &mut engine, + backend: &mut backend, + }, + ); let mut ticks = 0; - while m.current().is_some() && ticks < 1000 { - m.tick(Some(&game), 0.0, false, &mut out); + while m.current_instance().is_some() && ticks < 1000 { + m.tick( + Some(&game), + 0.0, + false, + &mut Bound { + engine: &mut engine, + backend: &mut backend, + }, + ); ticks += 1; } // 0.97^n < 1e-4 after ~303 ticks. assert!((290..=310).contains(&ticks), "{ticks}"); - assert!(out.playing.is_none()); } #[test] diff --git a/crates/horizon-client/src/sound_engine.rs b/crates/horizon-client/src/sound_engine.rs index f51545595..2a47b5db2 100644 --- a/crates/horizon-client/src/sound_engine.rs +++ b/crates/horizon-client/src/sound_engine.rs @@ -934,3 +934,86 @@ pub fn unique_seed() -> i64 { .map_or(0, |d| d.as_nanos() as i64); next ^ nanos } +/// The `SoundManager` calls game code makes. +pub trait Sounds { + fn engine(&mut self) -> &mut SoundEngine; + /// `SoundManager.play` of a new instance (`retain`: the caller keeps it). + fn play_instance(&mut self, instance: SoundInstance, retain: bool) -> (InstanceId, PlayResult); + /// `SoundManager.play` of an instance the caller holds. + fn play_id(&mut self, id: InstanceId) -> PlayResult; + /// `SoundManager.stop(SoundInstance)`. + fn stop_instance(&mut self, id: InstanceId); + /// `SoundManager.isActive`. + fn is_active(&mut self, id: InstanceId) -> bool { + self.engine().is_active(id) + } + /// `SoundManager.updateCategoryVolume`. + fn update_category_volume(&mut self, source: usize, gain: f32); + /// The caller drops its instance. + fn release(&mut self, id: InstanceId) { + self.engine().release(id); + } +} +/// An engine with its backend. +pub struct Bound<'a, B: Backend> { + pub engine: &'a mut SoundEngine, + pub backend: &'a mut B, +} +impl Sounds for Bound<'_, B> { + fn engine(&mut self) -> &mut SoundEngine { + self.engine + } + fn play_instance(&mut self, instance: SoundInstance, retain: bool) -> (InstanceId, PlayResult) { + self.engine.play_new(instance, retain, self.backend) + } + fn play_id(&mut self, id: InstanceId) -> PlayResult { + self.engine.play(id, self.backend) + } + fn stop_instance(&mut self, id: InstanceId) { + self.engine.stop(id, self.backend); + } + fn update_category_volume(&mut self, source: usize, gain: f32) { + self.engine + .update_category_volume(source, gain, self.backend); + } +} +#[cfg(test)] +pub mod test_backend { + use super::{Backend, ChannelId}; + use crate::sound_events::Sound; + use std::collections::HashMap; + /// Channels that play until stopped. + #[derive(Default)] + pub struct Null { + next: ChannelId, + pub stopped: HashMap, + pub volume: HashMap, + } + impl Backend for Null { + fn create(&mut self, _streaming: bool) -> Option { + self.next += 1; + self.stopped.insert(self.next, false); + Some(self.next) + } + fn destroy(&mut self, c: ChannelId) { + self.stopped.remove(&c); + } + fn set_pitch(&mut self, _: ChannelId, _: f32) {} + fn set_volume(&mut self, c: ChannelId, v: f32) { + self.volume.insert(c, v); + } + fn set_attenuation(&mut self, _: ChannelId, _: Option) {} + fn set_looping(&mut self, _: ChannelId, _: bool) {} + fn set_position(&mut self, _: ChannelId, _: [f64; 3]) {} + fn set_relative(&mut self, _: ChannelId, _: bool) {} + fn start(&mut self, _: ChannelId, _: &Sound, _: bool) {} + fn stop(&mut self, c: ChannelId) { + self.stopped.insert(c, true); + } + fn pause(&mut self, _: ChannelId) {} + fn unpause(&mut self, _: ChannelId) {} + fn stopped(&mut self, c: ChannelId) -> bool { + self.stopped.get(&c).copied().unwrap_or(true) + } + } +} From f85411f2fbd68da7e9d0fa6414c08583e76938e4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:45:35 +0200 Subject: [PATCH 08/28] Port the camera, field of view and view/hurt bobbing exactly Camera.tick, tickFov, alignWithEntity with getMaxZoom over visual-shape clipping, setRotation and move with JOML quaternion arithmetic, calculateFov/calculateHudFov, getFieldOfViewModifier (now including flight), ClientAvatarState walk/bob history (the backwards-extrapolated walk distance and velocity-based bob) and GameRenderer.bobHurt/bobView as the JOML pose matrix with property flags. The game renders through them, adding hurt tilt, the camera distance and scale attributes, the mirrored front camera and the sleeping camera. tools/test_camera_parity.py compares 18,502 cases against the real classes. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/camera_probe.rs | 338 ++++++++ crates/horizon-client/src/camera.rs | 776 ++++++++++++++++++ crates/horizon-client/src/game.rs | 59 +- crates/horizon-client/src/game/fov.rs | 155 ++-- crates/horizon-client/src/game/perspective.rs | 211 ++++- crates/horizon-client/src/game/remote.rs | 18 +- crates/horizon-client/src/gfx.rs | 14 +- crates/horizon-client/src/lib.rs | 1 + .../parity/VanillaCameraOracle.java | 419 ++++++++++ tools/test_camera_parity.py | 199 +++++ 10 files changed, 2053 insertions(+), 137 deletions(-) create mode 100644 crates/horizon-client/examples/camera_probe.rs create mode 100644 crates/horizon-client/src/camera.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCameraOracle.java create mode 100644 tools/test_camera_parity.py diff --git a/crates/horizon-client/examples/camera_probe.rs b/crates/horizon-client/examples/camera_probe.rs new file mode 100644 index 000000000..889c1020a --- /dev/null +++ b/crates/horizon-client/examples/camera_probe.rs @@ -0,0 +1,338 @@ +#![forbid(unsafe_code)] +//! Runs the JSON-lines scenarios of tools/test_camera_parity.py through the +//! Rust camera, field-of-view, avatar bob and view/hurt bobbing code. +use horizon_client::{ + Result, + camera::{ + AvatarBob, BobState, Camera, CameraEntity, CameraFluid, CameraType, FovPlayer, HurtBob, + LivingCamera, UseItem, bob_matrix, field_of_view_modifier, + }, +}; +use horizon_core::{ + geometry::{Aabb, ShapeOp, Vec3, VoxelShape}, + position::BlockPos, +}; +use horizon_world::world_ray::{RayBlockMode, RayFluidMode, RayWorld, clip_world}; +use serde_json::Value; +use std::{ + collections::HashMap, + convert::Infallible, + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, +}; + +fn fl(v: &Value) -> f32 { + f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) +} +fn db(v: &Value) -> f64 { + f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) +} +fn fb(v: f32) -> String { + format!("{:08x}", if v.is_nan() { 0x7fc0_0000 } else { v.to_bits() }) +} +fn dbs(v: f64) -> String { + format!( + "{:016x}", + if v.is_nan() { + 0x7ff8_0000_0000_0000 + } else { + v.to_bits() + } + ) +} +fn b(v: &Value) -> bool { + v.as_bool().unwrap() +} +fn vec3(v: &Value) -> [f64; 3] { + [db(&v[0]), db(&v[1]), db(&v[2])] +} + +fn fov_player(c: &Value) -> FovPlayer { + FovPlayer { + flying: b(&c["flying"]), + walking_speed: fl(&c["ws"]), + movement_speed: db(&c["speed"]), + using: c["use"].as_array().map(|u| { + let item = match u[0].as_str().unwrap() { + "bow" => UseItem::Bow, + "spyglass" => UseItem::Spyglass, + _ => UseItem::Other, + }; + (item, u[1].as_i64().unwrap() as i32) + }), + } +} + +/// A level of visual shapes keyed by cell, without fluids. +struct Cells { + shapes: Vec, + index: HashMap, +} +impl RayWorld for Cells { + type Error = Infallible; + type Block = usize; + type Fluid = (); + fn block_state(&mut self, p: BlockPos) -> std::result::Result { + Ok(self.index.get(&p).copied().unwrap_or(0)) + } + fn fluid_state(&mut self, _: BlockPos) -> std::result::Result<(), Infallible> { + Ok(()) + } + fn block_shape( + &mut self, + s: usize, + _: BlockPos, + _: RayBlockMode, + ) -> std::result::Result { + Ok(self.shapes[s].clone()) + } + fn interaction_shape(&mut self, _: usize, _: BlockPos) -> std::result::Result { + Ok(VoxelShape::empty()) + } + fn fluid_is_source(&mut self, _: ()) -> std::result::Result { + Ok(false) + } + fn fluid_is_empty(&mut self, _: ()) -> std::result::Result { + Ok(true) + } + fn fluid_is_water(&mut self, _: ()) -> std::result::Result { + Ok(false) + } + fn fluid_shape(&mut self, _: (), _: BlockPos) -> std::result::Result { + Ok(VoxelShape::empty()) + } +} + +fn cells(c: &Value) -> Result { + let mut world = Cells { + shapes: vec![VoxelShape::empty()], + index: HashMap::new(), + }; + for (key, boxes) in c["cells"].as_object().unwrap() { + let at: Vec = key.split(' ').map(|v| v.parse().unwrap()).collect(); + let mut shape = VoxelShape::empty(); + for a in boxes.as_array().unwrap() { + shape = shape.join( + &VoxelShape::from_box(Aabb::new( + Vec3::new(db(&a[0]), db(&a[1]), db(&a[2])), + Vec3::new(db(&a[3]), db(&a[4]), db(&a[5])), + ))?, + ShapeOp::OR, + )?; + } + world.index.insert(BlockPos::new(at[0], at[1], at[2]), world.shapes.len()); + world.shapes.push(shape); + } + Ok(world) +} + +fn camera_type(v: &Value) -> CameraType { + [ + CameraType::FirstPerson, + CameraType::ThirdPersonBack, + CameraType::ThirdPersonFront, + ][v.as_u64().unwrap() as usize] +} + +/// The camera entity and, for players, what the field of view reads. +fn entity(s: &Value) -> (CameraEntity, Option) { + let player = s["kind"] == "player"; + let living = player.then(|| LivingCamera { + scale: db(&s["scale_attr"]) as f32, + camera_distance: db(&s["dist"]), + sleeping: s["sleeping"].as_array().map(|a| { + a[0].as_u64() + .map(|d| [0.0f32, 90.0, 180.0, 270.0][d as usize]) + }), + dead: s["dead"].as_i64().map(|t| t as i32), + }); + let mount = if player { + s["mount"] + .as_array() + .map(|a| (db(&a[0]) as f32, db(&a[1]))) + } else { + None + }; + ( + CameraEntity { + position: vec3(&s["pos"]), + previous: vec3(&s["prev"]), + x_rot: fl(&s["xr"]), + y_rot: fl(&s["yr"]), + x_rot_o: fl(&s["xro"]), + y_rot_o: fl(&s["yro"]), + eye_height: fl(&s["eye"]), + living, + mount, + }, + player.then(|| fov_player(s)), + ) +} + +fn camera(c: &Value, out: &mut impl Write) -> Result<()> { + let mut world = cells(c)?; + let fov_option = c["fov"].as_i64().unwrap() as i32; + let effect = db(&c["effect"]) as f32; + let mut kind = camera_type(&c["type"]); + let mut camera = Camera::default(); + let mut current: Option<(CameraEntity, Option)> = None; + for op in c["ops"].as_array().unwrap() { + match op[0].as_str().unwrap() { + "entity" => { + current = Some(entity(&op[1])); + writeln!(out, "entity")?; + } + "type" => { + kind = camera_type(&op[1]); + writeln!(out, "type")?; + } + "tick" => { + let target = current + .as_ref() + .and_then(|(_, p)| p.as_ref()) + .map_or(1.0, |p| { + field_of_view_modifier(p, kind.is_first_person(), effect) + }); + camera.tick(current.as_ref().map(|(e, _)| e.eye_height), target); + writeln!( + out, + "tick {} {} {} {}", + fb(camera.eye_height), + fb(camera.eye_height_old), + fb(camera.fov_modifier), + fb(camera.old_fov_modifier) + )?; + } + "frame" => { + let pt = fl(&op[1]); + let fluid = [ + CameraFluid::None, + CameraFluid::Water, + CameraFluid::Lava, + CameraFluid::PowderSnow, + ][op[2].as_u64().unwrap() as usize]; + let panoramic = b(&op[3]); + let (e, _) = current.as_ref().expect("entity"); + camera.align_with_entity(e, pt, kind, |from, to| { + let Ok(hit) = clip_world( + &mut world, + Vec3::new(from[0], from[1], from[2]), + Vec3::new(to[0], to[1], to[2]), + RayBlockMode::Visual, + RayFluidMode::None, + usize::MAX, + ) else { + panic!("ray") + }; + (!hit.miss).then(|| { + let l = hit.hit.location; + [l.x, l.y, l.z] + }) + }); + let dead = e.living.and_then(|l| l.dead); + let fov = camera.calculate_fov(pt, fov_option, effect, dead, fluid, panoramic); + let hud = camera.calculate_hud_fov(pt, effect, dead, fluid); + let p = camera.position; + let q = camera.rotation; + let v = |a: [f32; 3]| format!("{} {} {}", fb(a[0]), fb(a[1]), fb(a[2])); + writeln!( + out, + "frame {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}", + dbs(p[0]), + dbs(p[1]), + dbs(p[2]), + fb(camera.x_rot), + fb(camera.y_rot), + fb(q.x), + fb(q.y), + fb(q.z), + fb(q.w), + v(camera.forwards), + v(camera.up), + v(camera.left), + camera.detached, + fb(fov), + fb(hud) + )?; + } + other => panic!("{other}"), + } + } + Ok(()) +} + +fn bob(c: &Value, out: &mut impl Write) -> Result<()> { + let state = BobState { + living: (!c["living"].is_null()).then(|| { + let l = &c["living"]; + HurtBob { + hurt_time: fl(&l["hurt"]), + hurt_duration: l["duration"].as_i64().unwrap() as i32, + hurt_dir: fl(&l["dir"]), + death_time: (!l["death"].is_null()).then(|| fl(&l["death"])), + } + }), + player: c["player"].as_array().map(|p| (fl(&p[0]), fl(&p[1]))), + }; + let m = bob_matrix(&state, db(&c["tilt"]), b(&c["view"])); + let mut line = String::from("bob"); + for v in m.m { + line.push(' '); + line.push_str(&fb(v)); + } + writeln!(out, "{line} {}", m.properties)?; + Ok(()) +} + +fn avatar(c: &Value, out: &mut impl Write) -> Result<()> { + let mut state = AvatarBob::default(); + for op in c["ops"].as_array().unwrap() { + let name = op[0].as_str().unwrap(); + match name { + "tick" => state.tick(), + "move" => state.add_walked(fl(&op[1]), fl(&op[2])), + "bob" => state.update_bob(b(&op[1]) && !b(&op[2]) && !b(&op[3]), vec3(&op[4])), + "reset" => state.reset_bob(), + "frame" => { + let pt = fl(&op[1]); + writeln!( + out, + "frame {} {}", + fb(state.interpolated_bob(pt)), + fb(state.backwards_interpolated_walk_distance(pt)) + )?; + continue; + } + other => panic!("{other}"), + } + writeln!(out, "{name}")?; + } + Ok(()) +} + +fn main() -> Result<()> { + let args: Vec = std::env::args().collect(); + let input = BufReader::new(File::open(&args[1])?); + let mut out = BufWriter::new(File::create(&args[2])?); + for (n, line) in input.lines().enumerate() { + let c: Value = serde_json::from_str(&line?)?; + writeln!(out, "== {n}")?; + match c["t"].as_str().unwrap() { + "fov" => writeln!( + out, + "{}", + fb(field_of_view_modifier( + &fov_player(&c), + b(&c["fp"]), + fl(&c["scale"]) + )) + )?, + "camera" => camera(&c, &mut out)?, + "bob" => bob(&c, &mut out)?, + "avatar" => avatar(&c, &mut out)?, + other => panic!("{other}"), + } + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-client/src/camera.rs b/crates/horizon-client/src/camera.rs new file mode 100644 index 000000000..329ae3e86 --- /dev/null +++ b/crates/horizon-client/src/camera.rs @@ -0,0 +1,776 @@ +//! The camera (`Camera.tick`, `tickFov`, `calculateFov`, `alignWithEntity`, +//! `getMaxZoom`, `setRotation`, `move`), view and hurt bobbing +//! (`GameRenderer.bobView`, `bobHurt`), the walk and bob history they read +//! (`ClientAvatarState`), and `AbstractClientPlayer.getFieldOfViewModifier`. +//! +//! The float arithmetic follows vanilla and JOML's default (non-FMA, +//! non-fast-math) code paths operation by operation. +use horizon_core::geometry::trig; + +/// `(float) Math.PI`. +const PI: f32 = std::f32::consts::PI; +/// `(float) (Math.PI / 180.0)`. +const DEG_TO_RAD: f32 = trig::DEG_TO_RAD; + +/// `Math.min(float, float)`: NaN wins and -0.0 is below 0.0. +pub fn java_min(a: f32, b: f32) -> f32 { + if a.is_nan() || b.is_nan() { + f32::NAN + } else if a == 0.0 && b == 0.0 { + f32::from_bits(a.to_bits() | b.to_bits()) + } else if a <= b { + a + } else { + b + } +} +/// `Math.max(float, float)`. +pub fn java_max(a: f32, b: f32) -> f32 { + if a.is_nan() || b.is_nan() { + f32::NAN + } else if a == 0.0 && b == 0.0 { + f32::from_bits(a.to_bits() & b.to_bits()) + } else if a >= b { + a + } else { + b + } +} +/// `Mth.lerp(float, float, float)`. +pub fn lerp(alpha: f32, p0: f32, p1: f32) -> f32 { + p0 + alpha * (p1 - p0) +} +/// `Mth.lerp(double, double, double)`. +pub fn lerp_d(alpha: f64, p0: f64, p1: f64) -> f64 { + p0 + alpha * (p1 - p0) +} +/// `Mth.wrapDegrees(float)`. +pub fn wrap_degrees(angle: f32) -> f32 { + let mut normalized = angle % 360.0; + if normalized >= 180.0 { + normalized -= 360.0; + } + if normalized < -180.0 { + normalized += 360.0; + } + normalized +} +/// `Mth.clamp(float, float, float)`. +pub fn clamp(value: f32, min: f32, max: f32) -> f32 { + if value < min { min } else { java_min(value, max) } +} + +/// JOML's float trigonometry (`org.joml.Math` without fast math). +pub mod joml { + use super::PI; + const TAU: f32 = std::f32::consts::TAU; + const HALF_PI: f32 = std::f32::consts::FRAC_PI_2; + + /// `Math.sin(float)`: `java.lang.Math.sin` narrowed. + pub fn sin(rad: f32) -> f32 { + f64::from(rad).sin() as f32 + } + /// `Math.cosFromSin(float, float)`. + pub fn cos_from_sin(sin: f32, angle: f32) -> f32 { + let cos = (1.0 - sin * sin).sqrt(); + let a = angle + HALF_PI; + let mut b = a - (a / TAU) as i32 as f32 * TAU; + if f64::from(b) < 0.0 { + b += TAU; + } + if b >= PI { -cos } else { cos } + } + + /// A JOML `Quaternionf` (x, y, z, w). + #[derive(Clone, Copy, Debug, PartialEq)] + pub struct Quat { + pub x: f32, + pub y: f32, + pub z: f32, + pub w: f32, + } + impl Quat { + pub const IDENTITY: Self = Self { + x: 0.0, + y: 0.0, + z: 0.0, + w: 1.0, + }; + /// `Quaternionf.rotationYXZ(angleY, angleX, angleZ)`. + pub fn rotation_yxz(angle_y: f32, angle_x: f32, angle_z: f32) -> Self { + let sx = sin(angle_x * 0.5); + let cx = cos_from_sin(sx, angle_x * 0.5); + let sy = sin(angle_y * 0.5); + let cy = cos_from_sin(sy, angle_y * 0.5); + let sz = sin(angle_z * 0.5); + let cz = cos_from_sin(sz, angle_z * 0.5); + let x = cy * sx; + let y = sy * cx; + let z = sy * sx; + let w = cy * cx; + Self { + x: x * cz + y * sz, + y: y * cz - x * sz, + z: w * sz - z * cz, + w: w * cz + z * sz, + } + } + /// `Quaternionf.transform(x, y, z, dest)` (`Vector3f.rotate`). + pub fn transform(&self, v: [f32; 3]) -> [f32; 3] { + let [x, y, z] = v; + let xx = self.x * self.x; + let yy = self.y * self.y; + let zz = self.z * self.z; + let ww = self.w * self.w; + let xy = self.x * self.y; + let xz = self.x * self.z; + let yz = self.y * self.z; + let xw = self.x * self.w; + let zw = self.z * self.w; + let yw = self.y * self.w; + let k = 1.0 / (xx + yy + zz + ww); + [ + (xx - yy - zz + ww) * k * x + + (2.0 * (xy - zw) * k * y + 2.0 * (xz + yw) * k * z), + 2.0 * (xy + zw) * k * x + + ((yy - xx - zz + ww) * k * y + 2.0 * (yz - xw) * k * z), + 2.0 * (xz - yw) * k * x + + (2.0 * (yz + xw) * k * y + (zz - xx - yy + ww) * k * z), + ] + } + } + + const PERSPECTIVE: u8 = 1; + const IDENTITY: u8 = 4; + const TRANSLATION: u8 = 8; + + /// A JOML `Matrix4f` with its property flags, which select the code + /// paths (and so the rounding) of later operations. `m[column * 4 + row]`. + #[derive(Clone, Copy, Debug, PartialEq)] + pub struct Mat4 { + pub m: [f32; 16], + pub properties: u8, + } + impl Default for Mat4 { + fn default() -> Self { + Self::IDENTITY + } + } + impl Mat4 { + /// `new Matrix4f()`. + pub const IDENTITY: Self = Self { + m: [ + 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, + ], + properties: 30, + }; + fn get(&self, column: usize, row: usize) -> f32 { + self.m[column * 4 + row] + } + fn set(&mut self, column: usize, row: usize, v: f32) { + self.m[column * 4 + row] = v; + } + fn reset_unless_identity(&mut self) { + if self.properties & IDENTITY == 0 { + self.m = Self::IDENTITY.m; + } + } + /// `Matrix4f.translation(x, y, z)`. + pub fn translation(&mut self, x: f32, y: f32, z: f32) { + self.reset_unless_identity(); + self.set(3, 0, x); + self.set(3, 1, y); + self.set(3, 2, z); + self.properties = 26; + } + /// `Matrix4f.setTranslation(x, y, z)`. + pub fn set_translation(&mut self, x: f32, y: f32, z: f32) { + self.set(3, 0, x); + self.set(3, 1, y); + self.set(3, 2, z); + self.properties &= !(PERSPECTIVE | IDENTITY); + } + /// `Matrix4f.translate(x, y, z)`. + pub fn translate(&mut self, x: f32, y: f32, z: f32) { + if self.properties & IDENTITY != 0 { + self.translation(x, y, z); + return; + } + for row in 0..4 { + let v = self.get(0, row) * x + + (self.get(1, row) * y + (self.get(2, row) * z + self.get(3, row))); + self.set(3, row, v); + } + self.properties &= !(PERSPECTIVE | IDENTITY); + } + fn rotation_axis(&mut self, axis: usize, ang: f32) { + let sin = sin(ang); + let cos = cos_from_sin(sin, ang); + self.reset_unless_identity(); + match axis { + 0 => { + self.set(1, 1, cos); + self.set(1, 2, sin); + self.set(2, 1, -sin); + self.set(2, 2, cos); + } + 1 => { + self.set(0, 0, cos); + self.set(0, 2, -sin); + self.set(2, 0, sin); + self.set(2, 2, cos); + } + _ => { + self.set(0, 0, cos); + self.set(0, 1, sin); + self.set(1, 0, -sin); + self.set(1, 1, cos); + } + } + self.properties = 18; + } + /// `Matrix4f.rotateX/rotateY/rotateZ(ang)`, with the identity and + /// pure-translation shortcuts. + fn rotate_axis(&mut self, axis: usize, ang: f32) { + if self.properties & IDENTITY != 0 { + self.rotation_axis(axis, ang); + return; + } + if self.properties & TRANSLATION != 0 { + let (x, y, z) = (self.get(3, 0), self.get(3, 1), self.get(3, 2)); + self.rotation_axis(axis, ang); + self.set_translation(x, y, z); + return; + } + let sin = sin(ang); + let cos = cos_from_sin(sin, ang); + let s = *self; + match axis { + 0 => { + for row in 0..4 { + let (l1, l2) = (s.get(1, row), s.get(2, row)); + self.set(2, row, l1 * -sin + l2 * cos); + self.set(1, row, l1 * cos + l2 * sin); + } + } + 1 => { + for row in 0..4 { + let (l0, l2) = (s.get(0, row), s.get(2, row)); + self.set(0, row, l0 * cos + l2 * -sin); + self.set(2, row, l0 * sin + l2 * cos); + } + } + _ => { + // rotateTowardsXY(sin, cos). + let (dx, dy) = (sin, cos); + for row in 0..4 { + let (l0, l1) = (s.get(0, row), s.get(1, row)); + self.set(0, row, l0 * dy + l1 * dx); + self.set(1, row, l0 * -dx + l1 * dy); + } + } + } + self.properties &= !(PERSPECTIVE | IDENTITY | TRANSLATION); + } + pub fn rotate_x(&mut self, ang: f32) { + self.rotate_axis(0, ang); + } + pub fn rotate_y(&mut self, ang: f32) { + self.rotate_axis(1, ang); + } + pub fn rotate_z(&mut self, ang: f32) { + // rotateTowardsXY also short-cuts on identity, but rotateZ has + // already taken that branch. + self.rotate_axis(2, ang); + } + } +} +use joml::{Mat4, Quat}; + +/// `CameraType`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum CameraType { + #[default] + FirstPerson, + ThirdPersonBack, + ThirdPersonFront, +} +impl CameraType { + pub fn is_first_person(self) -> bool { + self == Self::FirstPerson + } + pub fn is_mirrored(self) -> bool { + self == Self::ThirdPersonFront + } + /// `CameraType.cycle` (F5). + pub fn cycle(self) -> Self { + match self { + Self::FirstPerson => Self::ThirdPersonBack, + Self::ThirdPersonBack => Self::ThirdPersonFront, + Self::ThirdPersonFront => Self::FirstPerson, + } + } +} + +/// What `AbstractClientPlayer.getFieldOfViewModifier` reads. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FovPlayer { + /// `Abilities.flying`. + pub flying: bool, + /// `Abilities.getWalkingSpeed()`. + pub walking_speed: f32, + /// `getAttributeValue(MOVEMENT_SPEED)`. + pub movement_speed: f64, + /// The item in use and its use ticks, when using one. + pub using: Option<(UseItem, i32)>, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum UseItem { + Bow, + Spyglass, + Other, +} +/// `AbstractClientPlayer.getFieldOfViewModifier(firstPerson, effectScale)`. +pub fn field_of_view_modifier(p: &FovPlayer, first_person: bool, effect_scale: f32) -> f32 { + let mut modifier = 1.0f32; + if p.flying { + modifier *= 1.1; + } + let walking_speed = p.walking_speed; + if walking_speed != 0.0 { + let speed_factor = p.movement_speed as f32 / walking_speed; + modifier *= (speed_factor + 1.0) / 2.0; + } + if let Some((item, ticks)) = p.using { + match item { + UseItem::Bow => { + let scale = java_min(ticks as f32 / 20.0, 1.0); + modifier *= 1.0 - scale * scale * 0.15; + } + // isScoping: using a spyglass. + UseItem::Spyglass if first_person => return 0.1, + _ => {} + } + } + lerp(effect_scale, 1.0, modifier) +} + +/// The camera entity as `Camera.alignWithEntity` and the field-of-view +/// death and hurt effects see it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CameraEntity { + pub position: [f64; 3], + /// `xo`, `yo`, `zo`. + pub previous: [f64; 3], + pub x_rot: f32, + pub y_rot: f32, + pub x_rot_o: f32, + pub y_rot_o: f32, + /// `Entity.getEyeHeight()`. + pub eye_height: f32, + /// A living entity's `getScale()` and camera distance attribute. + pub living: Option, + /// The vehicle's scale and camera distance when it is living. + pub mount: Option<(f32, f64)>, +} +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct LivingCamera { + pub scale: f32, + pub camera_distance: f64, + /// `isSleeping()` with `getBedOrientation()` as its `toYRot()`. + pub sleeping: Option>, + /// `isDeadOrDying()` and `deathTime`. + pub dead: Option, +} +impl CameraEntity { + /// `Entity.getXRot(partialTicks)`. + pub fn view_x_rot(&self, partial: f32) -> f32 { + if partial == 1.0 { + self.x_rot + } else { + lerp(partial, self.x_rot_o, self.x_rot) + } + } + /// `LocalPlayer.getViewYRot` (`getYRot(partialTicks)`, a `Mth.rotLerp`). + pub fn view_y_rot(&self, partial: f32) -> f32 { + if partial == 1.0 { + self.y_rot + } else { + self.y_rot_o + partial * wrap_degrees(self.y_rot - self.y_rot_o) + } + } +} + +/// The fluid `Camera.getFluidInCamera` reports, as the field of view sees it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum CameraFluid { + #[default] + None, + Water, + Lava, + PowderSnow, +} + +/// `Camera`: the eye-height and field-of-view easing and the view placement. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Camera { + pub eye_height: f32, + pub eye_height_old: f32, + pub fov_modifier: f32, + pub old_fov_modifier: f32, + pub position: [f64; 3], + pub x_rot: f32, + pub y_rot: f32, + pub rotation: Quat, + pub forwards: [f32; 3], + pub up: [f32; 3], + pub left: [f32; 3], + pub detached: bool, +} +impl Default for Camera { + fn default() -> Self { + Self { + eye_height: 0.0, + eye_height_old: 0.0, + fov_modifier: 0.0, + old_fov_modifier: 0.0, + position: [0.0; 3], + x_rot: 0.0, + y_rot: 0.0, + rotation: Quat::IDENTITY, + forwards: [0.0, 0.0, -1.0], + up: [0.0, 1.0, 0.0], + left: [-1.0, 0.0, 0.0], + detached: false, + } + } +} +impl Camera { + /// `Camera.tick`: the eye height eases halfway toward the entity's + /// (with a level and an entity), then `tickFov` with the camera entity's + /// field-of-view modifier target (1 when it is not a player). + pub fn tick(&mut self, entity_eye_height: Option, target_fov_modifier: f32) { + if let Some(eye) = entity_eye_height { + self.eye_height_old = self.eye_height; + self.eye_height += (eye - self.eye_height) * 0.5; + } + self.old_fov_modifier = self.fov_modifier; + self.fov_modifier += (target_fov_modifier - self.fov_modifier) * 0.5; + self.fov_modifier = clamp(self.fov_modifier, 0.1, 1.5); + } + /// `Camera.setRotation`. + pub fn set_rotation(&mut self, y_rot: f32, x_rot: f32) { + self.x_rot = x_rot; + self.y_rot = y_rot; + self.rotation = Quat::rotation_yxz(PI - y_rot * DEG_TO_RAD, -x_rot * DEG_TO_RAD, 0.0); + self.forwards = self.rotation.transform([0.0, 0.0, -1.0]); + self.up = self.rotation.transform([0.0, 1.0, 0.0]); + self.left = self.rotation.transform([-1.0, 0.0, 0.0]); + } + /// `Camera.move(forwards, up, right)`. + pub fn move_by(&mut self, forwards: f32, up: f32, right: f32) { + let offset = self.rotation.transform([right, up, -forwards]); + self.position = [ + self.position[0] + f64::from(offset[0]), + self.position[1] + f64::from(offset[1]), + self.position[2] + f64::from(offset[2]), + ]; + } + /// `Camera.alignWithEntity` (not riding a minecart with the new + /// movement): the entity's view rotation and interpolated eye, then a + /// detached camera backed off along the view (`getMaxZoom`) or a sleeping + /// one turned to the bed. `clip` is `Level.clip` with + /// `ClipContext.Block.VISUAL` and no fluids; it returns the hit location + /// unless the ray misses. + pub fn align_with_entity( + &mut self, + entity: &CameraEntity, + partial: f32, + camera_type: CameraType, + mut clip: impl FnMut([f64; 3], [f64; 3]) -> Option<[f64; 3]>, + ) { + self.set_rotation(entity.view_y_rot(partial), entity.view_x_rot(partial)); + let p = f64::from(partial); + self.position = [ + lerp_d(p, entity.previous[0], entity.position[0]), + lerp_d(p, entity.previous[1], entity.position[1]) + + f64::from(lerp(partial, self.eye_height_old, self.eye_height)), + lerp_d(p, entity.previous[2], entity.position[2]), + ]; + self.detached = !camera_type.is_first_person(); + if self.detached { + if camera_type.is_mirrored() { + self.set_rotation(self.y_rot + 180.0, -self.x_rot); + } + let (mut distance, mut scale) = (4.0f32, 1.0f32); + if let Some(living) = &entity.living { + scale = living.scale; + distance = living.camera_distance as f32; + } + let (mut mount_scale, mut mount_distance) = (scale, distance); + if let Some((s, d)) = entity.mount { + mount_scale = s; + mount_distance = d as f32; + } + let zoom = self.max_zoom( + java_max(scale * distance, mount_scale * mount_distance), + &mut clip, + ); + self.move_by(-zoom, 0.0, 0.0); + } else if let Some(LivingCamera { + sleeping: Some(bed), + .. + }) = entity.living + { + self.set_rotation(bed.map_or(0.0, |yaw| yaw - 180.0), 0.0); + self.move_by(0.0, 0.15, 0.0); + } + } + /// `Camera.getMaxZoom`: eight rays from the corners of a 0.2 cube about + /// the eye, shortening the distance to the nearest visual-shape hit. + pub fn max_zoom( + &self, + mut distance: f32, + clip: &mut impl FnMut([f64; 3], [f64; 3]) -> Option<[f64; 3]>, + ) -> f32 { + let at = self.position; + for i in 0..8 { + let offset = [ + ((i & 1) * 2 - 1) as f32, + ((i >> 1 & 1) * 2 - 1) as f32, + ((i >> 2 & 1) * 2 - 1) as f32, + ]; + let from: [f64; 3] = std::array::from_fn(|a| at[a] + f64::from(offset[a] * 0.1)); + let back = f64::from(-distance); + let to: [f64; 3] = + std::array::from_fn(|a| from[a] + f64::from(self.forwards[a]) * back); + if let Some(hit) = clip(from, to) { + let d = [hit[0] - at[0], hit[1] - at[1], hit[2] - at[2]]; + let dist_sq = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]) as f32; + if dist_sq < distance * distance { + distance = dist_sq.sqrt(); + } + } + } + distance + } + /// `Camera.calculateFov`: the option scaled by the eased modifier, then + /// the death and fluid effects. + pub fn calculate_fov( + &self, + partial: f32, + fov_option: i32, + effect_scale: f32, + dead: Option, + fluid: CameraFluid, + panoramic: bool, + ) -> f32 { + if panoramic { + return 90.0; + } + let fov = + fov_option as f32 * lerp(partial, self.old_fov_modifier, self.fov_modifier); + modify_fov_based_on_death_or_fluid(partial, fov, effect_scale, dead, fluid) + } + /// `Camera.calculateHudFov`. + pub fn calculate_hud_fov( + &self, + partial: f32, + effect_scale: f32, + dead: Option, + fluid: CameraFluid, + ) -> f32 { + modify_fov_based_on_death_or_fluid(partial, 70.0, effect_scale, dead, fluid) + } +} +/// `Camera.modifyFovBasedOnDeathOrFluid`. `dead` is the camera entity's +/// `deathTime` while it is a living entity that is dead or dying. +pub fn modify_fov_based_on_death_or_fluid( + partial: f32, + mut fov: f32, + effect_scale: f32, + dead: Option, + fluid: CameraFluid, +) -> f32 { + if let Some(death_time) = dead { + let duration = java_min(death_time as f32 + partial, 20.0); + fov /= (1.0 - 500.0 / (duration + 500.0)) * 2.0 + 1.0; + } + if matches!(fluid, CameraFluid::Lava | CameraFluid::Water) { + fov *= lerp(effect_scale, 1.0, 0.857_142_87); + } + fov +} + +/// `ClientAvatarState`: the walked distance and view bob of a player. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct AvatarBob { + pub walk_dist: f32, + pub walk_dist_o: f32, + pub bob: f32, + pub bob_o: f32, +} +impl AvatarBob { + /// `ClientAvatarState.tick` (at the start of `AbstractClientPlayer.tick`). + pub fn tick(&mut self) { + self.walk_dist_o = self.walk_dist; + } + /// `LocalPlayer.move`: `addWalkedDistance(Mth.length(dx, dz) * 0.6F)` + /// with the float horizontal displacement. + pub fn add_walked(&mut self, dx: f32, dz: f32) { + self.walk_dist += (dx * dx + dz * dz).sqrt() * 0.6; + } + /// `AbstractClientPlayer.updateBob`: toward the horizontal speed (at most + /// 0.1) on the ground, toward 0 otherwise. + pub fn update_bob(&mut self, on_ground_alive_not_swimming: bool, velocity: [f64; 3]) { + let target = if on_ground_alive_not_swimming { + java_min( + 0.1, + (velocity[0] * velocity[0] + velocity[2] * velocity[2]).sqrt() as f32, + ) + } else { + 0.0 + }; + self.bob_o = self.bob; + self.bob += (target - self.bob) * 0.4; + } + /// `ClientAvatarState.resetBob` (`AbstractClientPlayer.rideTick`). + pub fn reset_bob(&mut self) { + self.bob_o = self.bob; + self.bob = 0.0; + } + pub fn interpolated_bob(&self, partial: f32) -> f32 { + lerp(partial, self.bob_o, self.bob) + } + pub fn backwards_interpolated_walk_distance(&self, partial: f32) -> f32 { + let wda = self.walk_dist - self.walk_dist_o; + -(self.walk_dist + wda * partial) + } +} + +/// The parts of `CameraRenderState.entityRenderState` the bobbing reads. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct BobState { + /// A living camera entity: `hurtTime - partial`, `hurtDuration`, + /// `getHurtDir()`, and `deathTime + partial` when dead or dying. + pub living: Option, + /// A player camera entity: the backwards-interpolated walk distance and + /// the interpolated bob. + pub player: Option<(f32, f32)>, +} +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct HurtBob { + pub hurt_time: f32, + pub hurt_duration: i32, + pub hurt_dir: f32, + pub death_time: Option, +} +/// `PoseStack.rotateDegrees` on the pose with an `Axis`. +fn rotate_degrees(m: &mut Mat4, axis: usize, degrees: f32) { + let ang = degrees * DEG_TO_RAD; + match axis { + 0 => m.rotate_x(ang), + 1 => m.rotate_y(ang), + _ => m.rotate_z(ang), + } +} +/// `GameRenderer.bobHurt`. +pub fn bob_hurt(state: &BobState, damage_tilt_strength: f64, pose: &mut Mat4) { + let Some(living) = state.living else { return }; + let mut hurt = living.hurt_time; + if let Some(death_time) = living.death_time { + let duration = java_min(death_time, 20.0); + rotate_degrees(pose, 2, 40.0 - 8000.0 / (duration + 200.0)); + } + if hurt < 0.0 { + return; + } + hurt /= living.hurt_duration as f32; + hurt = trig::sin(f64::from(hurt * hurt * hurt * hurt * PI)); + let rr = living.hurt_dir; + rotate_degrees(pose, 1, -rr); + let tilt = (f64::from(-hurt) * 14.0 * damage_tilt_strength) as f32; + rotate_degrees(pose, 2, tilt); + rotate_degrees(pose, 1, rr); +} +/// `GameRenderer.bobView`. +pub fn bob_view(state: &BobState, pose: &mut Mat4) { + let Some((walk, bob)) = state.player else { + return; + }; + pose.translate( + trig::sin(f64::from(walk * PI)) * bob * 0.5, + -(trig::cos(f64::from(walk * PI)) * bob).abs(), + 0.0, + ); + rotate_degrees(pose, 2, trig::sin(f64::from(walk * PI)) * bob * 3.0); + rotate_degrees(pose, 0, (trig::cos(f64::from(walk * PI - 0.2)) * bob).abs() * 5.0); +} +/// The bob matrix `GameRenderer.renderLevel` multiplies into the projection +/// (and `renderItemInHand` into the hand's pose). +pub fn bob_matrix(state: &BobState, damage_tilt_strength: f64, bob_view_option: bool) -> Mat4 { + let mut pose = Mat4::IDENTITY; + bob_hurt(state, damage_tilt_strength, &mut pose); + if bob_view_option { + bob_view(state, &mut pose); + } + pose +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn camera_eases_eye_height_and_fov() { + let mut camera = Camera::default(); + camera.tick(Some(1.62), 1.0); + assert_eq!(camera.eye_height, 0.81); + assert_eq!(camera.fov_modifier, 0.5); + camera.tick(None, 1.0); + assert_eq!(camera.eye_height, 0.81); + assert_eq!(camera.fov_modifier, 0.75); + } + #[test] + fn rotation_faces_south_at_zero_yaw() { + let mut camera = Camera::default(); + camera.set_rotation(0.0, 0.0); + assert!((camera.forwards[2] - 1.0).abs() < 1e-6); + camera.set_rotation(90.0, 0.0); + assert!((camera.forwards[0] + 1.0).abs() < 1e-6); + } + #[test] + fn detached_camera_backs_off_until_blocked() { + let entity = CameraEntity { + position: [0.0; 3], + previous: [0.0; 3], + x_rot: 0.0, + y_rot: 0.0, + x_rot_o: 0.0, + y_rot_o: 0.0, + eye_height: 1.62, + living: None, + mount: None, + }; + let mut camera = Camera::default(); + camera.align_with_entity(&entity, 1.0, CameraType::ThirdPersonBack, |_, _| None); + assert!((camera.position[2] + 4.0).abs() < 1e-6); + camera.align_with_entity(&entity, 1.0, CameraType::ThirdPersonBack, |_, _| { + Some([0.0, 0.0, -1.0]) + }); + assert!(camera.position[2] > -1.1 && camera.position[2] < -0.9); + } + #[test] + fn fov_modifier_combines_speed_flight_and_bow() { + let mut p = FovPlayer { + flying: false, + walking_speed: 0.1, + movement_speed: 0.13, + using: None, + }; + assert_eq!(field_of_view_modifier(&p, true, 1.0), (0.13f32 / 0.1 + 1.0) / 2.0); + assert_eq!(field_of_view_modifier(&p, true, 0.0), 1.0); + p.using = Some((UseItem::Spyglass, 3)); + assert_eq!(field_of_view_modifier(&p, true, 1.0), 0.1); + assert_ne!(field_of_view_modifier(&p, false, 1.0), 0.1); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b81c403fd..23162566b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -615,7 +615,8 @@ struct Game<'a> { /// Item being used (eaten): hotbar slot and ticks used. using: Option<(usize, u32)>, /// Camera.oldFovModifier / fovModifier. - fov_modifier: [f32; 2], + /// `Camera` (eye height and field-of-view easing, view placement). + view: horizon_client::camera::Camera, /// Hud.scopeScale (spyglass overlay size). scope_scale: f32, /// Duration of the last frame in ticks (GUI easing). @@ -645,8 +646,8 @@ struct Game<'a> { /// Where the options screen returns: true = title, false = pause menu. options_from_title: bool, dragging: bool, - walk: (f32, f32), - bob: (f32, f32), + /// `ClientAvatarState`: walked distance and view bob. + avatar: horizon_client::camera::AvatarBob, flash: u32, /// Sleeping in a bed: (bed head position, ticks asleep). sleeping: Option<([i32; 3], u32)>, @@ -2536,6 +2537,11 @@ impl Game<'_> { .and_then(|s| self.res.items.get(&s.item)) .map(|i| i.use_speed); let grounded = player.ground.on_ground; + let before = ( + grounded, + [player.velocity.x, player.velocity.y, player.velocity.z], + [player.position.x, player.position.y, player.position.z], + ); if !riding { MotionWorld { player, @@ -2562,6 +2568,7 @@ impl Game<'_> { self.previous_eye = self.eye; self.eye += (player.dimensions.eye_height - self.eye) * 0.5; let crouching = player.pose == horizon_client::pose::Pose::Crouching; + self.tick_avatar(before, riding); self.record_combat(&events); for event in events { match event { @@ -2706,23 +2713,6 @@ impl Game<'_> { self.tick_falling()?; self.tick_tnt()?; } - if let Some(p) = &self.player { - // Player.aiStep bob and Entity.walkDist (0.6 per block). - let (dx, dz) = ( - p.position.x - self.previous_position.x, - p.position.z - self.previous_position.z, - ); - let speed = ((dx * dx + dz * dz).sqrt() as f32).min(0.1); - self.walk.0 = self.walk.1; - self.walk.1 += (dx * dx + dz * dz).sqrt() as f32 * 0.6; - self.bob.0 = self.bob.1; - let target = if p.ground.on_ground && !p.health.dead_or_dying() { - speed - } else { - 0.0 - }; - self.bob.1 += (target - self.bob.1) * 0.4; - } if running { self.tick_block_entities()?; self.tick_sculk()?; @@ -7387,16 +7377,8 @@ impl Game<'_> { return Ok(false); }; let alpha = self.clock.fraction(); - let (camera, underwater, view_yaw, view_pitch) = match &self.player { - Some(p) => { - let (a, b) = (self.previous_position, p.position); - let eye = self.previous_eye + alpha as f32 * (self.eye - self.previous_eye); - let c = glam::DVec3::new( - a.x + (b.x - a.x) * alpha, - a.y + (b.y - a.y) * alpha + f64::from(eye), - a.z + (b.z - a.z) * alpha, - ); - let (c, yaw, pitch) = self.camera_view(c); + let (camera, underwater, view_yaw, view_pitch) = match self.camera_view(alpha as f32) { + Some((c, yaw, pitch)) => { let s = self.world .block(c.x.floor() as i32, c.y.floor() as i32, c.z.floor() as i32); @@ -7534,13 +7516,11 @@ impl Game<'_> { } else { self.fov_degrees(alpha as f32, camera.to_array()) }, - bob: (self.settings.view_bobbing && !title && self.player.is_some()).then(|| { - let a = alpha as f32; - ( - self.walk.0 + (self.walk.1 - self.walk.0) * a, - self.bob.0 + (self.bob.1 - self.bob.0) * a, - ) - }), + bob: if title { + glam::Mat4::IDENTITY + } else { + self.bob_matrix(alpha as f32) + }, sky, distance: (self.streaming.radius * 16) as f32, underwater, @@ -8523,7 +8503,7 @@ pub fn run() -> Result<()> { last_hurt_by_player: HashSet::new(), chest_open: HashMap::new(), using: None, - fov_modifier: [1.0, 1.0], + view: Default::default(), scope_scale: 0.5, frame_ticks: 0.0, title: None, @@ -8544,8 +8524,7 @@ pub fn run() -> Result<()> { settings, options_from_title: false, dragging: false, - walk: (0.0, 0.0), - bob: (0.0, 0.0), + avatar: Default::default(), flash: 0, sleeping: None, dim: Dim::Overworld, diff --git a/crates/horizon-client/src/game/fov.rs b/crates/horizon-client/src/game/fov.rs index a40be8a13..faf0f0924 100644 --- a/crates/horizon-client/src/game/fov.rs +++ b/crates/horizon-client/src/game/fov.rs @@ -1,16 +1,18 @@ //! Field of view (`Camera.tickFov`, `calculateFov`, -//! `AbstractClientPlayer.getFieldOfViewModifier`) and the spyglass -//! (`SpyglassItem`, `Hud.extractSpyglassOverlay`). +//! `AbstractClientPlayer.getFieldOfViewModifier`), view and hurt bobbing +//! (`GameRenderer.bobHurt`, `bobView`) and the spyglass (`SpyglassItem`, +//! `Hud.extractSpyglassOverlay`). The arithmetic is `horizon_client::camera`. use super::Game; use horizon_client::{ + camera::{ + BobState, CameraFluid, FovPlayer, HurtBob, UseItem, bob_matrix, field_of_view_modifier, + }, fog::{FogType, fog_type}, hud::{HudBatch, rgba}, }; /// `Abilities.walkingSpeed`. const WALKING_SPEED: f32 = 0.1; -/// `options.fovEffectScale` (vanilla default 1). -const FOV_EFFECT_SCALE: f32 = 1.0; impl Game<'_> { /// `Player.isScoping`: using a spyglass. @@ -19,54 +21,115 @@ impl Game<'_> { .and_then(|(slot, _)| self.stack_in(slot)) .is_some_and(|s| &*s.item == "minecraft:spyglass") } - /// `AbstractClientPlayer.getFieldOfViewModifier` (first person). - fn fov_target(&self) -> f32 { - let Some(p) = &self.player else { return 1.0 }; - let mut modifier = 1.0f32; - // Movement speed (sprinting, speed and slowness) relative to walking. - modifier *= (p.speed / WALKING_SPEED + 1.0) / 2.0; - if let Some((slot, ticks)) = self.using - && let Some(stack) = self.stack_in(slot) - { - match &*stack.item { - "minecraft:bow" => { - let scale = (ticks as f32 / 20.0).min(1.0); - modifier *= 1.0 - scale * scale * 0.15; - } - "minecraft:spyglass" => return 0.1, - _ => {} - } - } - 1.0 + (modifier - 1.0) * FOV_EFFECT_SCALE + /// `options.fovEffectScale`. + pub(super) fn fov_effect_scale(&self) -> f32 { + self.settings.file.double("fovEffectScale") as f32 } - /// `Camera.tickFov`. + /// What `AbstractClientPlayer.getFieldOfViewModifier` reads. + fn fov_player(&self) -> Option { + let p = self.player.as_ref()?; + let using = self.using.and_then(|(slot, ticks)| { + let stack = self.stack_in(slot)?; + let item = match &*stack.item { + "minecraft:bow" => UseItem::Bow, + "minecraft:spyglass" => UseItem::Spyglass, + _ => UseItem::Other, + }; + Some((item, ticks as i32)) + }); + Some(FovPlayer { + flying: p.flying, + walking_speed: WALKING_SPEED, + // Player.aiStep keeps `speed` as the float movement speed attribute. + movement_speed: f64::from(p.speed), + using, + }) + } + /// `Camera.tick`: the eye height and the field-of-view modifier ease + /// halfway toward the player's each tick. pub(super) fn tick_fov(&mut self) { - let target = self.fov_target(); - let [_, current] = self.fov_modifier; - let next = (current + (target - current) * 0.5).clamp(0.1, 1.5); - self.fov_modifier = [current, next]; + let first_person = self.camera_type.first_person(); + let effect = self.fov_effect_scale(); + let target = self + .fov_player() + .map_or(1.0, |p| field_of_view_modifier(&p, first_person, effect)); + let eye = self.player.as_ref().map(|p| p.dimensions.eye_height); + self.view.tick(eye, target); + } + /// The player's `deathTime` while dead or dying. + fn death_time(&self) -> Option { + let p = self.player.as_ref()?; + p.health.dead_or_dying().then(|| { + self.ui + .died_at + .map_or(0, |t| (t.elapsed().as_secs_f32() * 20.0) as i32) + }) + } + /// The fluid at the camera, as `Camera.getFluidInCamera` reports it. + fn camera_fluid(&self, camera: [f64; 3]) -> CameraFluid { + match fog_type(&self.world, &self.res.facts, camera, self.forward()) { + FogType::Water => CameraFluid::Water, + FogType::Lava => CameraFluid::Lava, + FogType::PowderSnow => CameraFluid::PowderSnow, + FogType::Atmospheric => CameraFluid::None, + } } /// `Camera.calculateFov` with `modifyFovBasedOnDeathOrFluid`. pub(super) fn fov_degrees(&self, partial: f32, camera: [f64; 3]) -> f32 { - let [old, new] = self.fov_modifier; - let mut fov = self.settings.fov * (old + (new - old) * partial); - if let Some(p) = &self.player - && p.health.dead_or_dying() - { - let ticks = self - .ui - .died_at - .map_or(0.0, |t| t.elapsed().as_secs_f32() * 20.0); - let duration = (ticks + partial).min(20.0); - fov /= (1.0 - 500.0 / (duration + 500.0)) * 2.0 + 1.0; + self.view.calculate_fov( + partial, + self.settings.fov as i32, + self.fov_effect_scale(), + self.death_time(), + self.camera_fluid(camera), + false, + ) + } + /// The pose `GameRenderer.renderLevel` multiplies into the projection: + /// `bobHurt`, then `bobView` with the View Bobbing option. + pub(super) fn bob_matrix(&self, partial: f32) -> glam::Mat4 { + let Some(p) = self.player.as_ref() else { + return glam::Mat4::IDENTITY; + }; + let hurt = &p.health.hurt; + let state = BobState { + living: Some(HurtBob { + hurt_time: hurt.hurt_time as f32 - partial, + hurt_duration: hurt.hurt_duration, + hurt_dir: 0.0, + death_time: self.death_time().map(|t| t as f32 + partial), + }), + player: Some(( + self.avatar.backwards_interpolated_walk_distance(partial), + self.avatar.interpolated_bob(partial), + )), + }; + let tilt = self.settings.file.double("damageTiltStrength"); + glam::Mat4::from_cols_array(&bob_matrix(&state, tilt, self.settings.view_bobbing).m) + } + /// `AbstractClientPlayer.tick` and `aiStep` (`ClientAvatarState.tick`, + /// `updateBob`), `rideTick`'s `resetBob` and `LocalPlayer.move`'s walked + /// distance, after the player's movement this tick. `before` is the + /// ground state, velocity and position at the start of the tick. + pub(super) fn tick_avatar(&mut self, before: (bool, [f64; 3], [f64; 3]), riding: bool) { + let Some(p) = self.player.as_ref() else { + return; + }; + let (ground, velocity, start) = before; + let swimming = p.pose == horizon_client::pose::Pose::Swimming; + let alive = !p.health.dead_or_dying(); + let (dx, dz) = ( + (p.position.x - start[0]) as f32, + (p.position.z - start[2]) as f32, + ); + self.avatar.tick(); + self.avatar + .update_bob(ground && alive && !swimming, velocity); + if riding { + self.avatar.reset_bob(); + } else { + self.avatar.add_walked(dx, dz); } - if matches!( - fog_type(&self.world, &self.res.facts, camera, self.forward()), - FogType::Water | FogType::Lava - ) { - fov *= 1.0 + (0.857_142_87 - 1.0) * FOV_EFFECT_SCALE; - } - fov } /// `SpyglassItem.use`: start scoping. pub(super) fn use_spyglass(&mut self) { diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index c175733bb..ee60887dc 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -8,8 +8,100 @@ use horizon_client::{ mobs::{Anim, Brain, Mob, MobType}, pose::Pose, }; -use horizon_core::geometry::Vec3; -use std::{path::Path, sync::Arc}; +use horizon_client::{ + blocks::BlockFacts, + camera::{CameraEntity, LivingCamera}, + collisions::SceneCollisions, +}; +use horizon_core::{ + geometry::{Aabb, ShapeOp, Vec3, VoxelShape}, + position::BlockPos, +}; +use horizon_world::{ + collision_context::{CollisionContext, CollisionEntity, CollisionItem}, + entity_obstruction::EntityIdentity, + registry::BlockStateId, + world_ray::{RayBlockMode, RayFluidMode, RayWorld, clip_world}, +}; +use std::{io, path::Path, sync::Arc}; + +/// `Level.clip` with `ClipContext.Block.VISUAL` and no fluids: +/// `BlockBehaviour.getVisualShape` is the collision shape except for the +/// blocks that override it. +struct VisualRays<'a, 'r> { + scene: SceneCollisions<'a, 'r>, + facts: &'a BlockFacts, + context: CollisionContext<'static>, +} +impl RayWorld for VisualRays<'_, '_> { + type Error = io::Error; + type Block = BlockStateId; + type Fluid = (); + fn block_state(&mut self, p: BlockPos) -> io::Result { + Ok(self.scene.world.block(p.x, p.y, p.z)) + } + fn fluid_state(&mut self, _: BlockPos) -> io::Result<()> { + Ok(()) + } + fn block_shape( + &mut self, + state: BlockStateId, + p: BlockPos, + _: RayBlockMode, + ) -> io::Result { + let facts = self.facts.get(state); + let name = &*facts.name; + // TransparentBlock (glass, stained and tinted glass, copper grates), + // IronBarsBlock (bars and panes) and PowderSnowBlock: nothing; + // SoulSandBlock and MudBlock: a full block; SnowLayerBlock and + // FenceBlock: their outline. + if name.ends_with("glass") + || name.ends_with("glass_pane") + || name.ends_with("_bars") + || name.ends_with("copper_grate") + || name == "minecraft:powder_snow" + { + return Ok(VoxelShape::empty()); + } + if name == "minecraft:soul_sand" || name == "minecraft:mud" { + return Ok(VoxelShape::block()); + } + if name == "minecraft:snow" || name.ends_with("_fence") { + let mut shape = VoxelShape::empty(); + for b in facts.outline.iter() { + let b = b.map(f64::from); + let part = VoxelShape::from_box(Aabb::new( + Vec3::new(b[0], b[1], b[2]), + Vec3::new(b[3], b[4], b[5]), + )) + .map_err(|e| io::Error::other(format!("{e:?}")))?; + shape = shape + .join(&part, ShapeOp::OR) + .map_err(|e| io::Error::other(format!("{e:?}")))?; + } + return Ok(shape); + } + let binding = self.scene.binding; + binding + .collision_shape_with_context(&mut self.scene, state, p, &self.context) + .map_err(|e| io::Error::other(format!("{e:?}"))) + } + fn interaction_shape(&mut self, _: BlockStateId, _: BlockPos) -> io::Result { + Ok(VoxelShape::empty()) + } + fn fluid_is_source(&mut self, _: ()) -> io::Result { + Ok(false) + } + fn fluid_is_empty(&mut self, _: ()) -> io::Result { + Ok(true) + } + fn fluid_is_water(&mut self, _: ()) -> io::Result { + Ok(false) + } + fn fluid_shape(&mut self, _: (), _: BlockPos) -> io::Result { + Ok(VoxelShape::empty()) + } +} #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(super) enum CameraType { @@ -95,34 +187,95 @@ impl Game<'_> { pub(super) fn cycle_camera(&mut self) { self.camera_type = self.camera_type.cycle(); } - /// `Camera.setup`: the eye, or a point up to four blocks behind (or in - /// front of) it, pulled in where blocks are in the way. Returns the + /// `Camera.update` (`alignWithEntity` and `getMaxZoom`): the + /// interpolated eye, or a point up to the camera distance behind (or in + /// front of) it, pulled in where visual shapes are in the way. Returns the /// position, yaw and pitch to render from. - pub(super) fn camera_view(&self, eye: glam::DVec3) -> (glam::DVec3, f32, f32) { - let (mut yaw, mut pitch) = (self.yaw, self.pitch); - if self.camera_type.first_person() || self.player.is_none() || self.sleeping.is_some() { - return (eye, yaw, pitch); - } - if self.camera_type == CameraType::ThirdPersonFront { - yaw += 180.0; - pitch = -pitch; - } - let f = super::view_vector(yaw, pitch); - let mut dist = 4.0f64; - for i in 0..8 { - let o = [ - f64::from((i & 1) * 2 - 1) * 0.1, - f64::from((i >> 1 & 1) * 2 - 1) * 0.1, - f64::from((i >> 2 & 1) * 2 - 1) * 0.1, - ]; - let from = [eye.x + o[0], eye.y + o[1], eye.z + o[2]]; - let back = [-f[0], -f[1], -f[2]]; - if let Some(hit) = self.clip_ray(from, back, dist) { - let d = glam::DVec3::from_array(hit.point) - eye; - dist = dist.min(d.length()); - } - } - (eye - glam::DVec3::from_array(f) * dist, yaw, pitch) + pub(super) fn camera_view(&mut self, partial: f32) -> Option<(glam::DVec3, f32, f32)> { + let (scale, distance) = { + let p = self.player.as_mut()?; + ( + p.attribute("minecraft:scale").unwrap_or(1.0) as f32, + p.attribute("minecraft:camera_distance").unwrap_or(4.0), + ) + }; + let p = self.player.as_ref()?; + let sleeping = self.sleeping.map(|(head, _)| { + let state = self.world.block(head[0], head[1], head[2]); + let props = self.res.assets.registry.state(state).map(|s| &s.properties); + // BedBlock.getBedOrientation as Direction.toYRot. + props.and_then(|props| match props.get("facing").map(String::as_str) { + Some("south") => Some(0.0), + Some("west") => Some(90.0), + Some("north") => Some(180.0), + Some("east") => Some(270.0), + _ => None, + }) + }); + // A living mount at the default scale and camera distance. + let mount = self + .riding + .and_then(|id| self.mobs.iter().find(|m| m.id == id)) + .map(|_| (1.0, 4.0)); + let entity = CameraEntity { + position: [p.position.x, p.position.y, p.position.z], + previous: [ + self.previous_position.x, + self.previous_position.y, + self.previous_position.z, + ], + // Entity.turn moves the old rotation with the new: the mouse + // turns the view every frame without interpolation. + x_rot: self.pitch, + y_rot: self.yaw, + x_rot_o: self.pitch, + y_rot_o: self.yaw, + eye_height: p.dimensions.eye_height, + living: Some(LivingCamera { + scale, + camera_distance: distance, + sleeping, + dead: None, + }), + mount, + }; + let mut view = self.view; + let kind = match self.camera_type { + CameraType::FirstPerson => horizon_client::camera::CameraType::FirstPerson, + CameraType::ThirdPersonBack => horizon_client::camera::CameraType::ThirdPersonBack, + CameraType::ThirdPersonFront => horizon_client::camera::CameraType::ThirdPersonFront, + }; + let context = CollisionContext::for_entity( + CollisionEntity { + identity: EntityIdentity(0), + y: p.position.y, + descending: p.shift_key_down, + main_hand: Some(CollisionItem::EMPTY), + }, + false, + ); + let mut rays = VisualRays { + scene: SceneCollisions { + world: &self.world, + binding: self.collision, + }, + facts: &self.res.facts, + context, + }; + view.align_with_entity(&entity, partial, kind, |from, to| { + let hit = clip_world( + &mut rays, + Vec3::new(from[0], from[1], from[2]), + Vec3::new(to[0], to[1], to[2]), + RayBlockMode::Visual, + RayFluidMode::None, + 4096, + ) + .ok()?; + (!hit.miss).then(|| [hit.hit.location.x, hit.hit.location.y, hit.hit.location.z]) + }); + self.view = view; + Some((glam::DVec3::from_array(view.position), view.y_rot, view.x_rot)) } /// Keep the player's model in step with the player (`LivingEntity.tick` /// body turning, `WalkAnimationState`, the swing and the pose). diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index ab9585758..472c8d24b 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1309,6 +1309,11 @@ impl Game<'_> { | u8::from(keys.shift) << 5 | u8::from(keys.sprint) << 6; self.previous_position = player.position; + let before = ( + player.ground.on_ground, + [player.velocity.x, player.velocity.y, player.velocity.z], + [player.position.x, player.position.y, player.position.z], + ); player.yaw = self.yaw; let dead = self.screen == Screen::Dead; if !dead { @@ -1337,18 +1342,7 @@ impl Game<'_> { } // The server owns health and hunger: undo local food/fall changes. self.apply_remote_health(); - if let Some(p) = &self.player { - let (dx, dz) = ( - p.position.x - self.previous_position.x, - p.position.z - self.previous_position.z, - ); - let speed = ((dx * dx + dz * dz).sqrt() as f32).min(0.1); - self.walk.0 = self.walk.1; - self.walk.1 += (dx * dx + dz * dz).sqrt() as f32 * 0.6; - self.bob.0 = self.bob.1; - let target = if p.ground.on_ground { speed } else { 0.0 }; - self.bob.1 += (target - self.bob.1) * 0.4; - } + self.tick_avatar(before, false); if !dead { self.remote_mining(); if self.right && self.use_delay == 0 && playing { diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 264b10d32..9654d9ca3 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -40,8 +40,9 @@ pub struct Frame<'a> { pub yaw: f32, pub pitch: f32, pub fov_degrees: f32, - /// GameRenderer.bobView: (walk distance, bob amount), interpolated. - pub bob: Option<(f32, f32)>, + /// The `GameRenderer.bobHurt`/`bobView` pose multiplied into the + /// projection (`crate::camera::bob_matrix`). + pub bob: Mat4, pub sky: Sky, /// Render distance in blocks (fog end). pub distance: f32, @@ -1074,14 +1075,7 @@ impl Renderer { yaw.cos() * pitch.cos(), ); let far = (frame.distance * 4.0).max(1024.0); - let bob = frame.bob.map_or(Mat4::IDENTITY, |(walk, bob)| { - let f = -walk * std::f32::consts::PI; - Mat4::from_translation(Vec3::new(f.sin() * bob * 0.5, -(f.cos() * bob).abs(), 0.0)) - * Mat4::from_rotation_z((f.sin() * bob * 3.0).to_radians()) - * Mat4::from_rotation_x( - ((f - 0.2).cos() * bob).abs().mul_add(5.0, 0.0).to_radians(), - ) - }); + let bob = frame.bob; Mat4::perspective_rh(frame.fov_degrees.to_radians(), aspect, 0.05, far) * bob * Mat4::look_to_rh(Vec3::ZERO, forward, Vec3::Y) diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index e5080ea4a..5bb313406 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -14,6 +14,7 @@ pub mod block_entity_render; pub mod block_transform; pub mod blocks; pub mod bossbar; +pub mod camera; pub mod brewing; pub mod cauldron; pub mod chat; diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCameraOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCameraOracle.java new file mode 100644 index 000000000..9d276cbe7 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCameraOracle.java @@ -0,0 +1,419 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import com.mojang.blaze3d.vertex.PoseStack; +import java.io.*; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.*; +import net.minecraft.client.entity.ClientAvatarState; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.renderer.state.GameRenderState; +import net.minecraft.client.renderer.state.level.CameraRenderState; +import net.minecraft.core.*; +import net.minecraft.util.Mth; +import net.minecraft.world.attribute.EnvironmentAttributeProbe; +import net.minecraft.world.entity.*; +import net.minecraft.world.entity.ai.attributes.*; +import net.minecraft.world.entity.player.*; +import net.minecraft.world.item.*; +import net.minecraft.world.level.*; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.*; +import net.minecraft.world.phys.*; +import net.minecraft.world.phys.shapes.*; +import org.joml.Matrix4f; + +/** + * Drives the real Camera (tick, tickFov, alignWithEntity with getMaxZoom over + * Level.clip, calculateFov, calculateHudFov), AbstractClientPlayer + * .getFieldOfViewModifier and updateBob, ClientAvatarState and + * GameRenderer.bobHurt/bobView with scripted entity states, and prints every + * observable bit-exactly. Entities, the level and the renderer are + * uninitialised shells (Unsafe) with controlled queries; block visual shapes + * come from the case. + */ +public final class VanillaCameraOracle { + static Object unsafe; + static Method allocate; + + @SuppressWarnings("unchecked") + static T make(Class type) throws Exception { + return (T) allocate.invoke(unsafe, type); + } + + static Field field(Class type, String name) throws Exception { + Field f = type.getDeclaredField(name); + f.setAccessible(true); + return f; + } + + static Method method(Class type, String name, Class... args) throws Exception { + Method m = type.getDeclaredMethod(name, args); + m.setAccessible(true); + return m; + } + + static float f(JsonElement v) { + return Float.intBitsToFloat(Integer.parseUnsignedInt(v.getAsString(), 16)); + } + + static double d(JsonElement v) { + return Double.longBitsToDouble(Long.parseUnsignedLong(v.getAsString(), 16)); + } + + static String fb(float v) { + return String.format("%08x", Float.isNaN(v) ? 0x7fc00000 : Float.floatToRawIntBits(v)); + } + + static String db(double v) { + return String.format("%016x", Double.isNaN(v) ? 0x7ff8000000000000L : Double.doubleToRawLongBits(v)); + } + + static Vec3 vec(JsonElement v) { + var a = v.getAsJsonArray(); + return new Vec3(d(a.get(0)), d(a.get(1)), d(a.get(2))); + } + + // ---- level with controlled visual shapes ---------------------------------------------- + static final class State extends BlockState { + VoxelShape visual; + + State() { + super(null, null, null); + } + + @Override public VoxelShape getVisualShape(BlockGetter w, BlockPos p, CollisionContext c) { return visual; } + @Override public VoxelShape getInteractionShape(BlockGetter w, BlockPos p) { return Shapes.empty(); } + } + + static final class Level extends net.minecraft.server.level.ServerLevel { + Map cells = new HashMap<>(); + State air; + + Level() { + super(null, null, null, null, null, null, false, 0L, List.of(), false); + } + + @Override public BlockState getBlockState(BlockPos p) { return cells.getOrDefault(p, air); } + @Override public FluidState getFluidState(BlockPos p) { return Fluids.EMPTY.defaultFluidState(); } + } + + static final class NoProbe extends EnvironmentAttributeProbe { + @Override public void tick(net.minecraft.world.level.Level level, Vec3 position) { } + } + + static final class StubCamera extends Camera { + net.minecraft.world.level.material.FogType fluid = net.minecraft.world.level.material.FogType.NONE; + + @Override public net.minecraft.world.level.material.FogType getFluidInCamera() { return fluid; } + } + + // ---- camera entities ---------------------------------------------------------------- + static final class StubPlayer extends LocalPlayer { + AttributeMap attributes; + boolean using, dead, sleeping, swimming, ground; + ItemStack useItem = ItemStack.EMPTY; + int useTicks; + Direction bed; + Vec3 motion = Vec3.ZERO; + + StubPlayer() { + super(null, null, null, null, null, Input.EMPTY, false, null, null); + } + + @Override public AttributeMap getAttributes() { return attributes; } + @Override public boolean isUsingItem() { return using; } + @Override public ItemStack getUseItem() { return useItem; } + @Override public int getTicksUsingItem() { return useTicks; } + @Override public boolean isDeadOrDying() { return dead; } + @Override public boolean isSleeping() { return sleeping; } + @Override public Direction getBedOrientation() { return bed; } + @Override public boolean isDescending() { return false; } + @Override public ItemStack getMainHandItem() { return ItemStack.EMPTY; } + @Override public boolean isSwimming() { return swimming; } + @Override public boolean onGround() { return ground; } + @Override public Vec3 getDeltaMovement() { return motion; } + @Override public boolean isSpectator() { return false; } + } + + static final class StubMarker extends Marker { + StubMarker() { + super(null, null); + } + + @Override public boolean isDescending() { return false; } + } + + static Minecraft shell; + static Options options; + static Field position, xRot, yRot, eyeHeight, vehicle, abilities; + static Constructor stack; + + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + var u = Class.forName("sun.misc.Unsafe"); + unsafe = field(u, "theUnsafe").get(null); + allocate = u.getMethod("allocateInstance", Class.class); + shell = make(Minecraft.class); + field(Minecraft.class, "fixerUpper").set(shell, net.minecraft.util.datafix.DataFixers.getDataFixer()); + field(Minecraft.class, "instance").set(null, shell); + options = new Options(shell, Files.createTempDirectory("opts").toFile()); + field(Minecraft.class, "options").set(shell, options); + position = field(Entity.class, "position"); + xRot = field(Entity.class, "xRot"); + yRot = field(Entity.class, "yRot"); + eyeHeight = field(Entity.class, "eyeHeight"); + vehicle = field(Entity.class, "vehicle"); + abilities = field(Player.class, "abilities"); + stack = ItemStack.class.getDeclaredConstructor(Holder.class, int.class, net.minecraft.core.component.PatchedDataComponentMap.class); + stack.setAccessible(true); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8)); + var lines = Files.lines(Path.of(args[0]))) { + int n = 0; + for (var line : (Iterable) lines::iterator) { + var c = JsonParser.parseString(line).getAsJsonObject(); + out.println("== " + n++); + switch (c.get("t").getAsString()) { + case "fov" -> out.println(fb(player(c).getFieldOfViewModifier(c.get("fp").getAsBoolean(), f(c.get("scale"))))); + case "camera" -> camera(c, out); + case "bob" -> bob(c, out); + case "avatar" -> avatar(c, out); + default -> throw new IllegalArgumentException(line); + } + } + } + System.exit(0); + } + + static AttributeMap attributes(double scale, double distance, double speed) { + var map = new AttributeMap(Player.createAttributes().build()); + map.getInstance(Attributes.SCALE).setBaseValue(scale); + map.getInstance(Attributes.CAMERA_DISTANCE).setBaseValue(distance); + map.getInstance(Attributes.MOVEMENT_SPEED).setBaseValue(speed); + return map; + } + + /** A player shell from the "fov" fields of a case or an entity op. */ + static StubPlayer player(JsonObject c) throws Exception { + StubPlayer p = make(StubPlayer.class); + fill(p, c); + return p; + } + + static void fill(StubPlayer p, JsonObject c) throws Exception { + var a = new Abilities(); + a.flying = c.get("flying").getAsBoolean(); + a.setWalkingSpeed(f(c.get("ws"))); + abilities.set(p, a); + double scale = c.has("scale_attr") ? d(c.get("scale_attr")) : 1.0; + double distance = c.has("dist") ? d(c.get("dist")) : 4.0; + p.attributes = attributes(scale, distance, d(c.get("speed"))); + var use = c.get("use"); + p.using = !use.isJsonNull(); + if (p.using) { + var u = use.getAsJsonArray(); + Item item = switch (u.get(0).getAsString()) { + case "bow" -> Items.BOW; + case "spyglass" -> Items.SPYGLASS; + default -> Items.STICK; + }; + p.useItem = stack.newInstance(Holder.direct(item), 1, + new net.minecraft.core.component.PatchedDataComponentMap(net.minecraft.core.component.DataComponentMap.EMPTY)); + p.useTicks = u.get(1).getAsInt(); + } + } + + static void camera(JsonObject c, PrintWriter out) throws Exception { + var level = make(Level.class); + level.cells = new HashMap<>(); + level.air = make(State.class); + level.air.visual = Shapes.empty(); + for (var e : c.getAsJsonObject("cells").entrySet()) { + var at = e.getKey().split(" "); + var s = make(State.class); + VoxelShape shape = Shapes.empty(); + for (var b : e.getValue().getAsJsonArray()) { + var a = b.getAsJsonArray(); + shape = Shapes.or(shape, Shapes.box(d(a.get(0)), d(a.get(1)), d(a.get(2)), d(a.get(3)), d(a.get(4)), d(a.get(5)))); + } + s.visual = shape; + level.cells.put(new BlockPos(Integer.parseInt(at[0]), Integer.parseInt(at[1]), Integer.parseInt(at[2])), s); + } + options.fov().set(c.get("fov").getAsInt()); + options.fovEffectScale().set(d(c.get("effect"))); + options.setCameraType(CameraType.values()[c.get("type").getAsInt()]); + var camera = new StubCamera(); + field(Camera.class, "attributeProbe").set(camera, new NoProbe()); + field(Camera.class, "level").set(camera, level); + GameRenderer renderer = make(GameRenderer.class); + field(GameRenderer.class, "mainCamera").set(renderer, camera); + field(Minecraft.class, "gameRenderer").set(shell, renderer); + var align = method(Camera.class, "alignWithEntity", float.class); + var fov = method(Camera.class, "calculateFov", float.class); + var hud = method(Camera.class, "calculateHudFov", float.class); + var panoramic = field(Camera.class, "isPanoramicMode"); + var eye = field(Camera.class, "eyeHeight"); + var eyeOld = field(Camera.class, "eyeHeightOld"); + var mod = field(Camera.class, "fovModifier"); + var modOld = field(Camera.class, "oldFovModifier"); + Entity entity = null; + for (var e : c.getAsJsonArray("ops")) { + var op = e.getAsJsonArray(); + switch (op.get(0).getAsString()) { + case "entity" -> { + var s = op.get(1).getAsJsonObject(); + entity = entity(s, entity); + camera.setEntity(entity); + out.println("entity"); + } + case "type" -> { + options.setCameraType(CameraType.values()[op.get(1).getAsInt()]); + out.println("type"); + } + case "tick" -> { + camera.tick(); + out.println("tick " + fb(eye.getFloat(camera)) + " " + fb(eyeOld.getFloat(camera)) + " " + + fb(mod.getFloat(camera)) + " " + fb(modOld.getFloat(camera))); + } + case "frame" -> { + float pt = f(op.get(1)); + camera.fluid = net.minecraft.world.level.material.FogType.valueOf( + new String[] {"NONE", "WATER", "LAVA", "POWDER_SNOW"}[op.get(2).getAsInt()]); + panoramic.setBoolean(camera, op.get(3).getAsBoolean()); + align.invoke(camera, pt); + float fv = (float) fov.invoke(camera, pt); + float hv = (float) hud.invoke(camera, pt); + var p = camera.position(); + var q = camera.rotation(); + var fw = camera.forwardVector(); + var up = camera.upVector(); + var left = camera.leftVector(); + out.println("frame " + db(p.x) + " " + db(p.y) + " " + db(p.z) + " " + fb(camera.xRot()) + " " + fb(camera.yRot()) + + " " + fb(q.x) + " " + fb(q.y) + " " + fb(q.z) + " " + fb(q.w) + + " " + fb(fw.x()) + " " + fb(fw.y()) + " " + fb(fw.z()) + + " " + fb(up.x()) + " " + fb(up.y()) + " " + fb(up.z()) + + " " + fb(left.x()) + " " + fb(left.y()) + " " + fb(left.z()) + + " " + camera.isDetached() + " " + fb(fv) + " " + fb(hv)); + } + default -> throw new IllegalArgumentException(op.toString()); + } + } + } + + /** Applies an entity op: a player (with fov fields) or a non-living marker. */ + static Entity entity(JsonObject s, Entity previous) throws Exception { + Entity entity; + if (s.get("kind").getAsString().equals("player")) { + StubPlayer p = previous instanceof StubPlayer old ? old : make(StubPlayer.class); + fill(p, s); + p.dead = !s.get("dead").isJsonNull(); + if (p.dead) { + p.deathTime = s.get("dead").getAsInt(); + } + p.sleeping = !s.get("sleeping").isJsonNull(); + p.bed = null; + if (p.sleeping && !s.get("sleeping").getAsJsonArray().get(0).isJsonNull()) { + p.bed = Direction.from2DDataValue(s.get("sleeping").getAsJsonArray().get(0).getAsInt()); + } + var mount = s.get("mount"); + if (mount.isJsonNull()) { + vehicle.set(p, null); + } else { + StubPlayer m = make(StubPlayer.class); + var a = mount.getAsJsonArray(); + m.attributes = attributes(d(a.get(0)), d(a.get(1)), 0.1); + vehicle.set(p, m); + } + entity = p; + } else { + entity = previous instanceof StubMarker old ? old : make(StubMarker.class); + } + position.set(entity, vec(s.get("pos"))); + var prev = vec(s.get("prev")); + entity.xo = prev.x; + entity.yo = prev.y; + entity.zo = prev.z; + xRot.setFloat(entity, f(s.get("xr"))); + yRot.setFloat(entity, f(s.get("yr"))); + entity.xRotO = f(s.get("xro")); + entity.yRotO = f(s.get("yro")); + eyeHeight.setFloat(entity, f(s.get("eye"))); + return entity; + } + + static void bob(JsonObject c, PrintWriter out) throws Exception { + GameRenderer renderer = make(GameRenderer.class); + var state = new GameRenderState(); + field(GameRenderer.class, "gameRenderState").set(renderer, state); + state.optionsRenderState.damageTiltStrength = d(c.get("tilt")); + state.optionsRenderState.bobView = c.get("view").getAsBoolean(); + var camera = new CameraRenderState(); + var es = camera.entityRenderState; + var living = c.get("living"); + es.isLiving = !living.isJsonNull(); + if (es.isLiving) { + var l = living.getAsJsonObject(); + es.hurtTime = f(l.get("hurt")); + es.hurtDuration = l.get("duration").getAsInt(); + es.hurtDir = f(l.get("dir")); + es.isDeadOrDying = !l.get("death").isJsonNull(); + if (es.isDeadOrDying) { + es.deathTime = f(l.get("death")); + } + } + var player = c.get("player"); + es.isPlayer = !player.isJsonNull(); + if (es.isPlayer) { + es.backwardsInterpolatedWalkDistance = f(player.getAsJsonArray().get(0)); + es.bob = f(player.getAsJsonArray().get(1)); + } + var stack = new PoseStack(); + method(GameRenderer.class, "bobHurt", CameraRenderState.class, PoseStack.class).invoke(renderer, camera, stack); + if (state.optionsRenderState.bobView) { + method(GameRenderer.class, "bobView", CameraRenderState.class, PoseStack.class).invoke(renderer, camera, stack); + } + Matrix4f m = stack.last().pose(); + var sb = new StringBuilder("bob"); + for (int col = 0; col < 4; col++) { + for (int row = 0; row < 4; row++) { + sb.append(' ').append(fb(m.get(col, row))); + } + } + sb.append(' ').append(m.properties()); + out.println(sb); + } + + static void avatar(JsonObject c, PrintWriter out) throws Exception { + StubPlayer p = make(StubPlayer.class); + var state = new ClientAvatarState(); + field(net.minecraft.client.player.AbstractClientPlayer.class, "clientAvatarState").set(p, state); + var updateBob = method(net.minecraft.client.player.AbstractClientPlayer.class, "updateBob"); + for (var e : c.getAsJsonArray("ops")) { + var op = e.getAsJsonArray(); + switch (op.get(0).getAsString()) { + case "tick" -> state.tick(Vec3.ZERO, Vec3.ZERO); + case "move" -> state.addWalkDistance(Mth.length(f(op.get(1)), f(op.get(2))) * 0.6F); + case "bob" -> { + p.ground = op.get(1).getAsBoolean(); + p.dead = op.get(2).getAsBoolean(); + p.swimming = op.get(3).getAsBoolean(); + p.motion = vec(op.get(4)); + updateBob.invoke(p); + } + case "reset" -> state.resetBob(); + case "frame" -> { + float pt = f(op.get(1)); + out.println("frame " + fb(state.getInterpolatedBob(pt)) + " " + fb(state.getBackwardsInterpolatedWalkDistance(pt))); + continue; + } + default -> throw new IllegalArgumentException(op.toString()); + } + out.println(op.get(0).getAsString()); + } + } +} diff --git a/tools/test_camera_parity.py b/tools/test_camera_parity.py new file mode 100644 index 000000000..07c0ad242 --- /dev/null +++ b/tools/test_camera_parity.py @@ -0,0 +1,199 @@ +#!/usr/bin/env python3 +"""Compare the camera with the pinned client: Camera.tick (eye height and +field-of-view easing), alignWithEntity (view rotation quaternion and basis, +interpolated eye, third person back and front, camera distance and scale +attributes with mounts, getMaxZoom clipping against visual shapes, sleeping), +calculateFov/calculateHudFov (option, modifier, death and fluid effects, +panoramic mode), AbstractClientPlayer.getFieldOfViewModifier (flight, speed +attribute against walking speed, bow draw, spyglass), the walk and bob +history (ClientAvatarState, updateBob) and GameRenderer.bobHurt/bobView, +driven tick by tick and frame by frame with identical scripted states.""" +import json +import random +import struct + +try: + from . import lab, oracle_harness as harness +except ImportError: + import lab, oracle_harness as harness + + +def fbits(v): + return struct.pack('>f', v).hex() + + +def dbits(v): + return struct.pack('>d', v).hex() + + +def f32(v): + return struct.unpack('>f', struct.pack('>f', v))[0] + + +WALK = [0.1, 0.0, 0.05, 0.2, 1e-3, -0.1, 0.15] +SPEED = [f32(0.1), f32(0.1) * 1.3, 0.0, 0.03, 0.5, 1024.0, 0.13, f32(0.1) * 0.85, f32(0.1) * 1.4] +TICKS = [0, 1, 5, 10, 19, 20, 21, 72000, -5, 3] + + +def fov_fields(rng): + use = rng.choice([None, None, ['bow', rng.choice(TICKS)], ['spyglass', rng.choice(TICKS)], ['other', rng.choice(TICKS)]]) + return dict(flying=rng.random() < 0.3, ws=fbits(rng.choice(WALK + [rng.uniform(-0.3, 0.3)])), + speed=dbits(rng.choice(SPEED + [rng.uniform(0, 2)])), use=use) + + +def fov_cases(rng): + for flying in (False, True): + for ws in WALK: + for speed in SPEED: + for use in [None, ['bow', 0], ['bow', 7], ['bow', 20], ['bow', 40], ['spyglass', 2], ['other', 5]]: + for fp in (False, True): + for scale in (0.0, 0.5, 1.0): + yield dict(t='fov', flying=flying, ws=fbits(ws), speed=dbits(speed), use=use, fp=fp, scale=fbits(scale)) + for _ in range(3000): + yield dict(t='fov', **fov_fields(rng), fp=rng.random() < 0.6, scale=fbits(rng.choice([0.0, 1.0, rng.random()]))) + + +FULL = [[0, 0, 0, 1, 1, 1]] +SHAPES = [FULL, FULL, [[0, 0, 0, 1, 0.5, 1]], [[0, 0.5, 0, 1, 1, 1]], [[0, 0, 0, 1, 1, 0.125]], [[0.375, 0, 0.375, 0.625, 1, 0.625]], + [[0, 0, 0, 0.5, 1, 1], [0.5, 0, 0.5, 1, 1, 1]], []] + + +def world(rng, center): + cells = {} + cx, cy, cz = center + for _ in range(rng.choice([0, 3, 10, 40, 120])): + p = (cx + rng.randint(-6, 6), cy + rng.randint(-3, 5), cz + rng.randint(-6, 6)) + cells[f'{p[0]} {p[1]} {p[2]}'] = [[dbits(v) for v in box] for box in rng.choice(SHAPES)] + return cells + + +ANGLES = [0.0, 90.0, -90.0, 180.0, -180.0, 45.0, 360.0, 720.5, -33.3, 1e-3, 89.9] + + +def angle(rng): + return rng.choice(ANGLES + [rng.uniform(-90, 90), rng.uniform(-400, 400)]) + + +def entity_state(rng, center): + pos = [center[i] + rng.uniform(0, 1) for i in range(3)] + prev = [p - rng.choice([0, 0, 0.1, 0.3, 1.0, rng.uniform(-1, 1)]) for p in pos] + kind = 'player' if rng.random() < 0.85 else 'marker' + xr, yr = angle(rng), angle(rng) + s = dict(kind=kind, pos=[dbits(v) for v in pos], prev=[dbits(v) for v in prev], xr=fbits(xr), yr=fbits(yr), + xro=fbits(rng.choice([xr, xr - 5, angle(rng)])), yro=fbits(rng.choice([yr, yr + 10, angle(rng)])), + eye=fbits(rng.choice([1.62, 1.27, 0.4, 0.2, 0.81, 3.24, rng.uniform(0, 4)]))) + s.update(fov_fields(rng)) + s.update(scale_attr=dbits(rng.choice([1.0, 1.0, 0.5, 2.0, 0.0625, 16.0, rng.uniform(0.0625, 3)])), + dist=dbits(rng.choice([4.0, 4.0, 0.0, 1.0, 10.0, 32.0, rng.uniform(0, 32)])), + sleeping=rng.choice([None] * 6 + [[None], [0], [1], [2], [3]]), + dead=rng.choice([None] * 6 + [0, 1, 5, 19, 20, 25]), + mount=rng.choice([None] * 4 + [[dbits(rng.choice([1.0, 2.0, 0.5])), dbits(rng.choice([4.0, 8.0, 1.0]))]])) + return s + + +def camera_cases(rng): + for n in range(2500): + center = rng.choice([(0, 64, 0), (-10, -60, 7), (1000, 120, -3000), (0, 0, 0)]) + ops = [] + for _ in range(rng.randrange(1, 40)): + kind = rng.choice(['entity', 'tick', 'tick', 'tick', 'frame', 'frame', 'frame', 'type']) + if not ops: + kind = 'entity' + if kind == 'entity': + ops.append(['entity', entity_state(rng, center)]) + elif kind == 'tick': + ops.append(['tick']) + elif kind == 'frame': + pt = rng.choice([0.0, 1.0, 0.5, 0.25, 0.999, rng.random()]) + ops.append(['frame', fbits(pt), rng.choice([0, 0, 0, 1, 2, 3]), rng.random() < 0.05]) + else: + ops.append(['type', rng.randrange(3)]) + yield dict(t='camera', fov=rng.choice([70, 30, 110, 90, rng.randint(30, 110)]), + effect=dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])), type=rng.choice([0, 1, 1, 2]), + cells=world(rng, center), ops=ops) + # A walled-in third-person camera stepping through every distance bound. + for dist in [0.0, 0.5, 1.0, 2.0, 4.0, 8.0, 32.0]: + for wall in range(0, 6): + for yaw in [0.0, 90.0, 180.0, 270.0, 45.0]: + cells = {} + for dx in range(-6, 7): + for dy in range(62, 68): + cells[f'{dx} {dy} {-wall - 1}'] = [[dbits(v) for v in box] for box in FULL] + cells[f'{dx} {dy} {wall + 1}'] = [[dbits(v) for v in box] for box in FULL] + s = dict(kind='player', pos=[dbits(0.5), dbits(64.0), dbits(0.5)], prev=[dbits(0.5), dbits(64.0), dbits(0.5)], + xr=fbits(15.0), yr=fbits(yaw), xro=fbits(15.0), yro=fbits(yaw), eye=fbits(1.62), flying=False, + ws=fbits(0.1), speed=dbits(f32(0.1)), use=None, scale_attr=dbits(1.0), dist=dbits(dist), + sleeping=None, dead=None, mount=None) + ops = [['entity', s]] + [['tick']] * 6 + [['frame', fbits(pt), 0, False] for pt in (0.0, 0.5, 1.0)] + yield dict(t='camera', fov=70, effect=dbits(1.0), type=1 + (wall % 2), cells=cells, ops=ops) + + +def bob_cases(rng): + for n in range(6000): + living = None + if rng.random() < 0.8: + living = dict(hurt=fbits(rng.choice([-1.0, -0.5, 0.0, 10.0, 9.5, 5.25, 1.0, rng.uniform(-2, 11)])), + duration=rng.choice([10, 10, 0, 5, 20]), dir=fbits(rng.choice([0.0, 90.0, -45.0, 180.0, rng.uniform(-360, 360)])), + death=rng.choice([None, None, None, fbits(rng.choice([0.0, 0.5, 19.5, 20.0, 25.0, rng.uniform(0, 30)]))])) + player = None + if rng.random() < 0.8: + player = [fbits(rng.choice([0.0, -0.3, -1.7, -100.25, rng.uniform(-1000, 0)])), + fbits(rng.choice([0.0, 0.1, 0.05, 0.0999, rng.uniform(0, 0.1)]))] + yield dict(t='bob', living=living, player=player, tilt=dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])), + view=rng.random() < 0.8) + + +def avatar_cases(rng): + for n in range(1500): + ops = [] + for _ in range(rng.randrange(1, 60)): + kind = rng.choice(['tick', 'move', 'move', 'bob', 'bob', 'frame', 'frame', 'reset']) + if kind == 'tick': + ops.append(['tick']) + elif kind == 'move': + ops.append(['move', fbits(rng.choice([0.0, 0.2158, -0.1, rng.uniform(-1, 1)])), fbits(rng.choice([0.0, 0.2806, rng.uniform(-1, 1)]))]) + elif kind == 'bob': + v = [rng.choice([0.0, 0.05, -0.2, rng.uniform(-0.5, 0.5)]), rng.uniform(-1, 1), rng.choice([0.0, 0.08, rng.uniform(-0.5, 0.5)])] + ops.append(['bob', rng.random() < 0.7, rng.random() < 0.1, rng.random() < 0.1, [dbits(x) for x in v]]) + elif kind == 'frame': + ops.append(['frame', fbits(rng.choice([0.0, 1.0, 0.5, rng.random()]))]) + else: + ops.append(['reset']) + yield dict(t='avatar', ops=ops) + + +def make_cases(build): + rng = random.Random(0x43414d45) + path = build / 'cases.jsonl' + cases = build / 'cases' + cases.mkdir(exist_ok=True) + count = 0 + with path.open('w') as out: + for generator in (fov_cases, camera_cases, bob_cases, avatar_cases): + for case in generator(rng): + text = json.dumps(case, separators=(',', ':')) + out.write(text + '\n') + if count < 20000: + (cases / str(count)).write_text(text) + count += 1 + return path, count + + +def main(): + scope = ('Real Camera.tick, tickFov, alignWithEntity (setRotation quaternion and forwards/up/left basis, move, ' + 'interpolated eye with eye-height easing, first person, third person back and mirrored front, scale and ' + 'camera_distance attributes including a living mount, getMaxZoom over the actual Level.clip with ' + 'ClipContext.Block.VISUAL against controlled visual shapes, sleeping bed orientation), calculateFov and ' + 'calculateHudFov (option, eased modifier, death, water/lava with the effect scale, panoramic), ' + 'AbstractClientPlayer.getFieldOfViewModifier with real Abilities, attribute maps and item stacks, ' + 'ClientAvatarState walk/bob history with AbstractClientPlayer.updateBob, and GameRenderer.bobHurt/bobView ' + 'as the full JOML pose matrix with its property flags. The camera entity is a shell with controlled ' + 'queries; getFluidInCamera is supplied (the fog harnesses cover fluid detection) and the new-minecart ' + 'interpolation branch is not exercised.') + harness.differential( + 'rust-camera-parity', 'VanillaCameraOracle', 'camera_probe', make_cases, scope, + sources=[lab.ROOT / 'crates/horizon-client/src/camera.rs']) + + +if __name__ == '__main__': + main() From b29f51f8e12ef0ba369287d3e70fdd79a498131a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:46:57 +0200 Subject: [PATCH 09/28] Add a differential mob AI harness and match vanilla mob movement math VanillaMobAiOracle runs vanilla mobs in a real headless flat server level, ticking them as ServerLevel does while the rest of the level stands still; mob_ai_probe replays the same scenarios on Horizon. Both print each mob's AI-visible state every tick (position, motion, rotations, goals, targets, navigation, controls, input, brain activities and memories, sounds) and tools/test_mob_ai_parity.py reports the first divergence. Fixes found: float entity dimensions, Mth.sin/cos in moveRelative and the strafe/swim controls, Mth.atan2 and the float thresholds of the controls, RandomPos float constants, the ambient sound clock starting at zero, hurt and death sounds drawn from the mob's own random (also when burning), knockback for every damage type not tagged no_knockback, Entity.move's collision flags, restitution and footstep/swim sounds, and mob sound volumes. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/mob_ai_probe.rs | 505 ++++++++++++++++ crates/horizon-client/src/game.rs | 16 +- crates/horizon-client/src/game/creatures.rs | 36 +- crates/horizon-client/src/mobs.rs | 62 +- crates/horizon-client/src/mobs/ai.rs | 152 ++++- crates/horizon-client/src/mobs/control.rs | 49 +- crates/horizon-client/src/mobs/goals.rs | 6 +- crates/horizon-client/src/mobs/living.rs | 184 ++++-- crates/horizon-core/src/geometry/trig.rs | 56 ++ .../horizonlab/parity/VanillaMobAiOracle.java | 563 ++++++++++++++++++ tools/test_mob_ai_parity.py | 230 +++++++ 11 files changed, 1756 insertions(+), 103 deletions(-) create mode 100644 crates/horizon-client/examples/mob_ai_probe.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java create mode 100644 tools/test_mob_ai_parity.py diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs new file mode 100644 index 000000000..952723b9e --- /dev/null +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -0,0 +1,505 @@ +//! Replays `tools/test_mob_ai_parity.py` scenarios on Horizon's mob AI and +//! prints each mob's AI-visible state after every tick in the format of +//! `VanillaMobAiOracle`. +//! +//! usage: mob_ai_probe RESOURCES SCENARIOS OUTPUT +use horizon_client::{ + assets::Assets, + biome::Biomes, + blocks::BlockFacts, + chunk::{Chunk, HEIGHT, MIN_Y}, + collisions, + items::Items, + light::{LightTables, light_chunk}, + mobs::{ + Mob, MobData, MobEvent, MobTypes, MobWorld, PlayerView, Seen, Species, Who, + control::Operation, spawning::LocalDifficulty, + }, + world::World, +}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + random::LegacyRandom, +}; +use horizon_world::{chunk::BlockState, registry::BlockRegistry, registry::BlockStateId}; +use std::{collections::BTreeMap, fmt::Write as _, fs, path::Path, sync::Arc}; + +struct MobSpec { + kind: String, + pos: [f64; 3], + yaw: f32, + seed: i64, + baby: bool, + flags: Vec, +} +#[derive(Default)] +struct Scenario { + name: String, + ticks: i32, + time: i64, + rain: bool, + thunder: bool, + origin: [i32; 2], + blocks: Vec>, + player: Option<[f64; 3]>, + creative: bool, + mobs: Vec, +} + +fn parse(text: &str) -> Vec { + let mut out = Vec::new(); + let mut cur: Option = None; + for line in text.lines() { + let f: Vec<&str> = line.split_whitespace().collect(); + if f.is_empty() || f[0].starts_with('#') { + continue; + } + let s = cur.get_or_insert_with(Scenario::default); + match f[0] { + "scenario" => { + s.name = f[1].to_owned(); + s.time = 6000; + for kv in &f[2..] { + let (k, v) = kv.split_once('=').unwrap_or((kv, "")); + match k { + "ticks" => s.ticks = v.parse().unwrap(), + "time" => s.time = v.parse().unwrap(), + "rain" => s.rain = true, + "thunder" => s.thunder = true, + "levelseed" => {} + _ => panic!("unknown scenario option {kv}"), + } + } + } + "origin" => s.origin = [f[1].parse().unwrap(), f[2].parse().unwrap()], + "fill" | "block" => s.blocks.push(f.iter().map(|x| (*x).to_owned()).collect()), + "player" => { + s.player = Some([ + f[1].parse().unwrap(), + f[2].parse().unwrap(), + f[3].parse().unwrap(), + ]); + s.creative = f.get(4) == Some(&"creative"); + } + "mob" => s.mobs.push(MobSpec { + kind: f[1].to_owned(), + pos: [ + f[2].parse().unwrap(), + f[3].parse().unwrap(), + f[4].parse().unwrap(), + ], + yaw: f[5].parse().unwrap(), + seed: f[6].parse().unwrap(), + baby: f[7..].contains(&"baby"), + flags: f[7..] + .iter() + .filter(|x| **x != "baby") + .map(|x| (*x).to_owned()) + .collect(), + }), + "end" => out.push(cur.take().unwrap()), + other => panic!("unknown scenario line {other}"), + } + } + out +} + +/// `minecraft:name[key=value,...]` +fn state(registry: &BlockRegistry, text: &str) -> BlockStateId { + let (name, props) = match text.split_once('[') { + Some((n, rest)) => (n, rest.trim_end_matches(']')), + None => (text, ""), + }; + let mut properties = BTreeMap::new(); + for kv in props.split(',').filter(|s| !s.is_empty()) { + let (k, v) = kv.split_once('=').expect("property"); + properties.insert(k.to_owned(), v.to_owned()); + } + registry + .resolve(&BlockState { + name: name.to_owned(), + properties, + }) + .unwrap_or_else(|e| panic!("{text}: {e}")) +} + +fn d(v: f64) -> String { + format!("{:x}", v.to_bits()) +} +fn f(v: f32) -> String { + format!("{:x}", v.to_bits()) +} +fn who(w: Option) -> String { + match w { + None => "none".into(), + Some(Who::Player) => "player".into(), + Some(Who::Mob(id)) => format!("e{id}"), + } +} + +/// Vanilla's goal class for a Horizon goal (most share the name). +fn goal_name(m: &Mob, name: &str) -> String { + let vanilla = match name { + "Float" => "FloatGoal", + "Stroll" => "WaterAvoidingRandomStrollGoal", + "LookAtPlayer" => "LookAtPlayerGoal", + "RandomLookAround" => "RandomLookAroundGoal", + "HurtByTarget" => "HurtByTargetGoal", + "NearestTarget" => "NearestAttackableTargetGoal", + "Panic" => "PanicGoal", + "Breed" => "BreedGoal", + "Tempt" => "TemptGoal", + "FollowParent" => "FollowParentGoal", + "MeleeAttack" => match m.species() { + Species::Zombie | Species::Husk | Species::ZombieVillager => "ZombieAttackGoal", + _ => "MeleeAttackGoal", + }, + "MoveThroughVillage" => "MoveThroughVillageGoal", + "RestrictSun" => "RestrictSunGoal", + "FleeSun" => "FleeSunGoal", + "AvoidEntity" => "AvoidEntityGoal", + "BowAttack" => "RangedBowAttackGoal", + "Swell" => "SwellGoal", + "LeapAtTarget" => "LeapAtTargetGoal", + "EatBlock" => "EatBlockGoal", + "MoveTowardsRestriction" => "MoveTowardsRestrictionGoal", + "TradeWithPlayer" => "TradeWithPlayerGoal", + "LookAtTradingPlayer" => "LookAtTradingPlayerGoal", + "WanderToPosition" => "WanderToPositionGoal", + "DrinkItem" => "UseItemGoal", + "BreathAir" => "BreathAirGoal", + "TryFindWater" => "TryFindWaterGoal", + "RangedAttack" => "RangedAttackGoal", + "MoveTowardsTarget" => "MoveTowardsTargetGoal", + other => return other.to_owned(), + }; + vanilla.to_owned() +} + +fn goals(m: &Mob, names: Vec<&'static str>) -> String { + if names.is_empty() { + return "-".into(); + } + names + .iter() + .map(|n| goal_name(m, n)) + .collect::>() + .join("|") +} + +fn seen(m: &Mob) -> Seen { + Seen { + id: m.id, + species: m.species(), + position: m.position, + bounds: m.bounds(), + eye_y: m.eye_y(), + alive: m.alive(), + baby: m.is_baby(), + in_love: if m.species() == Species::Villager { + horizon_client::mobs::villager::can_breed(m) + } else { + m.extra.in_love > 0 + }, + tame: m.extra.tame, + hostile: m.hostile(), + target: m.ai.target, + health: m.health, + variant: m.extra.variant, + color: m.extra.color, + job: (m.species() == Species::Villager) + .then_some(m.extra.home) + .flatten(), + bed: (m.species() == Species::Villager) + .then_some(m.extra.bed) + .flatten(), + yaw: m.yaw, + velocity: m.velocity, + leash: m.extra.leash, + caravan: horizon_client::mobs::caravan::head_of(m), + delay: m.extra.ints[5], + hurt_by: m.ai.last_hurt_by.map(|w| (w, m.ai.last_hurt_by_time)), + active_raid: horizon_client::mobs::raider::has_active_raid(m), + player_rep: 0, + } +} + +fn print(out: &mut String, t: i32, i: usize, m: &Mob) { + let _ = write!(out, "{t} {i}"); + if m.removed { + let _ = writeln!(out, " removed DISCARDED"); + return; + } + let p = m.position; + let v = m.velocity; + let _ = write!( + out, + "\tp {},{},{}\tv {},{},{}", + d(p.x), + d(p.y), + d(p.z), + d(v.x), + d(v.y), + d(v.z) + ); + let _ = write!( + out, + "\tr {},{},{},{}", + f(m.yaw), + f(m.head_pitch), + f(m.head_yaw), + f(m.body_yaw) + ); + let _ = write!( + out, + "\tg {}{}\thp {}", + u8::from(m.on_ground), + u8::from(m.horizontal_collision), + f(m.health) + ); + let _ = write!( + out, + "\tgoals {}\ttargets {}\ttarget {}", + goals(m, m.ai.goals.running_names()), + goals(m, m.ai.targets.running_names()), + who(m.ai.target) + ); + let _ = write!(out, "\tnav "); + match &m.ai.nav.path { + None => out.push_str("none"), + Some(path) => { + let _ = write!( + out, + "{},{},{} {}/{}{}", + path.target[0], + path.target[1], + path.target[2], + path.next, + path.nodes.len(), + if path.next >= path.nodes.len() { + " done" + } else { + "" + } + ); + } + } + let mv = &m.ai.mov; + let op = match mv.operation { + Operation::Wait => "WAIT", + Operation::MoveTo => "MOVE_TO", + Operation::Strafe => "STRAFE", + Operation::Jumping => "JUMPING", + }; + let _ = write!( + out, + "\tmove {op} {},{},{} {}", + d(mv.wanted[0]), + d(mv.wanted[1]), + d(mv.wanted[2]), + d(mv.speed_modifier) + ); + let lk = &m.ai.look; + let _ = write!( + out, + "\tlook {} {},{},{}", + lk.cooldown, + d(lk.wanted[0]), + d(lk.wanted[1]), + d(lk.wanted[2]) + ); + let _ = writeln!( + out, + "\tin {},{},{},{}", + f(m.ai.xxa), + f(m.ai.zza), + f(m.ai.speed), + u8::from(m.ai.jumping) + ); +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().skip(1).collect(); + if args.len() != 3 { + return Err("usage: mob_ai_probe RESOURCES SCENARIOS OUTPUT".into()); + } + let root = Path::new(&args[0]); + let assets = Assets::load(root)?; + let registry = assets.registry; + let facts = BlockFacts::load(root, registry)?; + let data = MobData::load(root, &facts); + let types = MobTypes::load(root)?; + let biomes = Biomes::load(root)?; + let items = Items::load(root, registry, &facts)?; + let tables = LightTables::load(root, registry, &facts)?; + let collision = collisions::load(root, registry)?; + let air = registry.default_state("minecraft:air").ok_or("no air")?; + let layers = [ + state(registry, "minecraft:bedrock"), + state(registry, "minecraft:dirt"), + state(registry, "minecraft:dirt"), + state(registry, "minecraft:grass_block"), + ]; + let plains = biomes.id("minecraft:plains"); + let mut out = String::new(); + for s in parse(&fs::read_to_string(&args[1])?) { + let _ = writeln!(out, "== {}", s.name); + let mut world = World::new(air, 0); + let (ocx, ocz) = (s.origin[0] >> 4, s.origin[1] >> 4); + const R: i32 = 4; + for cz in ocz - R..=ocz + R { + for cx in ocx - R..=ocx + R { + let mut chunk = Chunk::empty(cx, cz); + for qy in 0..HEIGHT / 4 { + for qz in 0..4 { + for qx in 0..4 { + chunk.set_biome_cell(qx, qy, qz, plains); + } + } + } + world.chunks.insert((cx, cz), Arc::new(chunk)); + for z in 0..16 { + for x in 0..16 { + for (y, layer) in layers.iter().enumerate() { + world.set(cx * 16 + x, MIN_Y + y as i32, cz * 16 + z, *layer)?; + } + } + } + } + } + for b in &s.blocks { + let n = |i: usize| b[i].parse::().unwrap(); + if b[0] == "block" { + world.set(n(1), n(2), n(3), state(registry, &b[4]))?; + } else { + let st = state(registry, &b[7]); + for x in n(1).min(n(4))..=n(1).max(n(4)) { + for y in n(2).min(n(5))..=n(2).max(n(5)) { + for z in n(3).min(n(6))..=n(3).max(n(6)) { + world.set(x, y, z, st)?; + } + } + } + } + } + let keys: Vec<(i32, i32)> = world.chunks.keys().copied().collect(); + let lit: Vec<((i32, i32), Chunk)> = keys + .iter() + .map(|&(x, z)| { + let region: [[Option<&Chunk>; 3]; 3] = std::array::from_fn(|dz| { + std::array::from_fn(|dx| { + world + .chunks + .get(&(x + dx as i32 - 1, z + dz as i32 - 1)) + .map(|c| &**c) + }) + }); + let mut c = (*world.chunks[&(x, z)]).clone(); + c.sections = light_chunk(®ion, &tables, true); + c.lit = true; + ((x, z), c) + }) + .collect(); + for (k, c) in lit { + world.chunks.insert(k, Arc::new(c)); + } + world.day_time = s.time; + let mut mobs: Vec = Vec::new(); + for (i, spec) in s.mobs.iter().enumerate() { + let kind = types + .types + .get(&spec.kind) + .ok_or_else(|| format!("unknown mob {}", spec.kind))?; + let mut m = Mob::new( + 100_000 + i as u32, + Arc::new(kind.clone()), + Vec3::new(spec.pos[0], spec.pos[1], spec.pos[2]), + spec.yaw, + ); + if spec.baby { + m.extra.age = -24000; + } + for flag in &spec.flags { + match flag.as_str() { + "persistent" => m.persistent = true, + "noai" => m.no_ai = true, + other => panic!("unknown mob flag {other}"), + } + } + m.random = LegacyRandom::new(spec.seed); + mobs.push(m); + } + let player = s.player.map(|p| { + let position = Vec3::new(p[0], p[1], p[2]); + PlayerView { + position, + bounds: Aabb::new( + Vec3::new(p[0] - 0.3, p[1], p[2] - 0.3), + Vec3::new(p[0] + 0.3, p[1] + 1.8, p[2] + 0.3), + ), + eye: [p[0], p[1] + f64::from(1.62_f32), p[2]], + alive: true, + creative: s.creative, + sneaking: false, + look: [0.0, 0.0, 1.0], + main_hand: None, + off_hand: None, + head: None, + armor_cover: 0.0, + spectator: false, + gold_armor: false, + hurt_by: None, + last_hurt: None, + velocity: Vec3::ZERO, + yaw: 0.0, + hero: false, + uuid: [0, 0x1234, 0, 0x5678], + } + }); + let mut scratch = LegacyRandom::new(0); + for t in 1..=s.ticks { + world.game_time += 1; + let snapshot: Vec = mobs.iter().filter(|m| !m.removed).map(seen).collect(); + let w = MobWorld { + world: &world, + registry, + facts: &facts, + collision: &collision, + data: &data, + player: player.clone(), + others: &snapshot, + daylight: (s.time.rem_euclid(24000)) < 12000, + game_time: world.game_time, + day_time: world.day_time, + raining: s.rain, + thundering: s.thunder, + nether: false, + block_tags: &items.block_tags, + biomes: &biomes, + mob_griefing: true, + difficulty: LocalDifficulty::new(2, world.day_time, 0, 0.0), + }; + let mut events = Vec::new(); + for m in &mut mobs { + if m.removed { + continue; + } + if !m.tick(&w, &mut scratch, &mut events) { + m.removed = true; + } + } + for (i, m) in mobs.iter().enumerate() { + print(&mut out, t, i, m); + } + for e in &events { + if let MobEvent::Sound(name, _, volume, pitch) = e { + let _ = writeln!(out, "{t} sound minecraft:{name} {} {}", f(*volume), f(*pitch)); + } else if let MobEvent::SoundId(name, _, volume, pitch) = e { + let _ = writeln!(out, "{t} sound {name} {} {}", f(*volume), f(*pitch)); + } + } + } + } + fs::write(&args[2], out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b81c403fd..0f5962ff6 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4893,9 +4893,6 @@ impl Game<'_> { ); } self.last_hurt_by_player.insert(mob.id); - // getHurtSound / getDeathSound (by species state). - let voice = horizon_client::mobs::ai::voice_sounds(mob); - let dead = !mob.alive(); let sound = if crit { "minecraft:entity.player.attack.crit" } else if scale > 0.9 { @@ -4904,10 +4901,15 @@ impl Game<'_> { "minecraft:entity.player.attack.weak" }; self.audio.play(sound, Some(center), 1.0, 1.0); - let event = format!("minecraft:{}", voice[if dead { 2 } else { 1 }]); - let pitch = - (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 1.0; - self.audio.play(&event, Some(center), 1.0, pitch); + // The hurt or death sound the mob raised (getHurtSound / getDeathSound, + // its voice pitch from its own random). + let queued = std::mem::take(&mut self.mobs[index].outbox); + for event in queued { + if let horizon_client::mobs::MobEvent::Sound(s, _, volume, pitch) = event { + self.audio + .play(&format!("minecraft:{s}"), Some(center), volume, pitch); + } + } self.post_attack(index); if let Some(stack) = self.inventory[self.selected].clone() && let Some(max) = self diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 26c1bf86f..96bba0fda 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -734,6 +734,12 @@ impl Game<'_> { self.tick_player_effects(); self.piglin_pickups(); self.sulfur_cube_pickups(); + // Hurt and death sounds of damage dealt outside the mob ticks. + let mut queued = Vec::new(); + for m in &mut self.mobs { + queued.append(&mut m.outbox); + } + self.handle_mob_events(queued)?; Ok(()) } /// LivingEntity.die / dropAllDeathLoot. @@ -950,24 +956,18 @@ impl Game<'_> { if let Some(t) = self.mobs.iter_mut().find(|m| m.id == target) { let hit = t.damage(amount, source); if hit { - let (voice, center, dead) = ( - horizon_client::mobs::ai::voice_sounds(t), - t.center(), - !t.alive(), - ); - killed = dead; - let pitch = (self.world.random.next_float() - - self.world.random.next_float()) - * 0.2 - + 1.0; - let s = voice[if dead { 2 } else { 1 }]; - if !s.is_empty() { - self.audio.play( - &format!("minecraft:{s}"), - Some(center), - 1.0, - pitch, - ); + killed = !t.alive(); + // The hurt or death sound the mob raised. + let center = t.center(); + for event in std::mem::take(&mut t.outbox) { + if let MobEvent::Sound(s, _, volume, pitch) = event { + self.audio.play( + &format!("minecraft:{s}"), + Some(center), + volume, + pitch, + ); + } } } } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index f46420cad..c5a06b135 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -419,6 +419,22 @@ impl Damage { DamageKind::OnFire | DamageKind::InFire | DamageKind::Lava | DamageKind::Fireball ) } + /// DamageTypeTags.NO_KNOCKBACK + pub fn no_knockback(&self) -> bool { + matches!( + self.kind, + DamageKind::Explosion + | DamageKind::Fall + | DamageKind::OnFire + | DamageKind::InFire + | DamageKind::Lava + | DamageKind::Drown + | DamageKind::Magic + | DamageKind::Cactus + | DamageKind::Generic + | DamageKind::InWall + ) + } pub fn is_projectile(&self) -> bool { matches!( self.kind, @@ -589,6 +605,10 @@ pub struct Mob { pub attrs: Attrs, /// The player riding this mob and its input. pub rider: Option, + /// Events raised outside a tick (hurt and death sounds of damage taken + /// from the game), handed over with the next tick's events or drained + /// by the game. + pub outbox: Vec, } /// Events a mob tick asks the game to act on. #[derive(Clone, Debug)] @@ -934,7 +954,8 @@ impl Mob { previous_limb_speed: 0.0, swell: 0, previous_swell: 0, - ambient_timer: -kind.ambient_interval, + // Mob.ambientSoundTime starts at 0. + ambient_timer: 0, fall_distance: 0.0, persistent: false, random, @@ -955,6 +976,7 @@ impl Mob { name_visible: false, anim: anim::AnimState::default(), rider: None, + outbox: Vec::new(), attrs: Attrs { speed: kind.speed, attack_damage: kind.attack_damage, @@ -1063,17 +1085,35 @@ impl Mob { self.ai.last_hurt_by_player = 100; } } - if knock - && let Some(f) = source.from - && !matches!(source.kind, DamageKind::Explosion) - { - let (dx, dz) = (f[0] - self.position.x, f[2] - self.position.z); + // dealDefaultKnockback, unless the damage type is tagged no_knockback; + // a source without a position knocks in a random direction. + if knock && !source.no_knockback() { + let (dx, dz) = source + .from + .map_or((0.0, 0.0), |f| (f[0] - self.position.x, f[2] - self.position.z)); self.knockback(0.4, dx, dz); } ai::after_hurt(self, &source); if self.health <= 0.0 { self.health = 0.0; } + if knock { + // playHurtSound (Mob: also resets the ambient sound clock) or the + // death sound: makeSound draws the voice pitch whenever there is a sound. + let dead = !self.alive(); + let sound = ai::voice_sounds(self)[if dead { 2 } else { 1 }]; + if !dead { + self.ambient_timer = -self.kind.ambient_interval; + } + if !sound.is_empty() { + let pitch = self.voice_pitch(); + if !self.silent { + let at = [self.position.x, self.position.y, self.position.z]; + self.outbox + .push(MobEvent::Sound(sound, at, ai::sound_volume(self), pitch)); + } + } + } true } /// LivingEntity.knockback(power, xd, zd) towards the negative direction. @@ -1082,7 +1122,7 @@ impl Mob { if power <= 0.0 { return; } - while xd * xd + zd * zd < 1.0e-5 { + while xd * xd + zd * zd < f64::from(1.0e-5_f32) { xd = (self.random.next_double() - self.random.next_double()) * 0.01; zd = (self.random.next_double() - self.random.next_double()) * 0.01; } @@ -1158,10 +1198,14 @@ impl Mob { let at = [self.position.x, self.eye_y(), self.position.z]; events.push(MobEvent::Sound(event, at, 1.0, 1.0)); } + /// LivingEntity.getVoicePitch. + pub fn voice_pitch(&mut self) -> f32 { + (self.random.next_float() - self.random.next_float()) * 0.2 + + if self.is_baby() { 1.5 } else { 1.0 } + } /// Mob.playSound with LivingEntity.getVoicePitch. pub fn voice(&mut self, event: &'static str, events: &mut Vec) { - let pitch = (self.random.next_float() - self.random.next_float()) * 0.2 - + if self.is_baby() { 1.5 } else { 1.0 }; + let pitch = self.voice_pitch(); let at = [self.position.x, self.eye_y(), self.position.z]; events.push(MobEvent::Sound(event, at, ai::sound_volume(self), pitch)); } diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index d27024f31..027a55125 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -47,6 +47,8 @@ pub struct Ai { /// Swing animation progress (attackAnim) and ticks. pub swing_time: i32, pub swinging: bool, + /// Walked distance and the next footstep. + pub steps: super::living::Steps, } impl Mob { /// LivingEntity.swing @@ -298,6 +300,7 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { if m.alive() { m.body_rotation_tick(); } + events.append(&mut m.outbox); m.update_walk_animation(); m.anim.end_tick(m.ai.swinging); tick_swing(m); @@ -326,6 +329,9 @@ fn tick_swing(m: &mut Mob) { /// Entity.baseTick + LivingEntity.baseTick + Mob.baseTick. fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.fluids = w.fluids(m.bounds(), m.eye_y()); + if m.fluids.in_water { + m.fall_distance = 0.0; + } // Fire: water extinguishes, lava ignites, burning hurts every second. if m.fluids.in_water && m.fire_ticks > 0 { m.fire_ticks = 0; @@ -401,6 +407,8 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { if !m.alive() { m.death_time += 1; } + // Hurt sounds of the damage above come before the ambient sound. + events.append(&mut m.outbox); // Mob.baseTick: ambient sounds. if m.alive() { let roll = m.random.next_int_bound(1000).unwrap_or(999); @@ -752,17 +760,15 @@ pub fn sound_volume(m: &Mob) -> f32 { Species::Slime | Species::MagmaCube | Species::SulfurCube => { 0.4 * m.extra.size.max(1) as f32 } - Species::Cod - | Species::Salmon - | Species::TropicalFish - | Species::Pufferfish - | Species::Bat => 0.1, - Species::Squid | Species::GlowSquid => 0.4, - Species::Horse - | Species::Donkey - | Species::Mule - | Species::Llama - | Species::TraderLlama => 0.8, + Species::Bat => 0.1, + Species::Squid + | Species::GlowSquid + | Species::Cow + | Species::Mooshroom + | Species::Bee + | Species::Allay + | Species::Wolf => 0.4, + s if super::equine::is_equine(s) => 0.8, _ => 1.0, } } @@ -972,3 +978,127 @@ fn tick_effects(m: &mut Mob) { effects.retain(|e| e.1 > 0); m.extra.effects = effects; } + +/// `Entity.getMovementEmission` is not NONE (silverfish, endermites, +/// shulkers, guardians and breezes emit only events, no step sounds). +pub fn emits_movement(m: &Mob) -> bool { + !matches!(m.species(), Species::Shulker) +} +/// The movement emission includes sounds. +pub fn movement_sounds(m: &Mob) -> bool { + !matches!( + m.species(), + Species::Silverfish + | Species::Endermite + | Species::Guardian + | Species::ElderGuardian + | Species::Breeze + ) +} +/// `playStepSound`: the species' footstep, or the block's step sound at 15%. +pub fn step_sound( + m: &Mob, + w: &MobWorld, + pos: [i32; 3], + state: horizon_world::registry::BlockStateId, +) -> Option<(&'static str, f32, f32)> { + use Species as S; + let baby = m.is_baby(); + let quiet = |s: &'static str| Some((s, 0.15, 1.0)); + match m.species() { + // Silent footsteps, or only movement events. + S::Allay + | S::Bee + | S::Cod + | S::Salmon + | S::TropicalFish + | S::Pufferfish + | S::Tadpole + | S::HappyGhast + | S::Nautilus + | S::ZombieNautilus + | S::Silverfish + | S::Endermite + | S::Guardian + | S::ElderGuardian + | S::Breeze => None, + S::Armadillo => quiet("entity.armadillo.step"), + S::Chicken if baby => quiet("entity.baby_chicken.step"), + S::Chicken => quiet("entity.chicken.step"), + S::Cow | S::Mooshroom => quiet("entity.cow.step"), + S::Pig if baby => quiet("entity.baby_pig.step"), + S::Pig => quiet("entity.pig.step"), + S::Wolf => quiet("entity.wolf.step"), + S::Llama | S::TraderLlama => quiet("entity.llama.step"), + S::Frog => quiet("entity.frog.step"), + S::Goat => quiet("entity.goat.step"), + S::Panda => quiet("entity.panda.step"), + S::Parrot => quiet("entity.parrot.step"), + S::PolarBear => quiet("entity.polar_bear.step"), + S::Sheep => quiet("entity.sheep.step"), + S::Sniffer => quiet("entity.sniffer.step"), + S::Turtle if baby => quiet("entity.turtle.shamble_baby"), + S::Turtle => quiet("entity.turtle.shamble"), + S::Creaking => quiet("entity.creaking.step"), + S::Hoglin => quiet("entity.hoglin.step"), + S::Zoglin => quiet("entity.zoglin.step"), + S::Piglin => quiet("entity.piglin.step"), + S::PiglinBrute => quiet("entity.piglin_brute.step"), + S::Ravager => quiet("entity.ravager.step"), + S::Skeleton => quiet("entity.skeleton.step"), + S::Stray => quiet("entity.stray.step"), + S::Bogged => quiet("entity.bogged.step"), + S::Parched => quiet("entity.parched.step"), + S::WitherSkeleton => quiet("entity.wither_skeleton.step"), + S::Spider | S::CaveSpider => quiet("entity.spider.step"), + S::Zombie | S::ZombifiedPiglin => quiet("entity.zombie.step"), + S::Husk => quiet("entity.husk.step"), + S::Drowned => quiet("entity.drowned.step"), + S::ZombieVillager => quiet("entity.zombie_villager.step"), + S::CamelHusk => Some(("entity.camel_husk.step", 0.4, 1.0)), + S::Camel => Some(("entity.camel.step", 1.0, 1.0)), + S::IronGolem => Some(("entity.iron_golem.step", 1.0, 1.0)), + S::Strider if m.fluids.in_lava => Some(("entity.strider.step_lava", 1.0, 1.0)), + S::Strider => Some(("entity.strider.step", 1.0, 1.0)), + S::Warden => Some(("entity.warden.step", 10.0, 1.0)), + _ => { + // Entity.playStepSound: the block's sound type. + let _ = pos; + let sounds = &w.facts.get(state).sounds; + let step: &'static str = super::ai::intern_sound(&sounds.step); + Some((step, sounds.volume * 0.15, sounds.pitch)) + } + } +} +/// A block sound id as a static string (the block facts intern them). +pub fn intern_sound(s: &std::sync::Arc) -> &'static str { + use std::{collections::HashSet, sync::Mutex}; + static NAMES: Mutex>> = Mutex::new(None); + let mut names = NAMES.lock().unwrap_or_else(|e| e.into_inner()); + let set = names.get_or_insert_with(HashSet::new); + let key = s.strip_prefix("minecraft:").unwrap_or(s); + if let Some(found) = set.get(key) { + return found; + } + let leaked: &'static str = Box::leak(key.to_owned().into_boxed_str()); + set.insert(leaked); + leaked +} +/// `getSwimSound`. +pub fn swim_sound(m: &Mob) -> &'static str { + match m.species() { + Species::Drowned => "entity.drowned.swim", + Species::Axolotl => "entity.axolotl.swim", + Species::Dolphin => "entity.dolphin.swim", + Species::Cod + | Species::Salmon + | Species::TropicalFish + | Species::Pufferfish + | Species::Tadpole => "entity.fish.swim", + Species::Nautilus if m.is_baby() => "entity.baby_nautilus.swim", + Species::Nautilus => "entity.nautilus.swim", + Species::ZombieNautilus => "entity.zombie_nautilus.swim", + Species::Turtle => "entity.turtle.swim", + _ => "entity.generic.swim", + } +} diff --git a/crates/horizon-client/src/mobs/control.rs b/crates/horizon-client/src/mobs/control.rs index 05c0c67a3..4e2dd124f 100644 --- a/crates/horizon-client/src/mobs/control.rs +++ b/crates/horizon-client/src/mobs/control.rs @@ -1,6 +1,12 @@ //! Mob controls: `MoveControl` (with the flying and smooth-swimming //! variants), `LookControl`, `JumpControl` and `BodyRotationControl`. use super::{Mob, MobWorld, living::wrap}; +use horizon_core::geometry::trig; + +/// `2.5000003E-7F` widened: the squared distance controls treat as arrived. +const ARRIVED: f64 = 2.500_000_3e-7_f32 as f64; +/// `1.0E-5F` widened. +const EPSILON: f64 = 1.0e-5_f32 as f64; #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] pub enum Operation { @@ -117,8 +123,8 @@ impl Mob { let (dx, dz) = (at[0] - self.position.x, at[2] - self.position.z); let dy = at[1] - self.eye_y(); let sd = (dx * dx + dz * dz).sqrt(); - let y_rot = (dz.atan2(dx).to_degrees() as f32) - 90.0; - let x_rot = -(dy.atan2(sd).to_degrees() as f32); + let y_rot = trig::atan2_degrees(dz, dx) - 90.0; + let x_rot = -trig::atan2_degrees(dy, sd); self.head_pitch = rotate_toward_max(self.head_pitch, x_rot, x_max); self.yaw = rotate_toward_max(self.yaw, y_rot, y_max); } @@ -139,12 +145,12 @@ impl Mob { wy - self.position.y, wz - self.position.z, ); - if xd * xd + yd * yd + zd * zd < 2.500_000_3e-7 { + if xd * xd + yd * yd + zd * zd < ARRIVED { self.ai.yya = 0.0; self.ai.zza = 0.0; return; } - let y_rot = (zd.atan2(xd).to_degrees() as f32) - 90.0; + let y_rot = trig::atan2_degrees(zd, xd) - 90.0; self.yaw = rotlerp(self.yaw, y_rot, 90.0); let speed = (self.ai.mov.speed_modifier * if self.on_ground { @@ -154,8 +160,8 @@ impl Mob { }) as f32; self.set_speed(speed); let sd = (xd * xd + zd * zd).sqrt(); - if yd.abs() > 1.0e-5 || sd.abs() > 1.0e-5 { - let x_rot = -(yd.atan2(sd).to_degrees() as f32); + if yd.abs() > EPSILON || sd.abs() > EPSILON { + let x_rot = -trig::atan2_degrees(yd, sd); self.head_pitch = rotlerp(self.head_pitch, x_rot, max_turn); self.ai.yya = if yd > 0.0 { speed } else { -speed }; } @@ -184,10 +190,10 @@ impl Mob { wy - self.position.y, wz - self.position.z, ); - if xd * xd + yd * yd + zd * zd < 2.500_000_3e-7 { + if xd * xd + yd * yd + zd * zd < ARRIVED { self.ai.zza = 0.0; } else { - let y_rot = (zd.atan2(xd).to_degrees() as f32) - 90.0; + let y_rot = trig::atan2_degrees(zd, xd) - 90.0; self.yaw = rotlerp(self.yaw, y_rot, max_turn_y); self.body_yaw = self.yaw; self.head_yaw = self.yaw; @@ -195,15 +201,13 @@ impl Mob { if self.fluids.in_water { self.ai.speed = speed * in_water; let sd = (xd * xd + zd * zd).sqrt(); - if yd.abs() > 1.0e-5 || sd.abs() > 1.0e-5 { - let x_rot = -(yd.atan2(sd).to_degrees() as f32); + if yd.abs() > EPSILON || sd.abs() > EPSILON { + let x_rot = -trig::atan2_degrees(yd, sd); let x_rot = wrap(x_rot).clamp(-max_turn_x, max_turn_x); self.head_pitch = rotate_towards(self.head_pitch, x_rot, 5.0); } - let (c, s) = ( - self.head_pitch.to_radians().cos(), - self.head_pitch.to_radians().sin(), - ); + let angle = f64::from(self.head_pitch * trig::DEG_TO_RAD); + let (c, s) = (trig::cos(angle), trig::sin(angle)); self.ai.zza = c * speed; self.ai.yya = -s * speed; } else { @@ -229,7 +233,7 @@ impl Mob { fn ground_move_tick(&mut self, w: &MobWorld, attr_speed: f64) { match self.ai.mov.operation { Operation::Strafe => { - let speed = (self.ai.mov.speed_modifier * attr_speed) as f32; + let speed = self.ai.mov.speed_modifier as f32 * attr_speed as f32; let (mut xa, mut za) = (self.ai.mov.strafe_forwards, self.ai.mov.strafe_right); let mut dist = (xa * xa + za * za).sqrt(); if dist < 1.0 { @@ -238,7 +242,8 @@ impl Mob { dist = speed / dist; xa *= dist; za *= dist; - let (s, c) = (self.yaw.to_radians().sin(), self.yaw.to_radians().cos()); + let angle = f64::from(self.yaw * trig::DEG_TO_RAD); + let (s, c) = (trig::sin(angle), trig::cos(angle)); let dx = xa * c - za * s; let dz = za * c + xa * s; if !self.walkable(w, dx, dz) { @@ -258,11 +263,11 @@ impl Mob { wy - self.position.y, wz - self.position.z, ); - if xd * xd + yd * yd + zd * zd < 2.500_000_3e-7 { + if xd * xd + yd * yd + zd * zd < ARRIVED { self.ai.zza = 0.0; return; } - let y_rot = (zd.atan2(xd).to_degrees() as f32) - 90.0; + let y_rot = trig::atan2_degrees(zd, xd) - 90.0; self.yaw = rotlerp(self.yaw, y_rot, 90.0); self.set_speed((self.ai.mov.speed_modifier * attr_speed) as f32); let (bx, by, bz) = ( @@ -359,9 +364,9 @@ impl Mob { ); let sd = (xd * xd + zd * zd).sqrt(); let x = - (yd.abs() > 1.0e-5 || sd.abs() > 1.0e-5).then(|| -(yd.atan2(sd).to_degrees() as f32)); - let y = (zd.abs() > 1.0e-5 || xd.abs() > 1.0e-5) - .then(|| (zd.atan2(xd).to_degrees() as f32) - 90.0); + (yd.abs() > EPSILON || sd.abs() > EPSILON).then(|| -trig::atan2_degrees(yd, sd)); + let y = (zd.abs() > EPSILON || xd.abs() > EPSILON) + .then(|| trig::atan2_degrees(zd, xd) - 90.0); (x, y) } /// JumpControl.tick. @@ -374,7 +379,7 @@ impl Mob { let dx = self.position.x - self.previous.x; let dz = self.position.z - self.previous.z; let max = self.kind.max_head_y_rot; - if dx * dx + dz * dz > 2.500_000_3e-7 { + if dx * dx + dz * dz > ARRIVED { self.body_yaw = self.yaw; self.head_yaw = rotate_if_necessary(self.head_yaw, self.body_yaw, max); self.ai.body.last_stable_head = self.head_yaw; diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index e2700e22a..def62484b 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -196,10 +196,12 @@ impl Mob { zd: f64, max_rad: f64, ) -> Option<[i32; 3]> { - let center = zd.atan2(xd) - std::f64::consts::FRAC_PI_2; + let center = + horizon_core::geometry::trig::atan2(zd, xd) - f64::from(std::f32::consts::FRAC_PI_2); let yrad = center + f64::from(2.0 * self.random.next_float() - 1.0) * max_rad; let dist = - (min + self.random.next_double().sqrt() * (max - min)) * std::f64::consts::SQRT_2; + (min + self.random.next_double().sqrt() * (max - min)) + * f64::from(std::f32::consts::SQRT_2); let xt = -dist * yrad.sin(); let zt = dist * yrad.cos(); if xt.abs() > max || zt.abs() > max { diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 02ef3702d..8d294cdcc 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -4,8 +4,27 @@ //! damage, fire and the walk animation. use super::{Mob, MobEvent, MobWorld}; use crate::{blocks::Fluid, collisions::SceneCollisions}; -use horizon_core::geometry::{Aabb, Vec3}; +use horizon_core::{ + geometry::{Aabb, Vec3, trig}, + random::RandomSource, +}; +/// `Entity.moveDist`, `flyDist` and `nextStep`. +#[derive(Clone, Copy, Debug)] +pub struct Steps { + pub move_dist: f32, + pub fly_dist: f32, + pub next_step: f32, +} +impl Default for Steps { + fn default() -> Self { + Self { + move_dist: 0.0, + fly_dist: 0.0, + next_step: 1.0, + } + } +} #[derive(Clone, Copy, Debug, Default)] pub struct Fluids { pub water: f64, @@ -87,18 +106,22 @@ impl Mob { } /// Entity dimensions: the type's, a class's BABY_DIMENSIONS, or the /// slime size scaling. + /// `EntityDimensions` (float width, height and eye height) widened to double. pub fn dims(&self) -> (f64, f64, f64) { let k = &self.kind; - let (mut w, mut h, mut e) = (k.width, k.height, k.eye_height); + let (mut w, mut h, mut e) = (k.width as f32, k.height as f32, k.eye_height as f32); // Sniffer.DIGGING_DIMENSIONS: 0.4 lower, its eyes at 0.81. if k.species == super::Species::Sniffer && super::sniffer::digging(self) { - (h, e) = (h - f64::from(0.4_f32), f64::from(0.81_f32)); + (h, e) = (h - 0.4, 0.81); } if self.is_baby() { match super::species::def(k.species).baby { - super::species::Baby::Abs(bw, bh, be) => (w, h, e) = (bw, bh, be), + super::species::Baby::Abs(bw, bh, be) => { + (w, h, e) = (bw as f32, bh as f32, be as f32) + } super::species::Baby::Scale(s, eye) => { - (w, h, e) = (w * s, h * s, eye.unwrap_or(e * s)) + let s = s as f32; + (w, h, e) = (w * s, h * s, eye.map_or(e * s, |x| x as f32)) } super::species::Baby::None => {} } @@ -109,13 +132,13 @@ impl Mob { e = 0.85; } if self.kind.species == super::Species::Pufferfish { - let s = super::aquatic::puff_scale(self.extra.size); + let s = super::aquatic::puff_scale(self.extra.size) as f32; (w, h, e) = (w * s, h * s, e * s); } else if self.extra.size > 0 { - let s = f64::from(self.extra.size); + let s = self.extra.size as f32; (w, h, e) = (w * s, h * s, e * s); } - (w, h, e) + (f64::from(w), f64::from(h), f64::from(e)) } pub fn eye_height(&self) -> f64 { self.dims().2 @@ -149,8 +172,13 @@ impl Mob { return; } let v = if len_sq > 1.0 { + // Vec3.normalize let l = len_sq.sqrt(); - Vec3::new(input.x / l, input.y / l, input.z / l) + if l < f64::from(1.0e-5_f32) { + Vec3::ZERO + } else { + Vec3::new(input.x / l, input.y / l, input.z / l) + } } else { input }; @@ -159,10 +187,8 @@ impl Mob { v.y * f64::from(speed), v.z * f64::from(speed), ); - let (s, c) = ( - f64::from(self.yaw.to_radians().sin()), - f64::from(self.yaw.to_radians().cos()), - ); + let angle = f64::from(self.yaw * trig::DEG_TO_RAD); + let (s, c) = (f64::from(trig::sin(angle)), f64::from(trig::cos(angle))); self.velocity = Vec3::new( self.velocity.x + (v.x * c - v.z * s), self.velocity.y + v.y, @@ -181,38 +207,128 @@ impl Mob { let moved = scene .resolve(self.bounds(), wanted, step, self.on_ground) .unwrap_or(Vec3::ZERO); - self.position = Vec3::new( - self.position.x + moved.x, - self.position.y + moved.y, - self.position.z + moved.z, - ); - let x_hit = (moved.x - wanted.x).abs() > 1.0e-5; - let z_hit = (moved.z - wanted.z).abs() > 1.0e-5; + let length = moved.x * moved.x + moved.y * moved.y + moved.z * moved.z; + let wanted_length = wanted.x * wanted.x + wanted.y * wanted.y + wanted.z * wanted.z; + if length > 1.0e-7 || wanted_length - length < 1.0e-7 { + self.position = Vec3::new( + self.position.x + moved.x, + self.position.y + moved.y, + self.position.z + moved.z, + ); + } + // !Mth.equal(delta, movement) + let differs = |a: f64, b: f64| (b - a).abs() >= f64::from(1.0e-5_f32); + let x_hit = differs(wanted.x, moved.x); + let z_hit = differs(wanted.z, moved.z); self.horizontal_collision = x_hit || z_hit; - let vertical = (moved.y - wanted.y).abs() > 1.0e-5; - self.vertical_collision_below = vertical && wanted.y < 0.0; - self.on_ground = self.vertical_collision_below; - if x_hit { - self.velocity.x = 0.0; + let moved_vertically = wanted.y.abs() > 0.0; + let mut vertical = false; + if moved_vertically { + vertical = wanted.y != moved.y; + self.vertical_collision_below = vertical && wanted.y < 0.0; + self.on_ground = self.vertical_collision_below; } - if z_hit { - self.velocity.z = 0.0; - } - if vertical { - self.velocity.y = 0.0; + // LivingEntity.checkFallDamage refreshes the fluid state out of water + // (touching water resets the fall). + if !self.fluids.in_water { + self.fluids = w.fluids(self.bounds(), self.eye_y()); + if self.fluids.in_water { + self.fall_distance = 0.0; + } } // Entity.checkFallDamage + if !self.fluids.in_water && moved.y < 0.0 { + self.fall_distance -= f64::from(moved.y as f32); + } if self.on_ground { if self.fall_distance > 0.0 { self.cause_fall_damage(events); } self.fall_distance = 0.0; - } else if moved.y < 0.0 { - self.fall_distance -= moved.y; } - if self.fluids.in_water { - self.fall_distance = 0.0; + // restituteMovementAfterCollisions with no bounciness: the colliding + // components become (signed) zero. + if moved_vertically && vertical || self.horizontal_collision { + let v = self.velocity; + if x_hit { + self.velocity.x = -v.x * 0.0; + } + if z_hit { + self.velocity.z = -v.z * 0.0; + } + if vertical { + self.velocity.y = (0.0 - v.y) * 1.0 * 0.0; + } } + self.movement_emission(w, moved, events); + } + /// Entity.applyMovementEmissionAndPlaySound: walked distance, footsteps + /// and swimming sounds. + fn movement_emission(&mut self, w: &MobWorld, moved: Vec3, events: &mut Vec) { + if !super::ai::emits_movement(self) || self.extra.mount.is_some() { + return; + } + let full = (moved.length() * f64::from(0.6_f32)) as f32; + let horizontal = + ((moved.x * moved.x + moved.z * moved.z).sqrt() * f64::from(0.6_f32)) as f32; + let on = self.on_pos(1.0e-5); + let state = w.world.block(on[0], on[1], on[2]); + let climbable = w.facts.get(state).name.as_ref() == "minecraft:powder_snow" + || w.has_tag("minecraft:climbable", &w.facts.get(state).name); + let steps = &mut self.ai.steps; + steps.move_dist += if climbable { full } else { horizontal }; + steps.fly_dist += full; + if steps.move_dist > steps.next_step && !w.facts.is_air(state) { + let legacy = self.on_pos(0.2); + let legacy_state = w.world.block(legacy[0], legacy[1], legacy[2]); + let produced = !w.facts.is_air(legacy_state) + && (self.on_ground || climbable) + && !self.fluids_swimming(); + if produced { + if let Some((sound, volume, pitch)) = + super::ai::step_sound(self, w, legacy, legacy_state) + && !self.silent + { + let at = [self.position.x, self.position.y, self.position.z]; + events.push(MobEvent::Sound(sound, at, volume, pitch)); + } + self.ai.steps.next_step = (self.ai.steps.move_dist as i32).wrapping_add(1) as f32; + } else if self.fluids.in_water { + self.ai.steps.next_step = (self.ai.steps.move_dist as i32).wrapping_add(1) as f32; + // Entity.waterSwimSound + let v = self.velocity; + let volume = 1.0_f32.min( + (v.x * v.x * f64::from(0.2_f32) + v.y * v.y + v.z * v.z * f64::from(0.2_f32)) + .sqrt() as f32 + * 0.35, + ); + if !super::ai::movement_sounds(self) { + return; + } + let pitch = 1.0 + (self.random.next_float() - self.random.next_float()) * 0.4; + if !self.silent { + let at = [self.position.x, self.position.y, self.position.z]; + events.push(MobEvent::Sound( + super::ai::swim_sound(self), + at, + volume, + pitch, + )); + } + } + } + } + /// Entity.isSwimming (mobs never swim in the player sense). + fn fluids_swimming(&self) -> bool { + false + } + /// Entity.getOnPos(offset) without a supporting block record. + pub fn on_pos(&self, offset: f32) -> [i32; 3] { + [ + self.position.x.floor() as i32, + (self.position.y - f64::from(offset)).floor() as i32, + self.position.z.floor() as i32, + ] } fn cause_fall_damage(&mut self, events: &mut Vec) { if self.kind.flags.fall_immune { diff --git a/crates/horizon-core/src/geometry/trig.rs b/crates/horizon-core/src/geometry/trig.rs index bdc3529cf..8a8aba77e 100644 --- a/crates/horizon-core/src/geometry/trig.rs +++ b/crates/horizon-core/src/geometry/trig.rs @@ -23,6 +23,62 @@ pub fn cos(angle: f64) -> f32 { sine_table()[((angle * SCALE + 16384.0) as i64 & 65535) as usize] } +/// `Mth.atan2`: vanilla's table-driven arctangent. +pub fn atan2(mut y: f64, mut x: f64) -> f64 { + static TABLES: OnceLock<(Vec, Vec)> = OnceLock::new(); + let (asin, cos) = TABLES.get_or_init(|| { + (0..257) + .map(|i| { + let a = (f64::from(i) / 256.0).asin(); + (a, a.cos()) + }) + .unzip() + }); + let frac_bias = f64::from_bits(4_805_340_802_404_319_232); + let d2 = x * x + y * y; + if d2.is_nan() { + return f64::NAN; + } + let negative_y = y < 0.0; + if negative_y { + y = -y; + } + let negative_x = x < 0.0; + if negative_x { + x = -x; + } + let steep = y > x; + if steep { + std::mem::swap(&mut x, &mut y); + } + // Mth.fastInvSqrt + let half = 0.5 * d2; + let mut r = f64::from_bits((6_910_469_410_427_058_090i64 - (d2.to_bits() as i64 >> 1)) as u64); + r *= 1.5 - half * r * r; + x *= r; + y *= r; + let yp = frac_bias + y; + let index = yp.to_bits() as i32 as usize; + let s_phi = yp - frac_bias; + let sd = y * cos[index] - x * s_phi; + let mut theta = asin[index] + (6.0 + sd * sd) * sd * 0.166_666_666_666_666_66; + if steep { + theta = std::f64::consts::FRAC_PI_2 - theta; + } + if negative_x { + theta = std::f64::consts::PI - theta; + } + if negative_y { + theta = -theta; + } + theta +} +/// `(float)(Mth.atan2(y, x) * 180.0F / (float)Math.PI)`: the angle in degrees +/// as the AI controls compute it. +pub fn atan2_degrees(y: f64, x: f64) -> f32 { + (atan2(y, x) * 180.0 / f64::from(std::f32::consts::PI)) as f32 +} + /// `Mth.sin` / `Mth.cos` on a float, as the models call them. pub trait Mth { fn msin(self) -> f32; diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java new file mode 100644 index 000000000..4fd1af517 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -0,0 +1,563 @@ +package dev.horizonlab.parity; + +import com.mojang.authlib.GameProfile; +import com.mojang.serialization.Lifecycle; +import io.netty.channel.embedded.EmbeddedChannel; +import java.io.PrintWriter; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.net.Proxy; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.BooleanSupplier; +import net.minecraft.SharedConstants; +import net.minecraft.SystemReport; +import net.minecraft.commands.Commands; +import net.minecraft.commands.arguments.blocks.BlockStateParser; +import net.minecraft.core.BlockPos; +import net.minecraft.core.GlobalPos; +import net.minecraft.core.MappedRegistry; +import net.minecraft.core.Registry; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.gametest.framework.GameTestServer; +import net.minecraft.gizmos.GizmoCollector; +import net.minecraft.gizmos.Gizmos; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketFlow; +import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket; +import net.minecraft.network.protocol.game.ClientboundSoundPacket; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.Bootstrap; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.Services; +import net.minecraft.server.WorldLoader; +import net.minecraft.server.WorldStem; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.progress.LoggingLevelLoadListener; +import net.minecraft.server.network.CommonListenerCookie; +import net.minecraft.server.notifications.EmptyNotificationService; +import net.minecraft.server.notifications.NotificationManager; +import net.minecraft.server.packs.repository.PackRepository; +import net.minecraft.server.packs.repository.ServerPacksSource; +import net.minecraft.server.permissions.LevelBasedPermissionSet; +import net.minecraft.server.permissions.PermissionSet; +import net.minecraft.server.players.NameAndId; +import net.minecraft.server.players.PlayerList; +import net.minecraft.util.Util; +import net.minecraft.util.datafix.DataFixers; +import net.minecraft.util.debugchart.LocalSampleLogger; +import net.minecraft.util.debugchart.SampleLogger; +import net.minecraft.world.clock.WorldClocks; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.AgeableMob; +import net.minecraft.world.entity.ai.Brain; +import net.minecraft.world.entity.ai.behavior.BlockPosTracker; +import net.minecraft.world.entity.ai.behavior.EntityTracker; +import net.minecraft.world.entity.ai.control.LookControl; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.entity.ai.goal.GoalSelector; +import net.minecraft.world.entity.ai.goal.WrappedGoal; +import net.minecraft.world.entity.ai.memory.MemoryModuleType; +import net.minecraft.world.entity.ai.memory.WalkTarget; +import net.minecraft.world.entity.ai.navigation.PathNavigation; +import net.minecraft.world.entity.ai.sensing.Sensor; +import net.minecraft.world.flag.FeatureFlagSet; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.level.DataPackConfig; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LevelSettings; +import net.minecraft.world.level.WorldDataConfiguration; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.dimension.LevelStem; +import net.minecraft.world.level.gamerules.GameRules; +import net.minecraft.world.level.levelgen.WorldDimensions; +import net.minecraft.world.level.levelgen.WorldGenSettings; +import net.minecraft.world.level.levelgen.WorldOptions; +import net.minecraft.world.level.levelgen.presets.WorldPresets; +import net.minecraft.world.level.storage.LevelDataAndDimensions; +import net.minecraft.world.level.storage.LevelStorageSource; +import net.minecraft.world.level.storage.PrimaryLevelData; +import net.minecraft.world.phys.Vec3; + +/** + * Mob AI oracle: a real (headless, flat, structure-free) vanilla server level. Each scenario + * builds blocks, places a target player and mobs with seeded random sources, then ticks the + * mobs exactly as ServerLevel.tick does (despawn check, then tickNonPassenger) while the rest of + * the level stands still (no block ticks, weather, spawning or random ticks), printing the + * AI-visible state of every mob after each tick: position, motion, rotations, running goals, + * targets, navigation, move/look/jump controls, brain activities and memories, and sounds. + */ +public final class VanillaMobAiOracle { + static final List SCENARIOS = new ArrayList<>(); + static PrintWriter out; + static final List SOUNDS = new ArrayList<>(); + + static final class MobSpec { + String type; + double x, y, z; + float yaw; + long seed; + boolean baby; + List flags = new ArrayList<>(); + } + + static final class Scenario { + String name; + int ticks; + long time = 6000; + boolean rain, thunder; + int originX, originZ; + List blocks = new ArrayList<>(); + double[] player; + boolean creative; + List mobs = new ArrayList<>(); + long levelSeed = 0; + } + + static void parse(Path path) throws Exception { + Scenario s = null; + for (String raw : Files.readAllLines(path)) { + String line = raw.strip(); + if (line.isEmpty() || line.startsWith("#")) continue; + String[] f = line.split("\\s+"); + switch (f[0]) { + case "scenario" -> { + s = new Scenario(); + s.name = f[1]; + for (int i = 2; i < f.length; i++) { + String[] kv = f[i].split("=", 2); + switch (kv[0]) { + case "ticks" -> s.ticks = Integer.parseInt(kv[1]); + case "time" -> s.time = Long.parseLong(kv[1]); + case "rain" -> s.rain = true; + case "thunder" -> s.thunder = true; + case "levelseed" -> s.levelSeed = Long.parseLong(kv[1]); + default -> throw new IllegalArgumentException(line); + } + } + } + case "origin" -> { s.originX = Integer.parseInt(f[1]); s.originZ = Integer.parseInt(f[2]); } + case "fill", "block" -> s.blocks.add(f); + case "player" -> { + s.player = new double[] {Double.parseDouble(f[1]), Double.parseDouble(f[2]), Double.parseDouble(f[3])}; + s.creative = f.length > 4 && f[4].equals("creative"); + } + case "mob" -> { + MobSpec m = new MobSpec(); + m.type = f[1]; + m.x = Double.parseDouble(f[2]); + m.y = Double.parseDouble(f[3]); + m.z = Double.parseDouble(f[4]); + m.yaw = Float.parseFloat(f[5]); + m.seed = Long.parseLong(f[6]); + for (int i = 7; i < f.length; i++) { + if (f[i].equals("baby")) m.baby = true; else m.flags.add(f[i]); + } + s.mobs.add(m); + } + case "end" -> { SCENARIOS.add(s); s = null; } + default -> throw new IllegalArgumentException(line); + } + } + } + + public static void main(String[] args) throws Exception { + parse(Path.of(args[0])); + out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]))); + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + Util.startTimerHackThread(); + Path universe = Files.createTempDirectory("horizon-mob-ai"); + LevelStorageSource.LevelStorageAccess access = LevelStorageSource.createDefault(universe).createAccess("aiworld"); + PackRepository packs = ServerPacksSource.createPackRepository(access); + MinecraftServer.spin(thread -> Server.create(thread, access, packs)); + } + + static String d(double v) { return Long.toHexString(Double.doubleToRawLongBits(v)); } + static String f(float v) { return Integer.toHexString(Float.floatToRawIntBits(v)); } + + static Field field(Class c, String name) throws Exception { + for (Class k = c; k != null; k = k.getSuperclass()) { + try { + Field fl = k.getDeclaredField(name); + fl.setAccessible(true); + return fl; + } catch (NoSuchFieldException e) { + // keep looking + } + } + throw new NoSuchFieldException(name); + } + + static Method method(Class c, String name, Class... types) throws Exception { + for (Class k = c; k != null; k = k.getSuperclass()) { + try { + Method m = k.getDeclaredMethod(name, types); + m.setAccessible(true); + return m; + } catch (NoSuchMethodException e) { + // keep looking + } + } + throw new NoSuchMethodException(name); + } + + static Object get(Object o, String name) throws Exception { return field(o.getClass(), name).get(o); } + + static final class Server extends MinecraftServer { + static final FeatureFlagSet FEATURES = FeatureFlags.REGISTRY + .allFlags() + .subtract(FeatureFlagSet.of(FeatureFlags.REDSTONE_EXPERIMENTS, FeatureFlags.MINECART_IMPROVEMENTS)); + final LocalSampleLogger sampleLogger = new LocalSampleLogger(4); + int scenario = 0; + int phase = 0; + int wait = 0; + ServerPlayer player; + int failures = 0; + + static Server create(Thread thread, LevelStorageSource.LevelStorageAccess access, PackRepository packs) { + try { + packs.reload(); + ArrayList enabled = new ArrayList<>(packs.getAvailableIds()); + enabled.remove("vanilla"); + enabled.addFirst("vanilla"); + WorldDataConfiguration config = new WorldDataConfiguration(new DataPackConfig(enabled, List.of()), FEATURES); + LevelSettings settings = new LevelSettings("AI Level", GameType.SURVIVAL, LevelSettings.DifficultySettings.DEFAULT, true, config); + WorldLoader.PackConfig packConfig = new WorldLoader.PackConfig(packs, config, false, true); + WorldLoader.InitConfig init = new WorldLoader.InitConfig(packConfig, Commands.CommandSelection.DEDICATED, LevelBasedPermissionSet.OWNER); + WorldStem stem = Util.blockUntilDone(executor -> WorldLoader.load(init, context -> { + Registry none = new MappedRegistry<>(Registries.LEVEL_STEM, Lifecycle.stable()).freeze(); + WorldDimensions dims = context.datapackWorldRegistries().lookupOrThrow(Registries.WORLD_PRESET) + .getOrThrow(WorldPresets.FLAT).value().createWorldDimensions(); + WorldDimensions.Complete complete = dims.bake(none); + PrimaryLevelData data = new PrimaryLevelData(settings, complete.specialWorldProperty(), complete.lifecycle()); + return new WorldLoader.DataLoadOutput<>( + new LevelDataAndDimensions.WorldDataAndGenSettings(data, new WorldGenSettings(new WorldOptions(0L, false, false), dims)), + complete.dimensionsRegistryAccess()); + }, WorldStem::new, Util.backgroundExecutor(), executor)).get(); + GameRules rules = new GameRules(FEATURES); + rules.set(GameRules.SPAWN_MOBS, false, null); + rules.set(GameRules.SPAWN_MONSTERS, false, null); + rules.set(GameRules.SPAWN_PATROLS, false, null); + rules.set(GameRules.SPAWN_PHANTOMS, false, null); + rules.set(GameRules.SPAWN_WANDERING_TRADERS, false, null); + rules.set(GameRules.SPAWN_WARDENS, false, null); + rules.set(GameRules.ADVANCE_TIME, false, null); + rules.set(GameRules.ADVANCE_WEATHER, false, null); + rules.set(GameRules.RAIDS, false, null); + Field nf = GameTestServer.class.getDeclaredField("NO_SERVICES"); + nf.setAccessible(true); + return new Server(thread, access, packs, stem, rules, (Services) nf.get(null)); + } catch (Exception e) { + e.printStackTrace(); + System.exit(2); + throw new IllegalStateException(e); + } + } + + Server(Thread thread, LevelStorageSource.LevelStorageAccess access, PackRepository packs, WorldStem stem, GameRules rules, Services services) { + super(thread, access, packs, stem, Optional.of(rules), Proxy.NO_PROXY, DataFixers.getDataFixer(), services, + LoggingLevelLoadListener.forDedicatedServer(), false, new NotificationManager()); + } + + @Override + protected boolean initServer() { + this.setPlayerList(new PlayerList(this, this.registries(), this.playerDataStorage, new EmptyNotificationService()) { + @Override + public void broadcast(Player except, double x, double y, double z, double range, ResourceKey dim, Packet packet) { + capture(packet); + } + }); + Gizmos.withCollector(GizmoCollector.NOOP); + this.loadLevel(); + return true; + } + + static void capture(Packet packet) { + if (packet instanceof ClientboundSoundPacket p) { + SOUNDS.add(p.getSound().value().location() + " " + f(p.getVolume()) + " " + f(p.getPitch())); + } else if (packet instanceof ClientboundSoundEntityPacket p) { + SOUNDS.add(p.getSound().value().location() + " " + f(p.getVolume()) + " " + f(p.getPitch())); + } + } + + @Override + protected void tickServer(BooleanSupplier haveTime) { + try { + step(haveTime); + } catch (Throwable t) { + t.printStackTrace(); + out.flush(); + System.exit(3); + } + } + + ServerLevel level() { return this.overworld(); } + + void step(BooleanSupplier haveTime) throws Exception { + if (scenario >= SCENARIOS.size()) { + out.close(); + // Nothing to save: skip the shutdown. + Runtime.getRuntime().halt(0); + return; + } + Scenario s = SCENARIOS.get(scenario); + ServerLevel level = level(); + int cx = s.originX >> 4, cz = s.originZ >> 4; + switch (phase) { + case 0 -> { + for (int dx = -4; dx <= 4; dx++) + for (int dz = -4; dz <= 4; dz++) + level.setChunkForced(cx + dx, cz + dz, true); + phase = 1; + super.tickServer(haveTime); + } + case 1 -> { + super.tickServer(haveTime); + boolean ready = true; + for (int dx = -4; dx <= 4 && ready; dx++) + for (int dz = -4; dz <= 4 && ready; dz++) + ready = level.isPositionEntityTicking(new BlockPos((cx + dx) * 16, -60, (cz + dz) * 16)); + if (ready) { + build(s, level); + phase = 2; + wait = 0; + } + } + case 2 -> { + super.tickServer(haveTime); + if (!level.getChunkSource().getLightEngine().hasLightWork() && ++wait > 5) { + run(s, level); + for (int dx = -4; dx <= 4; dx++) + for (int dz = -4; dz <= 4; dz++) + level.setChunkForced(cx + dx, cz + dz, false); + scenario++; + phase = 0; + } + } + default -> throw new IllegalStateException(); + } + } + + void build(Scenario s, ServerLevel level) throws Exception { + var blocks = level.holderLookup(Registries.BLOCK); + for (String[] b : s.blocks) { + if (b[0].equals("block")) { + BlockState state = BlockStateParser.parseForBlock(blocks, b[4], false).blockState(); + level.setBlock(new BlockPos(Integer.parseInt(b[1]), Integer.parseInt(b[2]), Integer.parseInt(b[3])), state, 2 | 16); + } else { + BlockState state = BlockStateParser.parseForBlock(blocks, b[7], false).blockState(); + int x0 = Integer.parseInt(b[1]), y0 = Integer.parseInt(b[2]), z0 = Integer.parseInt(b[3]); + int x1 = Integer.parseInt(b[4]), y1 = Integer.parseInt(b[5]), z1 = Integer.parseInt(b[6]); + for (int x = Math.min(x0, x1); x <= Math.max(x0, x1); x++) + for (int y = Math.min(y0, y1); y <= Math.max(y0, y1); y++) + for (int z = Math.min(z0, z1); z <= Math.max(z0, z1); z++) + level.setBlock(new BlockPos(x, y, z), state, 2 | 16); + } + } + } + + void run(Scenario s, ServerLevel level) throws Exception { + out.println("== " + s.name); + var clock = level.registryAccess().lookupOrThrow(Registries.WORLD_CLOCK).getOrThrow(WorldClocks.OVERWORLD); + this.clockManager().setTotalTicks(clock, s.time); + // isRaining/isThundering read the rain and thunder levels only. + level.setRainLevel(s.rain ? 1.0F : 0.0F); + level.setThunderLevel(s.thunder ? 1.0F : 0.0F); + if (s.player != null) { + if (player == null) { + CommonListenerCookie cookie = CommonListenerCookie.createInitial(new GameProfile(new UUID(0x1234L, 0x5678L), "horizon-ai"), false); + player = new ServerPlayer(this, level, cookie.gameProfile(), cookie.clientInformation()); + Connection connection = new Connection(PacketFlow.SERVERBOUND); + new EmbeddedChannel(connection); + this.getPlayerList().placeNewPlayer(connection, player, cookie); + } + player.setGameMode(s.creative ? GameType.CREATIVE : GameType.SURVIVAL); + player.snapTo(s.player[0], s.player[1], s.player[2], 0.0F, 0.0F); + player.setDeltaMovement(Vec3.ZERO); + } else if (player != null) { + player.snapTo(s.originX + 5000, -60, s.originZ, 0.0F, 0.0F); + } + List mobs = new ArrayList<>(); + int id = 100000; + for (MobSpec spec : s.mobs) { + EntityType type = BuiltInRegistries.ENTITY_TYPE.getValue(net.minecraft.resources.Identifier.parse(spec.type)); + Mob mob = (Mob) type.create(level, EntitySpawnReason.COMMAND); + mob.setId(id++); + mob.snapTo(spec.x, spec.y, spec.z, spec.yaw, 0.0F); + mob.setYHeadRot(spec.yaw); + mob.setYBodyRot(spec.yaw); + if (spec.baby) { + if (mob instanceof AgeableMob a) a.setBaby(true); + else mob.setBaby(true); + } + for (String flag : spec.flags) { + if (flag.equals("persistent")) mob.setPersistenceRequired(); + else if (flag.equals("noai")) mob.setNoAi(true); + else throw new IllegalArgumentException(flag); + } + level.addFreshEntity(mob); + mob.getRandom().setSeed(spec.seed); + Brain brain = mob.getBrain(); + @SuppressWarnings("unchecked") + Map> sensors = (Map>) get(brain, "sensors"); + for (Sensor sensor : sensors.values()) sensor.randomlyDelayStart(mob.getRandom()); + mobs.add(mob); + } + level.getRandom().setSeed(s.levelSeed); + SOUNDS.clear(); + Method tickTime = method(ServerLevel.class, "tickTime"); + Object manager = get(level, "entityManager"); + Method managerTick = method(manager.getClass(), "tick"); + for (int t = 1; t <= s.ticks; t++) { + level.environmentAttributes().invalidateTickCache(); + level.updateSkyBrightness(); + tickTime.invoke(level); + if (player != null && s.player != null) { + player.setHealth(player.getMaxHealth()); + player.setInvulnerableTime(0); + player.hurtTime = 0; + player.snapTo(s.player[0], s.player[1], s.player[2], 0.0F, 0.0F); + player.setDeltaMovement(Vec3.ZERO); + } + SOUNDS.clear(); + for (Mob mob : mobs) { + if (mob.isRemoved()) continue; + mob.checkDespawn(); + if (mob.isRemoved()) continue; + level.tickNonPassenger(mob); + } + managerTick.invoke(manager); + for (int i = 0; i < mobs.size(); i++) print(t, i, mobs.get(i)); + for (String sound : SOUNDS) out.println(t + " sound " + sound); + } + for (Mob mob : mobs) mob.discard(); + managerTick.invoke(manager); + out.flush(); + } + + static String who(Entity e) { + if (e == null) return "none"; + if (e instanceof ServerPlayer) return "player"; + return "e" + e.getId(); + } + + static String goals(GoalSelector selector) { + StringBuilder sb = new StringBuilder(); + for (WrappedGoal g : selector.getAvailableGoals()) { + if (!g.isRunning()) continue; + if (sb.length() > 0) sb.append('|'); + Class c = g.getGoal().getClass(); + String name = c.getSimpleName(); + if (name.isEmpty()) name = c.getName().substring(c.getName().lastIndexOf('.') + 1); + sb.append(name); + } + return sb.length() == 0 ? "-" : sb.toString(); + } + + static String pos(BlockPos p) { return p.getX() + "," + p.getY() + "," + p.getZ(); } + + static String value(Object v) { + if (v == null) return "null"; + if (v instanceof Entity e) return who(e); + if (v instanceof BlockPos p) return pos(p); + if (v instanceof GlobalPos g) return pos(g.pos()); + if (v instanceof WalkTarget w) return value(w.getTarget()) + "/" + f(w.getSpeedModifier()) + "/" + w.getCloseEnoughDist(); + if (v instanceof EntityTracker e) return who(e.getEntity()); + if (v instanceof BlockPosTracker b) return pos(b.currentBlockPosition()); + if (v instanceof Boolean || v instanceof Integer || v instanceof Long) return v.toString(); + if (v instanceof net.minecraft.util.Unit) return "u"; + if (v instanceof Collection c) return "n" + c.size(); + if (v instanceof net.minecraft.world.level.pathfinder.Path p) return "path" + pos(p.getTarget()); + return v.getClass().getSimpleName(); + } + + void print(int t, int i, Mob m) throws Exception { + StringBuilder sb = new StringBuilder(); + sb.append(t).append(' ').append(i); + if (m.isRemoved()) { + out.println(sb.append(" removed ").append(m.getRemovalReason())); + return; + } + sb.append("\tp ").append(d(m.getX())).append(',').append(d(m.getY())).append(',').append(d(m.getZ())); + Vec3 v = m.getDeltaMovement(); + sb.append("\tv ").append(d(v.x)).append(',').append(d(v.y)).append(',').append(d(v.z)); + sb.append("\tr ").append(f(m.getYRot())).append(',').append(f(m.getXRot())).append(',').append(f(m.getYHeadRot())).append(',').append(f(m.yBodyRot)); + sb.append("\tg ").append(m.onGround() ? 1 : 0).append(m.horizontalCollision ? 1 : 0); + sb.append("\thp ").append(f(m.getHealth())); + sb.append("\tgoals ").append(goals((GoalSelector) get(m, "goalSelector"))); + sb.append("\ttargets ").append(goals((GoalSelector) get(m, "targetSelector"))); + sb.append("\ttarget ").append(who(m.getTarget())); + PathNavigation nav = m.getNavigation(); + var path = nav.getPath(); + sb.append("\tnav "); + if (path == null) sb.append("none"); + else sb.append(pos(path.getTarget())).append(' ').append(path.getNextNodeIndex()).append('/').append(path.getNodeCount()) + .append(path.isDone() ? " done" : ""); + MoveControl mc = m.getMoveControl(); + sb.append("\tmove ").append(get(mc, "operation")).append(' ').append(d((double) get(mc, "wantedX"))).append(',') + .append(d((double) get(mc, "wantedY"))).append(',').append(d((double) get(mc, "wantedZ"))).append(' ') + .append(d((double) get(mc, "speedModifier"))); + LookControl lc = m.getLookControl(); + sb.append("\tlook ").append(get(lc, "lookAtCooldown")).append(' ').append(d((double) get(lc, "wantedX"))).append(',') + .append(d((double) get(lc, "wantedY"))).append(',').append(d((double) get(lc, "wantedZ"))); + sb.append("\tin ").append(f(m.xxa)).append(',').append(f(m.zza)).append(',').append(f(m.getSpeed())).append(',') + .append(field(LivingEntity.class, "jumping").getBoolean(m) ? 1 : 0); + Brain brain = m.getBrain(); + if (!brain.getActiveActivities().isEmpty() && !((Map) get(brain, "sensors")).isEmpty()) { + List acts = new ArrayList<>(); + for (var a : brain.getActiveActivities()) acts.add(a.getName()); + acts.sort(null); + sb.append("\tact ").append(String.join("|", acts)); + List mem = new ArrayList<>(); + brain.forEach(new Brain.Visitor() { + @Override public void acceptEmpty(MemoryModuleType type) {} + @Override public void accept(MemoryModuleType type, U value) { mem.add(name(type) + "=" + value(value)); } + @Override public void accept(MemoryModuleType type, U value, long ttl) { mem.add(name(type) + "=" + value(value) + "@" + ttl); } + }); + mem.sort(null); + sb.append("\tmem ").append(String.join(" ", mem)); + } + out.println(sb); + } + + static String name(MemoryModuleType type) { + return BuiltInRegistries.MEMORY_MODULE_TYPE.getKey(type).getPath(); + } + + @Override protected SampleLogger getTickTimeLogger() { return sampleLogger; } + @Override public boolean isTickTimeLoggingEnabled() { return false; } + @Override protected void waitUntilNextTick() { this.runAllTasks(); } + @Override public SystemReport fillServerSystemReport(SystemReport report) { report.setDetail("Type", "Mob AI oracle"); return report; } + @Override protected void onServerExit() { super.onServerExit(); System.exit(0); } + @Override protected void onServerCrash(net.minecraft.CrashReport report) { super.onServerCrash(report); System.exit(1); } + @Override public boolean isHardcore() { return false; } + @Override public LevelBasedPermissionSet operatorUserPermissions() { return LevelBasedPermissionSet.ALL; } + @Override public PermissionSet getFunctionCompilationPermissions() { return LevelBasedPermissionSet.OWNER; } + @Override public boolean shouldRconBroadcast() { return false; } + @Override public boolean isDedicatedServer() { return false; } + @Override public int getRateLimitPacketsPerSecond() { return 0; } + @Override public int getCommandSpamThresholdSeconds() { return 0; } + @Override public int getChatSpamThresholdSeconds() { return 0; } + @Override public boolean useNativeTransport() { return false; } + @Override public boolean isPublished() { return false; } + @Override public boolean shouldInformAdmins() { return false; } + @Override public boolean isSingleplayerOwner(NameAndId nameAndId) { return false; } + @Override public int getMaxPlayers() { return 1; } + } +} diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py new file mode 100644 index 000000000..33e11edb4 --- /dev/null +++ b/tools/test_mob_ai_parity.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Differential mob AI harness. + +The Java oracle (VanillaMobAiOracle) runs vanilla mobs in a real, headless, flat vanilla server +level: each scenario builds a scene, places a target player and mobs with seeded random sources +and ticks the mobs the way ServerLevel.tick does. The Rust probe (mob_ai_probe) replays the same +scenarios on Horizon's mob AI. Both print every mob's AI-visible state after every tick (position, +motion, rotations, running goals and target goals, attack target, navigation path, move and look +controls, movement input, brain activities and memories) and the sounds played; this harness +reports, per scenario and mob, how many ticks match before the first divergence and what differs. + + python3 tools/test_mob_ai_parity.py [--only NAME ...] [--rust-only] [--java-only] [--strict] +""" +import argparse +import os +import struct +import subprocess +import sys +from pathlib import Path + +try: + from . import lab, oracle_harness, test_rust_parity as base, test_model_baking_parity as baking +except ImportError: + import lab + import oracle_harness + import test_rust_parity as base + import test_model_baking_parity as baking + +FLOOR = -60 # top of the flat preset's grass layer + 1 + + +def ring(x0, z0, size, state, y=FLOOR): + return [f'fill {x0 - size} {y} {z0 - size} {x0 + size} {y} {z0 + size} {state}'] + + +# Each scenario is (name, ticks, options, lines); positions are relative to the scenario origin +# and translated by the generator so scenarios never share chunks. +def scenarios(): + s = [] + + def add(name, ticks, lines, opts=''): + s.append((name, ticks, opts, lines)) + + # Passive and hostile land mobs on open grass with a survival player nearby. + for species, seed in [('zombie', 1), ('skeleton', 2), ('creeper', 3), ('spider', 4), ('husk', 5), + ('cow', 6), ('pig', 7), ('chicken', 8), ('sheep', 9), ('wandering_trader', 10), + ('villager', 11), ('drowned', 12), ('enderman', 13), ('witch', 14)]: + add(f'{species}_player', 200, [ + 'player 6.5 -60 0.5', + f'mob minecraft:{species} 0.5 -60 0.5 0 {seed} persistent', + ]) + add(f'{species}_alone', 200, [ + f'mob minecraft:{species} 0.5 -60 0.5 90 {seed * 7 + 1} persistent', + ]) + # Drowned in a pool with the player on the shore and in the water. + add('drowned_pool', 200, ['fill -6 -64 -6 6 -61 6 minecraft:water', + 'player 9.5 -60 0.5', + 'mob minecraft:drowned 0.5 -63 0.5 0 21 persistent']) + add('drowned_pool_swimmer', 200, ['fill -6 -64 -6 6 -61 6 minecraft:water', + 'player 3.5 -62 0.5', + 'mob minecraft:drowned -3.5 -63 0.5 0 22 persistent']) + # Night: undead do not burn, monsters seek darkness. + add('zombie_night', 200, ['player 10.5 -60 0.5', 'mob minecraft:zombie 0.5 -60 0.5 0 31 persistent'], 'time=18000') + add('skeleton_day_burn', 120, ['mob minecraft:skeleton 0.5 -60 0.5 0 32 persistent']) + # The wither (summoned, not built: no invulnerable spawn phase). + add('wither_player', 200, ['player 10.5 -60 0.5', 'mob minecraft:wither 0.5 -58 0.5 0 41 persistent']) + # A villager with a job site, a bed and a bell. + add('villager_village', 300, [ + 'block 4 -60 0 minecraft:composter', + 'block -4 -60 2 minecraft:red_bed[facing=north,part=foot]', + 'block -4 -60 1 minecraft:red_bed[facing=north,part=head]', + 'block 0 -60 -6 minecraft:bell', + 'player 12.5 -60 0.5', + 'mob minecraft:villager 0.5 -60 0.5 0 51 persistent', + ]) + return s + + +def write_scenarios(path, chosen): + lines = [] + for i, (name, ticks, opts, body) in chosen: + ox, oz = 512 * (i + 1), 0 + lines.append(f'scenario {name} ticks={ticks} {opts}'.rstrip()) + lines.append(f'origin {ox} {oz}') + for line in body: + f = line.split() + if f[0] == 'player': + f[1] = repr(float(f[1]) + ox) + f[3] = repr(float(f[3]) + oz) + elif f[0] == 'mob': + f[2] = repr(float(f[2]) + ox) + f[4] = repr(float(f[4]) + oz) + elif f[0] == 'block': + f[1] = str(int(f[1]) + ox) + f[3] = str(int(f[3]) + oz) + elif f[0] == 'fill': + for k in (1, 4): + f[k] = str(int(f[k]) + ox) + for k in (3, 6): + f[k] = str(int(f[k]) + oz) + lines.append(' '.join(f)) + lines.append('end') + path.write_text('\n'.join(lines) + '\n') + + +def parse(path): + """{scenario: {tick: {mob: {field: value}}, sounds: {tick: [..]}}}""" + result, cur = {}, None + for line in path.read_text().splitlines(): + if line.startswith('== '): + cur = result.setdefault(line[3:], {'ticks': {}, 'sounds': {}}) + continue + head, *fields = line.split('\t') + parts = head.split(' ', 2) + t = int(parts[0]) + if parts[1] == 'sound': + cur['sounds'].setdefault(t, []).append(parts[2]) + continue + mob = int(parts[1]) + row = {} + if len(parts) > 2: + row['removed'] = parts[2] + for f in fields: + k, _, v = f.partition(' ') + row[k] = v + cur['ticks'].setdefault(t, {})[mob] = row + return result + + +def decode(value): + """Hex float/double fields made readable.""" + def one(x): + try: + if len(x) > 8: + return f'{struct.unpack(">d", int(x, 16).to_bytes(8, "big"))[0]!r}' + return f'{struct.unpack(">f", int(x, 16).to_bytes(4, "big"))[0]:.9g}' + except ValueError: + return x + out = [] + for word in value.split(' '): + out.append(','.join(one(p) if all(c in '0123456789abcdef' for c in p) and len(p) >= 5 else p for p in word.split(','))) + return ' '.join(out) + + +def compare(vanilla, rust, fields=None): + """Returns (report lines, totals).""" + report, totals = [], {'mob_ticks': 0, 'matched': 0, 'scenarios': 0, 'clean': 0} + for name, v in vanilla.items(): + r = rust.get(name) + totals['scenarios'] += 1 + if r is None: + report.append(f'{name}: missing from Horizon') + continue + mobs = sorted({m for t in v['ticks'].values() for m in t}) + clean = True + for mob in mobs: + ticks = sorted(v['ticks']) + first = None + for t in ticks: + a = v['ticks'][t].get(mob) + b = r['ticks'].get(t, {}).get(mob) + totals['mob_ticks'] += 1 + if a == b or (b is not None and fields and all(a.get(k) == b.get(k) for k in fields)): + if first is None: + totals['matched'] += 1 + continue + if first is None: + first = t + diffs = [] + for k in (a or {}): + if b is None or a.get(k) != b.get(k): + diffs.append(f'{k}: vanilla {decode(a.get(k, "?"))} | horizon {decode((b or {}).get(k, "?"))}') + for k in (b or {}): + if a is None or k not in a: + diffs.append(f'{k}: vanilla ? | horizon {decode(b[k])}') + report.append(f'{name} mob {mob}: first divergence at tick {t} of {len(ticks)}') + report.extend(' ' + d for d in diffs[:12]) + if first is not None: + clean = False + # Sounds: first differing tick. + for t in sorted(set(v['sounds']) | set(r['sounds'])): + if v['sounds'].get(t, []) != r['sounds'].get(t, []): + report.append(f'{name}: sounds differ at tick {t}: vanilla {v["sounds"].get(t, [])} | horizon {r["sounds"].get(t, [])}') + clean = False + break + totals['clean'] += clean + if clean: + report.append(f'{name}: all {len(v["ticks"])} ticks match') + return report, totals + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('--only', nargs='*') + parser.add_argument('--java-only', action='store_true') + parser.add_argument('--rust-only', action='store_true', help='reuse the last vanilla output') + parser.add_argument('--strict', action='store_true', help='fail on any divergence') + args = parser.parse_args() + build = lab.LOCAL / 'mob-ai-parity' + build.mkdir(parents=True, exist_ok=True) + chosen = [(i, s) for i, s in enumerate(scenarios()) if not args.only or any(o in s[0] for o in args.only)] + inputs = build / 'scenarios.txt' + write_scenarios(inputs, chosen) + lock, jars, _ = base.verify_artifacts() + if not args.rust_only: + classes, dependencies, _ = oracle_harness.compile_oracle(build, 'VanillaMobAiOracle', jars, baking.client_libraries(), + lock['minecraft']['java_major']) + oracle_harness.run_logged(['java', '-Xmx3g', '-Djava.awt.headless=true', '-cp', str(classes) + os.pathsep + dependencies, + 'dev.horizonlab.parity.VanillaMobAiOracle', inputs, build / 'vanilla.txt'], + build, 'vanilla', timeout=3600) + if not args.java_only: + oracle_harness.run_logged(['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--example', 'mob_ai_probe'], + build, 'compile-rust') + binary = lab.ROOT / 'target/release/examples/mob_ai_probe' + oracle_harness.run_logged([binary, lab.ROOT / '.local/horizon-client/26.3', inputs, build / 'horizon.txt'], build, 'horizon') + if args.java_only: + return + names = {s[0] for _, s in chosen} + vanilla = {k: v for k, v in parse(build / 'vanilla.txt').items() if k in names} + report, totals = compare(vanilla, parse(build / 'horizon.txt')) + (build / 'report.txt').write_text('\n'.join(report) + '\n') + print('\n'.join(report)) + print(f"{totals['clean']}/{totals['scenarios']} scenarios match entirely; " + f"{totals['matched']}/{totals['mob_ticks']} mob-ticks match before each mob's first divergence") + if args.strict and totals['clean'] != totals['scenarios']: + raise SystemExit(1) + + +if __name__ == '__main__': + main() From 120ac3231153378e534f9da91939a894b0d42f33 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:47:11 +0200 Subject: [PATCH 10/28] Test LAN hosting against the vanilla client and track entities as ServerEntity does Add a decoding capture proxy (tools/net_capture.py), an offline vanilla client launcher (tools/vanilla_client.py) and a vanilla codec oracle that decodes every captured clientbound packet with vanilla's StreamCodecs. Fix the entity data serializer ids (vector3 onwards were off by one), the sheep wool and piglin baby indices, send mob variants, villager data and equipment, and send entity movement at each type's update interval and tracking range with position syncs, like ServerEntity.sendChanges. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/lan.rs | 269 +++++++++++++---- crates/horizon-client/src/lan/entity.rs | 275 ++++++++++------- crates/horizon-client/src/lan/hub.rs | 37 ++- crates/horizon-client/src/lan/mod.rs | 1 + crates/horizon-client/src/lan/tracking.rs | 176 +++++++++++ crates/horizon-protocol/src/entity_data.rs | 42 ++- .../parity/VanillaPacketCodecOracle.java | 165 ++++++++++ tools/generate_entity_tracking.py | 69 +++++ tools/net_capture.py | 284 ++++++++++++++++++ tools/vanilla_client.py | 150 +++++++++ 10 files changed, 1274 insertions(+), 194 deletions(-) create mode 100644 crates/horizon-client/src/lan/tracking.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPacketCodecOracle.java create mode 100644 tools/generate_entity_tracking.py create mode 100644 tools/net_capture.py create mode 100644 tools/vanilla_client.py diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 7cce27dac..664662249 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -58,38 +58,215 @@ fn entity_uuid(id: u32) -> u128 { 0x4856_5a4e_0000_0000_0000_0000_0000_0000u128 | u128::from(id) } -/// Species that are AgeableMob (or have a baby flag at the same index). -fn ageable(kind: &str) -> bool { - matches!( - kind, +/// The SynchedEntityData index of the baby flag: AgeableMob.DATA_BABY_ID and +/// Zombie.DATA_BABY_ID are both the first entry after Mob's (16); Piglin's +/// comes after AbstractPiglin's zombification flag (17). +fn baby_index(kind: &str) -> Option { + match kind { + "minecraft:piglin" => Some(17), "minecraft:cow" - | "minecraft:mooshroom" - | "minecraft:pig" - | "minecraft:sheep" - | "minecraft:chicken" - | "minecraft:horse" - | "minecraft:donkey" - | "minecraft:mule" - | "minecraft:llama" - | "minecraft:cat" - | "minecraft:wolf" - | "minecraft:fox" - | "minecraft:rabbit" - | "minecraft:panda" - | "minecraft:villager" - | "minecraft:zombie" - | "minecraft:husk" - | "minecraft:drowned" - | "minecraft:zombie_villager" - | "minecraft:piglin" - | "minecraft:hoglin" - | "minecraft:goat" - | "minecraft:ocelot" - | "minecraft:turtle" - | "minecraft:strider" - | "minecraft:camel" - | "minecraft:axolotl" - ) + | "minecraft:mooshroom" + | "minecraft:pig" + | "minecraft:sheep" + | "minecraft:chicken" + | "minecraft:horse" + | "minecraft:donkey" + | "minecraft:mule" + | "minecraft:skeleton_horse" + | "minecraft:zombie_horse" + | "minecraft:llama" + | "minecraft:trader_llama" + | "minecraft:cat" + | "minecraft:wolf" + | "minecraft:fox" + | "minecraft:rabbit" + | "minecraft:panda" + | "minecraft:polar_bear" + | "minecraft:bee" + | "minecraft:frog" + | "minecraft:sniffer" + | "minecraft:armadillo" + | "minecraft:villager" + | "minecraft:zombie" + | "minecraft:husk" + | "minecraft:drowned" + | "minecraft:zombie_villager" + | "minecraft:zombified_piglin" + | "minecraft:hoglin" + | "minecraft:goat" + | "minecraft:ocelot" + | "minecraft:turtle" + | "minecraft:strider" + | "minecraft:camel" + | "minecraft:axolotl" + | "minecraft:dolphin" + | "minecraft:squid" + | "minecraft:glow_squid" => Some(16), + _ => None, + } +} + +/// A mob's synched data as ServerEntity sends it (only the values that differ +/// from the defaults the client constructs), with vanilla's entry indices: +/// Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses. +fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> { + let mut meta = Vec::new(); + let kind = m.kind.id.as_str(); + if m.fire_ticks > 0 { + meta.push((0, serializer::BYTE, Value::Byte(1))); + } + if let Some(name) = &m.custom_name { + meta.push(( + 2, + serializer::OPTIONAL_COMPONENT, + Value::OptText(Some(horizon_protocol::text::literal(name))), + )); + if m.name_visible { + meta.push((3, serializer::BOOLEAN, Value::Bool(true))); + } + } + if m.health < m.kind.max_health { + meta.push((9, serializer::FLOAT, Value::Float(m.health.max(0.0)))); + } + if m.is_baby() + && let Some(index) = baby_index(kind) + { + meta.push((index, serializer::BOOLEAN, Value::Bool(true))); + } + let e = &m.extra; + let id = |registry: &str, name: &str| hub.registry_id(registry, &format!("minecraft:{name}")); + match kind { + // Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 when sheared. + "minecraft:sheep" => { + let value = (e.color & 15) | if e.sheared { 16 } else { 0 }; + if value != 0 { + meta.push((18, serializer::BYTE, Value::Byte(value as i8))); + } + } + "minecraft:cat" | "minecraft:wolf" => { + // TamableAnimal.DATA_FLAGS_ID: sitting 1, tame 4. + let flags = i8::from(e.sitting) | if e.tame { 4 } else { 0 }; + if flags != 0 { + meta.push((18, serializer::BYTE, Value::Byte(flags))); + } + let (index, registry, name) = if kind == "minecraft:cat" { + let v = horizon_client::mobs::tame::CAT_VARIANTS[(e.variant as usize).min(10)]; + (20, "minecraft:cat_variant", v) + } else { + let v = horizon_client::mobs::tame::WOLF_VARIANTS[(e.variant as usize).min(8)].0; + (23, "minecraft:wolf_variant", v) + }; + let serializer = if index == 20 { + serializer::CAT_VARIANT + } else { + serializer::WOLF_VARIANT + }; + if let Some(v) = id(registry, name) { + meta.push((index, serializer, Value::Id(v))); + } + } + "minecraft:horse" + | "minecraft:donkey" + | "minecraft:mule" + | "minecraft:llama" + | "minecraft:trader_llama" + | "minecraft:skeleton_horse" + | "minecraft:zombie_horse" + | "minecraft:camel" => { + // AbstractHorse.DATA_ID_FLAGS: tame 2. + if e.tame { + meta.push((18, serializer::BYTE, Value::Byte(2))); + } + if kind == "minecraft:horse" { + let v = i32::from(e.variant) | i32::from(e.variant2) << 8; + if v != 0 { + meta.push((19, serializer::INT, Value::Int(v))); + } + } else if kind.ends_with("llama") { + if e.chested { + meta.push((19, serializer::BOOLEAN, Value::Bool(true))); + } + meta.push((20, serializer::INT, Value::Int(i32::from(e.variant2.max(1))))); + if e.variant != 0 { + meta.push((21, serializer::INT, Value::Int(i32::from(e.variant)))); + } + } else if (kind == "minecraft:donkey" || kind == "minecraft:mule") && e.chested { + meta.push((19, serializer::BOOLEAN, Value::Bool(true))); + } + } + // Villager.DATA_VILLAGER_DATA and ZombieVillager's (after Zombie's three). + "minecraft:villager" | "minecraft:zombie_villager" => { + use horizon_client::mobs::render::{PROFESSIONS, VILLAGER_TYPES}; + let villager_type = VILLAGER_TYPES[e.variant as usize % VILLAGER_TYPES.len()]; + let profession = PROFESSIONS[e.variant2 as usize % PROFESSIONS.len()]; + if let (Some(t), Some(p)) = ( + id("minecraft:villager_type", villager_type), + id("minecraft:villager_profession", profession), + ) { + let index = if kind == "minecraft:villager" { 19 } else { 20 }; + let level = i32::from(e.variant3.max(1)); + meta.push((index, serializer::VILLAGER_DATA, Value::Ids(vec![t, p, level]))); + } + } + // AbstractCubeMob.ID_SIZE. + "minecraft:slime" | "minecraft:magma_cube" => { + if e.size > 1 { + meta.push((18, serializer::INT, Value::Int(e.size))); + } + } + // Creeper.DATA_IS_POWERED. + "minecraft:creeper" if e.charged => { + meta.push((17, serializer::BOOLEAN, Value::Bool(true))); + } + // Enderman.DATA_CARRY_STATE. + "minecraft:enderman" => { + if let Some(state) = e.carried { + meta.push(( + 16, + serializer::OPTIONAL_BLOCK_STATE, + Value::Id(i32::from(state.0 as u16)), + )); + } + } + _ => {} + } + meta +} + +/// The equipment a mob shows (ClientboundSetEquipmentPacket slots: main hand, +/// off hand, feet, legs, chest, head, body, saddle). +fn mob_equipment(m: &Mob, hub: &mut Hub) -> Vec<(u8, Option)> { + let e = &m.extra; + let mut out = Vec::new(); + let slots = [ + (0u8, &e.main_hand), + (1, &e.off_hand), + (2, &e.feet), + (3, &e.legs), + (4, &e.chest), + (5, &e.head), + ]; + for (slot, item) in slots { + if let Some(item) = item { + let stack = ItemStack { + item: item.clone(), + count: 1, + damage: 0, + extra: None, + }; + out.push((slot, hub.stack(&Some(stack)))); + } + } + if e.saddled { + let stack = e.saddle_stack.clone().unwrap_or(ItemStack { + item: Arc::from("minecraft:saddle"), + count: 1, + damage: 0, + extra: None, + }); + out.push((7, hub.stack(&Some(stack)))); + } + out } pub const HELP: &[&str] = &[ @@ -307,31 +484,9 @@ impl Game<'_> { fn lan_entities(&self, hub: &mut Hub) -> Vec { let mut out = Vec::with_capacity(self.mobs.len() + self.dropped.len()); for m in self.mobs.iter().filter(|m| !m.removed) { - let mut meta = Vec::new(); - if let Some(name) = &m.custom_name { - meta.push(( - 2, - serializer::OPTIONAL_COMPONENT, - Value::OptText(Some(horizon_protocol::text::literal(name))), - )); - if m.name_visible { - meta.push((3, serializer::BOOLEAN, Value::Bool(true))); - } - } - if m.fire_ticks > 0 { - meta.push((0, serializer::BYTE, Value::Byte(1))); - } - if m.health < m.kind.max_health { - meta.push((9, serializer::FLOAT, Value::Float(m.health.max(0.0)))); - } let kind = m.kind.id.as_str(); - if ageable(kind) && m.is_baby() { - meta.push((16, serializer::BOOLEAN, Value::Bool(true))); - } - if kind == "minecraft:sheep" { - let value = (m.extra.color & 15) | if m.extra.sheared { 16 } else { 0 }; - meta.push((17, serializer::BYTE, Value::Byte(value as i8))); - } + let meta = mob_meta(m, hub); + let equipment = mob_equipment(m, hub); let (yaw, pitch) = (m.yaw, m.head_pitch); out.push(EntityState { id: m.id as i32, @@ -345,8 +500,7 @@ impl Game<'_> { velocity: [m.velocity.x, m.velocity.y, m.velocity.z], data: 0, meta, - equipment: Vec::new(), - send_velocity: false, + equipment, }); } for d in &self.dropped { @@ -364,7 +518,6 @@ impl Game<'_> { data: 0, meta: vec![(8, serializer::ITEM_STACK, Value::Item(stack))], equipment: Vec::new(), - send_velocity: true, }); } out diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index 6ba8c1924..179a75a82 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -1,14 +1,17 @@ -//! Entity tracking (ServerEntity / TrackedEntity): the game describes every -//! entity it simulates as an `EntityState` each tick; a `Tracker` remembers -//! what one client has been told and produces the spawn, movement, metadata, -//! equipment and removal packets that bring it up to date. +//! Entity tracking (ChunkMap.TrackedEntity / ServerEntity): the game describes +//! every entity it simulates as an `EntityState` each tick; a `Tracker` +//! remembers what one client has been told and produces the spawn, movement, +//! motion, metadata, equipment and removal packets that bring it up to date, +//! at the entity type's update interval (`tracking`). +use super::tracking; use horizon_protocol::{ buf::pack_degrees, entity_data::Value, item::Stack, packets::play::{ - self, AddEntity, MoveEntity, MoveEntityPos, MoveEntityPosRot, MoveEntityRot, RotateHead, - SetEntityData, SetEntityMotion, SetEquipment, TeleportEntity, VecDelta, + self, AddEntity, EntityPositionSync, MoveEntity, MoveEntityPos, MoveEntityPosRot, + MoveEntityRot, PositionPath, RotateHead, SetEntityData, SetEntityMotion, SetEquipment, + VecDelta, }, }; @@ -30,24 +33,27 @@ pub struct EntityState { /// SynchedEntityData entries that differ from the defaults. pub meta: Vec<(u8, i32, Value)>, /// EquipmentSlot ordinals (0 main hand, 1 off hand, 2 feet, 3 legs, - /// 4 chest, 5 head) and their stacks. + /// 4 chest, 5 head, 6 body, 7 saddle) and their stacks. pub equipment: Vec<(u8, Option)>, - /// Whether movement packets should include a velocity (items, projectiles). - pub send_velocity: bool, } -/// What a client was last told about one entity. +/// What a client was last told about one entity (ServerEntity's fields). struct Sent { - /// The position in 1/4096 blocks (VecDeltaCodec base). - base: [i64; 3], - position: [f64; 3], + /// VecDeltaCodec's base: the last position sent. + base: [f64; 3], + /// lastSentYRot / lastSentXRot / lastSentYHeadRot. rotation: (i8, i8), head: i8, + /// lastSentMovement. velocity: [f64; 3], meta: Vec<(u8, i32, Value)>, equipment: Vec<(u8, Option)>, - on_ground: bool, - ticks: u32, + was_on_ground: bool, + tick: u32, + teleport_delay: u32, + /// The type's update interval (0: never) and whether velocity is tracked. + interval: u32, + track_deltas: bool, } #[derive(Default)] @@ -55,19 +61,16 @@ pub struct Tracker { sent: std::collections::HashMap, } -fn quantize(p: [f64; 3]) -> [i64; 3] { - [ - (p[0] * 4096.0).round() as i64, - (p[1] * 4096.0).round() as i64, - (p[2] * 4096.0).round() as i64, - ] +/// VecDeltaCodec.encode. +fn encode(v: f64) -> i64 { + (v * 4096.0).round() as i64 } -fn dequantize(q: [i64; 3]) -> [f64; 3] { - [ - q[0] as f64 / 4096.0, - q[1] as f64 / 4096.0, - q[2] as f64 / 4096.0, - ] + +/// The horizontal range within which a client sees an entity of `kind` +/// (TrackedEntity.updatePlayer: the type's range, capped by the view distance). +pub fn visible_range(kind: &str, view_distance: i32) -> f64 { + let chunks = i32::from(tracking::settings(kind).0); + f64::from(chunks.min(view_distance) * 16) } impl Tracker { @@ -94,6 +97,7 @@ impl Tracker { pub fn spawn(&mut self, e: &EntityState, entity_type: i32) -> Vec { let rotation = (pack_degrees(e.pitch), pack_degrees(e.yaw)); let head = pack_degrees(e.head_yaw); + let (_, interval, track_deltas) = tracking::settings(&e.kind); let mut out = vec![play::Clientbound::AddEntity(AddEntity { id: e.id, uuid: e.uuid, @@ -120,114 +124,132 @@ impl Tracker { self.sent.insert( e.id, Sent { - base: quantize(e.position), - position: e.position, + base: e.position, rotation, head, velocity: e.velocity, meta: e.meta.clone(), equipment: e.equipment.clone(), - on_ground: e.on_ground, - ticks: 0, + was_on_ground: e.on_ground, + tick: 0, + teleport_delay: 0, + interval, + track_deltas, }, ); out } - /// Changes since the last update (ServerEntity.sendChanges). + /// Changes since the last update (ServerEntity.sendChanges): movement and + /// rotation every update interval (positions at least every 60 ticks, a + /// full position sync every 400 or when the entity lands or leaves the + /// ground), velocity for types that track it, changed data at once. pub fn update(&mut self, e: &EntityState) -> Vec { let Some(s) = self.sent.get_mut(&e.id) else { return Vec::new(); }; let mut out = Vec::new(); - s.ticks += 1; - let rotation = (pack_degrees(e.pitch), pack_degrees(e.yaw)); - let rotated = rotation != s.rotation; - let now = quantize(e.position); - let delta = [now[0] - s.base[0], now[1] - s.base[1], now[2] - s.base[2]]; - let moved = delta != [0; 3]; - let fits = delta.iter().all(|d| i16::try_from(*d).is_ok()); - if moved && !fits { - out.push(play::Clientbound::TeleportEntity(TeleportEntity { + let dirty = e.meta != s.meta; + let due = s.interval != 0 && s.tick.is_multiple_of(s.interval); + if due || dirty { + let rotation = (pack_degrees(e.pitch), pack_degrees(e.yaw)); + let turned = |a: i8, b: i8| (i32::from(a) - i32::from(b)).abs() >= 1; + let rotate = turned(rotation.1, s.rotation.1) || turned(rotation.0, s.rotation.0); + s.teleport_delay += 1; + let d: f64 = (0..3).map(|k| (e.position[k] - s.base[k]).powi(2)).sum(); + let send_position = d >= 7.629_394_5e-6 || s.tick.is_multiple_of(60); + let sync = EntityPositionSync { id: e.id, - position: e.position, - delta: e.velocity, + path: PositionPath::Linear(e.position), yaw: e.yaw, pitch: e.pitch, - relatives: 0, on_ground: e.on_ground, - })); - s.base = now; - } else if moved || rotated || e.on_ground != s.on_ground { - let d = VecDelta::Linear([delta[0] as i16, delta[1] as i16, delta[2] as i16]); - let rot = Some((rotation.1, rotation.0)); - let packet = if moved && rotated { - play::Clientbound::MoveEntityPosRot(MoveEntityPosRot(MoveEntity { - id: e.id, - delta: Some(d), - rotation: rot, - on_ground: e.on_ground, - })) - } else if moved { - play::Clientbound::MoveEntityPos(MoveEntityPos(MoveEntity { - id: e.id, - delta: Some(d), - rotation: None, - on_ground: e.on_ground, - })) - } else { - play::Clientbound::MoveEntityRot(MoveEntityRot(MoveEntity { + }; + // ServerEntity.createMovePacket. + let packet = if s.teleport_delay > 400 || s.was_on_ground != e.on_ground { + s.was_on_ground = e.on_ground; + s.teleport_delay = 0; + Some(play::Clientbound::EntityPositionSync(sync)) + } else if send_position { + let delta = [0, 1, 2].map(|k| encode(e.position[k]) - encode(s.base[k])); + if delta.iter().any(|v| i16::try_from(*v).is_err()) { + Some(play::Clientbound::EntityPositionSync(sync)) + } else { + let m = MoveEntity { + id: e.id, + delta: Some(VecDelta::Linear(delta.map(|v| v as i16))), + rotation: rotate.then_some((rotation.1, rotation.0)), + on_ground: e.on_ground, + }; + Some(if rotate { + play::Clientbound::MoveEntityPosRot(MoveEntityPosRot(m)) + } else { + play::Clientbound::MoveEntityPos(MoveEntityPos(m)) + }) + } + } else if rotate { + Some(play::Clientbound::MoveEntityRot(MoveEntityRot(MoveEntity { id: e.id, delta: None, - rotation: rot, + rotation: Some((rotation.1, rotation.0)), on_ground: e.on_ground, - })) + }))) + } else { + None }; - out.push(packet); - if moved { - s.base = now; + if s.track_deltas { + let diff: f64 = (0..3).map(|k| (e.velocity[k] - s.velocity[k]).powi(2)).sum(); + let still = e.velocity.iter().all(|v| *v == 0.0); + if diff > 1.0e-7 || diff > 0.0 && still { + s.velocity = e.velocity; + out.push(play::Clientbound::SetEntityMotion(SetEntityMotion { + id: e.id, + velocity: e.velocity, + })); + } } - } - if moved || rotated || e.on_ground != s.on_ground { - s.rotation = rotation; - s.on_ground = e.on_ground; - } - s.position = dequantize(s.base); - let head = pack_degrees(e.head_yaw); - if head != s.head { - out.push(play::Clientbound::RotateHead(RotateHead { - id: e.id, - head_yaw: head, - })); - s.head = head; - } - if e.send_velocity { - let dv: f64 = (0..3) - .map(|i| (e.velocity[i] - s.velocity[i]).powi(2)) - .sum(); - if dv > 1.0e-7 || (e.velocity == [0.0; 3] && s.velocity != [0.0; 3]) { - out.push(play::Clientbound::SetEntityMotion(SetEntityMotion { + if let Some(packet) = packet { + let (position, rotated) = match &packet { + play::Clientbound::EntityPositionSync(_) + | play::Clientbound::MoveEntityPosRot(_) => (true, true), + play::Clientbound::MoveEntityPos(_) => (true, false), + _ => (false, true), + }; + out.push(packet); + if position { + s.base = e.position; + } + if rotated { + s.rotation = rotation; + } + } + // ServerEntity.sendDirtyEntityData. + if dirty { + let changed: Vec<_> = e + .meta + .iter() + .filter(|m| !s.meta.contains(m)) + .cloned() + .collect(); + if !changed.is_empty() { + out.push(play::Clientbound::SetEntityData(SetEntityData { + id: e.id, + values: changed, + })); + } + s.meta = e.meta.clone(); + } + let head = pack_degrees(e.head_yaw); + if turned(head, s.head) { + out.push(play::Clientbound::RotateHead(RotateHead { id: e.id, - velocity: e.velocity, + head_yaw: head, })); - s.velocity = e.velocity; + s.head = head; } } - if e.meta != s.meta { - let changed: Vec<_> = e - .meta - .iter() - .filter(|m| !s.meta.contains(m)) - .cloned() - .collect(); - if !changed.is_empty() { - out.push(play::Clientbound::SetEntityData(SetEntityData { - id: e.id, - values: changed, - })); - } - s.meta = e.meta.clone(); - } + s.tick += 1; + // LivingEntity.detectEquipmentUpdates: changed slots every tick. if e.equipment != s.equipment { // Cleared slots are sent as empty stacks. let mut slots: Vec<(u8, Option)> = e @@ -271,20 +293,46 @@ mod tests { data: 0, meta: Vec::new(), equipment: Vec::new(), - send_velocity: false, } } #[test] - fn small_moves_are_relative_and_large_ones_teleport() { + fn moves_go_out_every_update_interval() { let mut t = Tracker::default(); let spawn = t.spawn(&state(0.0), 100); assert!(matches!(spawn[0], play::Clientbound::AddEntity(_))); - assert!(t.update(&state(0.0)).is_empty()); - let step = t.update(&state(0.5)); - assert!(matches!(step[0], play::Clientbound::MoveEntityPos(_))); + // Tick 0 is due and a multiple of 60: the position goes out unchanged. + assert!(matches!( + t.update(&state(0.0))[..], + [play::Clientbound::MoveEntityPos(_)] + )); + // A zombie updates every third tick. + assert!(t.update(&state(0.5)).is_empty()); + assert!(t.update(&state(0.5)).is_empty()); + assert!(matches!( + t.update(&state(0.5))[..], + [play::Clientbound::MoveEntityPos(_)] + )); + for _ in 0..2 { + t.update(&state(40.0)); + } let jump = t.update(&state(40.0)); - assert!(matches!(jump[0], play::Clientbound::TeleportEntity(_))); + assert!(matches!(jump[0], play::Clientbound::EntityPositionSync(_))); + } + + #[test] + fn landing_sends_a_position_sync() { + let mut t = Tracker::default(); + let mut e = state(0.0); + t.spawn(&e, 100); + t.update(&e); + e.on_ground = false; + t.update(&e); + t.update(&e); + assert!(matches!( + t.update(&e)[..], + [play::Clientbound::EntityPositionSync(_)] + )); } #[test] @@ -292,6 +340,7 @@ mod tests { let mut t = Tracker::default(); let mut e = state(0.0); t.spawn(&e, 100); + t.update(&e); e.meta.push((0, 0, Value::Byte(1))); e.equipment.push((0, Some(Stack::new(5, 1)))); let out = t.update(&e); diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 7201c6a05..e7639cc41 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -146,6 +146,11 @@ impl Hub { self.guests.iter_mut().find(|g| g.conn == conn) } + /// The network id of a name in a built-in or synchronized registry. + pub fn registry_id(&self, registry: &str, name: &str) -> Option { + self.sync.id(registry, name) + } + pub fn item_id(&mut self, item: &Arc) -> i32 { if let Some(id) = self.item_ids.get(item) { return *id; @@ -864,7 +869,6 @@ impl Hub { data: 0, meta, equipment, - send_velocity: false, } } @@ -950,20 +954,26 @@ impl Hub { if !self.guests[gi].placed { continue; } - let range = f64::from(self.guests[gi].view_distance * 16).min(128.0); + let view = self.guests[gi].view_distance; let me = self.guests[gi].entity_id; let origin = self.guests[gi].position; + // TrackedEntity.updatePlayer: within the type's range (capped by the + // view distance) horizontally, in a chunk the client has. + let visible = |g: &Guest, e: &EntityState| { + let range = super::entity::visible_range(&e.kind, view); + let (dx, dz) = (origin[0] - e.position[0], origin[2] - e.position[2]); + let chunk = ( + (e.position[0].floor() as i32) >> 4, + (e.position[2].floor() as i32) >> 4, + ); + dx * dx + dz * dz <= range * range && g.sent_chunks.contains(&chunk) + }; // Forget what disappeared or left range. let mut removed = Vec::new(); for id in self.guests[gi].tracker.ids() { match by_id.get(&id) { - None => removed.push(id), - Some(&ei) => { - let e = &all[ei]; - if !in_range(origin, e.position, range + 8.0) { - removed.push(id); - } - } + Some(&ei) if visible(&self.guests[gi], &all[ei]) => {} + _ => removed.push(id), } } if !removed.is_empty() { @@ -979,12 +989,12 @@ impl Hub { if self.guests[gi].tracker.is_tracking(e.id) { let packets = self.guests[gi].tracker.update(e); self.guests[gi].send_all(&packets); - } else if in_range(origin, e.position, range) { + } else if visible(&self.guests[gi], e) { let Some(kind) = self.entity_type(&e.kind) else { continue; }; - let packets = self.guests[gi].tracker.spawn(e, kind); // Players need their list entry first; guests got it at join. + let packets = self.guests[gi].tracker.spawn(e, kind); self.guests[gi].send_all(&packets); } } @@ -1207,11 +1217,6 @@ impl Hub { } } -fn in_range(a: [f64; 3], b: [f64; 3], range: f64) -> bool { - let (dx, dz) = (a[0] - b[0], a[2] - b[2]); - dx * dx + dz * dz <= range * range && (a[1] - b[1]).abs() <= 400.0 -} - /// The commands guests may type when the host allows them. const COMMANDS: &[&str] = &[ "advancement", diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index b6af18530..e66406345 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -10,6 +10,7 @@ pub mod containers; pub mod data; pub mod discovery; pub mod entity; +pub mod tracking; pub mod guest; pub mod hub; pub mod menu; diff --git a/crates/horizon-client/src/lan/tracking.rs b/crates/horizon-client/src/lan/tracking.rs new file mode 100644 index 000000000..d0853507f --- /dev/null +++ b/crates/horizon-client/src/lan/tracking.rs @@ -0,0 +1,176 @@ +//! Entity tracking settings per entity type (EntityType.Builder +//! clientTrackingRange in chunks, updateInterval in ticks with 0 for never, +//! trackDeltas). Generated by tools/generate_entity_tracking.py from the +//! decompiled EntityTypes.java; do not edit by hand. + +/// (entity type, tracking range in chunks, update interval, track deltas), sorted. +pub const TRACKING: &[(&str, u8, u32, bool)] = &[ + ("minecraft:acacia_boat", 10, 3, true), + ("minecraft:acacia_chest_boat", 10, 3, true), + ("minecraft:allay", 8, 2, true), + ("minecraft:area_effect_cloud", 10, 0, true), + ("minecraft:armadillo", 10, 3, true), + ("minecraft:armor_stand", 10, 3, true), + ("minecraft:arrow", 4, 20, true), + ("minecraft:axolotl", 10, 3, true), + ("minecraft:bamboo_chest_raft", 10, 3, true), + ("minecraft:bamboo_raft", 10, 3, true), + ("minecraft:bat", 5, 3, false), + ("minecraft:bee", 8, 3, true), + ("minecraft:birch_boat", 10, 3, true), + ("minecraft:birch_chest_boat", 10, 3, true), + ("minecraft:blaze", 8, 3, true), + ("minecraft:block_display", 10, 1, true), + ("minecraft:bogged", 8, 3, true), + ("minecraft:breeze", 10, 3, true), + ("minecraft:breeze_wind_charge", 4, 10, true), + ("minecraft:camel", 10, 3, true), + ("minecraft:camel_husk", 10, 3, true), + ("minecraft:cat", 8, 3, true), + ("minecraft:cave_spider", 8, 3, true), + ("minecraft:cherry_boat", 10, 3, true), + ("minecraft:cherry_chest_boat", 10, 3, true), + ("minecraft:chest_minecart", 8, 3, true), + ("minecraft:chicken", 10, 3, true), + ("minecraft:cod", 4, 3, true), + ("minecraft:command_block_minecart", 8, 3, true), + ("minecraft:copper_golem", 10, 3, true), + ("minecraft:cow", 10, 3, true), + ("minecraft:creaking", 8, 3, true), + ("minecraft:creeper", 8, 3, true), + ("minecraft:cushion", 10, 0, false), + ("minecraft:dark_oak_boat", 10, 3, true), + ("minecraft:dark_oak_chest_boat", 10, 3, true), + ("minecraft:dolphin", 5, 3, true), + ("minecraft:donkey", 10, 3, true), + ("minecraft:dragon_fireball", 4, 10, true), + ("minecraft:drowned", 8, 3, true), + ("minecraft:egg", 4, 10, true), + ("minecraft:elder_guardian", 10, 3, true), + ("minecraft:end_crystal", 16, 0, false), + ("minecraft:ender_dragon", 10, 3, true), + ("minecraft:ender_pearl", 4, 10, true), + ("minecraft:enderman", 8, 3, true), + ("minecraft:endermite", 8, 3, true), + ("minecraft:evoker", 8, 3, true), + ("minecraft:evoker_fangs", 6, 2, false), + ("minecraft:experience_bottle", 4, 10, true), + ("minecraft:experience_orb", 6, 20, true), + ("minecraft:eye_of_ender", 4, 4, true), + ("minecraft:falling_block", 10, 20, true), + ("minecraft:fireball", 4, 10, true), + ("minecraft:firework_rocket", 4, 10, true), + ("minecraft:fishing_bobber", 4, 5, true), + ("minecraft:fox", 8, 3, true), + ("minecraft:frog", 10, 3, true), + ("minecraft:furnace_minecart", 8, 3, true), + ("minecraft:ghast", 10, 3, true), + ("minecraft:giant", 10, 3, true), + ("minecraft:glow_item_frame", 10, 0, false), + ("minecraft:glow_squid", 10, 3, true), + ("minecraft:goat", 10, 3, true), + ("minecraft:guardian", 8, 3, true), + ("minecraft:happy_ghast", 10, 3, true), + ("minecraft:hoglin", 8, 3, true), + ("minecraft:hopper_minecart", 8, 3, true), + ("minecraft:horse", 10, 3, true), + ("minecraft:husk", 8, 3, true), + ("minecraft:illusioner", 8, 3, true), + ("minecraft:interaction", 10, 3, true), + ("minecraft:iron_golem", 10, 3, true), + ("minecraft:item", 6, 20, true), + ("minecraft:item_display", 10, 1, true), + ("minecraft:item_frame", 10, 0, false), + ("minecraft:jungle_boat", 10, 3, true), + ("minecraft:jungle_chest_boat", 10, 3, true), + ("minecraft:leash_knot", 10, 0, false), + ("minecraft:lightning_bolt", 16, 0, true), + ("minecraft:lingering_potion", 4, 10, true), + ("minecraft:llama", 10, 3, true), + ("minecraft:llama_spit", 4, 10, false), + ("minecraft:magma_cube", 8, 3, true), + ("minecraft:mangrove_boat", 10, 3, true), + ("minecraft:mangrove_chest_boat", 10, 3, true), + ("minecraft:mannequin", 32, 2, true), + ("minecraft:marker", 0, 3, true), + ("minecraft:minecart", 8, 3, true), + ("minecraft:mooshroom", 10, 3, true), + ("minecraft:mule", 8, 3, true), + ("minecraft:nautilus", 10, 3, true), + ("minecraft:oak_boat", 10, 3, true), + ("minecraft:oak_chest_boat", 10, 3, true), + ("minecraft:ocelot", 10, 3, true), + ("minecraft:ominous_item_spawner", 8, 3, true), + ("minecraft:painting", 10, 0, false), + ("minecraft:pale_oak_boat", 10, 3, true), + ("minecraft:pale_oak_chest_boat", 10, 3, true), + ("minecraft:panda", 10, 3, true), + ("minecraft:parched", 8, 3, true), + ("minecraft:parrot", 8, 3, true), + ("minecraft:phantom", 8, 3, true), + ("minecraft:pig", 10, 3, true), + ("minecraft:piglin", 8, 3, true), + ("minecraft:piglin_brute", 8, 3, true), + ("minecraft:pillager", 8, 3, true), + ("minecraft:player", 32, 2, false), + ("minecraft:polar_bear", 10, 3, true), + ("minecraft:poplar_boat", 10, 3, true), + ("minecraft:poplar_chest_boat", 10, 3, true), + ("minecraft:pufferfish", 4, 3, true), + ("minecraft:rabbit", 8, 3, true), + ("minecraft:ravager", 10, 3, true), + ("minecraft:salmon", 4, 3, true), + ("minecraft:sheep", 10, 3, true), + ("minecraft:shulker", 10, 3, true), + ("minecraft:shulker_bullet", 8, 3, true), + ("minecraft:silverfish", 8, 3, true), + ("minecraft:skeleton", 8, 3, true), + ("minecraft:skeleton_horse", 10, 3, true), + ("minecraft:slime", 10, 3, true), + ("minecraft:small_fireball", 4, 10, true), + ("minecraft:sniffer", 10, 3, true), + ("minecraft:snow_golem", 8, 3, true), + ("minecraft:snowball", 4, 10, true), + ("minecraft:spawner_minecart", 8, 3, true), + ("minecraft:spectral_arrow", 4, 20, true), + ("minecraft:spider", 8, 3, true), + ("minecraft:splash_potion", 4, 10, true), + ("minecraft:spruce_boat", 10, 3, true), + ("minecraft:spruce_chest_boat", 10, 3, true), + ("minecraft:squid", 8, 3, true), + ("minecraft:stray", 8, 3, true), + ("minecraft:strider", 10, 3, true), + ("minecraft:sulfur_cube", 10, 3, true), + ("minecraft:tadpole", 10, 3, true), + ("minecraft:text_display", 10, 1, true), + ("minecraft:tnt", 10, 10, true), + ("minecraft:tnt_minecart", 8, 3, true), + ("minecraft:trader_llama", 10, 3, true), + ("minecraft:trident", 4, 20, true), + ("minecraft:tropical_fish", 4, 3, true), + ("minecraft:turtle", 10, 3, true), + ("minecraft:vex", 8, 3, true), + ("minecraft:villager", 10, 3, true), + ("minecraft:vindicator", 8, 3, true), + ("minecraft:wandering_trader", 10, 3, true), + ("minecraft:warden", 16, 3, true), + ("minecraft:wind_charge", 4, 10, true), + ("minecraft:witch", 8, 3, true), + ("minecraft:wither", 10, 3, false), + ("minecraft:wither_skeleton", 8, 3, true), + ("minecraft:wither_skull", 4, 10, true), + ("minecraft:wolf", 10, 3, true), + ("minecraft:zoglin", 8, 3, true), + ("minecraft:zombie", 8, 3, true), + ("minecraft:zombie_horse", 10, 3, true), + ("minecraft:zombie_nautilus", 10, 3, true), + ("minecraft:zombie_villager", 8, 3, true), + ("minecraft:zombified_piglin", 8, 3, true), +]; + +/// The settings of one entity type; unknown types get the builder defaults. +pub fn settings(kind: &str) -> (u8, u32, bool) { + TRACKING + .binary_search_by(|row| row.0.cmp(kind)) + .map_or((5, 3, true), |i| (TRACKING[i].1, TRACKING[i].2, TRACKING[i].3)) +} diff --git a/crates/horizon-protocol/src/entity_data.rs b/crates/horizon-protocol/src/entity_data.rs index 08872ed43..d0e977568 100644 --- a/crates/horizon-protocol/src/entity_data.rs +++ b/crates/horizon-protocol/src/entity_data.rs @@ -26,6 +26,8 @@ pub enum Value { OptUuid(Option), /// Any VarInt-valued serializer (direction, block state, pose, variants ...). Id(i32), + /// Several VarInts (VillagerData). + Ids(Vec), } /// Serializer ids in EntityDataSerializers registration order. pub mod serializer { @@ -45,12 +47,34 @@ pub mod serializer { pub const OPTIONAL_LIVING_ENTITY_REFERENCE: i32 = 13; pub const BLOCK_STATE: i32 = 14; pub const OPTIONAL_BLOCK_STATE: i32 = 15; + pub const PARTICLE: i32 = 16; + pub const PARTICLES: i32 = 17; + pub const VILLAGER_DATA: i32 = 18; pub const OPTIONAL_UNSIGNED_INT: i32 = 19; pub const POSE: i32 = 20; - pub const VECTOR3: i32 = 40; - pub const QUATERNION: i32 = 41; - pub const HUMANOID_ARM: i32 = 43; - pub const DYE_COLOR: i32 = 44; + pub const CAT_VARIANT: i32 = 21; + pub const CAT_SOUND_VARIANT: i32 = 22; + pub const COW_VARIANT: i32 = 23; + pub const COW_SOUND_VARIANT: i32 = 24; + pub const WOLF_VARIANT: i32 = 25; + pub const WOLF_SOUND_VARIANT: i32 = 26; + pub const FROG_VARIANT: i32 = 27; + pub const PIG_VARIANT: i32 = 28; + pub const PIG_SOUND_VARIANT: i32 = 29; + pub const CHICKEN_VARIANT: i32 = 30; + pub const CHICKEN_SOUND_VARIANT: i32 = 31; + pub const ZOMBIE_NAUTILUS_VARIANT: i32 = 32; + pub const OPTIONAL_GLOBAL_POS: i32 = 33; + pub const PAINTING_VARIANT: i32 = 34; + pub const SNIFFER_STATE: i32 = 35; + pub const ARMADILLO_STATE: i32 = 36; + pub const COPPER_GOLEM_STATE: i32 = 37; + pub const WEATHERING_COPPER_STATE: i32 = 38; + pub const VECTOR3: i32 = 39; + pub const QUATERNION: i32 = 40; + pub const RESOLVABLE_PROFILE: i32 = 41; + pub const HUMANOID_ARM: i32 = 42; + pub const DYE_COLOR: i32 = 43; } fn read_value(kind: i32, r: &mut Reader) -> Result> { use serializer::*; @@ -75,15 +99,18 @@ fn read_value(kind: i32, r: &mut Reader) -> Result> { OPTIONAL_LIVING_ENTITY_REFERENCE => { Value::OptUuid(if r.bool()? { Some(r.uuid()?) } else { None }) } + // VillagerData: type, profession and level. + VILLAGER_DATA => Value::Ids(vec![r.varint()?, r.varint()?, r.varint()?]), // VarInt-encoded: direction, block states, optional ints, pose, the - // holder-registry variants (21..=33) and enum states (36..=39), arm, dye. + // holder-registry variants (cat to zombie nautilus, painting) and the + // enum states (sniffer to weathering copper), arm, dye. DIRECTION | BLOCK_STATE | OPTIONAL_BLOCK_STATE | OPTIONAL_UNSIGNED_INT | POSE - | 21..=33 - | 36..=39 + | CAT_VARIANT..=ZOMBIE_NAUTILUS_VARIANT + | PAINTING_VARIANT..=WEATHERING_COPPER_STATE | HUMANOID_ARM | DYE_COLOR => Value::Id(r.varint()?), _ => return Ok(None), @@ -93,6 +120,7 @@ fn write_value(kind: i32, v: &Value, w: &mut Writer) { match v { Value::Byte(b) => w.i8(*b), Value::Int(i) | Value::Id(i) => w.varint(*i), + Value::Ids(ids) => ids.iter().for_each(|i| w.varint(*i)), Value::Long(l) => w.varlong(*l), Value::Float(f) => w.f32(*f), Value::String(s) => w.string(s), diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPacketCodecOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPacketCodecOracle.java new file mode 100644 index 000000000..ae16279eb --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPacketCodecOracle.java @@ -0,0 +1,165 @@ +package dev.horizonlab.parity; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import java.io.BufferedReader; +import java.io.PrintWriter; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HexFormat; +import java.util.Map; +import java.util.TreeMap; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.ProtocolInfo; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.configuration.ConfigurationProtocols; +import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket; +import net.minecraft.network.protocol.game.GameProtocols; +import net.minecraft.network.protocol.login.LoginProtocols; +import net.minecraft.network.protocol.status.StatusProtocols; +import net.minecraft.world.level.chunk.LevelChunkSection; +import net.minecraft.world.level.chunk.PalettedContainerFactory; + +/** + * Checks a capture written by tools/net_capture.py against vanilla's own + * packet codecs: every clientbound packet a server sent (login, + * configuration and play) must decode with vanilla's StreamCodec, consume + * its whole payload, and encode back to the same bytes, so the bytes are + * exactly what vanilla would have written for that packet. Chunk data is + * decoded section by section and the stored block counts are checked + * against a recount. Prints one line per packet: + * conn dir state name ok|ERROR|REENCODE|SECTIONS detail + * and a summary per packet type at the end. + */ +public final class VanillaPacketCodecOracle { + public static void main(String[] args) throws Exception { + ParityData.init(); + Path capture = Path.of(args[0]); + boolean verbose = args.length > 2 && args[2].equals("--verbose"); + var play = GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(ParityData.access)); + var factory = PalettedContainerFactory.create(ParityData.access); + Field nonEmpty = LevelChunkSection.class.getDeclaredField("nonEmptyBlockCount"); + Field fluids = LevelChunkSection.class.getDeclaredField("fluidCount"); + nonEmpty.setAccessible(true); + fluids.setAccessible(true); + Map totals = new TreeMap<>(); + int failures = 0; + try (BufferedReader in = Files.newBufferedReader(capture); + PrintWriter out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1])))) { + String line; + while ((line = in.readLine()) != null) { + if (line.isBlank()) continue; + JsonObject e = JsonParser.parseString(line).getAsJsonObject(); + if (!e.has("name") || !e.get("dir").getAsString().equals("s2c")) continue; + String state = e.get("state").getAsString(); + String name = e.get("name").getAsString(); + String key = state + "/" + name; + int[] t = totals.computeIfAbsent(key, k -> new int[2]); + t[0]++; + if (!e.has("data")) { + out.println(e.get("conn") + " s2c " + key + " SKIPPED payload not captured"); + t[1]++; + failures++; + continue; + } + byte[] payload = HexFormat.of().parseHex(e.get("data").getAsString()); + ProtocolInfo protocol = switch (state) { + case "status" -> StatusProtocols.CLIENTBOUND; + case "login" -> LoginProtocols.CLIENTBOUND; + case "configuration" -> ConfigurationProtocols.CLIENTBOUND; + case "play" -> play; + default -> null; + }; + if (protocol == null) continue; + ByteBuf original = Unpooled.buffer(); + new FriendlyByteBuf(original).writeVarInt(e.get("id").getAsInt()); + original.writeBytes(payload); + byte[] framed = new byte[original.readableBytes()]; + original.getBytes(0, framed); + String verdict; + String detail = ""; + try { + @SuppressWarnings("unchecked") + var codec = (net.minecraft.network.codec.StreamCodec>) (Object) protocol.codec(); + Packet packet = codec.decode(original); + if (original.readableBytes() != 0) { + verdict = "ERROR"; + detail = original.readableBytes() + " bytes left after decoding " + packet; + } else { + ByteBuf again = Unpooled.buffer(); + codec.encode(again, packet); + byte[] encoded = new byte[again.readableBytes()]; + again.getBytes(0, encoded); + if (!java.util.Arrays.equals(encoded, framed)) { + verdict = "REENCODE"; + detail = firstDifference(framed, encoded) + " " + abbreviate(packet.toString()); + } else if (packet instanceof ClientboundLevelChunkWithLightPacket chunk) { + String problem = checkSections(chunk, factory, nonEmpty, fluids); + verdict = problem == null ? "ok" : "SECTIONS"; + detail = problem == null ? "" : problem; + } else { + verdict = "ok"; + if (verbose) detail = abbreviate(packet.toString()); + } + } + } catch (Exception ex) { + verdict = "ERROR"; + detail = ex.toString(); + } + if (!verdict.equals("ok")) { + t[1]++; + failures++; + } + if (!verdict.equals("ok") || verbose) { + out.println(e.get("conn") + " s2c " + key + " " + verdict + " " + detail); + } + } + out.println("# packet type, count, failures"); + for (var entry : totals.entrySet()) { + out.println("# " + entry.getKey() + " " + entry.getValue()[0] + " " + entry.getValue()[1]); + } + out.println("# failures " + failures); + } + System.exit(failures == 0 ? 0 : 1); + } + + static String checkSections(ClientboundLevelChunkWithLightPacket chunk, PalettedContainerFactory factory, + Field nonEmpty, Field fluids) throws Exception { + FriendlyByteBuf buf = chunk.chunkData().getReadBuffer(); + int index = 0; + while (buf.isReadable()) { + int start = buf.readerIndex(); + short storedBlocks = buf.getShort(start); + short storedFluids = buf.getShort(start + 2); + LevelChunkSection section = new LevelChunkSection(factory); + section.read(buf); + section.recalcBlockCounts(); + int blocks = (short) (int) nonEmpty.get(section); + int fluidCount = (short) (int) fluids.get(section); + if (blocks != storedBlocks || fluidCount != storedFluids) { + return "section " + index + " of " + chunk.x() + "," + chunk.z() + " stores " + storedBlocks + " blocks/" + + storedFluids + " fluids, recount " + blocks + "/" + fluidCount; + } + index++; + } + if (index != 24 && index != 16) return index + " sections in " + chunk.x() + "," + chunk.z(); + return null; + } + + static String firstDifference(byte[] a, byte[] b) { + int n = Math.min(a.length, b.length); + for (int i = 0; i < n; i++) { + if (a[i] != b[i]) return "differs at byte " + i + " of " + a.length + " (vanilla writes " + b.length + ")"; + } + return "lengths " + a.length + " vs vanilla " + b.length; + } + + static String abbreviate(String s) { + s = s.replace('\n', ' '); + return s.length() > 400 ? s.substring(0, 400) + "..." : s; + } +} diff --git a/tools/generate_entity_tracking.py b/tools/generate_entity_tracking.py new file mode 100644 index 000000000..434033b37 --- /dev/null +++ b/tools/generate_entity_tracking.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Generate crates/horizon-client/src/lan/tracking.rs: every entity type's +tracking settings (EntityType.Builder clientTrackingRange, updateInterval and +trackDeltas, which ChunkMap.TrackedEntity and ServerEntity use to decide who +sees an entity and how often its movement is sent), read from the decompiled +EntityTypes.java. + + generate_entity_tracking.py [--sources .local/minecraft/26.3/sources/client] +""" +import argparse +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +INT_MAX = 2147483647 + + +def parse(sources): + text = (sources / "net/minecraft/world/entity/EntityTypes.java").read_text() + out = [] + for m in re.finditer(r"public static final EntityType<[\w.]+> (\w+) = register\((.*?)\n \);", text, re.S): + name, body = m.group(1).lower(), m.group(2) + range_ = re.findall(r"\.clientTrackingRange\((\d+)\)", body) + interval = re.findall(r"\.updateInterval\((\w+(?:\.\w+)?)\)", body) + track = ".dontTrackDeltas()" not in body + r = int(range_[-1]) if range_ else 5 + if ".noUpdateInterval()" in body or (interval and interval[-1] == "Integer.MAX_VALUE"): + i = 0 + else: + i = int(interval[-1]) if interval else 3 + out.append((f"minecraft:{name}", r, i, track)) + return sorted(out) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--sources", type=Path, default=ROOT / ".local/minecraft/26.3/sources/client") + parser.add_argument("--out", type=Path, default=ROOT / "crates/horizon-client/src/lan/tracking.rs") + args = parser.parse_args() + rows = parse(args.sources) + if len(rows) < 100: + raise SystemExit(f"only {len(rows)} entity types found") + lines = [ + "//! Entity tracking settings per entity type (EntityType.Builder", + "//! clientTrackingRange in chunks, updateInterval in ticks with 0 for never,", + "//! trackDeltas). Generated by tools/generate_entity_tracking.py from the", + "//! decompiled EntityTypes.java; do not edit by hand.", + "", + "/// (entity type, tracking range in chunks, update interval, track deltas), sorted.", + "pub const TRACKING: &[(&str, u8, u32, bool)] = &[", + ] + lines += [f' ("{n}", {r}, {i}, {str(t).lower()}),' for n, r, i, t in rows] + lines += [ + "];", + "", + "/// The settings of one entity type; unknown types get the builder defaults.", + "pub fn settings(kind: &str) -> (u8, u32, bool) {", + " TRACKING", + " .binary_search_by(|row| row.0.cmp(kind))", + " .map_or((5, 3, true), |i| (TRACKING[i].1, TRACKING[i].2, TRACKING[i].3))", + "}", + "", + ] + args.out.write_text("\n".join(lines)) + print(f"wrote {len(rows)} entity types to {args.out}") + + +if __name__ == "__main__": + main() diff --git a/tools/net_capture.py b/tools/net_capture.py new file mode 100644 index 000000000..1f643954b --- /dev/null +++ b/tools/net_capture.py @@ -0,0 +1,284 @@ +#!/usr/bin/env python3 +"""A decoding TCP proxy for the Minecraft 26.3 protocol (offline mode, no +encryption): clients connect to LISTEN, it forwards to TARGET and records +every packet in both directions as JSON lines (time, direction, state, id, +name, size and the payload), following the connection state through the +handshake, login, configuration and play (and back to configuration). + + net_capture.py --listen 25570 --target localhost:25565 --out capture.jsonl + +The packet names come from crates/horizon-protocol/src/ids.rs, which is +generated from vanilla's packets report. `summary` prints what a capture +contains, `diff` compares the packet sequences of two captures (for example +Horizon hosting and a vanilla server serving the same world). +""" +import argparse +import json +import re +import socket +import sys +import threading +import time +import zlib +from collections import Counter +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +STATES = ["handshake", "status", "login", "configuration", "play"] + + +def load_names(path=ROOT / "crates/horizon-protocol/src/ids.rs"): + """{(state, direction): [name by id]} from the generated id tables.""" + text = path.read_text() + names = {} + for state in STATES: + block = re.search(r"pub mod %s \{(.*?)\n\}" % state, text, re.S) + if not block: + continue + for direction in ("clientbound", "serverbound"): + part = re.search(r"pub mod %s \{.*?NAMES: &\[&str\] = &\[(.*?)\];" % direction, + block.group(1), re.S) + if part: + names[(state, direction)] = re.findall(r'"([^"]+)"', part.group(1)) + return names + + +def read_varint(data, pos): + value = shift = 0 + while True: + if pos >= len(data): + raise IndexError("truncated varint") + b = data[pos] + pos += 1 + value |= (b & 0x7F) << shift + shift += 7 + if not b & 0x80: + if value & 0x80000000: + value -= 1 << 32 + return value, pos + if shift > 35: + raise ValueError("varint too long") + + +class Session: + """The state both directions of one connection share.""" + + def __init__(self, conn_id, out, names, lock, full): + self.id = conn_id + self.state = {"clientbound": "handshake", "serverbound": "handshake"} + self.threshold = -1 + self.out = out + self.names = names + self.lock = lock + self.full = full + self.start = time.time() + self.closed = threading.Event() + + def name(self, direction, packet_id): + table = self.names.get((self.state[direction], direction), []) + return table[packet_id] if 0 <= packet_id < len(table) else f"unknown_{packet_id}" + + def record(self, direction, packet_id, payload): + state = self.state[direction] + name = self.name(direction, packet_id) + entry = { + "conn": self.id, + "t": round(time.time() - self.start, 4), + "dir": "s2c" if direction == "clientbound" else "c2s", + "state": state, + "id": packet_id, + "name": name, + "size": len(payload), + } + if self.full or len(payload) <= 4096: + entry["data"] = payload.hex() + else: + entry["head"] = payload[:512].hex() + with self.lock: + self.out.write(json.dumps(entry) + "\n") + self.out.flush() + self.transition(direction, name, payload) + + def transition(self, direction, name, payload): + s = self.state + if direction == "serverbound": + if s["serverbound"] == "handshake" and name == "intention": + pos = read_varint(payload, 0)[1] + length, pos = read_varint(payload, pos) + intent = read_varint(payload, pos + length + 2)[0] + nxt = {1: "status", 2: "login", 3: "login"}.get(intent, "login") + s["serverbound"] = s["clientbound"] = nxt + elif s["serverbound"] == "login" and name == "login_acknowledged": + s["serverbound"] = s["clientbound"] = "configuration" + elif s["serverbound"] == "configuration" and name == "finish_configuration": + s["serverbound"] = s["clientbound"] = "play" + elif s["serverbound"] == "play" and name == "configuration_acknowledged": + s["serverbound"] = s["clientbound"] = "configuration" + elif s["clientbound"] == "login" and name == "login_compression": + self.pending_threshold = read_varint(payload, 0)[0] + + +class Pipe(threading.Thread): + def __init__(self, session, direction, src, dst): + super().__init__(daemon=True) + self.session, self.direction, self.src, self.dst = session, direction, src, dst + + def run(self): + buffer = b"" + s = self.session + try: + while True: + chunk = self.src.recv(1 << 16) + if not chunk: + break + buffer += chunk + frames = [] + while True: + try: + length, pos = read_varint(buffer, 0) + except IndexError: + break + if len(buffer) < pos + length: + break + frames.append(buffer[:pos + length]) + body, buffer = buffer[pos:pos + length], buffer[pos + length:] + threshold = s.threshold + if threshold >= 0: + size, p = read_varint(body, 0) + body = zlib.decompress(body[p:]) if size else body[p:] + packet_id, p = read_varint(body, 0) + s.record(self.direction, packet_id, body[p:]) + # The compression threshold applies after its packet, in + # both directions; the client answers only after reading it. + pending = getattr(s, "pending_threshold", None) + if pending is not None: + s.threshold = pending + s.pending_threshold = None + # State switches must be in effect before the peer can + # answer, so forward each frame after recording it. + self.dst.sendall(frames.pop()) + except (OSError, ValueError, zlib.error) as e: + with s.lock: + s.out.write(json.dumps({"conn": s.id, "event": "error", "dir": self.direction, + "error": str(e)}) + "\n") + s.out.flush() + finally: + for sock in (self.src, self.dst): + try: + sock.shutdown(socket.SHUT_RDWR) + except OSError: + pass + s.closed.set() + + +def serve(listen, target, out_path, full=False, ready=None, stop=None): + names = load_names() + host, port = target.rsplit(":", 1) + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + server.bind(("127.0.0.1", listen)) + server.listen() + server.settimeout(0.5) + lock = threading.Lock() + conn_id = 0 + with open(out_path, "a") as out: + if ready: + ready.set() + while not (stop and stop.is_set()): + try: + client, _ = server.accept() + except socket.timeout: + continue + conn_id += 1 + try: + upstream = socket.create_connection((host, int(port))) + except OSError as e: + client.close() + with lock: + out.write(json.dumps({"conn": conn_id, "event": "error", + "error": f"upstream: {e}"}) + "\n") + continue + for sock in (client, upstream): + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + session = Session(conn_id, out, names, lock, full) + Pipe(session, "serverbound", client, upstream).start() + Pipe(session, "clientbound", upstream, client).start() + server.close() + + +def start_background(listen, target, out_path, full=False): + """Run the proxy on a thread; returns the stop event.""" + ready, stop = threading.Event(), threading.Event() + threading.Thread(target=serve, args=(listen, target, out_path, full, ready, stop), + daemon=True).start() + ready.wait(5) + return stop + + +def load(path): + return [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()] + + +def play_sessions(entries): + """Connections that reached the play state.""" + return sorted({e["conn"] for e in entries if e.get("state") == "play"}) + + +def summary(entries, conn=None): + lines = [] + conns = [conn] if conn else sorted({e["conn"] for e in entries}) + for c in conns: + mine = [e for e in entries if e["conn"] == c and "name" in e] + lines.append(f"connection {c}: {len(mine)} packets") + counts = Counter((e["dir"], e["state"], e["name"]) for e in mine) + for (d, s, n), k in sorted(counts.items()): + size = sum(e["size"] for e in mine if (e["dir"], e["state"], e["name"]) == (d, s, n)) + lines.append(f" {d} {s:13} {n:40} x{k:<6} {size} bytes") + for e in entries: + if e["conn"] == c and e.get("event") == "error": + lines.append(f" error ({e.get('dir')}): {e['error']}") + return "\n".join(lines) + + +def sequence(entries, conn, direction="s2c", until="player_position"): + """Packet names in order, up to and including the first `until`.""" + out = [] + for e in entries: + if e["conn"] != conn or e.get("dir") != direction or "name" not in e: + continue + out.append(f"{e['state']}/{e['name']}") + if e["name"] == until and e["state"] == "play": + break + return out + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + p = sub.add_parser("proxy") + p.add_argument("--listen", type=int, required=True) + p.add_argument("--target", required=True) + p.add_argument("--out", type=Path, required=True) + p.add_argument("--full", action="store_true", help="keep every payload in full") + s = sub.add_parser("summary") + s.add_argument("capture", type=Path) + d = sub.add_parser("diff") + d.add_argument("a", type=Path) + d.add_argument("b", type=Path) + d.add_argument("--until", default="player_position") + args = parser.parse_args() + if args.command == "proxy": + serve(args.listen, args.target, args.out, args.full) + elif args.command == "summary": + print(summary(load(args.capture))) + else: + import difflib + a, b = load(args.a), load(args.b) + sa = sequence(a, play_sessions(a)[0], until=args.until) + sb = sequence(b, play_sessions(b)[0], until=args.until) + sys.stdout.writelines(difflib.unified_diff([x + "\n" for x in sa], [x + "\n" for x in sb], + str(args.a), str(args.b))) + + +if __name__ == "__main__": + main() diff --git a/tools/vanilla_client.py b/tools/vanilla_client.py new file mode 100644 index 000000000..2196f79bc --- /dev/null +++ b/tools/vanilla_client.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Launch the vanilla 26.3 client offline (no Microsoft account, no auth +servers: --offlineDeveloperMode) and optionally join a server straight away +(--quickPlayMultiplayer). Meant to run on a virtual screen: + + vscreen start python3 tools/vanilla_client.py --name Guest --join localhost:25565 + +Sound goes to OpenAL's null backend. The game directory gets an options.txt +that skips the first-run screens, keeps the game running unfocused and +renders few chunks, so a harness can drive it with vscreen keys. +""" +import argparse +import hashlib +import json +import os +import subprocess +import sys +import uuid +import zipfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +GAME = ROOT / ".local/minecraft/26.3" + +OPTIONS = { + "onboardAccessibility": "false", + "skipMultiplayerWarning": "true", + "joinedFirstServer": "true", + "tutorialStep": "none", + "pauseOnLostFocus": "false", + "renderDistance": "6", + "simulationDistance": "6", + "maxFps": "30", + "narrator": "0", + "soundCategory_master": "0.0", + "realmsNotifications": "false", + "hideServerAddress": "false", + "autoJump": "false", + "chatLinksPrompt": "false", + "onlyShowSecureChat": "false", + "rawMouseInput": "false", +} + + +def offline_uuid(name): + digest = bytearray(hashlib.md5(("OfflinePlayer:" + name).encode()).digest()) + digest[6] = (digest[6] & 0x0F) | 0x30 + digest[8] = (digest[8] & 0x3F) | 0x80 + return uuid.UUID(bytes=bytes(digest)) + + +def linux_library(path): + name = Path(path).name + if "natives-" in name: + return name.endswith("natives-linux.jar") + if "netty-transport-native" in name and ("osx" in name or "aarch_64" in name): + return False + return "java-objc-bridge" not in name + + +def classpath(): + prepared = json.loads((GAME / "prepared.json").read_text()) + jars = [ROOT / p for p in prepared["libraries"]["client"] if linux_library(p)] + return [GAME / "jars/client.jar", *jars] + + +def extract_natives(jars, target): + target.mkdir(parents=True, exist_ok=True) + for jar in jars: + if not jar.name.endswith("natives-linux.jar"): + continue + with zipfile.ZipFile(jar) as archive: + for name in archive.namelist(): + if name.endswith(".so") and "arm" not in name and "aarch" not in name: + out = target / Path(name).name + if not out.exists(): + out.write_bytes(archive.read(name)) + + +def write_options(game_dir, extra): + path = game_dir / "options.txt" + current = {} + if path.exists(): + for line in path.read_text().splitlines(): + if ":" in line: + k, v = line.split(":", 1) + current[k] = v + current.update(OPTIONS) + current.update(extra) + path.write_text("".join(f"{k}:{v}\n" for k, v in current.items())) + + +def environment(): + env = dict(os.environ) + libs = [p for p in (os.environ.get("NIX_LD_LIBRARY_PATH", ""), "/run/opengl-driver/lib", + "/run/current-system/sw/share/nix-ld/lib") if p] + env["LD_LIBRARY_PATH"] = ":".join(libs + [env.get("LD_LIBRARY_PATH", "")]).strip(":") + env["ALSOFT_DRIVERS"] = "null" + return env + + +def command(args): + jars = classpath() + natives = args.game_dir / "natives" + extract_natives(jars, natives) + assets = args.assets or (args.game_dir / "assets") + (assets / "indexes").mkdir(parents=True, exist_ok=True) + cmd = ["java", f"-Xmx{args.heap}", "-XX:StackShadowPages=32", + "--enable-native-access=ALL-UNNAMED", + "--add-exports", "java.base/jdk.internal.misc=ALL-UNNAMED", + f"-Djava.library.path={natives}", f"-Dorg.lwjgl.system.SharedLibraryExtractPath={natives}", + f"-Dio.netty.native.workdir={natives}", + "-cp", os.pathsep.join(map(str, jars)), "net.minecraft.client.main.Main", + "--username", args.name, "--uuid", offline_uuid(args.name).hex, + "--accessToken", "0", "--offlineDeveloperMode", + "--version", "26.3", "--gameDir", str(args.game_dir), + "--assetsDir", str(assets), "--assetIndex", "34", + "--width", str(args.width), "--height", str(args.height)] + if args.join: + cmd += ["--quickPlayMultiplayer", args.join] + if args.backend: + cmd += ["--graphicsBackend", args.backend] + return cmd + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--name", default="Guest") + parser.add_argument("--join", help="HOST:PORT to join on start") + parser.add_argument("--game-dir", type=Path, default=ROOT / ".local/vanilla-client") + parser.add_argument("--assets", type=Path) + parser.add_argument("--heap", default="3G") + parser.add_argument("--width", type=int, default=1280) + parser.add_argument("--height", type=int, default=800) + parser.add_argument("--backend", help="graphics backend (opengl or vulkan)") + parser.add_argument("--option", action="append", default=[], help="KEY:VALUE for options.txt") + parser.add_argument("--print", action="store_true", help="print the command and exit") + args = parser.parse_args() + args.game_dir = args.game_dir.resolve() + args.game_dir.mkdir(parents=True, exist_ok=True) + write_options(args.game_dir, dict(o.split(":", 1) for o in args.option)) + cmd = command(args) + if args.print: + print(" ".join(cmd)) + return + sys.exit(subprocess.run(cmd, cwd=args.game_dir, env=environment()).returncode) + + +if __name__ == "__main__": + main() From 13e434d49d48af726a8f4f9d09f98664953956e1 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:49:11 +0200 Subject: [PATCH 11/28] Compare the music manager tick by tick with the real vanilla MusicManager The oracle drives MusicManager over the real SoundEngine with the situation as input; the script covers delays, replacements, frequencies, fades, loading screens, pauses, silent starts, toasts and unplayable events. Co-Authored-By: Claude Opus 5.5 --- .../examples/audio_common/mod.rs | 176 +++++++++++++++++ .../horizon-client/examples/music_fixture.rs | 108 +++++++++++ .../examples/sound_engine_fixture.rs | 177 +----------------- crates/horizon-client/src/game/music.rs | 16 +- .../horizonlab/parity/VanillaMusicOracle.java | 145 ++++++++++++++ tools/test_music_parity.py | 167 +++++++++++++++++ 6 files changed, 611 insertions(+), 178 deletions(-) create mode 100644 crates/horizon-client/examples/audio_common/mod.rs create mode 100644 crates/horizon-client/examples/music_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMusicOracle.java create mode 100644 tools/test_music_parity.py diff --git a/crates/horizon-client/examples/audio_common/mod.rs b/crates/horizon-client/examples/audio_common/mod.rs new file mode 100644 index 000000000..3b177eba5 --- /dev/null +++ b/crates/horizon-client/examples/audio_common/mod.rs @@ -0,0 +1,176 @@ +//! Shared by the audio fixtures: a backend recording what an OpenAL source +//! would hold, and the per-step dump the Java oracles print. +#![allow(dead_code)] +use horizon_client::sound_engine::{Backend, ChannelId, InstanceId, PlayResult, SoundEngine}; +use horizon_client::sound_events::Sound; +use std::collections::HashMap; +use std::io::Write; + +const INITIAL: u32 = 0x1011; +const PLAYING: u32 = 0x1012; +const PAUSED: u32 = 0x1013; +const STOPPED: u32 = 0x1014; + +/// An OpenAL source's state as `alGetSource*` reports it. +#[derive(Clone)] +pub struct Source { + pub state: u32, + pub gain: f32, + pub pitch: f32, + pub position: [f32; 3], + pub relative: bool, + pub looping: bool, + pub model: u32, + pub max: f32, + pub rolloff: f32, + pub reference: f32, +} +impl Default for Source { + fn default() -> Self { + Self { + state: INITIAL, + gain: 1.0, + pitch: 1.0, + position: [0.0; 3], + relative: false, + looping: false, + model: 0xD002, + max: f32::MAX, + rolloff: 1.0, + reference: 1.0, + } + } +} +/// Buffers and streams are ready at once (silence in the oracle); stopping an +/// initial source leaves it initial, as in OpenAL Soft. +#[derive(Default)] +pub struct Fake { + pub sources: HashMap, + next: ChannelId, +} +impl Backend for Fake { + fn create(&mut self, _streaming: bool) -> Option { + self.next += 1; + self.sources.insert(self.next, Source::default()); + Some(self.next) + } + fn destroy(&mut self, channel: ChannelId) { + self.sources.remove(&channel); + } + fn set_pitch(&mut self, c: ChannelId, pitch: f32) { + self.sources.get_mut(&c).expect("source").pitch = pitch; + } + fn set_volume(&mut self, c: ChannelId, volume: f32) { + self.sources.get_mut(&c).expect("source").gain = volume; + } + fn set_attenuation(&mut self, c: ChannelId, linear: Option) { + let s = self.sources.get_mut(&c).expect("source"); + match linear { + Some(max) => { + s.model = 0xD003; + s.max = max; + s.rolloff = 1.0; + s.reference = 0.0; + } + None => s.model = 0, + } + } + fn set_looping(&mut self, c: ChannelId, looping: bool) { + self.sources.get_mut(&c).expect("source").looping = looping; + } + fn set_position(&mut self, c: ChannelId, p: [f64; 3]) { + self.sources.get_mut(&c).expect("source").position = + [p[0] as f32, p[1] as f32, p[2] as f32]; + } + fn set_relative(&mut self, c: ChannelId, relative: bool) { + self.sources.get_mut(&c).expect("source").relative = relative; + } + fn start(&mut self, c: ChannelId, _sound: &Sound, _looping: bool) { + self.sources.get_mut(&c).expect("source").state = PLAYING; + } + fn stop(&mut self, c: ChannelId) { + if let Some(s) = self.sources.get_mut(&c) + && s.state != INITIAL + { + s.state = STOPPED; + } + } + fn pause(&mut self, c: ChannelId) { + let s = self.sources.get_mut(&c).expect("source"); + if s.state == PLAYING { + s.state = PAUSED; + } + } + fn unpause(&mut self, c: ChannelId) { + let s = self.sources.get_mut(&c).expect("source"); + if s.state == PAUSED { + s.state = PLAYING; + } + } + fn stopped(&mut self, c: ChannelId) -> bool { + self.sources.get(&c).is_none_or(|s| s.state == STOPPED) + } +} +pub fn bits(v: f32) -> String { + format!("{:08x}", v.to_bits()) +} +pub fn f(hex: &str) -> f32 { + f32::from_bits(u32::from_str_radix(hex, 16).expect("float")) +} +pub fn d(hex: &str) -> f64 { + f64::from_bits(u64::from_str_radix(hex, 16).expect("double")) +} +/// The shared per-step dump (instances, notifications, pool counts). +pub fn describe(engine: &SoundEngine, backend: &Fake, name: &str, id: InstanceId) -> String { + let mut s = format!(" {name} active={}", engine.is_active(id)); + match engine.channel(id).and_then(|c| backend.sources.get(&c)) { + None => s.push_str(" channel=-"), + Some(src) => s.push_str(&format!( + " state={:x} gain={} pitch={} pos={},{},{} rel={} loop={} model={:x} max={} rolloff={} ref={}", + src.state, + bits(src.gain), + bits(src.pitch), + bits(src.position[0]), + bits(src.position[1]), + bits(src.position[2]), + u8::from(src.relative), + u8::from(src.looping), + src.model, + bits(src.max), + bits(src.rolloff), + bits(src.reference) + )), + } + s +} +pub fn flush(engine: &mut SoundEngine, out: &mut impl Write) { + for n in std::mem::take(&mut engine.notifications) { + writeln!( + out, + "notify {} {} {} {} {:016x} {:016x} {:016x}", + n.identifier, + n.subtitle.as_deref().unwrap_or("-"), + bits(n.range), + n.looping, + n.position[0].to_bits(), + n.position[1].to_bits(), + n.position[2].to_bits() + ) + .expect("write"); + } + let [used, streaming] = engine.used_channels(); + writeln!( + out, + " Sounds: {used}/{} + {streaming}/{}", + engine.limits[0], engine.limits[1] + ) + .expect("write"); +} + +pub fn result_name(r: PlayResult) -> &'static str { + match r { + PlayResult::Started => "STARTED", + PlayResult::StartedSilently => "STARTED_SILENTLY", + PlayResult::NotStarted => "NOT_STARTED", + } +} diff --git a/crates/horizon-client/examples/music_fixture.rs b/crates/horizon-client/examples/music_fixture.rs new file mode 100644 index 000000000..29ccb99b2 --- /dev/null +++ b/crates/horizon-client/examples/music_fixture.rs @@ -0,0 +1,108 @@ +//! Replays `tools/test_music_parity.py` scripts through Horizon's +//! `MusicManager` over its `SoundEngine`: `music_fixture ROOT INPUT OUTPUT`. +#[path = "audio_common/mod.rs"] +mod common; +use common::{Fake, describe, f, flush}; +use horizon_client::music::{Music, MusicFrequency, MusicManager}; +use horizon_client::sound_engine::{Bound, MUSIC, SoundEngine, TickContext}; +use horizon_client::sound_events::SoundRegistry; +use std::io::Write; + +fn music(spec: &str) -> Option { + if spec == "-" { + return None; + } + let p: Vec<&str> = spec.split(',').collect(); + Some(Music::new( + &horizon_client::sound_events::normalize(p[0]), + p[1].parse().expect("min"), + p[2].parse().expect("max"), + p[3] == "1", + )) +} + +fn main() { + let args: Vec = std::env::args().collect(); + let mut engine = SoundEngine::new(SoundRegistry::load(std::path::Path::new(&args[1]))); + engine.listening = true; + let mut backend = Fake::default(); + let mut manager = MusicManager::new(0); + let (mut situation, mut volume) = (None::, 1.0f32); + let input = std::fs::read_to_string(&args[2]).expect("input"); + let mut out = std::io::BufWriter::new(std::fs::File::create(&args[3]).expect("output")); + for line in input.lines() { + writeln!(out, "{line}").expect("write"); + let a: Vec<&str> = line.split(' ').collect(); + match a[0] { + "start" => { + if let Some(id) = manager.current_instance() { + engine.release(id); + } + manager = MusicManager::new(a[1].parse().expect("seed")); + manager.frequency = MusicFrequency::parse(a[2]); + engine.stop_all(&mut backend); + } + "situation" => { + situation = music(a[1]); + volume = f(a[2]); + } + "tick" => { + let mut sounds = Bound { + engine: &mut engine, + backend: &mut backend, + }; + manager.tick(situation.as_ref(), volume, a[1] == "1", &mut sounds); + engine.tick(a[2] == "1", &TickContext::default(), &mut backend); + } + "finish" => { + if let Some(c) = manager.current_instance().and_then(|id| engine.channel(id)) { + horizon_client::sound_engine::Backend::stop(&mut backend, c); + } + } + "stop" => manager.stop_playing( + situation.as_ref(), + &mut Bound { + engine: &mut engine, + backend: &mut backend, + }, + ), + "stopmusic" => { + let m = music(a[1]).expect("music"); + manager.stop_playing_music( + &m, + situation.as_ref(), + &mut Bound { + engine: &mut engine, + backend: &mut backend, + }, + ); + } + "freq" => manager.set_frequency(MusicFrequency::parse(a[1]), situation.as_ref()), + "toast" => manager.show_now_playing_toast_if_needed(), + "volume" => { + let source: usize = a[1].parse().expect("source"); + engine.source_volumes[source] = f(a[2]); + engine.refresh_category_volume(source, &mut backend); + } + "stopall" => engine.stop_all(&mut backend), + _ => panic!("{line}"), + } + writeln!( + out, + " current={} delay={} gain={:08x} toastShown={} musicGain={:08x}", + manager.current(&engine).unwrap_or("-"), + manager.next_song_delay(), + manager.current_gain().to_bits(), + manager.toast_shown(), + engine.category_gain(MUSIC).to_bits() + ) + .expect("write"); + for show in std::mem::take(&mut manager.toast_requests) { + writeln!(out, " toast {}", if show { "show" } else { "hide" }).expect("write"); + } + if let Some(id) = manager.current_instance() { + writeln!(out, "{}", describe(&engine, &backend, "music", id)).expect("write"); + } + flush(&mut engine, &mut out); + } +} diff --git a/crates/horizon-client/examples/sound_engine_fixture.rs b/crates/horizon-client/examples/sound_engine_fixture.rs index a9dfbbb02..5bc8f1a61 100644 --- a/crates/horizon-client/examples/sound_engine_fixture.rs +++ b/crates/horizon-client/examples/sound_engine_fixture.rs @@ -1,175 +1,17 @@ //! Replays `tools/test_sound_engine_parity.py` scripts through Horizon's //! `SoundEngine` with a backend recording what an OpenAL source would hold: //! `sound_engine_fixture ROOT INPUT OUTPUT`. +#[path = "audio_common/mod.rs"] +mod common; +use common::{Fake, d, describe, f, flush, result_name}; use horizon_client::sound_engine::{ - Attenuation, Backend, ChannelId, InstanceId, SoundEngine, SoundInstance, TickContext, + Attenuation, Backend, InstanceId, SoundEngine, SoundInstance, TickContext, }; -use horizon_client::sound_events::{Sound, SoundRegistry}; +use horizon_client::sound_events::SoundRegistry; use horizon_core::random::LegacyRandom; -use std::collections::{BTreeMap, HashMap}; +use std::collections::BTreeMap; use std::io::Write; -const INITIAL: u32 = 0x1011; -const PLAYING: u32 = 0x1012; -const PAUSED: u32 = 0x1013; -const STOPPED: u32 = 0x1014; - -/// An OpenAL source's state as `alGetSource*` reports it. -#[derive(Clone)] -pub struct Source { - pub state: u32, - pub gain: f32, - pub pitch: f32, - pub position: [f32; 3], - pub relative: bool, - pub looping: bool, - pub model: u32, - pub max: f32, - pub rolloff: f32, - pub reference: f32, -} -impl Default for Source { - fn default() -> Self { - Self { - state: INITIAL, - gain: 1.0, - pitch: 1.0, - position: [0.0; 3], - relative: false, - looping: false, - model: 0xD002, - max: f32::MAX, - rolloff: 1.0, - reference: 1.0, - } - } -} -/// Buffers and streams are ready at once (silence in the oracle); stopping an -/// initial source leaves it initial, as in OpenAL Soft. -#[derive(Default)] -pub struct Fake { - pub sources: HashMap, - next: ChannelId, -} -impl Backend for Fake { - fn create(&mut self, _streaming: bool) -> Option { - self.next += 1; - self.sources.insert(self.next, Source::default()); - Some(self.next) - } - fn destroy(&mut self, channel: ChannelId) { - self.sources.remove(&channel); - } - fn set_pitch(&mut self, c: ChannelId, pitch: f32) { - self.sources.get_mut(&c).expect("source").pitch = pitch; - } - fn set_volume(&mut self, c: ChannelId, volume: f32) { - self.sources.get_mut(&c).expect("source").gain = volume; - } - fn set_attenuation(&mut self, c: ChannelId, linear: Option) { - let s = self.sources.get_mut(&c).expect("source"); - match linear { - Some(max) => { - s.model = 0xD003; - s.max = max; - s.rolloff = 1.0; - s.reference = 0.0; - } - None => s.model = 0, - } - } - fn set_looping(&mut self, c: ChannelId, looping: bool) { - self.sources.get_mut(&c).expect("source").looping = looping; - } - fn set_position(&mut self, c: ChannelId, p: [f64; 3]) { - self.sources.get_mut(&c).expect("source").position = - [p[0] as f32, p[1] as f32, p[2] as f32]; - } - fn set_relative(&mut self, c: ChannelId, relative: bool) { - self.sources.get_mut(&c).expect("source").relative = relative; - } - fn start(&mut self, c: ChannelId, _sound: &Sound, _looping: bool) { - self.sources.get_mut(&c).expect("source").state = PLAYING; - } - fn stop(&mut self, c: ChannelId) { - if let Some(s) = self.sources.get_mut(&c) - && s.state != INITIAL - { - s.state = STOPPED; - } - } - fn pause(&mut self, c: ChannelId) { - let s = self.sources.get_mut(&c).expect("source"); - if s.state == PLAYING { - s.state = PAUSED; - } - } - fn unpause(&mut self, c: ChannelId) { - let s = self.sources.get_mut(&c).expect("source"); - if s.state == PAUSED { - s.state = PLAYING; - } - } - fn stopped(&mut self, c: ChannelId) -> bool { - self.sources.get(&c).is_none_or(|s| s.state == STOPPED) - } -} -fn bits(v: f32) -> String { - format!("{:08x}", v.to_bits()) -} -fn f(hex: &str) -> f32 { - f32::from_bits(u32::from_str_radix(hex, 16).expect("float")) -} -fn d(hex: &str) -> f64 { - f64::from_bits(u64::from_str_radix(hex, 16).expect("double")) -} -/// The shared per-step dump (instances, notifications, pool counts). -pub fn describe(engine: &SoundEngine, backend: &Fake, name: &str, id: InstanceId) -> String { - let mut s = format!(" {name} active={}", engine.is_active(id)); - match engine.channel(id).and_then(|c| backend.sources.get(&c)) { - None => s.push_str(" channel=-"), - Some(src) => s.push_str(&format!( - " state={:x} gain={} pitch={} pos={},{},{} rel={} loop={} model={:x} max={} rolloff={} ref={}", - src.state, - bits(src.gain), - bits(src.pitch), - bits(src.position[0]), - bits(src.position[1]), - bits(src.position[2]), - u8::from(src.relative), - u8::from(src.looping), - src.model, - bits(src.max), - bits(src.rolloff), - bits(src.reference) - )), - } - s -} -pub fn flush(engine: &mut SoundEngine, out: &mut impl Write) { - for n in std::mem::take(&mut engine.notifications) { - writeln!( - out, - "notify {} {} {} {} {:016x} {:016x} {:016x}", - n.identifier, - n.subtitle.as_deref().unwrap_or("-"), - bits(n.range), - n.looping, - n.position[0].to_bits(), - n.position[1].to_bits(), - n.position[2].to_bits() - ) - .expect("write"); - } - let [used, streaming] = engine.used_channels(); - writeln!( - out, - " Sounds: {used}/{} + {streaming}/{}", - engine.limits[0], engine.limits[1] - ) - .expect("write"); -} - fn main() { let args: Vec = std::env::args().collect(); let mut engine = SoundEngine::new(SoundRegistry::load(std::path::Path::new(&args[1]))); @@ -264,10 +106,3 @@ fn main() { flush(&mut engine, &mut out); } } -fn result_name(r: horizon_client::sound_engine::PlayResult) -> &'static str { - match r { - horizon_client::sound_engine::PlayResult::Started => "STARTED", - horizon_client::sound_engine::PlayResult::StartedSilently => "STARTED_SILENTLY", - horizon_client::sound_engine::PlayResult::NotStarted => "NOT_STARTED", - } -} diff --git a/crates/horizon-client/src/game/music.rs b/crates/horizon-client/src/game/music.rs index a7e054fdb..699996e11 100644 --- a/crates/horizon-client/src/game/music.rs +++ b/crates/horizon-client/src/game/music.rs @@ -1,11 +1,7 @@ //! `Minecraft.getSituationalMusic` and `getMusicVolume` for the music manager, //! the local player's ambient sound handlers and the sound engine tick. use super::Game; -use horizon_client::{ - blocks::Fluid, - music::Music, - sound_engine::TickContext, -}; +use horizon_client::{blocks::Fluid, music::Music, sound_engine::TickContext}; impl Game<'_> { /// `Minecraft.tick` -> `MusicManager.tick`, once per client tick. @@ -59,12 +55,18 @@ impl Game<'_> { } /// `BiomeManager.getNoiseBiomeAtPosition`: the quart cell holding a position. fn biome_at(&self, p: [f64; 3]) -> &str { - let (x, y, z) = (p[0].floor() as i32, p[1].floor() as i32, p[2].floor() as i32); + let (x, y, z) = ( + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32, + ); self.world .chunks .get(&(x >> 4, z >> 4)) .map_or("minecraft:plains", |c| { - self.res.biomes.list[c.biome(x, y, z) as usize].name.as_str() + self.res.biomes.list[c.biome(x, y, z) as usize] + .name + .as_str() }) } /// `isEyeInFluid(WATER)`: the eye inside the water of its block column. diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMusicOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMusicOracle.java new file mode 100644 index 000000000..19af845e5 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMusicOracle.java @@ -0,0 +1,145 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.components.toasts.ToastManager; +import net.minecraft.client.gui.screens.LevelLoadingScreen; +import net.minecraft.client.resources.sounds.SoundInstance; +import net.minecraft.client.sounds.MusicManager; +import net.minecraft.client.sounds.SoundEngine; +import net.minecraft.client.sounds.SoundManager; +import net.minecraft.core.Holder; +import net.minecraft.resources.Identifier; +import net.minecraft.sounds.Music; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.RandomSource; + +/** + * Drives the real MusicManager over the real SoundEngine (VanillaSoundRig). + * The situation, Minecraft.getSituationalMusic and getMusicVolume, is the + * script's input; the loading screen is a LevelLoadingScreen in the Gui; the + * toast manager records showNowPlayingToast/hideNowPlayingToast. Each client + * tick is musicManager.tick() then soundManager.tick(pause), as Minecraft.tick + * runs them. Prints the manager's state and the music channel every step. + */ +public final class VanillaMusicOracle { + public static final class Mc extends Minecraft { + Music music; + float volume = 1.0F; + + Mc() { + super(null); + } + + @Override + public Music getSituationalMusic() { + return music; + } + + @Override + public float getMusicVolume() { + return volume; + } + } + + public static final class Toasts extends ToastManager { + final List calls = new ArrayList<>(); + + Toasts() { + super(null, null); + } + + @Override + public void showNowPlayingToast() { + calls.add("show"); + } + + @Override + public void hideNowPlayingToast() { + calls.add("hide"); + } + } + + static Music music(String spec) { + if (spec.equals("-")) return null; + String[] p = spec.split(","); + return new Music(Holder.direct(SoundEvent.createVariableRangeEvent(Identifier.parse(p[0]))), Integer.parseInt(p[1]), + Integer.parseInt(p[2]), p[3].equals("1")); + } + + static float f(String hex) { + return Float.intBitsToFloat(Integer.parseUnsignedInt(hex, 16)); + } + + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + var rig = new VanillaSoundRig(Path.of(args[0])); + Mc mc = VanillaSoundRig.make(Mc.class); + Gui gui = VanillaSoundRig.make(Gui.class); + Toasts toasts = VanillaSoundRig.make(Toasts.class); + VanillaSoundRig.set(toasts, Toasts.class, "calls", new ArrayList()); + VanillaSoundRig.set(gui, Gui.class, "toastManager", toasts); + VanillaSoundRig.set(mc, Minecraft.class, "gui", gui); + VanillaSoundRig.set(mc, Minecraft.class, "soundManager", rig.manager); + var loading = VanillaSoundRig.make(LevelLoadingScreen.class); + MusicManager manager = null; + var gains = VanillaSoundRig.field(SoundEngine.class, "gainBySource"); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2])))) { + for (String line : Files.readAllLines(Path.of(args[1]))) { + out.println(line); + String[] a = line.split(" "); + switch (a[0]) { + case "start" -> { + // A fresh manager: MusicManager(minecraft) with a seeded random. + manager = VanillaSoundRig.make(MusicManager.class); + VanillaSoundRig.set(manager, MusicManager.class, "minecraft", mc); + VanillaSoundRig.set(manager, MusicManager.class, "random", RandomSource.create(Long.parseLong(a[1]))); + VanillaSoundRig.set(manager, MusicManager.class, "gameMusicFrequency", MusicManager.MusicFrequency.valueOf(a[2])); + VanillaSoundRig.set(manager, MusicManager.class, "currentGain", 1.0F); + VanillaSoundRig.set(manager, MusicManager.class, "nextSongDelay", 100); + rig.manager.stop(); + } + case "situation" -> { + mc.music = music(a[1]); + mc.volume = f(a[2]); + } + case "tick" -> { + VanillaSoundRig.set(gui, Gui.class, "screen", a[1].equals("1") ? loading : null); + manager.tick(); + rig.manager.tick(a[2].equals("1")); + } + case "finish" -> { + var current = (SoundInstance) VanillaSoundRig.get(manager, MusicManager.class, "currentMusic"); + if (current != null) rig.finish(current); + } + case "stop" -> manager.stopPlaying(); + case "stopmusic" -> manager.stopPlaying(music(a[1])); + case "freq" -> manager.setMinutesBetweenSongs(MusicManager.MusicFrequency.valueOf(a[1])); + case "toast" -> manager.showNowPlayingToastIfNeeded(); + case "volume" -> { + rig.volume(SoundSource.values()[Integer.parseInt(a[1])], f(a[2])); + rig.manager.refreshCategoryVolume(SoundSource.values()[Integer.parseInt(a[1])]); + } + case "stopall" -> rig.manager.stop(); + default -> throw new IllegalArgumentException(line); + } + var current = (SoundInstance) VanillaSoundRig.get(manager, MusicManager.class, "currentMusic"); + out.printf(" current=%s delay=%d gain=%08x toastShown=%s musicGain=%08x%n", current == null ? "-" : current.getIdentifier(), + (int) VanillaSoundRig.get(manager, MusicManager.class, "nextSongDelay"), + Float.floatToRawIntBits((float) VanillaSoundRig.get(manager, MusicManager.class, "currentGain")), + VanillaSoundRig.get(manager, MusicManager.class, "toastShown"), + Float.floatToRawIntBits(((it.unimi.dsi.fastutil.objects.Object2FloatMap) gains.get(rig.engine)).getFloat(SoundSource.MUSIC))); + for (String call : toasts.calls) out.println(" toast " + call); + toasts.calls.clear(); + if (current != null) out.println(rig.describe("music", current)); + rig.flush(out); + } + } + System.exit(0); + } +} diff --git a/tools/test_music_parity.py b/tools/test_music_parity.py new file mode 100644 index 000000000..7d41be5f1 --- /dev/null +++ b/tools/test_music_parity.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""Compare the music manager with the vanilla 26.3 client. + +The oracle runs the real `MusicManager` over the real `SoundEngine` (OpenAL +Soft "No Output" device, see VanillaSoundRig). The situation +(`getSituationalMusic`, `getMusicVolume`), the loading screen, pauses, the +end of a track, `stopPlaying`, `setMinutesBetweenSongs`, the music category +volume and `showNowPlayingToastIfNeeded` are script inputs; every step prints +the current track, `nextSongDelay`, `currentGain`, `toastShown`, the toast +calls, the MUSIC category gain and the music channel's AL source. Horizon's +`MusicManager` and `SoundEngine` replay the scripts. Tracks use events whose +variants share one volume, since `forMusic` resolves with an unseeded random. +""" +import random + +try: + from . import audio_harness as h +except ImportError: + import audio_harness as h + +TRACKS = ['minecraft:music.credits', 'minecraft:music.dragon', 'minecraft:music.end', 'minecraft:music.under_water', + 'minecraft:music.overworld.swamp', 'minecraft:music_disc.cat', 'minecraft:music_disc.13'] +ODD = ['minecraft:music.nether.warped_forest', 'minecraft:not.a.track'] + + +class Script: + def __init__(self): + self.lines = [] + + def add(self, *parts): + self.lines.append(' '.join(map(str, parts))) + + def situation(self, sound=None, lo=0, hi=0, replace=0, volume=1.0): + self.add('situation', '-' if sound is None else f'{sound},{lo},{hi},{replace}', h.bits(volume)) + + def tick(self, n=1, loading=0, paused=0): + for _ in range(n): + self.add('tick', loading, paused) + + +def scripted(s): + end, dragon, water, credits, cat = TRACKS[2], TRACKS[1], TRACKS[3], TRACKS[0], TRACKS[5] + s.add('start', 1, 'DEFAULT') + # Menu-like music: 20..600 ticks, replacing. + s.situation(end, 20, 600, 1) + s.tick(3, loading=1) + s.tick(120) + s.add('finish') + s.tick(650) + # Game music does not replace, and the next delay comes from its range. + s.situation(water, 12000, 24000, 0) + s.tick(5) + s.add('finish') + s.tick(30) + s.add('freq', 'FREQUENT') + s.tick(3) + s.add('freq', 'CONSTANT') + s.tick(110) + s.add('freq', 'DEFAULT') + s.tick(2) + # A replacing track stops the current one over the following ticks. + s.situation(dragon, 0, 0, 1) + s.tick(30) + s.situation(credits, 0, 0, 1) + s.tick(30) + s.situation(None) + s.tick(5) + s.add('finish') + s.tick(5) + s.situation(end, 6000, 24000, 1) + s.tick(130) + # Music volume fades: down to silence, then up from a partial volume. + s.situation(end, 6000, 24000, 1, volume=0.0) + s.tick(320) + s.situation(cat, 0, 0, 1, volume=0.25) + s.tick(5) + s.situation(cat, 0, 0, 1, volume=1.0) + s.tick(400) + s.situation(cat, 0, 0, 1, volume=0.6) + s.tick(80) + # Silent starts and the toast, stops, pauses. + s.add('volume', 1, h.bits(0.0)) + s.add('stop') + s.situation(dragon, 0, 0, 1) + s.tick(105) + s.add('toast') + s.add('volume', 1, h.bits(0.5)) + s.add('toast') + s.tick(2) + s.add('stopmusic', f'{end},0,0,1') + s.add('stopmusic', f'{dragon},0,0,1') + s.tick(105, paused=1) + s.add('finish') + s.tick(3, paused=1) + s.tick(5) + s.add('stopall') + s.tick(5) + # Events that cannot play. + for event in ODD: + s.add('start', 7, 'DEFAULT') + s.situation(event, 0, 40, 1) + s.tick(150) + # Real Musics delays over a long session. + s.add('start', 99, 'DEFAULT') + s.situation(water, 12000, 24000, 0) + s.tick(130) + s.add('finish') + s.tick(24100) + + +def fuzz(s, rng, steps): + s.add('start', rng.getrandbits(63), rng.choice(['DEFAULT', 'FREQUENT', 'CONSTANT'])) + for _ in range(steps): + op = rng.random() + if op < 0.08: + sound = rng.choice(TRACKS + ODD[:1]) if rng.random() < 0.9 else None + lo = rng.choice([0, 20, 100, 300]) + s.situation(sound, lo, lo + rng.choice([0, 50, 280, 600]), int(rng.random() < 0.5), + rng.choice([1.0, 1.0, 1.0, 0.0, 0.5, rng.random()])) + elif op < 0.13: + s.add('finish') + elif op < 0.15: + s.add('stop') + elif op < 0.16: + s.add('stopmusic', f'{rng.choice(TRACKS)},0,0,1') + elif op < 0.17: + s.add('freq', rng.choice(['DEFAULT', 'FREQUENT', 'CONSTANT'])) + elif op < 0.18: + s.add('toast') + elif op < 0.20: + s.add('volume', rng.choice([0, 1]), h.bits(rng.choice([0.0, 1.0, 0.5]))) + elif op < 0.21: + s.add('stopall') + elif op < 0.25: + s.tick(rng.randrange(1, 30), loading=1) + elif op < 0.28: + s.tick(rng.randrange(1, 30), paused=1) + else: + s.tick(rng.randrange(1, 60)) + + +def fixtures(): + s = Script() + scripted(s) + rng = random.Random(0x4d55534943) + for _ in range(60): + fuzz(s, rng, 120) + return s.lines + + +def main(): + lines = fixtures() + matched, report = h.run_harness( + 'music', 'VanillaMusicOracle', 'music_fixture', ''.join(l + '\n' for l in lines), + extra_sources=[h.lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java', + h.lab.ROOT / 'crates/horizon-client/src/music.rs', + h.lab.ROOT / 'crates/horizon-client/examples/audio_common/mod.rs'], + java_args=[h.RESOURCES], rust_args=[h.RESOURCES], + scope='Real MusicManager.tick/startPlaying/stopPlaying/fadePlaying/setMinutesBetweenSongs/showNowPlayingToastIfNeeded with a seeded ' + 'random over the real SoundEngine: track starts and replacements, nextSongDelay draws, the three music frequencies, the loading ' + 'screen hold, fades and the MUSIC category gain, silent starts, toasts, pauses, track ends and unplayable events. The situation ' + '(getSituationalMusic/getMusicVolume) is an input here; see test_audio_attributes_parity.py for the attribute values.') + print(f'{matched:,} music lines match the pinned client ({len(lines):,} steps): {report}', flush=True) + + +if __name__ == '__main__': + main() From ebb66e451f3f4a3d2eff775ee568c5d80cc1c38f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:50:51 +0200 Subject: [PATCH 12/28] Pace frames with vanilla's FramerateLimiter and compare it The game now ends each frame with FramerateLimiter.limitDisplayFPS below 260 fps (sleep, overshoot averaging, spin-wait) instead of waking the event loop at a computed deadline, and the limiter honours Thread.interrupted. tools/test_frame_limiter_parity.py runs the real limiter bytecode with its clock calls rewritten to a scripted virtual clock (5,288 cases). Co-Authored-By: Claude Opus 5.5 --- .../examples/frame_limiter_probe.rs | 96 ++++++++++ crates/horizon-client/src/game.rs | 10 +- crates/horizon-client/src/game/options.rs | 25 +-- crates/horizon-client/src/window.rs | 71 +++++++- .../parity/VanillaFrameLimiterOracle.java | 171 ++++++++++++++++++ tools/test_frame_limiter_parity.py | 69 +++++++ 6 files changed, 416 insertions(+), 26 deletions(-) create mode 100644 crates/horizon-client/examples/frame_limiter_probe.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFrameLimiterOracle.java create mode 100644 tools/test_frame_limiter_parity.py diff --git a/crates/horizon-client/examples/frame_limiter_probe.rs b/crates/horizon-client/examples/frame_limiter_probe.rs new file mode 100644 index 000000000..a877d05f9 --- /dev/null +++ b/crates/horizon-client/examples/frame_limiter_probe.rs @@ -0,0 +1,96 @@ +#![forbid(unsafe_code)] +//! Runs the JSON-lines scenarios of tools/test_frame_limiter_parity.py through +//! the Rust `FramerateLimiter` with the same scripted virtual clock. +use horizon_client::{ + Result, + window::{FramerateLimiter, LimiterClock, end_frame}, +}; +use serde_json::Value; +use std::{ + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, +}; + +/// The scripted clock of the case: every query costs `call` ns, parking +/// sleeps the request plus the next overshoot (at least 1 ns), spinning +/// costs `spin` ns and interruptions follow their script. +struct Script { + now: i64, + call: i64, + spin: i64, + overshoot: Vec, + next_overshoot: usize, + interrupts: Vec, + next_interrupt: usize, + parks: Vec, + spins: u64, + queries: u64, +} +impl LimiterClock for Script { + fn nanos(&mut self) -> i64 { + self.queries += 1; + let t = self.now; + self.now = self.now.wrapping_add(self.call); + t + } + fn park(&mut self, nanos: i64) { + self.parks.push(nanos); + let o = self.overshoot[self.next_overshoot % self.overshoot.len()]; + self.next_overshoot += 1; + self.now = self.now.wrapping_add(nanos.max(0).wrapping_add(o).max(1)); + } + fn spin(&mut self) { + self.spins += 1; + self.now = self.now.wrapping_add(self.spin); + } + fn interrupted(&mut self) -> bool { + let i = self.interrupts[self.next_interrupt % self.interrupts.len()]; + self.next_interrupt += 1; + i + } +} + +fn main() -> Result<()> { + let args: Vec = std::env::args().collect(); + let input = BufReader::new(File::open(&args[1])?); + let mut out = BufWriter::new(File::create(&args[2])?); + for (n, line) in input.lines().enumerate() { + let c: Value = serde_json::from_str(&line?)?; + writeln!(out, "== {n}")?; + let i = |k: &str| c[k].as_i64().unwrap(); + let mut clock = Script { + now: i("now"), + call: i("call"), + spin: i("spin"), + overshoot: c["overshoot"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect(), + next_overshoot: 0, + interrupts: c["interrupts"].as_array().unwrap().iter().map(|v| v.as_bool().unwrap()).collect(), + next_interrupt: 0, + parks: Vec::new(), + spins: 0, + queries: 0, + }; + let mut limiter = FramerateLimiter::with_state(i("last"), i("average"), i("last_limit") as i32); + for frame in c["frames"].as_array().unwrap() { + clock.now = clock.now.wrapping_add(frame[0].as_i64().unwrap()); + clock.parks.clear(); + clock.spins = 0; + clock.queries = 0; + end_frame(&mut limiter, frame[1].as_i64().unwrap() as i32, &mut clock); + let parks: Vec = clock.parks.iter().map(i64::to_string).collect(); + writeln!( + out, + "frame {} {} {} {} queries {} spins {} parks [{}]", + clock.now, + limiter.last_frame_time(), + limiter.average_overshoot_ns(), + limiter.last_framerate_limit(), + clock.queries, + clock.spins, + parks.join(",") + )?; + } + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 23162566b..6a1413d2c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -617,6 +617,9 @@ struct Game<'a> { /// Camera.oldFovModifier / fovModifier. /// `Camera` (eye height and field-of-view easing, view placement). view: horizon_client::camera::Camera, + /// `FramerateLimiter` and its clock. + limiter: horizon_client::window::FramerateLimiter, + frame_clock: horizon_client::window::SystemClock, /// Hud.scopeScale (spyglass overlay size). scope_scale: f32, /// Duration of the last frame in ticks (GUI easing). @@ -8196,6 +8199,7 @@ impl ApplicationHandler for Game<'_> { } self.apply_mouse_look(); let rendered = self.render()?; + self.limit_frame(); self.pause = self.pauses_game(); self.clock.end_frame(self.pause); let finished = self @@ -8261,10 +8265,6 @@ impl ApplicationHandler for Game<'_> { event_loop.exit(); return; } - if let Some(due) = self.next_frame_due() { - event_loop.set_control_flow(ControlFlow::WaitUntil(due)); - return; - } if let Some(w) = &self.window { w.request_redraw(); } @@ -8504,6 +8504,8 @@ pub fn run() -> Result<()> { chest_open: HashMap::new(), using: None, view: Default::default(), + limiter: horizon_client::window::FramerateLimiter::new(0), + frame_clock: Default::default(), scope_scale: 0.5, frame_ticks: 0.0, title: None, diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index 07cb5ba88..666656df3 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -176,13 +176,9 @@ impl Game<'_> { self.settings.save(&Self::options_path()); self.apply_ui_settings(); } - /// Frame limiter for the Max Framerate option: when the next frame is due. - pub(super) fn next_frame_due(&self) -> Option { - if self.options.frames.is_some() { - return None; - } - // FramerateLimitTracker.getFramerateLimit: the option, throttled when - // minimised, idle, or in a menu without a world. + /// `FramerateLimitTracker.getFramerateLimit`: the Max Framerate option, + /// throttled when minimised, idle, or in a menu without a world. + pub(super) fn framerate_limit(&self) -> i32 { let context = FrameContext { inactivity: if self.settings.inactivity_fps_limit == "minimized" { InactivityFpsLimit::Minimized @@ -201,11 +197,16 @@ impl Game<'_> { has_screen: self.title.is_some() || self.screen != super::Screen::Playing, has_overlay: false, }; - let fps = framerate_limit(self.settings.max_fps as i32, context); - if fps >= 260 { - return None; + framerate_limit(self.settings.max_fps as i32, context) + } + /// `Minecraft.runTick`'s frame limiter: `FramerateLimiter.limitDisplayFPS` + /// below 260 frames per second, sleeping then spin-waiting until the + /// frame's slot ends (not in scripted frame-count runs). + pub(super) fn limit_frame(&mut self) { + if self.options.frames.is_some() { + return; } - let due = self.previous + std::time::Duration::from_secs_f64(1.0 / f64::from(fps)); - (due > std::time::Instant::now()).then_some(due) + let limit = self.framerate_limit(); + horizon_client::window::end_frame(&mut self.limiter, limit, &mut self.frame_clock); } } diff --git a/crates/horizon-client/src/window.rs b/crates/horizon-client/src/window.rs index 18c76e683..bfcb973dd 100644 --- a/crates/horizon-client/src/window.rs +++ b/crates/horizon-client/src/window.rs @@ -143,16 +143,64 @@ pub trait LimiterClock { fn park(&mut self, nanos: i64); /// `Thread.onSpinWait`. fn spin(&mut self); + /// `Thread.interrupted`: an interrupted limiter skips that sleep. + fn interrupted(&mut self) -> bool { + false + } +} + +/// The real clock: `System.nanoTime` from a fixed origin, sleeping for +/// `LockSupport.parkNanos` and a CPU spin hint for `Thread.onSpinWait`. +#[derive(Clone, Copy, Debug)] +pub struct SystemClock { + origin: std::time::Instant, +} +impl Default for SystemClock { + fn default() -> Self { + Self { + origin: std::time::Instant::now(), + } + } +} +impl LimiterClock for SystemClock { + fn nanos(&mut self) -> i64 { + i64::try_from(self.origin.elapsed().as_nanos()).unwrap_or(i64::MAX) + } + fn park(&mut self, nanos: i64) { + std::thread::sleep(std::time::Duration::from_nanos(nanos.max(0) as u64)); + } + fn spin(&mut self) { + std::hint::spin_loop(); + } +} + +/// `Minecraft.runTick`'s frame-limiter step: only limits below 260 +/// (the "unlimited" setting) pace frames. +pub fn end_frame(limiter: &mut FramerateLimiter, framerate_limit: i32, clock: &mut impl LimiterClock) { + if framerate_limit < 260 { + limiter.limit_display_fps(framerate_limit, clock); + } } impl FramerateLimiter { pub fn new(now_ns: i64) -> Self { + Self::with_state(now_ns, 0, 0) + } + /// The limiter's static state: `lastFrameTime`, `averageOvershootNs` + /// and `lastFramerateLimit`. + pub fn with_state(last_frame_time: i64, average_overshoot_ns: i64, last_framerate_limit: i32) -> Self { Self { - last_frame_time: now_ns, - average_overshoot_ns: 0, - last_framerate_limit: 0, + last_frame_time, + average_overshoot_ns, + last_framerate_limit, } } + pub fn average_overshoot_ns(&self) -> i64 { + self.average_overshoot_ns + } + pub fn last_framerate_limit(&self) -> i32 { + self.last_framerate_limit + } pub fn limit_display_fps(&mut self, framerate_limit: i32, clock: &mut impl LimiterClock) { let target_time_per_frame = 1_000_000_000 / i64::from(framerate_limit); let target_time_ns = self.last_frame_time + target_time_per_frame; @@ -168,13 +216,16 @@ impl FramerateLimiter { if remaining > self.average_overshoot_ns + 500_000 { let sleep_start = clock.nanos(); let expected = remaining - self.average_overshoot_ns - 500_000; - clock.park(expected); - let duration = clock.nanos() - sleep_start; - let overshoot = duration - expected; - if overshoot > 0 && overshoot < 25_000_000 { - self.average_overshoot_ns = - (0.1 * overshoot as f64 + 0.9 * self.average_overshoot_ns as f64) as i64; - self.average_overshoot_ns = self.average_overshoot_ns.min(2_000_000); + if !clock.interrupted() { + clock.park(expected); + let duration = clock.nanos() - sleep_start; + let overshoot = duration - expected; + if overshoot > 0 && overshoot < 25_000_000 { + self.average_overshoot_ns = (0.1 * overshoot as f64 + + 0.9 * self.average_overshoot_ns as f64) + as i64; + self.average_overshoot_ns = self.average_overshoot_ns.min(2_000_000); + } } } else { clock.spin(); diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFrameLimiterOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFrameLimiterOracle.java new file mode 100644 index 000000000..d6e2fa119 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFrameLimiterOracle.java @@ -0,0 +1,171 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.io.*; +import java.lang.classfile.*; +import java.lang.classfile.instruction.InvokeInstruction; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; + +/** + * Runs the real FramerateLimiter.limitDisplayFPS from the client jar with its + * clock calls (System.nanoTime, LockSupport.parkNanos, Thread.interrupted, + * Thread.onSpinWait) redirected by a ClassFile rewrite to a scripted virtual + * clock, and the Minecraft.runTick condition (limits below 260), printing the + * limiter state and clock interaction of every frame. + */ +public final class VanillaFrameLimiterOracle { + /** The scripted clock the rewritten limiter calls. */ + public static final class Clock { + static long now, call, spin; + static long[] overshoot; + static int nextOvershoot; + static boolean[] interrupts; + static int nextInterrupt; + static List parks = new ArrayList<>(); + static long spins, queries; + + public static long nanoTime() { + queries++; + long t = now; + now += call; + return t; + } + + public static void parkNanos(long nanos) { + parks.add(nanos); + long o = overshoot[nextOvershoot++ % overshoot.length]; + now += Math.max(Math.max(nanos, 0) + o, 1); + } + + public static void onSpinWait() { + spins++; + now += spin; + } + + public static boolean interrupted() { + return interrupts[nextInterrupt++ % interrupts.length]; + } + } + + static final ClassDesc CLOCK = ClassDesc.of(Clock.class.getName()); + + /** Loads FramerateLimiter itself, rewritten; everything else from the parent. */ + static final class Rewriting extends ClassLoader { + Rewriting(ClassLoader parent) { + super(parent); + } + + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if (!name.equals("net.minecraft.client.FramerateLimiter")) { + return super.loadClass(name, resolve); + } + synchronized (getClassLoadingLock(name)) { + Class loaded = findLoadedClass(name); + if (loaded == null) { + try (var in = getParent().getResourceAsStream("net/minecraft/client/FramerateLimiter.class")) { + byte[] bytes = rewrite(in.readAllBytes()); + loaded = defineClass(name, bytes, 0, bytes.length); + } catch (IOException e) { + throw new ClassNotFoundException(name, e); + } + } + return loaded; + } + } + } + + static int rewrites; + + static byte[] rewrite(byte[] bytes) { + var cf = ClassFile.of(); + ClassModel model = cf.parse(bytes); + return cf.transformClass(model, ClassTransform.transformingMethodBodies((builder, element) -> { + if (element instanceof InvokeInstruction call && call.opcode() == Opcode.INVOKESTATIC) { + String owner = call.owner().asInternalName(); + String name = call.name().stringValue(); + String target = switch (owner + "." + name) { + case "java/lang/System.nanoTime" -> "nanoTime"; + case "java/util/concurrent/locks/LockSupport.parkNanos" -> "parkNanos"; + case "java/lang/Thread.interrupted" -> "interrupted"; + case "java/lang/Thread.onSpinWait" -> "onSpinWait"; + default -> null; + }; + if (target != null) { + rewrites++; + builder.invokestatic(CLOCK, target, MethodTypeDesc.ofDescriptor(call.type().stringValue())); + return; + } + } + builder.with(element); + })); + } + + public static void main(String[] args) throws Exception { + Clock.overshoot = new long[] {0}; + Clock.interrupts = new boolean[] {false}; + Class limiter = Class.forName("net.minecraft.client.FramerateLimiter", true, + new Rewriting(VanillaFrameLimiterOracle.class.getClassLoader())); + // System.nanoTime x4 (and once in the static initialiser), parkNanos, interrupted, onSpinWait. + if (rewrites != 8) { + throw new AssertionError("unexpected clock calls in FramerateLimiter: " + rewrites); + } + Method limit = limiter.getMethod("limitDisplayFPS", int.class); + Field last = limiter.getDeclaredField("lastFrameTime"); + Field average = limiter.getDeclaredField("averageOvershootNs"); + Field lastLimit = limiter.getDeclaredField("lastFramerateLimit"); + for (Field f : List.of(last, average, lastLimit)) { + f.setAccessible(true); + } + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8)); + var lines = Files.lines(Path.of(args[0]))) { + int n = 0; + for (var line : (Iterable) lines::iterator) { + var c = JsonParser.parseString(line).getAsJsonObject(); + out.println("== " + n++); + Clock.now = c.get("now").getAsLong(); + Clock.call = c.get("call").getAsLong(); + Clock.spin = c.get("spin").getAsLong(); + var o = c.getAsJsonArray("overshoot"); + Clock.overshoot = new long[o.size()]; + for (int i = 0; i < o.size(); i++) { + Clock.overshoot[i] = o.get(i).getAsLong(); + } + var in = c.getAsJsonArray("interrupts"); + Clock.interrupts = new boolean[in.size()]; + for (int i = 0; i < in.size(); i++) { + Clock.interrupts[i] = in.get(i).getAsBoolean(); + } + Clock.nextOvershoot = 0; + Clock.nextInterrupt = 0; + last.setLong(null, c.get("last").getAsLong()); + average.setLong(null, c.get("average").getAsLong()); + lastLimit.setInt(null, c.get("last_limit").getAsInt()); + for (var e : c.getAsJsonArray("frames")) { + var frame = e.getAsJsonArray(); + Clock.now += frame.get(0).getAsLong(); + Clock.parks.clear(); + Clock.spins = 0; + Clock.queries = 0; + int framerateLimit = frame.get(1).getAsInt(); + // Minecraft.runTick: "if (framerateLimit < 260) FramerateLimiter.limitDisplayFPS(framerateLimit)". + if (framerateLimit < 260) { + limit.invoke(null, framerateLimit); + } + var parks = new StringJoiner(","); + for (long p : Clock.parks) { + parks.add(Long.toString(p)); + } + out.println("frame " + Clock.now + " " + last.getLong(null) + " " + average.getLong(null) + " " + + lastLimit.getInt(null) + " queries " + Clock.queries + " spins " + Clock.spins + " parks [" + parks + "]"); + } + } + } + System.exit(0); + } +} diff --git a/tools/test_frame_limiter_parity.py b/tools/test_frame_limiter_parity.py new file mode 100644 index 000000000..1ff2099be --- /dev/null +++ b/tools/test_frame_limiter_parity.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Compare the frame limiter with the pinned client: the real +FramerateLimiter.limitDisplayFPS bytecode, its clock calls rewritten to a +scripted virtual clock, against the Rust limiter with the same script, frame +by frame: sleep requests, spin-waits, overshoot averaging and its reset on a +limit change, interrupted sleeps, oversleep and early wake-ups, the "below +260" condition of Minecraft.runTick, and the limits FramerateLimitTracker +hands it (option values, 60 in menus, 10 when minimised or idle).""" +import json +import random + +try: + from . import lab, oracle_harness as harness +except ImportError: + import lab, oracle_harness as harness + +LIMITS = [10, 30, 60, 60, 120, 144, 165, 240, 250, 259, 260, 1, 2, 7, 1000, 2**31 - 1] + + +def cases(rng): + for limit in LIMITS: + for overshoot in ([0], [50_000], [3_000_000], [30_000_000], [-200_000], [100_000, 2_500_000, 0, 24_999_999, 25_000_000]): + for spin in (1_000, 50_000, 7_919): + frames = [[rng.choice([0, 1_000_000, 4_000_000, 16_000_000]), limit] for _ in range(12)] + yield dict(now=10**12, call=rng.choice([0, 25]), spin=spin, overshoot=overshoot, interrupts=[False], + last=10**12, average=0, last_limit=0, frames=frames) + for n in range(5000): + frames = [] + limit = rng.choice(LIMITS) + for _ in range(rng.randrange(1, 40)): + if rng.random() < 0.15: + limit = rng.choice(LIMITS) + work = rng.choice([0, 100_000, 2_000_000, 5_000_000, 16_666_666, 30_000_000, 120_000_000, rng.randrange(0, 50_000_000)]) + frames.append([work, limit]) + start = rng.choice([0, 10**9, 10**15, rng.randrange(0, 10**16)]) + yield dict(now=start, call=rng.choice([1, 30, 400, 20_000]), spin=rng.choice([100, 1_000, 70_000, 600_000]), + overshoot=[rng.choice([0, 30_000, 80_000, 1_200_000, 2_100_000, 24_000_000, 26_000_000, -300_000, rng.randrange(-1_000_000, 4_000_000)]) + for _ in range(rng.randrange(1, 8))], + interrupts=[False] + [rng.random() < 0.3 for _ in range(rng.randrange(0, 5))], + last=start - rng.choice([0, 1, 5_000_000, 200_000_000]), + average=rng.choice([0, 0, 1, 500_000, 2_000_000]), last_limit=rng.choice([0, 60, limit]), frames=frames) + + +def make_cases(build): + rng = random.Random(0x46505331) + path = build / 'cases.jsonl' + count = 0 + with path.open('w') as out: + for case in cases(rng): + out.write(json.dumps(case, separators=(',', ':')) + '\n') + count += 1 + return path, count + + +def main(): + scope = ('The actual FramerateLimiter.limitDisplayFPS bytecode from the client jar, loaded through a ClassFile ' + 'rewrite that redirects System.nanoTime, LockSupport.parkNanos, Thread.interrupted and Thread.onSpinWait ' + 'to a scripted virtual clock (query cost, oversleep/early wake per park, spin cost, interrupt pattern), ' + 'with its static state seeded per case and the Minecraft.runTick "limit < 260" gate. Compares every ' + 'frame\'s park requests, spin count, clock queries, lastFrameTime, averageOvershootNs and ' + 'lastFramerateLimit. The limits themselves (FramerateLimitTracker) are compared by the game loop harness; ' + 'real OS sleep accuracy is outside the comparison.') + harness.differential( + 'rust-frame-limiter-parity', 'VanillaFrameLimiterOracle', 'frame_limiter_probe', make_cases, scope, + sources=[lab.ROOT / 'crates/horizon-client/src/window.rs']) + + +if __name__ == '__main__': + main() From 6eee2e32620d8cb7699dab091b98cc50a86652c1 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:52:28 +0200 Subject: [PATCH 13/28] Compare audio environment attributes and Musics with the vanilla data Co-Authored-By: Claude Opus 5.5 --- .../examples/audio_attributes_fixture.rs | 85 +++++++++++++ crates/horizon-client/src/music.rs | 16 +++ .../parity/VanillaAudioAttributesOracle.java | 112 ++++++++++++++++++ tools/test_audio_attributes_parity.py | 36 ++++++ 4 files changed, 249 insertions(+) create mode 100644 crates/horizon-client/examples/audio_attributes_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAudioAttributesOracle.java create mode 100644 tools/test_audio_attributes_parity.py diff --git a/crates/horizon-client/examples/audio_attributes_fixture.rs b/crates/horizon-client/examples/audio_attributes_fixture.rs new file mode 100644 index 000000000..73f463fc4 --- /dev/null +++ b/crates/horizon-client/examples/audio_attributes_fixture.rs @@ -0,0 +1,85 @@ +//! Audio environment attributes from Horizon's `MusicTables` and +//! `AmbientTables` for `tools/test_audio_attributes_parity.py`: +//! `audio_attributes_fixture ROOT INPUT OUTPUT`. +use horizon_client::ambience::AmbientTables; +use horizon_client::music::{Music, MusicTables}; +use horizon_client::sound_events::normalize; +use std::io::Write; + +fn music(m: Option<&Music>) -> String { + m.map_or("-".to_owned(), |m| { + format!( + "{},{},{},{}", + normalize(&m.sound), + m.min_delay, + m.max_delay, + m.replace_current_music + ) + }) +} + +fn main() { + let args: Vec = std::env::args().collect(); + let root = std::path::Path::new(&args[1]); + let tables = MusicTables::load(root); + let ambient = AmbientTables::load(root); + let input = std::fs::read_to_string(&args[2]).expect("input"); + let mut out = std::io::BufWriter::new(std::fs::File::create(&args[3]).expect("output")); + for (name, m) in [ + ("MENU", Music::menu()), + ("CREDITS", Music::credits()), + ("END_BOSS", Music::end_boss()), + ("CREATIVE", Music::creative()), + ("END", Music::end()), + ("UNDER_WATER", Music::under_water()), + ("GAME", Music::game()), + ] { + writeln!(out, "{name} {}", music(Some(&m))).expect("write"); + } + for line in input.lines() { + let f: Vec<&str> = line.split(' ').collect(); + let (dimension, biome) = (f[0], f[1]); + let bg = tables.background(dimension, biome); + let mut s = format!( + "{line} default={} creative={} underwater={}", + music(bg.default.as_ref()), + music(bg.creative.as_ref()), + music(bg.underwater.as_ref()) + ); + for creative in [false, true] { + for underwater in [false, true] { + s.push_str(&format!( + " select={}", + music(bg.select(creative, underwater)) + )); + } + } + s.push_str(&format!( + " volume={:08x}", + tables.volume(dimension, biome).to_bits() + )); + let a = ambient.get(dimension, biome); + s.push_str(&format!( + " loop={}", + a.r#loop.as_deref().map_or("-".to_owned(), normalize) + )); + s.push_str(&format!( + " mood={}", + a.mood.as_ref().map_or("-".to_owned(), |m| format!( + "{},{},{},{:016x}", + normalize(&m.sound), + m.tick_delay, + m.block_search_extent, + m.offset.to_bits() + )) + )); + for (sound, chance) in &a.additions { + s.push_str(&format!( + " addition={},{:016x}", + normalize(sound), + chance.to_bits() + )); + } + writeln!(out, "{s}").expect("write"); + } +} diff --git a/crates/horizon-client/src/music.rs b/crates/horizon-client/src/music.rs index 94a7f87a0..08dbea125 100644 --- a/crates/horizon-client/src/music.rs +++ b/crates/horizon-client/src/music.rs @@ -36,6 +36,22 @@ impl Music { pub fn end_boss() -> Self { Self::new("minecraft:music.dragon", 0, 0, true) } + /// `Musics.CREATIVE`. + pub fn creative() -> Self { + Self::new("minecraft:music.creative", 12000, 24000, false) + } + /// `Musics.END`. + pub fn end() -> Self { + Self::new("minecraft:music.end", 6000, 24000, true) + } + /// `Musics.UNDER_WATER`. + pub fn under_water() -> Self { + Self::new("minecraft:music.under_water", 12000, 24000, false) + } + /// `Musics.GAME`. + pub fn game() -> Self { + Self::new("minecraft:music.game", 12000, 24000, false) + } /// `Music.CODEC`. fn parse(v: &Value) -> Option { let sound = v["sound"].as_str()?; diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAudioAttributesOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAudioAttributesOracle.java new file mode 100644 index 000000000..33cc38776 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAudioAttributesOracle.java @@ -0,0 +1,112 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.SharedConstants; +import net.minecraft.core.*; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.RegistryDataLoader; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.Bootstrap; +import net.minecraft.server.RegistryLayer; +import net.minecraft.server.packs.PackType; +import net.minecraft.server.packs.repository.ServerPacksSource; +import net.minecraft.server.packs.resources.MultiPackResourceManager; +import net.minecraft.sounds.Music; +import net.minecraft.sounds.Musics; +import net.minecraft.tags.TagLoader; +import net.minecraft.world.attribute.*; +import net.minecraft.world.clock.*; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.phys.Vec3; + +/** + * The audio environment attributes as the vanilla EnvironmentAttributeSystem + * evaluates them from the vanilla data pack (dimension layer, the biome's + * positional layer, the dimension timelines and weather layers): + * BACKGROUND_MUSIC with BackgroundMusic.select for every creative/underwater + * combination, MUSIC_VOLUME and AMBIENT_SOUNDS, for lines "dimension biome + * ticks"; plus the Musics constants. + */ +public final class VanillaAudioAttributesOracle { + static String music(Music m) { + return m == null ? "-" : m.sound().value().location() + "," + m.minDelay() + "," + m.maxDelay() + "," + m.replaceCurrentMusic(); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private static void addBiome(EnvironmentAttributeSystem.Builder b, EnvironmentAttribute attr, Biome biome) { + b.addPositionalLayer(attr, (base, pos, w) -> biome.getAttributes().applyModifier(attr, base)); + } + + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + var repo = ServerPacksSource.createVanillaTrustedRepository(); + repo.reload(); + repo.setSelected(List.of("vanilla")); + var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected()); + var layers = RegistryLayer.createRegistryAccess(); + var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC)); + var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags); + RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join(); + staticTags.forEach(Registry.PendingTags::apply); + var dimensions = world.lookupOrThrow(Registries.DIMENSION_TYPE); + var biomes = world.lookupOrThrow(Registries.BIOME); + try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) { + w.println("MENU " + music(Musics.MENU)); + w.println("CREDITS " + music(Musics.CREDITS)); + w.println("END_BOSS " + music(Musics.END_BOSS)); + w.println("CREATIVE " + music(Musics.CREATIVE)); + w.println("END " + music(Musics.END)); + w.println("UNDER_WATER " + music(Musics.UNDER_WATER)); + w.println("GAME " + music(Musics.GAME)); + for (String line : Files.readAllLines(Path.of(args[0]), StandardCharsets.UTF_8)) { + String[] f = line.split(" "); + DimensionType dim = dimensions.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.parse(f[0]))).value(); + Biome biome = biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(f[1]))).value(); + long ticks = Long.parseLong(f[2]); + ClockManager clocks = h -> new ClockInstance() { + public long totalTicks() { return ticks; } + public float partialTick() { return 0.0F; } + public float rate() { return 1.0F; } + public boolean isPaused() { return false; } + }; + var b = EnvironmentAttributeSystem.builder(); + b.addConstantLayer(dim.attributes()); + for (EnvironmentAttribute attr : biome.getAttributes().keySet()) addBiome(b, attr, biome); + dim.timelines().forEach(t -> b.addTimelineLayer(t, clocks)); + if (dim.hasSkyLight() && !dim.hasCeiling()) { + WeatherAttributes.addBuiltinLayers(b, new WeatherAttributes.WeatherAccess() { + public float rainLevel() { return 0.0F; } + public float thunderLevel() { return 0.0F; } + }); + } + var system = b.build(); + BackgroundMusic bg = system.getValue(EnvironmentAttributes.BACKGROUND_MUSIC, Vec3.ZERO); + StringBuilder sb = new StringBuilder(line); + sb.append(" default=").append(music(bg.defaultMusic().orElse(null))) + .append(" creative=").append(music(bg.creativeMusic().orElse(null))) + .append(" underwater=").append(music(bg.underwaterMusic().orElse(null))); + for (boolean creative : new boolean[]{false, true}) { + for (boolean underwater : new boolean[]{false, true}) { + sb.append(" select=").append(music(bg.select(creative, underwater).orElse(null))); + } + } + sb.append(String.format(" volume=%08x", Float.floatToRawIntBits(system.getValue(EnvironmentAttributes.MUSIC_VOLUME, Vec3.ZERO)))); + AmbientSounds ambient = system.getValue(EnvironmentAttributes.AMBIENT_SOUNDS, Vec3.ZERO); + sb.append(" loop=").append(ambient.loop().map(s -> s.value().location().toString()).orElse("-")); + sb.append(" mood=").append(ambient.mood().map(m -> m.soundEvent().value().location() + "," + m.tickDelay() + "," + + m.blockSearchExtent() + "," + String.format("%016x", Double.doubleToRawLongBits(m.soundPositionOffset()))).orElse("-")); + for (AmbientAdditionsSettings a : ambient.additions()) { + sb.append(" addition=").append(a.soundEvent().value().location()).append(String.format(",%016x", Double.doubleToRawLongBits(a.tickChance()))); + } + w.println(sb); + } + } + System.exit(0); + } +} diff --git a/tools/test_audio_attributes_parity.py b/tools/test_audio_attributes_parity.py new file mode 100644 index 000000000..78b28ecbe --- /dev/null +++ b/tools/test_audio_attributes_parity.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +"""Compare the audio environment attributes with the vanilla 26.3 data pack. + +The oracle evaluates vanilla's `EnvironmentAttributeSystem` (dimension layer, +biome positional layer, dimension timelines, weather layers) for every +dimension type and biome and prints `BACKGROUND_MUSIC` (all three tracks and +`BackgroundMusic.select` for each creative/underwater combination), +`MUSIC_VOLUME` and `AMBIENT_SOUNDS` (loop, mood, additions), plus the +`Musics` constants. Horizon's `MusicTables` and `AmbientTables` answer the same. +""" +try: + from . import audio_harness as h +except ImportError: + import audio_harness as h + + +def fixtures(): + data = h.RESOURCES / 'data/minecraft' + biomes = sorted('minecraft:' + p.stem for p in (data / 'worldgen/biome').glob('*.json')) + dimensions = sorted('minecraft:' + p.stem for p in (data / 'dimension_type').glob('*.json')) + return [f'{d} {b} {t}' for d in dimensions for b in biomes for t in (0, 13000)] + + +def main(): + lines = fixtures() + matched, report = h.run_harness( + 'audio-attributes', 'VanillaAudioAttributesOracle', 'audio_attributes_fixture', ''.join(l + '\n' for l in lines), + extra_sources=[h.lab.ROOT / 'crates/horizon-client/src/music.rs', h.lab.ROOT / 'crates/horizon-client/src/ambience.rs'], + rust_args=[h.RESOURCES], + scope='Vanilla EnvironmentAttributeSystem values of audio/background_music (with BackgroundMusic.select), audio/music_volume and ' + 'audio/ambient_sounds for every dimension type x biome at two times of day, and the Musics constants.') + print(f'{matched:,} audio attribute lines match the pinned data ({len(lines):,} cases): {report}', flush=True) + + +if __name__ == '__main__': + main() From 268babc2571d90e637ad1bfe456404e9b4417383 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:56:23 +0200 Subject: [PATCH 14/28] 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 --- crates/horizon-client/examples/hud_fixture.rs | 143 +++++ crates/horizon-client/src/game.rs | 180 +++--- crates/horizon-client/src/game/health_hud.rs | 226 ------- crates/horizon-client/src/game/mounts.rs | 39 +- crates/horizon-client/src/hud_layout.rs | 599 ++++++++++++++++++ crates/horizon-client/src/lib.rs | 1 + .../horizonlab/parity/VanillaHudOracle.java | 292 +++++++++ tools/test_hud_parity.py | 126 ++++ 8 files changed, 1254 insertions(+), 352 deletions(-) create mode 100644 crates/horizon-client/examples/hud_fixture.rs delete mode 100644 crates/horizon-client/src/game/health_hud.rs create mode 100644 crates/horizon-client/src/hud_layout.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHudOracle.java create mode 100644 tools/test_hud_parity.py diff --git a/crates/horizon-client/examples/hud_fixture.rs b/crates/horizon-client/examples/hud_fixture.rs new file mode 100644 index 000000000..3b3285baf --- /dev/null +++ b/crates/horizon-client/examples/hud_fixture.rs @@ -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 = std::result::Result>; + +fn main() -> Result<()> { + let args: Vec = 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; 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 = 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(()) +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 64eb9ec65..a2eca557e 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -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, message: Option<(String, Instant)>, save: Arc, @@ -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, diff --git a/crates/horizon-client/src/game/health_hud.rs b/crates/horizon-client/src/game/health_hud.rs deleted file mode 100644 index 4e9aaee0a..000000000 --- a/crates/horizon-client/src/game/health_hud.rs +++ /dev/null @@ -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 = (0..5).map(|_| r.next_int(10)).collect(); - assert_eq!(v, [0, 3, 8, 4, 0]); - } -} diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index c3e642144..9fb26ec83 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -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) } } diff --git a/crates/horizon-client/src/hud_layout.rs b/crates/horizon-client/src/hud_layout.rs new file mode 100644 index 000000000..295a1a029 --- /dev/null +++ b/crates/horizon-client/src/hud_layout.rs @@ -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; 9], + pub offhand_pop: f32, + /// `getAttackStrengthScale(0)` when the attack indicator is in HOTBAR mode. + pub attack: Option, +} + +/// `Hud.extractItemHotbar`. +pub fn hotbar(w: i32, h: i32, i: &HotbarInputs) -> Vec { + 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| { + 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, full: bool) -> Vec { + 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 { + 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 { + 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, + 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 { + 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 { .. } => {} + } + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index e5080ea4a..8b2ed8ade 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -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; diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHudOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHudOracle.java new file mode 100644 index 000000000..249c71f8d --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHudOracle.java @@ -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 slots = new IdentityHashMap<>(); + + @SuppressWarnings("unchecked") + static T alloc(Class 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 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 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 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 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()); + 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); + } +} diff --git a/tools/test_hud_parity.py b/tools/test_hud_parity.py new file mode 100644 index 000000000..2268d3621 --- /dev/null +++ b/tools/test_hud_parity.py @@ -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() From 723ec3bb8ad7138ecc014346e828b63a8a617054 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:56:39 +0200 Subject: [PATCH 15/28] Drop entity death loot exactly as vanilla's LivingEntity.die does Entity loot tables now run on the faithful loot engine with an entity context: the victim, the killer and direct attacker, the damage type and its tags, the last player to hurt it and their luck, entity predicates (flags, equipment, components, sheep, cube size, raider captains, vehicles, entity type tags), damage source predicates, killed_by_player, random_chance_with_enchanted_bonus, enchanted_count_increase, furnace_smelt and tag entries. Draws come from the world's random sequence for the table. mobs::drops ports dropAllDeathLoot: Monster loot for babies, equipment drops in EquipmentSlot order with Looting's equipment_drops effect and durability, the fox's mouth item, the wither's star, the charged creeper head hook, horse inventories and chests, and getBaseExperienceReward with the equipment bonus and baby zombie reward, split into orbs. Fixes found on the way: sheep dropped their wool twice, baby monsters dropped nothing, armour bonus experience and the equipment slot order were wrong, hoglins were fire immune, and fishing treasure was unreachable (the hook predicate format changed). tools/test_entity_death_loot_parity.py: 1,578 cases over 87 entity types match vanilla. Co-Authored-By: Claude Opus 5.5 --- .../examples/entity_death_loot_fixture.rs | 266 ++++++++ crates/horizon-client/src/game/creatures.rs | 278 ++++---- crates/horizon-client/src/game/raids.rs | 15 - crates/horizon-client/src/mobs.rs | 4 + crates/horizon-client/src/mobs/drops.rs | 530 +++++++++++++++ crates/horizon-client/src/mobs/species.rs | 1 - crates/horizon-world/src/loot.rs | 617 ++++++++++++++++-- .../parity/VanillaEntityDeathLootOracle.java | 320 +++++++++ tools/test_entity_death_loot_parity.py | 185 ++++++ 9 files changed, 2022 insertions(+), 194 deletions(-) create mode 100644 crates/horizon-client/examples/entity_death_loot_fixture.rs create mode 100644 crates/horizon-client/src/mobs/drops.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityDeathLootOracle.java create mode 100644 tools/test_entity_death_loot_parity.py diff --git a/crates/horizon-client/examples/entity_death_loot_fixture.rs b/crates/horizon-client/examples/entity_death_loot_fixture.rs new file mode 100644 index 000000000..0e6dede38 --- /dev/null +++ b/crates/horizon-client/examples/entity_death_loot_fixture.rs @@ -0,0 +1,266 @@ +//! Entity death drops for differential tests against vanilla +//! (tools/test_entity_death_loot_parity.py): reads the cases of +//! `VanillaEntityDeathLootOracle` and prints what `mobs::drops::die` drops. +//! +//! usage: entity_death_loot_fixture RESOURCES INPUT OUTPUT +use horizon_client::{ + mobs::{ + Mob, MobTypes, Species, cube, drops, gear, raider, render::DYE_NAMES, sulfur_cube, + }, + random_sequences::RandomSequences, +}; +use horizon_core::{geometry::Vec3, random::LegacyRandom}; +use horizon_world::loot::{LootDamage, LootData, LootEntity, LootStack}; +use std::{collections::BTreeMap, fmt::Write as _, fs, path::Path, sync::Arc}; + +/// `id[;enchantment:level...]`. +fn stack(spec: &str) -> LootStack { + let mut parts = spec.split(';'); + let mut s = LootStack { + item: parts.next().unwrap_or("minecraft:air").to_owned(), + count: 1, + damage: 0, + enchantments: Vec::new(), + potion: None, + map: false, + ominous_amplifier: None, + }; + for e in parts { + let (name, level) = e.rsplit_once(':').unwrap_or((e, "1")); + let name = if name.contains(':') { + name.to_owned() + } else { + format!("minecraft:{name}") + }; + s.enchantments.push((name, level.parse().unwrap_or(1))); + } + s +} + +fn line(s: &LootStack) -> String { + let mut out = format!("drop {} {}", s.item, s.count); + if s.damage != 0 { + let _ = write!(out, " damage={}", s.damage); + } + for (e, l) in &s.enchantments { + let _ = write!(out, " ench={e}:{l}"); + } + if let Some(p) = &s.potion { + let _ = write!(out, " potion={p}"); + } + if let Some(a) = s.ominous_amplifier { + let _ = write!(out, " ominous={a}"); + } + out +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let root = Path::new( + args.get(1) + .ok_or("usage: entity_death_loot_fixture RESOURCES INPUT OUTPUT")?, + ); + let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; + let types = MobTypes::load(root)?; + let loot = LootData::load(root)?; + let mut out = String::new(); + for raw in input.lines() { + if raw.trim().is_empty() || raw.starts_with('#') { + continue; + } + let mut c = BTreeMap::new(); + let mut name = ""; + for token in raw.split_whitespace() { + match token.split_once('=') { + Some((k, v)) => { + c.insert(k, v); + } + None => name = token, + } + } + let get = |k: &str, d: &'static str| -> String { c.get(k).copied().unwrap_or(d).to_owned() }; + let _ = writeln!(out, "== {name}"); + let Some(kind) = types.types.get(c["type"]) else { + let _ = writeln!(out, "error unsupported {}", c["type"]); + continue; + }; + let kind = Arc::new(kind.clone()); + let world_seed: i64 = get("seed", "0").parse()?; + let kills: i64 = get("kills", "1").parse()?; + let rand: i64 = get("rand", "0").parse()?; + let mut sequences = RandomSequences::default(); + for k in 0..kills { + let _ = writeln!(out, "kill {k}"); + let mut m = Mob::new(1, kind.clone(), Vec3::new(0.5, 64.0, 0.5), 0.0); + // EntityType.create(LOAD) gives no equipment. + for slot in drops::SLOTS { + drops::clear_slot(&mut m, slot); + } + if get("baby", "0") == "1" && drops::can_be_baby(m.species()) { + m.extra.age = -24000; + } + if get("fire", "0") == "1" { + m.fire_ticks = 100; + } + // A cube made with EntityType.create(LOAD) was never sized. + if matches!(m.species(), Species::Slime | Species::MagmaCube) { + m.extra.size = 0; + } + if let Some(size) = c.get("size") { + let size: i32 = size.parse()?; + if m.species() == Species::SulfurCube { + sulfur_cube::set_size(&mut m, size, true); + } else { + cube::set_size(&mut m, size); + } + } + if let Some(color) = c.get("color") { + m.extra.color = DYE_NAMES.iter().position(|d| d == color).unwrap_or(0) as u8; + } + m.extra.sheared = get("sheared", "0") == "1"; + if get("leader", "0") == "1" { + raider::state_mut(&mut m).patrol_leader = true; + } + if get("captain", "0") == "1" { + m.extra.head = Some(Arc::from(raider::BANNER)); + } + let mut chances = [drops::DEFAULT_DROP_CHANCE; 8]; + for (i, slot) in drops::SLOTS.iter().enumerate() { + if let Some(spec) = c.get(slot) { + let s = stack(spec); + let item: Option> = Some(Arc::from(s.item.as_str())); + let index = match *slot { + "mainhand" => { + m.extra.main_hand = item; + Some(gear::MAIN) + } + "offhand" => { + m.extra.off_hand = item; + Some(gear::OFF) + } + "head" => { + m.extra.head = item; + Some(gear::HEAD) + } + "body" if drops::head_is_body(m.species()) => { + m.extra.head = item; + None + } + "saddle" => { + m.set_saddle(Some(horizon_client::items::ItemStack::new(&s.item, 1))); + None + } + "chest" => { + m.extra.chest = item; + Some(gear::CHEST) + } + "legs" => { + m.extra.legs = item; + Some(gear::LEGS) + } + "feet" => { + m.extra.feet = item; + Some(gear::FEET) + } + _ => None, + }; + if let Some(index) = index + && !s.enchantments.is_empty() + { + let levels = s + .enchantments + .iter() + .map(|(e, l)| (Arc::from(e.as_str()), *l as u32)) + .collect(); + gear::set(&mut m, index, levels); + } + } + if let Some(chance) = c.get(format!("chance_{slot}").as_str()) { + chances[i] = chance.parse()?; + } + } + m.extra.drop_chances = Some(Box::new(chances)); + m.random = LegacyRandom::new(rand + k); + // The killer, the last player to hurt the victim and the damage source. + let killer_id = get("killer", "none"); + let weapon = c.get("weapon").map(|w| stack(w)); + let armed = |kind: &str| { + let mut e = LootEntity::new(kind); + if let Some(w) = &weapon { + e.equipment.push(("mainhand".into(), w.clone())); + } + e + }; + let player = (killer_id == "player" || get("pkill", "0") == "1").then(|| { + if killer_id == "player" { + armed("minecraft:player") + } else { + LootEntity::new("minecraft:player") + } + }); + let killer = match killer_id.as_str() { + "player" => player.clone(), + "none" => None, + id => { + let mut e = armed(id); + e.frog_variant = c.get("frog").map(|f| f.to_string()); + e.powered = get("charged", "0") == "1"; + Some(e) + } + }; + let pkill = get("pkill", if killer_id == "player" { "1" } else { "0" }) == "1"; + let projectile = |kind: &str| LootEntity { + kind: kind.to_owned(), + ..LootEntity::default() + }; + let damage = |kind: &str, source: Option, direct: Option| LootDamage { + kind: kind.to_owned(), + source, + direct, + }; + let source = match get("source", "attack").as_str() { + "attack" => match &killer { + None => damage("minecraft:generic", None, None), + Some(k) if k.kind == "minecraft:player" => { + damage("minecraft:player_attack", Some(k.clone()), Some(k.clone())) + } + Some(k) => damage("minecraft:mob_attack", Some(k.clone()), Some(k.clone())), + }, + "arrow" => damage("minecraft:arrow", killer.clone(), Some(projectile("minecraft:arrow"))), + "fireball" => match &killer { + Some(k) => damage("minecraft:fireball", Some(k.clone()), Some(projectile("minecraft:fireball"))), + None => damage( + "minecraft:unattributed_fireball", + Some(projectile("minecraft:fireball")), + Some(projectile("minecraft:fireball")), + ), + }, + "explosion" => match &killer { + Some(k) => damage("minecraft:player_explosion", Some(k.clone()), Some(k.clone())), + None => damage("minecraft:explosion", None, None), + }, + "lightning" => damage("minecraft:lightning_bolt", None, None), + "fire" => damage("minecraft:on_fire", None, None), + _ => damage("minecraft:generic", None, None), + }; + let death = drops::Death { + loot: &loot, + damage: Some(source), + player: player.filter(|_| pkill), + luck: get("luck", "0").parse()?, + vehicle: c.get("vehicle").map(|v| LootEntity::new(v)), + mob_drops: true, + world_seed, + }; + let (items, _) = drops::die(&mut m, &death, &mut sequences); + for d in items { + let _ = match d { + drops::Drop::Item(s) => writeln!(out, "{}", line(&s)), + drops::Drop::Orb(v) => writeln!(out, "orb {v}"), + }; + } + } + } + fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 26c1bf86f..afd148af7 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -739,13 +739,14 @@ impl Game<'_> { /// LivingEntity.die / dropAllDeathLoot. fn mob_died(&mut self, m: &Mob) { let by_player = self.last_hurt_by_player.remove(&m.id) || m.ai.last_hurt_by_player > 0; + let mut dying = m.clone(); // LivingEntity.die: the death is heard, and a sculk catalyst nearby - // takes the experience. + // takes the experience (before the loot is dropped). self.sculk_mob_died(m); let consumed = - self.catalyst_takes_experience([m.position.x, m.position.y, m.position.z], |game| { + self.catalyst_takes_experience([m.position.x, m.position.y, m.position.z], |_| { if by_player { - experience_reward(m, &mut game.world.random) + horizon_client::mobs::drops::base_experience(&mut dying).max(0) as u32 } else { 0 } @@ -760,103 +761,8 @@ impl Game<'_> { self.score_entity_removed(m.id); self.raider_died(m, by_player); self.villager_murdered(m, by_player); - let held = self.held().cloned(); let pos = [m.position.x, m.position.y + 0.5, m.position.z]; - if !m.is_baby() { - let mut drops = self.res.items.entity_drops( - &m.kind.id, - by_player, - held.as_ref(), - &mut self.world.random, - ); - if m.species() == Species::Sheep && !m.extra.sheared { - let color = horizon_client::mobs::render::DYE_NAMES[m.extra.color as usize & 15]; - drops.extend(self.res.items.loot_table( - &format!("minecraft:entities/sheep/{color}"), - by_player, - held.as_ref(), - &mut self.world.random, - )); - } - for d in drops { - if d.count > 0 && &*d.item != "minecraft:air" { - self.spawn_item(d, pos, [0.0, 0.2, 0.0], 10); - } - } - // Saddles, horse armour and chests always drop. - let mut gear: Vec<&str> = Vec::new(); - if let Some(saddle) = m.saddle_item() { - self.spawn_item(saddle, pos, [0.0, 0.2, 0.0], 10); - } - // WitherBoss.dropCustomDeathLoot. - if m.species() == Species::Wither { - gear.push("minecraft:nether_star"); - } - if species_drops_harness(m) - && let Some(h) = m.extra.head.as_deref() - { - gear.push(h); - } - if m.extra.chested && horizon_client::mobs::equine::is_equine(m.species()) { - gear.push("minecraft:chest"); - } - if horizon_client::mobs::equine::is_equine(m.species()) - && let Some(armor) = m.extra.head.as_deref() - { - gear.push(armor); - } - for item in gear { - self.spawn_item(ItemStack::new(item, 1), pos, [0.0, 0.2, 0.0], 10); - } - // AbstractChestedHorse.dropEquipment: the chest contents. - for stack in m.extra.items.clone().into_iter().flatten() { - self.spawn_item(stack, pos, [0.0, 0.2, 0.0], 10); - } - self.raider_death_loot(m, pos); - let worn = if horizon_client::mobs::equine::is_equine(m.species()) { - [None, None, None, None] - } else { - [ - m.extra.head.clone(), - m.extra.chest.clone(), - m.extra.legs.clone(), - m.extra.feet.clone(), - ] - }; - for (index, item) in std::iter::once(m.extra.main_hand.clone()) - .chain(worn) - .enumerate() - { - // Main hand, then head to feet (the enchantment slots). - let slot = if index == 0 { - horizon_client::mobs::gear::MAIN - } else { - horizon_client::mobs::gear::HEAD + index - 1 - }; - // Equipment drop chance 8.5% (+ player kill only). - // Vexes never drop their sword. - if let Some(item) = &item - && by_player - && &**item != horizon_client::mobs::raider::BANNER - && m.species() != Species::Vex - && self.world.random.next_float() < 0.085 - { - let mut stack = ItemStack::new(item, 1); - if let Some(g) = horizon_client::mobs::gear::gear(m) { - for (e, l) in &g.slots[slot] { - stack.enchant(e, *l); - } - } - self.spawn_item(stack, pos, [0.0, 0.2, 0.0], 10); - } - } - } - if by_player && !consumed { - let xp = experience_reward(m, &mut self.world.random); - if xp > 0 { - self.spawn_orbs(pos, xp); - } - } + self.drop_death_loot(&mut dying, by_player, consumed, pos); if m.species() == Species::SulfurCube { self.split_sulfur_cube(m); } @@ -881,6 +787,88 @@ impl Game<'_> { } } } + /// `dropAllDeathLoot` through `mobs::drops`: the entity loot table from the + /// world's random sequence, equipment by drop chance, species extras and + /// the experience orbs, spawned in order. + fn drop_death_loot(&mut self, m: &mut Mob, by_player: bool, consumed: bool, pos: [f64; 3]) { + use horizon_client::mobs::{DamageKind, Who, drops}; + use horizon_world::loot::{LootDamage, LootEntity}; + let Some(loot) = horizon_client::structure_blocks::loot_data(&self.options.resources) else { + return; + }; + let player = || { + let mut e = LootEntity::new("minecraft:player"); + if let Some(held) = self.held() { + e.equipment.push(("mainhand".into(), to_loot(held))); + } + e + }; + let damage = m.last_damage.map(|(d, _)| { + let source = match d.attacker { + Some(Who::Player) => Some(player()), + Some(Who::Mob(id)) => self + .mobs + .iter() + .find(|o| o.id == id) + .map(|o| drops::loot_entity(o, None)), + None => None, + }; + let direct = match d.kind { + DamageKind::Arrow => Some(LootEntity { + kind: "minecraft:arrow".into(), + ..LootEntity::default() + }), + DamageKind::Fireball => Some(LootEntity { + kind: "minecraft:fireball".into(), + ..LootEntity::default() + }), + _ => source.clone(), + }; + let player_source = matches!(d.attacker, Some(Who::Player)); + LootDamage { + kind: damage_type(d.kind, player_source).into(), + source, + direct, + } + }); + let vehicle = m + .extra + .mount + .and_then(|id| self.mobs.iter().find(|o| o.id == id)) + .map(|o| LootEntity::new(&o.kind.id)); + let death = drops::Death { + loot: &loot, + damage, + player: by_player.then(player), + luck: 0.0, + vehicle, + mob_drops: self.ui.rules.bool("mob_drops"), + world_seed: self.level.seed, + }; + let (items, skulls) = drops::die(m, &death, &mut self.rand_sequences); + if skulls + && let Some(Who::Mob(id)) = m.last_damage.and_then(|(d, _)| d.attacker) + && let Some(creeper) = self.mobs.iter_mut().find(|o| o.id == id) + { + // Creeper.droppedSkulls: one head per charged explosion. + creeper.extra.charged = false; + } + let raider = horizon_client::mobs::raider::is_raider(m.species()); + for d in items { + match d { + drops::Drop::Item(stack) => { + let item = if raider && stack.item == horizon_client::mobs::raider::BANNER { + horizon_client::mobs::raider::ominous_banner() + } else { + from_loot(&stack) + }; + self.spawn_item(item, pos, [0.0, 0.2, 0.0], 10); + } + drops::Drop::Orb(value) if !consumed => self.spawn_orbs(pos, value as u32), + drops::Drop::Orb(_) => {} + } + } + } pub(super) fn handle_mob_events(&mut self, events: Vec) -> Result<()> { for e in events { match e { @@ -2614,11 +2602,6 @@ impl Game<'_> { } } } -fn species_drops_harness(m: &Mob) -> bool { - // Body equipment set to drop when killed: a harness, nautilus armour, a - // sulfur cube's swallowed block. - horizon_client::mobs::species::body_slot(m.species()) -} fn eat_sound(s: Species) -> &'static str { match s { Species::Pig => "entity.pig.eat", @@ -2633,37 +2616,66 @@ fn eat_sound(s: Species) -> &'static str { } } /// Mob.getBaseExperienceReward -fn experience_reward(m: &Mob, random: &mut impl RandomSource) -> u32 { - use Species as S; - match m.species() { - S::Blaze | S::Ghast | S::Hoglin | S::Zoglin | S::PiglinBrute | S::Breeze => 10, - S::Slime | S::MagmaCube => m.extra.size.max(1) as u32, - S::Endermite => 3, - S::Bat - | S::Squid - | S::GlowSquid - | S::Cod - | S::Salmon - | S::TropicalFish - | S::Pufferfish - | S::Dolphin => 1 + random.next_int_bound(3).unwrap_or(0) as u32, - S::IronGolem | S::SnowGolem | S::Villager | S::WanderingTrader => 0, - // SulfurCube.getBaseExperienceReward. - S::SulfurCube if m.is_baby() => 0, - S::SulfurCube => 1 + random.next_int_bound(2).unwrap_or(0) as u32, - // Animals in the monster category (Animal.getBaseExperienceReward). - S::CamelHusk | S::ZombieNautilus => 1 + random.next_int_bound(3).unwrap_or(0) as u32, - _ if m.hostile() => { - 5 + if m.extra.main_hand.is_some() { - 1 + random.next_int_bound(3).unwrap_or(0) as u32 - } else { - 0 - } - } - _ if m.is_baby() => 0, - _ => 1 + random.next_int_bound(3).unwrap_or(0) as u32, +/// The damage type id of a Horizon damage kind. +fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static str { + use horizon_client::mobs::DamageKind as K; + match kind { + K::PlayerAttack => "minecraft:player_attack", + K::MobAttack => "minecraft:mob_attack", + K::Arrow => "minecraft:arrow", + K::Thrown => "minecraft:thrown", + K::Fireball => "minecraft:fireball", + K::Explosion if player => "minecraft:player_explosion", + K::Explosion => "minecraft:explosion", + K::Fall => "minecraft:fall", + K::OnFire => "minecraft:on_fire", + K::InFire => "minecraft:in_fire", + K::Lava => "minecraft:lava", + K::Drown => "minecraft:drown", + K::Magic => "minecraft:magic", + K::Sting => "minecraft:sting", + K::Cactus => "minecraft:cactus", + K::Generic => "minecraft:generic", + K::InWall => "minecraft:in_wall", + K::Thorns => "minecraft:thorns", + K::SonicBoom => "minecraft:sonic_boom", } } +/// A Horizon item stack as a loot stack (id, count, damage, enchantments). +fn to_loot(stack: &ItemStack) -> horizon_world::loot::LootStack { + horizon_world::loot::LootStack { + item: stack.item.to_string(), + count: stack.count as i32, + damage: stack.damage as i32, + enchantments: stack + .enchantments() + .iter() + .map(|(e, l)| (e.to_string(), *l as i32)) + .collect(), + potion: None, + map: false, + ominous_amplifier: None, + } +} +/// A generated loot stack as a Horizon item stack. +fn from_loot(stack: &horizon_world::loot::LootStack) -> ItemStack { + let mut item = ItemStack { + item: Arc::from(stack.item.as_str()), + count: stack.count.max(1) as u32, + damage: stack.damage.max(0) as u32, + extra: None, + }; + for (id, level) in &stack.enchantments { + item.enchant(id, (*level).max(0) as u32); + } + if let Some(potion) = &stack.potion { + item = item.with_potion(potion); + } + if let Some(amplifier) = stack.ominous_amplifier.filter(|a| *a > 0) { + item.data_mut().ominous_amplifier = Some(amplifier as u8); + } + item +} /// Entity.push between overlapping mobs (LivingEntity.pushEntities). fn push_apart(mobs: &mut [Mob]) { let n = mobs.len(); diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index 3e2fdad58..91c454ce8 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -921,21 +921,6 @@ impl Game<'_> { } /// A raider's ominous banner (drop chance 2.0: always dropped) and a /// patrol captain's ominous bottle (`entities/pillager`). - pub(super) fn raider_death_loot(&mut self, m: &horizon_client::mobs::Mob, pos: [f64; 3]) { - if !raider::is_raider(m.species()) { - return; - } - if m.extra.head.as_deref() == Some(raider::BANNER) { - self.spawn_item(raider::ominous_banner(), pos, [0.0, 0.2, 0.0], 10); - } - if m.species() == Species::Pillager && raider::is_captain(m) { - let amplifier = self.world.random.next_int_bound(5).unwrap_or(0) as u8; - let amplifier = (amplifier > 0).then_some(amplifier); - let mut bottle = horizon_client::items::ItemStack::new("minecraft:ominous_bottle", 1); - bottle.data_mut().ominous_amplifier = amplifier; - self.spawn_item(bottle, pos, [0.0, 0.2, 0.0], 10); - } - } /// `OminousBottleAmplifier.onConsume`: Bad Omen for 100 minutes at the /// bottle's amplifier, then the dispose sound; the bottle is used up. pub(super) fn drink_ominous_bottle( diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index f46420cad..deda5984a 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -18,6 +18,7 @@ pub mod control; pub mod creaking; pub mod cube; pub mod data; +pub mod drops; pub mod enderman; pub mod equine; pub mod farm; @@ -528,6 +529,9 @@ pub struct Extra { pub trap_time: i32, /// Enchantments on the equipment above. pub gear: Option>, + /// `Mob.dropChances` by `EquipmentSlot` (`drops::SLOTS` order) when set + /// explicitly; None uses the defaults of `drops::drop_chance`. + pub drop_chances: Option>, } #[derive(Clone, Debug)] pub struct Mob { diff --git a/crates/horizon-client/src/mobs/drops.rs b/crates/horizon-client/src/mobs/drops.rs new file mode 100644 index 000000000..42010afd9 --- /dev/null +++ b/crates/horizon-client/src/mobs/drops.rs @@ -0,0 +1,530 @@ +//! What a dying mob leaves behind: `LivingEntity.die`'s drop step. The +//! killer's `killedEntity` hook (a charged creeper's head drop), then +//! `dropAllDeathLoot`: the entity loot table (drawn from the world's random +//! sequence), `Mob.dropCustomDeathLoot` (equipment by drop chance, with the +//! entity random), the species' extra drops and the experience orbs. +use super::{Mob, Species, equine, gear, raider, render::DYE_NAMES, species}; +use crate::random_sequences::RandomSequences; +use horizon_core::random::RandomSource; +use horizon_world::loot::{EntityLootParams, LootDamage, LootData, LootEntity, LootStack}; + +/// `DropChances.DEFAULT_EQUIPMENT_DROP_CHANCE`. +pub const DEFAULT_DROP_CHANCE: f32 = 0.085; +/// `EquipmentSlot.VALUES`. +pub use horizon_world::loot::EQUIPMENT_SLOTS as SLOTS; + +/// One thing a death leaves in the world, in spawn order. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Drop { + Item(LootStack), + /// An experience orb of this value. + Orb(i32), +} + +/// How the mob died. +pub struct Death<'a> { + pub loot: &'a LootData, + /// The killing `DamageSource`. + pub damage: Option, + /// The player who last hurt the mob, when `lastHurtByPlayerMemoryTime > 0`. + pub player: Option, + /// That player's luck. + pub luck: f32, + /// The entity the mob rides. + pub vehicle: Option, + /// The `doMobLoot` game rule. + pub mob_drops: bool, + pub world_seed: i64, +} + +/// `instanceof Monster` (Monster.shouldDropLoot/shouldDropExperience). +pub fn is_monster(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Blaze + | S::Bogged + | S::Breeze + | S::CaveSpider + | S::Creaking + | S::Creeper + | S::Drowned + | S::ElderGuardian + | S::Enderman + | S::Endermite + | S::Evoker + | S::Giant + | S::Guardian + | S::Husk + | S::Illusioner + | S::Parched + | S::Piglin + | S::PiglinBrute + | S::Pillager + | S::Ravager + | S::Silverfish + | S::Skeleton + | S::Spider + | S::Stray + | S::Vex + | S::Vindicator + | S::Warden + | S::Witch + | S::Wither + | S::WitherSkeleton + | S::Zoglin + | S::Zombie + | S::ZombieVillager + | S::ZombifiedPiglin + ) +} +/// `Mob.xpReward` as the constructors set it. +fn xp_reward(m: &Mob) -> i32 { + use Species as S; + match m.species() { + S::Blaze | S::Breeze | S::Guardian | S::ElderGuardian | S::Evoker => 10, + S::Vex | S::Endermite => 3, + S::PiglinBrute | S::Ravager => 20, + S::Wither => 50, + S::Creaking => 0, + // Hoglin.setBaby. + S::Hoglin if m.is_baby() => 3, + S::Ghast | S::Hoglin | S::Phantom | S::Shulker => 5, + // Slime.setSize / MagmaCube.setSize (unsized cubes keep 0). + S::Slime | S::MagmaCube => m.extra.size.max(0), + s if is_monster(s) => 5, + _ => 0, + } +} +fn is_animal(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Armadillo + | S::Axolotl + | S::Bee + | S::Camel + | S::CamelHusk + | S::Cat + | S::Chicken + | S::Cow + | S::Donkey + | S::Fox + | S::Frog + | S::HappyGhast + | S::Goat + | S::Hoglin + | S::Horse + | S::Llama + | S::Mooshroom + | S::Mule + | S::Nautilus + | S::Ocelot + | S::Panda + | S::Parrot + | S::Pig + | S::PolarBear + | S::Rabbit + | S::Sheep + | S::SkeletonHorse + | S::Sniffer + | S::Strider + | S::TraderLlama + | S::Turtle + | S::Wolf + | S::ZombieHorse + | S::ZombieNautilus + ) +} +/// AgeableWaterCreature and WaterAnimal. +fn is_water_creature(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Dolphin + | S::GlowSquid + | S::Squid + | S::Cod + | S::Salmon + | S::Pufferfish + | S::TropicalFish + | S::Tadpole + ) +} +fn zombie_family(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Zombie | S::Husk | S::Drowned | S::ZombieVillager | S::ZombifiedPiglin + ) +} +fn is_raider(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Pillager | S::Vindicator | S::Evoker | S::Illusioner | S::Witch | S::Ravager + ) +} +/// Whether `setBaby(true)` makes the species a baby (AgeableMob and the +/// zombies, minus the species that are never babies). +pub fn can_be_baby(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Armadillo + | S::Axolotl + | S::Bee + | S::Camel + | S::Cat + | S::Chicken + | S::Cow + | S::Dolphin + | S::Donkey + | S::Drowned + | S::Fox + | S::HappyGhast + | S::GlowSquid + | S::Goat + | S::Hoglin + | S::Horse + | S::Husk + | S::Llama + | S::Mooshroom + | S::Mule + | S::Nautilus + | S::Ocelot + | S::Panda + | S::Pig + | S::Piglin + | S::PolarBear + | S::Rabbit + | S::Sheep + | S::SkeletonHorse + | S::Sniffer + | S::Squid + | S::Strider + | S::SulfurCube + | S::TraderLlama + | S::Turtle + | S::Villager + | S::WanderingTrader + | S::Wolf + | S::Zoglin + | S::Zombie + | S::ZombieHorse + | S::ZombieVillager + | S::ZombifiedPiglin + ) +} +/// Whether the species keeps its body armour in `extra.head`. +pub fn head_is_body(s: Species) -> bool { + species::body_slot(s) || equine::is_equine(s) +} + +/// The item a mob has in an `EquipmentSlot` (by name), with its enchantments. +pub fn slot_item(m: &Mob, slot: &str) -> Option { + let body = head_is_body(m.species()); + let (item, index) = match slot { + "mainhand" => (m.extra.main_hand.as_deref(), Some(gear::MAIN)), + "offhand" => (m.extra.off_hand.as_deref(), Some(gear::OFF)), + "head" if !body => (m.extra.head.as_deref(), Some(gear::HEAD)), + "chest" => (m.extra.chest.as_deref(), Some(gear::CHEST)), + "legs" => (m.extra.legs.as_deref(), Some(gear::LEGS)), + "feet" => (m.extra.feet.as_deref(), Some(gear::FEET)), + "body" if body => (m.extra.head.as_deref(), None), + "saddle" => { + let saddle = m.saddle_item()?; + let mut stack = loot_stack(&saddle.item, 1); + stack.damage = saddle.damage as i32; + for (e, l) in saddle.enchantments() { + stack.enchantments.push((e.to_string(), *l as i32)); + } + return Some(stack); + } + _ => (None, None), + }; + let mut stack = loot_stack(item?, 1); + if let (Some(index), Some(g)) = (index, gear::gear(m)) { + for (e, l) in &g.slots[index] { + stack.enchantments.push((e.to_string(), *l as i32)); + } + } + Some(stack) +} +/// `setItemSlot(slot, EMPTY)`. +pub fn clear_slot(m: &mut Mob, slot: &str) { + let body = head_is_body(m.species()); + let index = match slot { + "mainhand" => { + m.extra.main_hand = None; + gear::MAIN + } + "offhand" => { + m.extra.off_hand = None; + gear::OFF + } + "head" if !body => { + m.extra.head = None; + gear::HEAD + } + "chest" => { + m.extra.chest = None; + gear::CHEST + } + "legs" => { + m.extra.legs = None; + gear::LEGS + } + "feet" => { + m.extra.feet = None; + gear::FEET + } + "body" if body => { + m.extra.head = None; + return; + } + "saddle" => { + m.set_saddle(None); + return; + } + _ => return, + }; + if m.extra.gear.is_some() { + gear::set(m, index, Vec::new()); + } +} +fn loot_stack(item: &str, count: i32) -> LootStack { + LootStack { + item: item.to_owned(), + count, + damage: 0, + enchantments: Vec::new(), + potion: None, + map: false, + ominous_amplifier: None, + } +} +/// `Mob.dropChances.byEquipment(slot)`: the recorded chance, or the one the +/// game's spawn and equip paths give (saddles and body armour are put on by +/// `Equippable` and always drop; a captain's banner always drops; a vex +/// never drops its sword). +pub fn drop_chance(m: &Mob, slot: &str) -> f32 { + let index = SLOTS.iter().position(|s| *s == slot).unwrap_or(0); + if let Some(chances) = &m.extra.drop_chances { + return chances[index]; + } + match slot { + "saddle" | "body" => 2.0, + "head" if is_raider(m.species()) && m.extra.head.as_deref() == Some(raider::BANNER) => 2.0, + "mainhand" if m.species() == Species::Vex => 0.0, + _ => DEFAULT_DROP_CHANCE, + } +} +/// The facts loot predicates read about a mob. +pub fn loot_entity(m: &Mob, vehicle: Option) -> LootEntity { + use Species as S; + let s = m.species(); + let mut e = LootEntity::new(&m.kind.id); + e.on_fire = m.fire_ticks > 0 && !m.kind.flags.fire_immune; + e.baby = m.is_baby(); + e.vehicle = vehicle.map(Box::new); + if matches!(s, S::Slime | S::MagmaCube | S::SulfurCube) { + // An unsized cube has the synced default size 1. + e.cube_size = Some(m.extra.size.max(1)); + } + if s == S::Sheep { + e.sheep = Some(( + DYE_NAMES[m.extra.color as usize & 15].to_owned(), + m.extra.sheared, + )); + } + if is_raider(s) { + e.captain = Some(raider::is_captain(m)); + } + if s == S::Frog { + e.frog_variant = Some( + ["minecraft:temperate", "minecraft:warm", "minecraft:cold"] + [usize::from(m.extra.variant).min(2)] + .to_owned(), + ); + } + e.powered = s == S::Creeper && m.extra.charged; + e.equipment = SLOTS + .iter() + .filter_map(|slot| slot_item(m, slot).map(|i| (slot.to_string(), i))) + .collect(); + e +} +/// `ExperienceOrb.getExperienceValue`. +pub fn orb_value(amount: i32) -> i32 { + for v in [2477, 1237, 617, 307, 149, 73, 37, 17, 7, 3] { + if amount >= v { + return v; + } + } + 1 +} + +/// `LivingEntity.die`'s drops for `m` (equipment it loses is removed from +/// it). Returns the drops in spawn order and whether a charged creeper +/// killer dropped a head (`Creeper.droppedSkulls`). +pub fn die(m: &mut Mob, d: &Death, sequences: &mut RandomSequences) -> (Vec, bool) { + let mut out = Vec::new(); + let this = loot_entity(m, d.vehicle.clone()); + let mut skulls = false; + // Creeper.killedEntity: a charged creeper's victim drops its head. + if let Some(source) = d.damage.as_ref().and_then(|x| x.source.as_ref()) + && source.kind == "minecraft:creeper" + && source.powered + && d.mob_drops + { + let params = EntityLootParams { + this: this.clone(), + damage: d.damage.clone(), + player: None, + luck: 0.0, + }; + let items = roll(d, "minecraft:charged_creeper/root", ¶ms, sequences); + skulls = items.iter().any(|i| !i.is_empty()); + out.extend(items.into_iter().filter(|i| !i.is_empty()).map(Drop::Item)); + } + let killed_by_player = d.player.is_some(); + let s = m.species(); + // Fox.dropAllDeathLoot: whatever it holds in its mouth comes out first. + if s == Species::Fox + && let Some(stack) = slot_item(m, "mainhand") + { + out.push(Drop::Item(stack)); + clear_slot(m, "mainhand"); + } + let drops_loot = d.mob_drops && (is_monster(s) || !m.is_baby()); + if drops_loot { + let table = format!("minecraft:entities/{}", m.kind.id.trim_start_matches("minecraft:")); + let params = EntityLootParams { + this: this.clone(), + damage: d.damage.clone(), + player: d.player.clone().filter(|_| killed_by_player), + luck: if killed_by_player { d.luck } else { 0.0 }, + }; + let items = roll(d, &table, ¶ms, sequences); + out.extend(items.into_iter().filter(|i| !i.is_empty()).map(Drop::Item)); + // Mob.dropCustomDeathLoot. + let damage_params = EntityLootParams { + this: this.clone(), + damage: d.damage.clone(), + player: None, + luck: 0.0, + }; + let living_attacker = d + .damage + .as_ref() + .and_then(|x| x.source.as_ref()) + .is_some_and(|a| a.living); + for slot in SLOTS { + let stack = slot_item(m, slot); + let mut chance = drop_chance(m, slot); + if chance == 0.0 { + continue; + } + let preserve = chance > 1.0; + if living_attacker { + chance = d.loot.equipment_drop_chance(&damage_params, chance); + } + let Some(mut stack) = stack else { continue }; + if d.loot.prevents_equipment_drop(&stack) || !(killed_by_player || preserve) { + continue; + } + if m.random.next_float() >= chance { + continue; + } + let max = d.loot.max_damage(&stack.item); + if !preserve && max > 0 { + let inner = m.random.next_int_bound((max - 3).max(1)).unwrap_or(0); + stack.damage = max - m.random.next_int_bound(1 + inner).unwrap_or(0); + } + out.push(Drop::Item(stack)); + clear_slot(m, slot); + } + // WitherBoss.dropCustomDeathLoot. + if s == Species::Wither { + out.push(Drop::Item(loot_stack("minecraft:nether_star", 1))); + } + } + // dropEquipment: AbstractHorse's inventory, then a chested horse's chest. + if equine::is_equine(s) { + for stack in m.extra.items.iter().flatten() { + if stack.count > 0 { + let mut item = loot_stack(&stack.item, stack.count as i32); + item.damage = stack.damage as i32; + out.push(Drop::Item(item)); + } + } + if m.extra.chested { + out.push(Drop::Item(loot_stack("minecraft:chest", 1))); + m.extra.chested = false; + } + } + // dropExperience. + let drops_experience = match s { + Species::Tadpole => false, + Species::Hoglin => true, + s if is_monster(s) => true, + _ => !m.is_baby(), + }; + if killed_by_player && drops_experience && d.mob_drops { + let mut amount = base_experience(m); + while amount > 0 { + let value = orb_value(amount); + amount -= value; + out.push(Drop::Orb(value)); + } + } + (out, skulls) +} +fn roll( + d: &Death, + table: &str, + params: &EntityLootParams, + sequences: &mut RandomSequences, +) -> Vec { + match d.loot.random_sequence(table) { + Some(id) => { + let random = sequences.get(id, d.world_seed); + d.loot.roll_entity(table, random, params) + } + None => Vec::new(), + } +} +/// `getBaseExperienceReward` (no vanilla enchantment changes mob experience). +pub fn base_experience(m: &mut Mob) -> i32 { + use Species as S; + let s = m.species(); + match s { + // Chicken.getBaseExperienceReward. + S::Chicken if m.extra.jockey => 10, + S::SulfurCube if m.is_baby() => 0, + S::SulfurCube => 1 + m.random.next_int_bound(2).unwrap_or(0), + // Hoglin / Piglin: the reward without the equipment bonus. + S::Hoglin | S::Piglin => xp_reward(m), + s if is_animal(s) || is_water_creature(s) => 1 + m.random.next_int_bound(3).unwrap_or(0), + _ => { + let mut reward = xp_reward(m); + // Zombie.getBaseExperienceReward: babies are worth 2.5 times as much. + if zombie_family(s) && m.is_baby() { + reward = (reward as f32 * 2.5) as i32; + } + if reward > 0 { + let mut result = reward; + for slot in SLOTS { + // EquipmentSlot.canIncreaseExperience: all but the saddle. + if slot != "saddle" && slot_item(m, slot).is_some() && drop_chance(m, slot) <= 1.0 { + result += 1 + m.random.next_int_bound(3).unwrap_or(0); + } + } + result + } else { + reward + } + } + } +} diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs index 9954298b9..899666265 100644 --- a/crates/horizon-client/src/mobs/species.rs +++ b/crates/horizon-client/src/mobs/species.rs @@ -1443,7 +1443,6 @@ impl Def { | S::WitherSkeleton | S::ZombifiedPiglin | S::Zoglin - | S::Hoglin | S::Wither ), burns_in_day: matches!( diff --git a/crates/horizon-world/src/loot.rs b/crates/horizon-world/src/loot.rs index d36b00a79..b863e9659 100644 --- a/crates/horizon-world/src/loot.rs +++ b/crates/horizon-world/src/loot.rs @@ -1,10 +1,13 @@ -//! Container loot: `LootTable.fill` for chest-style loot tables (pools, +//! Loot tables: `LootTable.fill` for chest-style loot tables (pools, //! weighted entries, nested tables, item modifiers and conditions, the -//! stack splitter and the slot shuffle) with vanilla's random draw order. +//! stack splitter and the slot shuffle) and `LootTable.getRandomItems` for +//! entity loot (the victim, its killer, the damage source and the last +//! player to hurt it), with vanilla's random draw order. //! //! Items keep their id, count, damage, enchantments and potion. Exploration //! maps are kept as found (structure search is not run); conditions that -//! need an entity, tool or damage source fail, as they do for containers. +//! need an entity, tool or damage source fail when the context has none, as +//! they do for containers. use horizon_core::random::{LegacyRandom, RandomSource}; use serde_json::Value; use std::{ @@ -41,6 +44,10 @@ impl LootStack { pub fn is_empty(&self) -> bool { self.count <= 0 || self.item == "minecraft:air" } + /// `ItemStack.getCount`: 0 for an empty stack. + pub fn get_count(&self) -> i32 { + if self.is_empty() { 0 } else { self.count } + } } #[derive(Clone, Copy, Debug, Default)] @@ -59,6 +66,10 @@ struct Enchantment { weight: i32, min_cost: (i32, i32), max_cost: (i32, i32), + /// `slots`: the equipment slot groups the enchantment works in. + slots: Vec, + /// `effects` (equipment_drops and others). + effects: Value, } impl Enchantment { fn min_cost(&self, level: i32) -> i32 { @@ -79,6 +90,134 @@ pub struct LootData { enchantments: Vec, /// Raw tag files by (registry, tag id). tags: HashMap<(String, String), Vec>, + /// Smelting recipes in recipe id order: (ingredient, result, result count). + smelting: Vec<(Value, String, i32)>, +} + +/// An entity a loot context names (`this`, `attacker`, `direct_attacker`, +/// `attacking_player`): the facts entity predicates read. +#[derive(Clone, Debug, Default)] +pub struct LootEntity { + /// Entity type id (`minecraft:zombie`). + pub kind: String, + /// A `LivingEntity` (has equipment and enchantment levels). + pub living: bool, + /// `Entity.isOnFire` (fire-immune entities never are). + pub on_fire: bool, + pub baby: bool, + /// The entity it rides (`getVehicle`). + pub vehicle: Option>, + /// `AbstractCubeMob.getSize`. + pub cube_size: Option, + /// A sheep's colour name and whether it is sheared. + pub sheep: Option<(String, bool)>, + /// A raider: whether it is a captain (wears the ominous banner). + pub captain: Option, + /// A frog's variant id (`minecraft:warm`). + pub frog_variant: Option, + /// A charged creeper (`Creeper.isPowered`). + pub powered: bool, + /// Worn and held items by `EquipmentSlot` name (mainhand, offhand, + /// feet, legs, chest, head, body, saddle). + pub equipment: Vec<(String, LootStack)>, +} +impl LootEntity { + pub fn new(kind: &str) -> Self { + Self { + kind: kind.to_owned(), + living: true, + ..Self::default() + } + } + pub fn item(&self, slot: &str) -> Option<&LootStack> { + self.equipment + .iter() + .find(|(s, i)| s == slot && !i.is_empty()) + .map(|(_, i)| i) + } +} +/// A `DamageSource`: its damage type and the entities behind it. +#[derive(Clone, Debug, Default)] +pub struct LootDamage { + /// Damage type id (`minecraft:player_attack`). + pub kind: String, + /// `getEntity`: the attacker (the shooter of a projectile). + pub source: Option, + /// `getDirectEntity`: the projectile, or the attacker itself. + pub direct: Option, +} +/// The parameters of `LivingEntity.dropFromLootTable`. +#[derive(Clone, Debug, Default)] +pub struct EntityLootParams { + pub this: LootEntity, + pub damage: Option, + /// `LAST_DAMAGE_PLAYER`: set when a player killed the entity. + pub player: Option, + /// The killing player's luck. + pub luck: f32, +} +/// `EquipmentSlot.VALUES` order. +pub const EQUIPMENT_SLOTS: [&str; 8] = [ + "mainhand", "offhand", "feet", "legs", "chest", "head", "body", "saddle", +]; +/// `EquipmentSlotGroup.test`. +fn slot_in_group(slot: &str, group: &str) -> bool { + match group { + "any" => true, + "hand" => slot == "mainhand" || slot == "offhand", + "armor" => matches!(slot, "feet" | "legs" | "chest" | "head" | "body"), + _ => slot == group, + } +} +/// `LevelBasedValue.calculate`. +pub fn level_value(v: &Value, level: i32) -> f32 { + match v { + Value::Number(n) => n.as_f64().unwrap_or(0.) as f32, + Value::Object(_) => match v["type"].as_str().unwrap_or("") { + "minecraft:linear" => { + level_value(&v["base"], level) + + level_value(&v["per_level_above_first"], level) * (level - 1) as f32 + } + "minecraft:constant" => level_value(&v["value"], level), + "minecraft:clamped" => { + let value = level_value(&v["value"], level); + let min = v["min"].as_f64().unwrap_or(0.) as f32; + let max = v["max"].as_f64().unwrap_or(0.) as f32; + value.clamp(min, max) + } + "minecraft:fraction" => { + level_value(&v["numerator"], level) / level_value(&v["denominator"], level) + } + "minecraft:levels_squared" => { + (level * level) as f32 + v["added"].as_f64().unwrap_or(0.) as f32 + } + "minecraft:lookup" => { + let values = v["values"].as_array().map_or(&[][..], Vec::as_slice); + match values.get((level - 1).max(0) as usize) { + Some(x) if level >= 1 => x.as_f64().unwrap_or(0.) as f32, + _ => level_value(&v["fallback"], level), + } + } + _ => 0., + }, + _ => 0., + } +} +/// `MinMaxBounds.Ints.matches` (a number or `{min, max}`). +fn int_bounds(v: &Value, value: i32) -> bool { + match v { + Value::Null => true, + Value::Number(n) => n.as_i64() == Some(i64::from(value)), + Value::Object(o) => { + o.get("min") + .and_then(Value::as_i64) + .is_none_or(|m| i64::from(value) >= m) + && o.get("max") + .and_then(Value::as_i64) + .is_none_or(|m| i64::from(value) <= m) + } + _ => false, + } } fn load_dir(dir: &Path, prefix: &str, out: &mut HashMap) -> io::Result<()> { @@ -150,11 +289,25 @@ impl LootData { weight: e["weight"].as_i64().unwrap_or(1) as i32, min_cost: cost(&e["min_cost"]), max_cost: cost(&e["max_cost"]), + slots: e["slots"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect(), + effects: e["effects"].clone(), } }) .collect(); let mut tags = HashMap::new(); - for registry in ["item", "enchantment", "instrument"] { + for registry in [ + "item", + "enchantment", + "instrument", + "entity_type", + "damage_type", + ] { let mut raw = HashMap::new(); load_dir(&data.join("tags").join(registry), "", &mut raw)?; for (name, value) in raw { @@ -162,6 +315,20 @@ impl LootData { tags.insert((registry.to_owned(), name), values); } } + let mut recipes = HashMap::new(); + load_dir(&data.join("recipe"), "", &mut recipes)?; + let mut ids: Vec<&String> = recipes.keys().collect(); + ids.sort(); + let smelting = ids + .into_iter() + .map(|id| &recipes[id]) + .filter(|r| r["type"] == "minecraft:smelting") + .filter_map(|r| { + let result = r["result"]["id"].as_str()?.to_owned(); + let count = r["result"]["count"].as_i64().unwrap_or(1) as i32; + Some((r["ingredient"].clone(), result, count)) + }) + .collect(); Ok(Self { tables, modifiers, @@ -169,11 +336,82 @@ impl LootData { items, enchantments, tags, + smelting, }) } pub fn has_table(&self, table: &str) -> bool { self.tables.contains_key(table) } + /// The table's `random_sequence` (where `getRandomItems` draws from). + pub fn random_sequence(&self, table: &str) -> Option<&str> { + self.tables.get(table)?["random_sequence"].as_str() + } + pub fn max_stack(&self, item: &str) -> i32 { + self.facts(item).max_stack + } + pub fn max_damage(&self, item: &str) -> i32 { + self.facts(item).max_damage + } + /// Whether a registry tag (`entity_type`, `damage_type`, `item`...) holds `id`. + pub fn in_tag(&self, registry: &str, tag: &str, id: &str) -> bool { + self.tag(registry, tag).iter().any(|m| m == id) + } + /// `EnchantmentHelper.getEnchantmentLevel(enchantment, entity)`: the best + /// level on the items in the enchantment's slots. + pub fn enchantment_level(&self, enchantment: &str, entity: &LootEntity) -> i32 { + let Some(e) = self.enchantments.iter().find(|e| e.name == enchantment) else { + return 0; + }; + if !entity.living { + return 0; + } + EQUIPMENT_SLOTS + .iter() + .filter(|slot| e.slots.iter().any(|g| slot_in_group(slot, g))) + .filter_map(|slot| entity.item(slot)) + .map(|stack| item_level(stack, enchantment)) + .max() + .unwrap_or(0) + } + /// Whether an item carries an enchantment with `prevent_equipment_drop`. + pub fn prevents_equipment_drop(&self, stack: &LootStack) -> bool { + stack.enchantments.iter().any(|(name, _)| { + self.enchantments.iter().any(|e| { + &e.name == name && !e.effects["minecraft:prevent_equipment_drop"].is_null() + }) + }) + } + /// `EnchantmentHelper.processEquipmentDropChance`: the victim's and the + /// attacker's `equipment_drops` effects (Looting) applied to `chance`. + pub fn equipment_drop_chance(&self, params: &EntityLootParams, chance: f32) -> f32 { + // Enchantment.damageContext: no luck and no killing player. + let damage_params = EntityLootParams { + this: params.this.clone(), + damage: params.damage.clone(), + player: None, + luck: 0.0, + }; + let mut c = Context { + data: self, + random: LegacyRandom::new(0), + biome: None, + visited: Vec::new(), + luck: 0.0, + open_water: None, + entity: Some(&damage_params), + }; + let mut chance = chance; + c.equipment_drops(¶ms.this, "victim", &mut chance); + if let Some(attacker) = params + .damage + .as_ref() + .and_then(|d| d.source.as_ref()) + .filter(|a| a.living) + { + c.equipment_drops(attacker, "attacker", &mut chance); + } + chance + } /// Tag members in tag order (nested tags expanded in place, duplicates /// dropped). fn tag(&self, registry: &str, name: &str) -> Vec { @@ -246,12 +484,54 @@ impl LootData { visited: Vec::new(), luck, open_water, + entity: None, }; let mut items = Vec::new(); c.table_raw(table, json, &mut |_, stack| items.push(stack)); *random = c.random; items } + /// LootTable.getRandomItems for an entity context: the generated stacks + /// after the stack splitter, in order. `random` is the table's random + /// sequence (or the level random) and is advanced. + pub fn roll_entity( + &self, + table: &str, + random: &mut R, + params: &EntityLootParams, + ) -> Vec { + let Some(json) = self.tables.get(table) else { + return Vec::new(); + }; + let mut c = Context { + data: self, + random: random.clone(), + biome: None, + visited: Vec::new(), + luck: params.luck, + open_water: None, + entity: Some(params), + }; + let mut items = Vec::new(); + c.table_raw(table, json, &mut |c, stack| c.data.split(stack, &mut items)); + *random = c.random; + items + } + /// LootTable.createStackSplitter (every item is enabled). + fn split(&self, stack: LootStack, items: &mut Vec) { + let max = self.facts(&stack.item).max_stack.max(1); + if stack.count < max { + items.push(stack); + } else { + let mut count = stack.count; + while count > 0 { + let mut copy = stack.clone(); + copy.count = max.min(count); + count -= copy.count; + items.push(copy); + } + } + } /// LootTable.fill into an empty container of `slots` slots with /// `RandomSource.create(seed)`; `biome` is the container's biome for /// location checks (None: no origin, checks fail). @@ -273,23 +553,10 @@ impl LootData { visited: Vec::new(), luck: 0.0, open_water: None, + entity: None, }; let mut items = Vec::new(); - c.table_raw(table, json, &mut |c, stack| { - // LootTable.createStackSplitter (every item is enabled). - let max = c.data.facts(&stack.item).max_stack.max(1); - if stack.count < max { - items.push(stack); - } else { - let mut count = stack.count; - while count > 0 { - let mut copy = stack.clone(); - copy.count = max.min(count); - count -= copy.count; - items.push(copy); - } - } - }); + c.table_raw(table, json, &mut |c, stack| c.data.split(stack, &mut items)); let random = &mut c.random; let mut available: Vec = (0..slots).collect(); shuffle(&mut available, random); @@ -302,15 +569,23 @@ impl LootData { } } +/// The level of one enchantment on a stack (its `enchantments` component). +fn item_level(stack: &LootStack, enchantment: &str) -> i32 { + stack + .enchantments + .iter() + .find(|(n, _)| n == enchantment) + .map_or(0, |(_, l)| *l) +} /// Util.shuffle. -fn shuffle(list: &mut [T], random: &mut LegacyRandom) { +fn shuffle(list: &mut [T], random: &mut impl RandomSource) { for i in (2..=list.len()).rev() { let j = random.next_int_bound(i as i32).unwrap_or(0) as usize; list.swap(i - 1, j); } } /// Mth.nextInt. -fn next_int(random: &mut LegacyRandom, min: i32, max: i32) -> i32 { +fn next_int(random: &mut impl RandomSource, min: i32, max: i32) -> i32 { if min >= max { min } else { @@ -353,19 +628,136 @@ fn shuffle_and_split(result: &mut Vec, slots: usize, random: &mut Leg shuffle(result, random); } -struct Context<'a> { +struct Context<'a, R> { data: &'a LootData, - random: LegacyRandom, + random: R, biome: Option<&'a str>, visited: Vec, /// LootContext.getLuck. luck: f32, /// A fishing hook's `is_open_water` for `entity_properties` (None: no entity). open_water: Option, + /// The entity, damage source and killer parameters. + entity: Option<&'a EntityLootParams>, } -type Sink<'s> = dyn FnMut(&mut Context<'_>, LootStack) + 's; +type Sink<'s, R> = dyn FnMut(&mut Context<'_, R>, LootStack) + 's; -impl Context<'_> { +impl Context<'_, R> { + /// A `LootContext.EntityTarget` parameter. + fn target(&self, name: &str) -> Option<&LootEntity> { + let p = self.entity?; + match name { + "this" => Some(&p.this), + "attacker" => p.damage.as_ref()?.source.as_ref(), + "direct_attacker" => p.damage.as_ref()?.direct.as_ref(), + "attacking_player" => p.player.as_ref(), + _ => None, + } + } + /// The `ATTACKING_ENTITY` parameter when it is a living entity. + fn living_attacker(&self) -> Option<&LootEntity> { + self.target("attacker").filter(|a| a.living) + } + /// The `equipment_drops` effects on one entity's equipment + /// (`runIterationOnEquipment`), for the given `enchanted` target. + fn equipment_drops(&mut self, holder: &LootEntity, enchanted: &str, chance: &mut f32) { + let data = self.data; + for slot in EQUIPMENT_SLOTS { + let Some(stack) = holder.item(slot) else { + continue; + }; + for (name, level) in &stack.enchantments { + let Some(e) = data.enchantments.iter().find(|e| &e.name == name) else { + continue; + }; + if !e.slots.iter().any(|g| slot_in_group(slot, g)) { + continue; + } + for effect in e.effects["minecraft:equipment_drops"] + .as_array() + .into_iter() + .flatten() + { + if effect["enchanted"].as_str() != Some(enchanted) + || effect["affected"].as_str().unwrap_or("victim") != "victim" + { + continue; + } + if !effect["requirements"].is_null() && !self.condition(&effect["requirements"]) { + continue; + } + let value = level_value(&effect["effect"]["value"], *level); + *chance = match effect["effect"]["type"].as_str().unwrap_or("") { + "minecraft:add" => *chance + value, + "minecraft:multiply" => *chance * value, + "minecraft:set" => value, + _ => *chance, + }; + } + } + } + } + /// EntityPredicate.matches (false without an entity). + fn entity_matches(&self, p: &Value, e: Option<&LootEntity>) -> bool { + let Some(e) = e else { return false }; + let Some(parts) = p.as_object() else { + return true; + }; + let data = self.data; + parts.iter().all(|(key, v)| match key.as_str() { + "minecraft:entity_type" => match v.as_str() { + Some(s) => match s.strip_prefix('#') { + Some(tag) => data.in_tag("entity_type", tag, &e.kind), + None => s == e.kind, + }, + None => v + .as_array() + .is_some_and(|a| a.iter().any(|x| x.as_str() == Some(&e.kind))), + }, + "minecraft:flags" => v.as_object().into_iter().flatten().all(|(flag, want)| { + let want = want.as_bool().unwrap_or(false); + match flag.as_str() { + "is_on_fire" => e.on_fire == want, + // EntityFlagsPredicate: only living entities have an age. + "is_baby" => !e.living || e.baby == want, + "is_fall_flying" => !e.living || !want, + _ => !want, + } + }), + "minecraft:equipment" => { + e.living + && v.as_object().into_iter().flatten().all(|(slot, item)| { + e.item(slot) + .is_some_and(|stack| self.item_matches(item, stack)) + }) + } + "minecraft:components" => v.as_object().into_iter().flatten().all(|(c, want)| { + match c.as_str() { + "minecraft:sheep/color" => e + .sheep + .as_ref() + .is_some_and(|(color, _)| want.as_str() == Some(color)), + "minecraft:frog/variant" => { + e.frog_variant.is_some() && want.as_str() == e.frog_variant.as_deref() + } + _ => false, + } + }), + "minecraft:type_specific/sheep" => e.sheep.as_ref().is_some_and(|(_, sheared)| { + v["sheared"].as_bool().is_none_or(|w| w == *sheared) + }), + "minecraft:type_specific/cube_mob" => { + e.cube_size.is_some_and(|size| int_bounds(&v["size"], size)) + } + // RaiderPredicate: no raid is running here. + "minecraft:type_specific/raider" => e.captain.is_some_and(|captain| { + !v["has_raid"].as_bool().unwrap_or(false) + && captain == v["is_captain"].as_bool().unwrap_or(false) + }), + "minecraft:vehicle" => self.entity_matches(v, e.vehicle.as_deref()), + _ => false, + }) + } fn int(&mut self, v: &Value) -> i32 { match v { Value::Number(n) => n.as_i64().unwrap_or(0) as i32, @@ -426,16 +818,62 @@ impl Context<'_> { .into_iter() .flatten() .any(|t| self.condition(t)), + "minecraft:entity_properties" if self.entity.is_some() => { + let target = self.target(c["entity"].as_str().unwrap_or("this")); + c["predicate"].is_null() || self.entity_matches(&c["predicate"], target) + } // FishingHookPredicate: the only entity property a hook has. "minecraft:entity_properties" => { - let fishing = &c["predicate"]["type_specific"]; - match (self.open_water, fishing["type"].as_str()) { - (Some(open), Some("minecraft:fishing_hook")) => fishing["in_open_water"] + let predicate = &c["predicate"]; + let fishing = &predicate["minecraft:type_specific/fishing_hook"]; + let only_hook = predicate.as_object().is_some_and(|o| o.len() == 1); + match self.open_water { + Some(open) if only_hook && fishing.is_object() => fishing["in_open_water"] .as_bool() .is_none_or(|want| want == open), _ => false, } } + "minecraft:killed_by_player" => self.entity.is_some_and(|p| p.player.is_some()), + "minecraft:random_chance_with_enchanted_bonus" => { + let level = self.living_attacker().map_or(0, |a| { + data.enchantment_level(c["enchantment"].as_str().unwrap_or(""), a) + }); + let chance = if level > 0 { + level_value(&c["enchanted_chance"], level) + } else { + c["unenchanted_chance"].as_f64().unwrap_or(0.) as f32 + }; + self.random.next_float() < chance + } + // DamageSourcePredicate (false without a damage source). + "minecraft:damage_source_properties" => { + let Some(damage) = self.entity.and_then(|p| p.damage.as_ref()) else { + return false; + }; + let p = &c["predicate"]; + let tags_ok = p["tags"].as_array().into_iter().flatten().all(|t| { + let id = t["id"].as_str().unwrap_or(""); + let has = match id.strip_prefix('#') { + Some(tag) => data.in_tag("damage_type", tag, &damage.kind), + None => id == damage.kind, + }; + has == t["expected"].as_bool().unwrap_or(false) + }); + tags_ok + && (p["direct_entity"].is_null() + || self.entity_matches(&p["direct_entity"], damage.direct.as_ref())) + && (p["source_entity"].is_null() + || self.entity_matches(&p["source_entity"], damage.source.as_ref())) + && p["is_direct"].as_bool().is_none_or(|want| { + let direct = match (&damage.source, &damage.direct) { + (Some(a), Some(b)) => a.kind == b.kind, + (None, None) => true, + _ => false, + }; + direct == want + }) + } "minecraft:random_chance" => { let chance = self.float(&c["chance"]); self.random.next_float() < chance @@ -489,7 +927,7 @@ impl Context<'_> { } "minecraft:set_count" => { let base = if f["add"].as_bool() == Some(true) { - stack.count + stack.get_count() } else { 0 }; @@ -497,12 +935,14 @@ impl Context<'_> { } "minecraft:limit_count" => { let limit = &f["limit"]; + let mut count = stack.get_count(); if let Some(min) = limit["min"].as_i64() { - stack.count = stack.count.max(min as i32); + count = count.max(min as i32); } if let Some(max) = limit["max"].as_i64() { - stack.count = stack.count.min(max as i32); + count = count.min(max as i32); } + stack.count = count; } "minecraft:set_damage" => { let max = data.facts(&stack.item).max_damage; @@ -611,19 +1051,74 @@ impl Context<'_> { stack = self.modify(branch, stack); } "minecraft:discard" => stack.count = 0, + "minecraft:enchanted_count_increase" => { + if let Some(attacker) = self.living_attacker() { + let level = + data.enchantment_level(f["enchantment"].as_str().unwrap_or(""), attacker); + if level != 0 { + let addition = level as f32 * self.float(&f["count"]); + // ItemStack.grow(Math.round(addition)). + stack.count = stack.get_count() + (addition + 0.5).floor() as i32; + let limit = f["limit"].as_i64().unwrap_or(0) as i32; + if limit > 0 && !stack.is_empty() && stack.count > limit { + stack.count = limit; + } + } + } + } + "minecraft:furnace_smelt" => { + if !stack.is_empty() + && let Some((_, result, count)) = data + .smelting + .iter() + .find(|(ingredient, _, _)| data.item_in(&stack.item, ingredient)) + { + let input = if f["use_input_count"].as_bool().unwrap_or(true) { + stack.count + } else { + 1 + }; + let mut smelted = LootStack::new(result); + smelted.count = (input * count).min(data.facts(result).max_stack); + stack = smelted; + } + } // Names, lore, components and other data without random draws. _ => {} } stack } - /// ItemPredicate subset used by filtered modifiers. + /// ItemPredicate subset used by filtered modifiers and equipment. fn item_matches(&self, p: &Value, stack: &LootStack) -> bool { if !p["items"].is_null() && !self.data.item_in(&stack.item, &p["items"]) { return false; } + if !int_bounds(&p["count"], stack.count) { + return false; + } if p["predicates"].get("minecraft:map_id").is_some() && !stack.map { return false; } + // EnchantmentsPredicate: every entry must hold. + if let Some(list) = p["predicates"]["minecraft:enchantments"].as_array() { + let data = self.data; + let ok = list.iter().all(|e| { + let levels = &e["levels"]; + match &e["enchantments"] { + Value::Null => stack + .enchantments + .iter() + .any(|(_, l)| int_bounds(levels, *l)), + set => data.holder_set("enchantment", set).iter().any(|name| { + let level = item_level(stack, name); + level != 0 && int_bounds(levels, level) + }), + } + }); + if !ok { + return false; + } + } true } /// EnchantmentHelper.selectEnchantment. @@ -662,7 +1157,7 @@ impl Context<'_> { if available.is_empty() { return results; } - let pick = |random: &mut LegacyRandom, list: &[(usize, i32)]| -> Option<(usize, i32)> { + let pick = |random: &mut R, list: &[(usize, i32)]| -> Option<(usize, i32)> { let total: i32 = list.iter().map(|&(i, _)| data.enchantments[i].weight).sum(); if total <= 0 { return None; @@ -702,7 +1197,7 @@ impl Context<'_> { .contains(&ea.name) } /// LootTable.getRandomItemsRaw. - fn table_raw(&mut self, name: &str, table: &Value, sink: &mut Sink<'_>) { + fn table_raw(&mut self, name: &str, table: &Value, sink: &mut Sink<'_, R>) { if self.visited.iter().any(|v| v == name) { return; } @@ -729,14 +1224,15 @@ impl Context<'_> { self.visited.pop(); } /// LootPool.addRandomItem. - fn add_random_item(&mut self, pool: &Value, sink: &mut Sink<'_>) { - let mut valid: Vec<&Value> = Vec::new(); + fn add_random_item(&mut self, pool: &Value, sink: &mut Sink<'_, R>) { + let mut valid: Vec> = Vec::new(); for entry in pool["entries"].as_array().into_iter().flatten() { self.expand(entry, &mut valid); } // EntryBase.getWeight: max(floor(weight + quality * luck), 0). let luck = self.luck; - let weight = |e: &Value| { + let weight = |c: &Choice<'_>| { + let e = c.entry; let w = e["weight"].as_i64().unwrap_or(1) as f32 + e["quality"].as_i64().unwrap_or(0) as f32 * luck; w.floor().max(0.0) as i32 @@ -746,21 +1242,21 @@ impl Context<'_> { return; } let chosen = if valid.len() == 1 { - valid[0] + valid.swap_remove(0) } else { let mut index = self.random.next_int_bound(total).unwrap_or(0); - let Some(e) = valid.iter().find(|e| { + let Some(at) = valid.iter().position(|e| { index -= weight(e); index < 0 }) else { return; }; - e + valid.swap_remove(at) }; - self.create(chosen, sink); + self.create(&chosen, sink); } /// LootPoolEntryContainer.expand: the singleton entries that can run. - fn expand<'v>(&mut self, entry: &'v Value, out: &mut Vec<&'v Value>) -> bool { + fn expand<'v>(&mut self, entry: &'v Value, out: &mut Vec>) -> bool { if !entry["condition"].is_null() && !self.condition(&entry["condition"]) { return false; } @@ -783,17 +1279,35 @@ impl Context<'_> { } "minecraft:item" | "minecraft:empty" | "minecraft:loot_table" => { if entry["weight"].as_i64().unwrap_or(1) > 0 { - out.push(entry); + out.push(Choice { entry, item: None }); } true } + // TagEntry: one choice per item when expanded, else one for all. + "minecraft:tag" => { + if entry["expand"].as_bool().unwrap_or(false) { + let items = self.data.holder_set("item", &entry["items"]); + for item in items { + if entry["weight"].as_i64().unwrap_or(1) > 0 { + out.push(Choice { entry, item: Some(item) }); + } + } + true + } else { + if entry["weight"].as_i64().unwrap_or(1) > 0 { + out.push(Choice { entry, item: None }); + } + true + } + } _ => false, } } /// LootPoolEntry.createItemStack with the entry's modifier. - fn create(&mut self, entry: &Value, sink: &mut Sink<'_>) { + fn create(&mut self, choice: &Choice<'_>, sink: &mut Sink<'_, R>) { + let entry = choice.entry; let modifier = &entry["modifier"]; - let mut out = |c: &mut Context<'_>, stack: LootStack| { + let mut out = |c: &mut Context<'_, R>, stack: LootStack| { let stack = c.modify(modifier, stack); sink(c, stack); }; @@ -802,6 +1316,14 @@ impl Context<'_> { let stack = LootStack::new(entry["name"].as_str().unwrap_or("minecraft:air")); out(self, stack); } + "minecraft:tag" => match &choice.item { + Some(item) => out(self, LootStack::new(item)), + None => { + for item in self.data.holder_set("item", &entry["items"]) { + out(self, LootStack::new(&item)); + } + } + }, "minecraft:loot_table" => match &entry["value"] { Value::String(name) => { if let Some(table) = self.data.tables.get(name) { @@ -815,6 +1337,11 @@ impl Context<'_> { } } } +/// A pool entry that can be chosen (an expanded tag entry names its item). +struct Choice<'v> { + entry: &'v Value, + item: Option, +} fn enchant(stack: &mut LootStack, name: &str, level: i32) { match stack.enchantments.iter_mut().find(|(n, _)| n == name) { Some(slot) => slot.1 = level, diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityDeathLootOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityDeathLootOracle.java new file mode 100644 index 000000000..bffe88e56 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityDeathLootOracle.java @@ -0,0 +1,320 @@ +package dev.horizonlab.parity; + +import com.mojang.authlib.GameProfile; +import java.io.PrintWriter; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import java.util.function.Predicate; +import net.minecraft.SharedConstants; +import net.minecraft.core.*; +import net.minecraft.core.component.DataComponents; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.RegistryDataLoader; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.Bootstrap; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.ReloadableServerRegistries; +import net.minecraft.server.ReloadableServerResources; +import net.minecraft.server.RegistryLayer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.packs.PackType; +import net.minecraft.server.packs.repository.ServerPacksSource; +import net.minecraft.server.packs.resources.MultiPackResourceManager; +import net.minecraft.tags.TagLoader; +import net.minecraft.util.RandomSource; +import net.minecraft.world.DifficultyInstance; +import net.minecraft.world.RandomSequences; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.damagesource.DamageSources; +import net.minecraft.world.entity.*; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.DyeColor; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.entity.EntityTypeTest; +import net.minecraft.world.level.gamerules.GameRules; +import net.minecraft.world.level.levelgen.WorldGenSettings; +import net.minecraft.world.level.levelgen.WorldOptions; +import net.minecraft.world.phys.AABB; + +/** + * Original oracle: entity death drops. Each input line describes a victim, its + * equipment and state, a killer and a damage source; the oracle creates the + * real entities on a stand-in ServerLevel (whose addFreshEntity records the + * spawned item entities and experience orbs) and runs LivingEntity.die's drop + * step: the source entity's killedEntity hook, then dropAllDeathLoot (loot + * table with the world's random sequence, dropCustomDeathLoot with the entity + * random, dropEquipment, dropExperience). Loot table randoms come from a fresh + * RandomSequences per case; each case kills `kills` identical victims in turn. + */ +public final class VanillaEntityDeathLootOracle { + static Object unsafe; + static Method allocate, putObject, objectFieldOffset; + + static Object alloc(Class c) throws Exception { return allocate.invoke(unsafe, c); } + + static void put(Object target, Class owner, String field, Object value) throws Exception { + Field f = owner.getDeclaredField(field); + long offset = (long) objectFieldOffset.invoke(unsafe, f); + putObject.invoke(unsafe, target, offset, value); + } + + static final class Lvl extends ServerLevel { + Lvl() { super(null, null, null, null, null, null, false, 0L, List.of(), false); } + MinecraftServer fake; + RegistryAccess registries; + GameRules rules; + List out; + int next = 1; + @Override public MinecraftServer getServer() { return fake; } + @Override public RegistryAccess registryAccess() { return registries; } + @Override public net.minecraft.world.Difficulty getDifficulty() { return net.minecraft.world.Difficulty.NORMAL; } + @Override public long getGameTime() { return 0L; } + @Override public int getNextEntityId() { return next++; } + @Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags(); } + @Override public GameRules getGameRules() { return rules; } + @Override public boolean addFreshEntity(Entity entity) { + if (entity instanceof ItemEntity item) out.add("drop " + stack(item.getItem())); + else if (entity instanceof ExperienceOrb orb) out.add("orb " + orb.getValue()); + else out.add("entity " + BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType())); + return true; + } + @Override public List getEntities(EntityTypeTest type, AABB bb, Predicate selector) { return new ArrayList<>(); } + net.minecraft.world.attribute.EnvironmentAttributeSystem attributes; + @Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { return attributes; } + @Override public int getSeaLevel() { return 63; } + @Override public net.minecraft.world.entity.raid.Raid getRaidAt(BlockPos pos) { return null; } + @Override public net.minecraft.world.level.BlockGetter getChunkForCollisions(int chunkX, int chunkZ) { return null; } + @Override public List getEntityCollisions(Entity source, AABB area) { return List.of(); } + @Override public DifficultyInstance getCurrentDifficultyAt(BlockPos pos) { return new DifficultyInstance(net.minecraft.world.Difficulty.NORMAL, 0L, 0L, 0.0F); } + } + + static final class OraclePlayer extends Player { + OraclePlayer(Level level) { super(level, new GameProfile(new UUID(1L, 2L), "oracle")); } + @Override public GameType gameMode() { return GameType.SURVIVAL; } + @Override public net.minecraft.world.item.component.ResolvableProfile getProfile() { return net.minecraft.world.item.component.ResolvableProfile.createResolved(this.getGameProfile()); } + } + + static String stack(ItemStack stack) { + StringBuilder line = new StringBuilder(BuiltInRegistries.ITEM.getKey(stack.getItem()) + " " + stack.getCount()); + if (stack.getDamageValue() != 0) line.append(" damage=").append(stack.getDamageValue()); + var enchantments = stack.getOrDefault(DataComponents.ENCHANTMENTS, net.minecraft.world.item.enchantment.ItemEnchantments.EMPTY); + for (var e : enchantments.entrySet()) line.append(" ench=").append(e.getKey().unwrapKey().get().identifier()).append(':').append(e.getIntValue()); + var potion = stack.get(DataComponents.POTION_CONTENTS); + if (potion != null && potion.potion().isPresent()) line.append(" potion=").append(potion.potion().get().unwrapKey().get().identifier()); + var ominous = stack.get(DataComponents.OMINOUS_BOTTLE_AMPLIFIER); + if (ominous != null) line.append(" ominous=").append(ominous.value()); + return line.toString(); + } + + static Map parse(String line) { + Map m = new LinkedHashMap<>(); + for (String token : line.trim().split("\\s+")) { + int eq = token.indexOf('='); + if (eq < 0) m.put("name", token); else m.put(token.substring(0, eq), token.substring(eq + 1)); + } + return m; + } + + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); + unsafeField.setAccessible(true); + unsafe = unsafeField.get(null); + allocate = unsafe.getClass().getMethod("allocateInstance", Class.class); + putObject = unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class); + objectFieldOffset = unsafe.getClass().getMethod("objectFieldOffset", Field.class); + + var repo = ServerPacksSource.createVanillaTrustedRepository(); + repo.reload(); + repo.setSelected(List.of("vanilla")); + var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected()); + var layers = RegistryLayer.createRegistryAccess(); + var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC)); + var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags); + RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join(); + var worldLayers = layers.replaceFrom(RegistryLayer.WORLD, world); + var loaded = ReloadableServerRegistries.reload(worldLayers, staticTags, resources, Runnable::run).join(); + HolderLookup.Provider lookup = loaded.lookupWithUpdatedTags(); + var components = BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(lookup); + staticTags.forEach(Registry.PendingTags::apply); + components.forEach(net.minecraft.core.component.DataComponentInitializers.PendingComponents::apply); + RegistryAccess access = loaded.layers().compositeAccess(); + + // A server that only answers reloadableRegistries, getRandomSequence and debug subscribers. + MinecraftServer server = (MinecraftServer) alloc(net.minecraft.server.dedicated.DedicatedServer.class); + put(server, MinecraftServer.class, "debugSubscribers", alloc(net.minecraft.util.debug.ServerDebugSubscribers.class)); + ReloadableServerResources managers = (ReloadableServerResources) alloc(ReloadableServerResources.class); + put(managers, ReloadableServerResources.class, "fullRegistryHolder", new ReloadableServerRegistries.Holder(lookup)); + Class holderRecord = Class.forName("net.minecraft.server.MinecraftServer$ReloadableResources"); + Constructor rr = holderRecord.getDeclaredConstructors()[0]; + rr.setAccessible(true); + put(server, MinecraftServer.class, "resources", rr.newInstance(null, managers)); + var recipes = new net.minecraft.world.item.crafting.RecipeManager(lookup); + recipes.finalizeRecipeLoading(net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags()); + put(managers, ReloadableServerResources.class, "recipes", recipes); + put(server, MinecraftServer.class, "scoreboard", new net.minecraft.server.ServerScoreboard(server)); + + Lvl level = (Lvl) alloc(Lvl.class); + level.fake = server; + level.registries = access; + put(level, ServerLevel.class, "server", server); + level.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().build(); + level.rules = new GameRules(net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags()); + put(level, Level.class, "damageSources", new DamageSources(access)); + put(level, Level.class, "random", RandomSource.create(0L)); + Method dropAll = LivingEntity.class.getDeclaredMethod("dropAllDeathLoot", ServerLevel.class, DamageSource.class); + dropAll.setAccessible(true); + var enchantments = access.lookupOrThrow(Registries.ENCHANTMENT); + + if (args.length > 2 && args[2].equals("facts")) { + // Per-type facts the death step reads (a debugging aid, not compared). + Field xp = Mob.class.getDeclaredField("xpReward"); + xp.setAccessible(true); + try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) { + for (var type : BuiltInRegistries.ENTITY_TYPE) { + Entity e; + try { e = type.create(level, EntitySpawnReason.LOAD); } catch (Throwable t) { continue; } + if (!(e instanceof Mob mob)) continue; + StringBuilder sb = new StringBuilder(BuiltInRegistries.ENTITY_TYPE.getKey(type).toString()); + sb.append(" monster=").append(e instanceof net.minecraft.world.entity.monster.Monster).append(" xp=").append(xp.get(mob)) + .append(" baby=").append(mob.isBaby()).append(" class=").append(e.getClass().getSimpleName()) + .append(" animal=").append(e instanceof net.minecraft.world.entity.animal.Animal) + .append(" agwater=").append(e instanceof net.minecraft.world.entity.animal.AgeableWaterCreature) + .append(" water=").append(e instanceof net.minecraft.world.entity.animal.fish.WaterAnimal) + .append(" ageable=").append(e instanceof AgeableMob); + mob.setBaby(true); + sb.append(" canbaby=").append(mob.isBaby()); + for (EquipmentSlot slot : EquipmentSlot.VALUES) if (mob.getDropChances().byEquipment(slot) != 0.085F) sb.append(' ').append(slot.getName()).append('=').append(mob.getDropChances().byEquipment(slot)); + w.println(sb); + } + } + System.exit(0); + } + List lines = Files.readAllLines(Path.of(args[0])); + try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) { + for (String raw : lines) { + if (raw.isBlank() || raw.startsWith("#")) continue; + Map c = parse(raw); + w.println("== " + c.get("name")); + List out = new ArrayList<>(); + level.out = out; + try { + long worldSeed = Long.parseLong(c.getOrDefault("seed", "0")); + put(server, MinecraftServer.class, "worldGenSettings", new WorldGenSettings(new WorldOptions(worldSeed, false, false), null)); + put(server, MinecraftServer.class, "randomSequences", new RandomSequences()); + int kills = Integer.parseInt(c.getOrDefault("kills", "1")); + long rand = Long.parseLong(c.getOrDefault("rand", "0")); + for (int k = 0; k < kills; k++) { + out.add("kill " + k); + run(level, access, enchantments, c, rand + k, dropAll); + } + } catch (Throwable t) { + Throwable cause = t instanceof InvocationTargetException ite ? ite.getCause() : t; + StringBuilder trace = new StringBuilder("error " + cause); + if (System.getenv("ORACLE_TRACE") != null) for (var frame : cause.getStackTrace()) trace.append("\n at ").append(frame); + out.add(trace.toString()); + } + out.forEach(w::println); + } + } + System.exit(0); + } + + static ItemStack item(HolderLookup.RegistryLookup enchantments, String spec) { + // id[;enchantment:level...] + String[] parts = spec.split(";"); + ItemStack stack = new ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.parse(parts[0]))); + for (int i = 1; i < parts.length; i++) { + int colon = parts[i].lastIndexOf(':'); + String name = parts[i].substring(0, colon); + if (!name.contains(":")) name = "minecraft:" + name; + stack.enchant(enchantments.getOrThrow(ResourceKey.create(Registries.ENCHANTMENT, Identifier.parse(name))), Integer.parseInt(parts[i].substring(colon + 1))); + } + return stack; + } + + static Entity create(Lvl level, String id) { + EntityType type = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(id)); + return type.create(level, EntitySpawnReason.LOAD); + } + + @SuppressWarnings("unchecked") + static void run(Lvl level, RegistryAccess access, HolderLookup.RegistryLookup enchantments, + Map c, long rand, Method dropAll) throws Exception { + LivingEntity victim = (LivingEntity) create(level, c.get("type")); + victim.setPos(0.5, 64.0, 0.5); + if (c.containsKey("baby") && victim instanceof Mob mob) mob.setBaby(c.get("baby").equals("1")); + if (c.getOrDefault("fire", "0").equals("1")) victim.setRemainingFireTicks(100); + if (c.containsKey("size")) victim.getClass().getMethod("setSize", int.class, boolean.class).invoke(victim, Integer.parseInt(c.get("size")), true); + if (c.containsKey("color") && victim instanceof net.minecraft.world.entity.animal.sheep.Sheep sheep) sheep.setColor(DyeColor.byName(c.get("color"), DyeColor.WHITE)); + if (c.getOrDefault("sheared", "0").equals("1") && victim instanceof net.minecraft.world.entity.animal.sheep.Sheep sheep) sheep.setSheared(true); + if (c.getOrDefault("leader", "0").equals("1")) ((net.minecraft.world.entity.monster.PatrollingMonster) victim).setPatrolLeader(true); + if (c.getOrDefault("captain", "0").equals("1")) + victim.setItemSlot(EquipmentSlot.HEAD, net.minecraft.world.entity.raid.Raid.getOminousBannerInstance(access.lookupOrThrow(Registries.BANNER_PATTERN))); + for (EquipmentSlot slot : EquipmentSlot.VALUES) { + String spec = c.get(slot.getName()); + if (spec != null) victim.setItemSlot(slot, item(enchantments, spec)); + String chance = c.get("chance_" + slot.getName()); + if (chance != null && victim instanceof Mob mob) mob.setDropChance(slot, Float.parseFloat(chance)); + } + if (c.containsKey("vehicle")) { + Entity vehicle = create(level, c.get("vehicle")); + vehicle.setPos(0.5, 64.0, 0.5); + if (!victim.startRiding(vehicle, true, false)) throw new IllegalStateException("could not ride"); + } + // Killer and damage source. + Player player = null; + LivingEntity killer = null; + String killerId = c.getOrDefault("killer", "none"); + if (killerId.equals("player") || c.getOrDefault("pkill", "0").equals("1")) { + player = new OraclePlayer(level); + player.setPos(2.5, 64.0, 0.5); + if (c.containsKey("luck")) player.getAttribute(Attributes.LUCK).setBaseValue(Double.parseDouble(c.get("luck"))); + if (killerId.equals("player") && c.containsKey("weapon")) player.setItemSlot(EquipmentSlot.MAINHAND, item(enchantments, c.get("weapon"))); + } + if (killerId.equals("player")) killer = player; + else if (!killerId.equals("none")) { + killer = (LivingEntity) create(level, killerId); + killer.setPos(2.5, 64.0, 0.5); + if (c.containsKey("weapon")) killer.setItemSlot(EquipmentSlot.MAINHAND, item(enchantments, c.get("weapon"))); + if (c.containsKey("frog")) killer.setComponent(DataComponents.FROG_VARIANT, + access.lookupOrThrow(Registries.FROG_VARIANT).getOrThrow(ResourceKey.create(Registries.FROG_VARIANT, Identifier.parse(c.get("frog"))))); + if (c.getOrDefault("charged", "0").equals("1")) { + Field powered = net.minecraft.world.entity.monster.Creeper.class.getDeclaredField("DATA_IS_POWERED"); + powered.setAccessible(true); + killer.getEntityData().set((net.minecraft.network.syncher.EntityDataAccessor) powered.get(null), true); + } + } + if (player != null && c.getOrDefault("pkill", killerId.equals("player") ? "1" : "0").equals("1")) victim.setLastHurtByPlayer(player, 100); + DamageSources sources = level.damageSources(); + DamageSource source = switch (c.getOrDefault("source", "attack")) { + case "attack" -> killer == null ? sources.generic() : killer instanceof Player p ? sources.playerAttack(p) : sources.mobAttack(killer); + case "arrow" -> { + var arrow = new net.minecraft.world.entity.projectile.arrow.Arrow(EntityTypes.ARROW, level); + arrow.setPos(1.5, 64.0, 0.5); + yield sources.arrow(arrow, killer); + } + case "fireball" -> { + var fireball = new net.minecraft.world.entity.projectile.hurtingprojectile.LargeFireball(EntityTypes.FIREBALL, level); + fireball.setPos(1.5, 64.0, 0.5); + yield sources.fireball(fireball, killer); + } + case "explosion" -> sources.explosion(killer, killer); + case "lightning" -> sources.lightningBolt(); + case "fire" -> sources.onFire(); + default -> sources.generic(); + }; + victim.getRandom().setSeed(rand); + Entity sourceEntity = source.getEntity(); + if (sourceEntity == null || sourceEntity.killedEntity(level, victim, source)) dropAll.invoke(victim, level, source); + } +} diff --git a/tools/test_entity_death_loot_parity.py b/tools/test_entity_death_loot_parity.py new file mode 100644 index 000000000..ecbd2c7c8 --- /dev/null +++ b/tools/test_entity_death_loot_parity.py @@ -0,0 +1,185 @@ +#!/usr/bin/env python3 +"""Compare entity death drops (loot tables, equipment drops, experience) with vanilla. + +Java (VanillaEntityDeathLootOracle) builds the real victim, killer and damage +source on a stand-in ServerLevel and runs LivingEntity.die's drop step; Rust +(entity_death_loot_fixture) runs horizon_client::mobs::drops on the same cases. +Every living entity type with a loot table is killed by a player with and +without looting, by nothing, on fire, with a smelting weapon, as a baby, with +luck and with worn equipment, plus each table's special conditions (sheep +colours, cube sizes, frog kills, skeleton and charged creeper kills, fireballs, +lightning, raid captains and vehicles). Loot draws come from the world's random +sequences; several victims are killed in turn per case. +""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + +# Living entity types with an entity loot table that the corpus skips: players +# and stands are not mobs, the dragon dies over 200 ticks, and the giant and +# the copper golem are not Horizon mob types. +SKIPPED = {'player', 'mannequin', 'armor_stand', 'ender_dragon', 'giant', 'copper_golem'} +# Types Horizon keeps body armour for in the head slot: their corpus wears +# body items instead of helmets. +BODY = {'horse', 'donkey', 'mule', 'skeleton_horse', 'zombie_horse', 'camel', 'camel_husk', 'llama', 'trader_llama', + 'happy_ghast', 'nautilus', 'zombie_nautilus', 'sulfur_cube'} +WEAPONS = ['minecraft:iron_sword', 'minecraft:diamond_sword;looting:1', 'minecraft:diamond_sword;looting:2', + 'minecraft:netherite_sword;looting:3', 'minecraft:golden_sword;fire_aspect:2', 'minecraft:diamond_axe;looting:3;fire_aspect:1'] +ARMOUR = {'head': 'minecraft:iron_helmet', 'chest': 'minecraft:chainmail_chestplate', 'legs': 'minecraft:golden_leggings', + 'feet': 'minecraft:diamond_boots', 'mainhand': 'minecraft:iron_sword', 'offhand': 'minecraft:shield'} +DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', + 'blue', 'brown', 'green', 'red', 'black'] + + +def corpus(types): + rng = random.Random(0x4C4F4F54) + cases = [] + + def add(name, **kv): + kv.setdefault('seed', rng.randrange(-2**63, 2**63)) + kv.setdefault('rand', rng.randrange(-2**47, 2**47)) + cases.append(name + ''.join(f' {k}={v}' for k, v in kv.items())) + for t in types: + n = t.split(':')[1] + add(f'{n}-player', type=t, killer='player', weapon='minecraft:iron_sword', kills=4) + add(f'{n}-none', type=t, source='generic', kills=3) + add(f'{n}-mob', type=t, killer='minecraft:spider', kills=2) + for i, weapon in enumerate(WEAPONS[1:]): + add(f'{n}-weapon{i}', type=t, killer='player', weapon=weapon, kills=4) + add(f'{n}-fire', type=t, killer='player', fire=1, kills=3) + add(f'{n}-fire-nokill', type=t, fire=1, source='fire', kills=2) + add(f'{n}-baby', type=t, killer='player', baby=1, weapon='minecraft:iron_sword;looting:3', kills=3) + add(f'{n}-luck', type=t, killer='player', luck=rng.choice([1, 2, 5]), kills=3) + add(f'{n}-arrow', type=t, killer='player', source='arrow', weapon='minecraft:bow;looting:3', kills=2) + head = 'body' if n in BODY else 'head' + armour = dict(ARMOUR) + if n in BODY: + armour['body'] = armour.pop('head').replace('helmet', 'horse_armor') + add(f'{n}-gear', type=t, killer='player', weapon='minecraft:iron_sword;looting:3', kills=6, **armour) + add(f'{n}-gear-plain', type=t, killer='player', kills=6, mainhand='minecraft:stone_axe', chance_mainhand=0.5, + **{head: 'minecraft:leather_helmet', f'chance_{head}': 2.0}) + add(f'{n}-gear-nokill', type=t, source='generic', kills=4, feet='minecraft:iron_boots', chance_feet=1.0, + **{head: 'minecraft:carved_pumpkin', f'chance_{head}': 2.0}) + add(f'{n}-gear-mob', type=t, killer='minecraft:skeleton', source='arrow', kills=4, feet='minecraft:iron_boots', chance_feet=1.0, + weapon='minecraft:bow;looting:3') + for color in DYES: + add(f'sheep-{color}', type='minecraft:sheep', color=color, killer='player', kills=3) + add(f'sheep-{color}-sheared', type='minecraft:sheep', color=color, sheared=1, killer='player', kills=2) + for cube in ['minecraft:slime', 'minecraft:magma_cube', 'minecraft:sulfur_cube']: + for size in [1, 2, 3, 4]: + add(f'{cube[10:]}-size{size}', type=cube, size=size, killer='player', weapon='minecraft:iron_sword;looting:2', kills=4) + for frog in ['temperate', 'warm', 'cold']: + for size in [1, 2, 4]: + add(f'magma_cube-frog-{frog}-{size}', type='minecraft:magma_cube', size=size, killer='minecraft:frog', frog='minecraft:' + frog, + pkill=rng.choice([0, 1]), kills=3) + add('creeper-skeleton', type='minecraft:creeper', killer='minecraft:skeleton', source='arrow', pkill=1, kills=3) + add('creeper-stray', type='minecraft:creeper', killer='minecraft:stray', source='arrow', kills=2) + for victim in ['zombie', 'skeleton', 'creeper', 'wither_skeleton', 'piglin', 'zombie_villager', 'cow']: + add(f'charged-{victim}', type='minecraft:' + victim, killer='minecraft:creeper', charged=1, source='explosion', kills=2) + add(f'uncharged-{victim}', type='minecraft:' + victim, killer='minecraft:creeper', source='explosion', kills=2) + add('ghast-fireball', type='minecraft:ghast', killer='player', source='fireball', kills=4) + add('ghast-fireball-ghast', type='minecraft:ghast', killer='minecraft:ghast', source='fireball', kills=2) + add('turtle-lightning', type='minecraft:turtle', source='lightning', kills=3) + add('turtle-lightning-player', type='minecraft:turtle', source='lightning', pkill=1, kills=3) + add('pillager-captain', type='minecraft:pillager', captain=1, leader=1, killer='player', kills=3) + add('pillager-captain-none', type='minecraft:pillager', captain=1, leader=1, source='generic', kills=2) + add('pillager-captain-looting', type='minecraft:pillager', captain=1, leader=1, killer='player', + weapon='minecraft:iron_sword;looting:3', kills=4, chance_head=2.0) + add('pillager-banner-only', type='minecraft:pillager', captain=1, killer='player', kills=3) + add('pillager-leader-only', type='minecraft:pillager', leader=1, killer='player', kills=2) + add('vindicator-captain', type='minecraft:vindicator', captain=1, leader=1, killer='player', kills=2) + for animal in ['pig', 'strider', 'horse', 'camel', 'donkey']: + add(f'{animal}-saddle', type='minecraft:' + animal, saddle='minecraft:saddle', chance_saddle=2.0, killer='player', kills=2) + add(f'{animal}-saddle-default', type='minecraft:' + animal, saddle='minecraft:saddle', killer='player', kills=6) + add('zombie-horse', type='minecraft:zombie', vehicle='minecraft:zombie_horse', killer='player', kills=4) + add('zombie-baby-chicken', type='minecraft:zombie', baby=1, vehicle='minecraft:chicken', killer='player', kills=3) + add('zombie-baby-chicken-none', type='minecraft:zombie', baby=1, vehicle='minecraft:chicken', source='generic', kills=2) + add('husk-camel', type='minecraft:husk', vehicle='minecraft:camel_husk', killer='player', kills=3) + for weapon in WEAPONS: + add('wither-' + weapon.split(';')[-1].replace(':', ''), type='minecraft:wither', killer='player', weapon=weapon, kills=2) + return cases + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--prepare', action='store_true') + args = parser.parse_args() + build = lab.LOCAL / 'rust-entity-death-loot-parity' + build.mkdir(parents=True, exist_ok=True) + if args.prepare: + lab.prepare() + lock, jars, libraries = base.verify_artifacts() + resources = lab.LOCAL / 'horizon-client/26.3' + tables = resources / 'data/minecraft/loot_table/entities' + types = sorted('minecraft:' + p.stem for p in tables.glob('*.json') if p.stem not in SKIPPED) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityDeathLootOracle.java' + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/entity_death_loot_fixture.rs', + lab.ROOT / 'crates/horizon-client/src/mobs/drops.rs', lab.ROOT / 'crates/horizon-world/src/loot.rs'] + tested = base.source_hashes(sources) + inputs = build / 'inputs.txt' + cases = corpus(types) + inputs.write_text(''.join(line + '\n' for line in cases), encoding='utf-8') + classes = build / 'classes' + classes.mkdir(exist_ok=True) + deps = os.pathsep.join(map(str, libraries)) + + def run(command, name): + with (build / (name + '.log')).open('w', encoding='utf-8') as log: + base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT) + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'), + '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') + run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), + 'dev.horizonlab.parity.VanillaEntityDeathLootOracle', inputs, build / 'server.txt'], 'server') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'entity_death_loot_fixture'], 'compile-rust') + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release/examples/entity_death_loot_fixture' + run([binary, resources, inputs, build / 'rust.txt'], 'rust') + errors = [l for l in (build / 'server.txt').read_text().splitlines() if l.startswith('error ')] + if errors: + raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}') + try: + matched = base.compare(build / 'server.txt', build / 'rust.txt') + except AssertionError as error: + raise SystemExit(str(error) + explain(build)) from None + base.ensure_sources_unchanged(sources, tested) + lab.write_json(build / 'report.json', { + 'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'cases': len(cases), + 'types': len(types), 'skipped': sorted(SKIPPED), 'matched_output_lines': matched, 'sources_sha256': tested, + 'scope': 'LivingEntity.dropAllDeathLoot after the killer\'s killedEntity hook: entity loot tables under the world random ' + 'sequence, Mob.dropCustomDeathLoot equipment drops and durability, species death loot, experience orbs.'}) + print(f'{len(cases):,} death-drop cases over {len(types)} entity types match vanilla ({matched:,} lines)') + + +def explain(build): + def sections(path): + out, name = {}, None + for line in path.read_text(encoding='utf-8', errors='replace').splitlines(): + if line.startswith('== '): + name = line[3:] + out[name] = [] + elif name is not None: + out[name].append(line) + return out + left, right = sections(build / 'server.txt'), sections(build / 'rust.txt') + bad = [n for n in left if left[n] != right.get(n)] + report = f'\n{len(bad)} differing cases' + for name in bad[:30]: + a, b = left[name], right.get(name, []) + diffs = [(x, y) for x, y in zip(a, b) if x != y][:3] + if len(a) != len(b): + diffs.append((f'<{len(a)} lines>', f'<{len(b)} lines>')) + report += f'\n {name}: {diffs}' + return report + + +if __name__ == '__main__': + main() From 9e4811dd6eb4d2982b7b343c2e414d1036c0d55d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:57:02 +0200 Subject: [PATCH 16/28] Compare the ambient sound handlers tick by tick with vanilla LocalPlayer The oracle runs the real updateIsUnderwater, UnderwaterAmbientSoundHandler and BiomeAmbientSoundsHandler over the real SoundEngine, comparing every level random draw, loop fade, mood sample and playing instance. Co-Authored-By: Claude Opus 5.5 --- .../examples/ambient_fixture.rs | 161 +++++++++++++ crates/horizon-client/src/ambience.rs | 8 + .../parity/VanillaAmbientOracle.java | 216 ++++++++++++++++++ tools/test_ambient_sound_parity.py | 168 ++++++++++++++ 4 files changed, 553 insertions(+) create mode 100644 crates/horizon-client/examples/ambient_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAmbientOracle.java create mode 100644 tools/test_ambient_sound_parity.py diff --git a/crates/horizon-client/examples/ambient_fixture.rs b/crates/horizon-client/examples/ambient_fixture.rs new file mode 100644 index 000000000..70a50fd87 --- /dev/null +++ b/crates/horizon-client/examples/ambient_fixture.rs @@ -0,0 +1,161 @@ +//! Replays `tools/test_ambient_sound_parity.py` scripts through Horizon's +//! ambient sound handlers over its `SoundEngine`: +//! `ambient_fixture ROOT INPUT OUTPUT`. +#[path = "audio_common/mod.rs"] +mod common; +use common::{Fake, d, f, flush}; +use horizon_client::ambience::{Ambience, AmbientContext, AmbientSounds, Mood}; +use horizon_client::sound_engine::{Bound, SoundEngine, TickContext, Ticking}; +use horizon_client::sound_events::{SoundRegistry, normalize}; +use horizon_core::random::RandomSource; +use std::io::Write; + +/// The oracle's scripted brightness. +fn light(mode: i32, x: i32, y: i32, z: i32) -> (u8, u8) { + let h = x.wrapping_mul(73856093) ^ y.wrapping_mul(19349663) ^ z.wrapping_mul(83492791); + let u = h as u32; + match mode { + 0 => (15, 0), + 1 => (0, 0), + 2 => (0, ((u >> 4) & 15) as u8), + _ => ( + if h & 3 == 0 { ((u >> 8) & 15) as u8 } else { 0 }, + ((u >> 12) & 15) as u8, + ), + } +} + +fn sounds(a: &[&str]) -> AmbientSounds { + AmbientSounds { + r#loop: (a[1] != "-").then(|| normalize(a[1])), + mood: (a[2] != "-").then(|| { + let m: Vec<&str> = a[2].split(',').collect(); + Mood { + sound: normalize(m[0]), + tick_delay: m[1].parse().expect("delay"), + block_search_extent: m[2].parse().expect("extent"), + offset: d(m[3]), + } + }), + additions: a[3..] + .iter() + .map(|s| { + let p: Vec<&str> = s.split(',').collect(); + (normalize(p[0]), d(p[1])) + }) + .collect(), + } +} + +fn main() { + let args: Vec = std::env::args().collect(); + let mut engine = SoundEngine::new(SoundRegistry::load(std::path::Path::new(&args[1]))); + engine.listening = true; + let mut backend = Fake::default(); + let mut ambience = Ambience::new(0); + let mut current = AmbientSounds::default(); + let (mut position, mut eye, mut eye_in_water, mut spectator, mut removed, mut mode) = + ([0.0f64; 3], 0.0f32, false, false, false, 0); + let input = std::fs::read_to_string(&args[2]).expect("input"); + let mut out = std::io::BufWriter::new(std::fs::File::create(&args[3]).expect("output")); + for line in input.lines() { + writeln!(out, "{line}").expect("write"); + let a: Vec<&str> = line.split(' ').collect(); + match a[0] { + "start" => { + engine.stop_all(&mut backend); + ambience.clear(&mut Bound { + engine: &mut engine, + backend: &mut backend, + }); + ambience = Ambience::new(a[1].parse().expect("seed")); + current = AmbientSounds::default(); + (position, eye, eye_in_water, spectator, removed, mode) = + ([0.0; 3], 0.0, false, false, false, 0); + } + "sounds" => current = sounds(&a), + "player" => { + position = [d(a[1]), d(a[2]), d(a[3])]; + eye = f(a[4]); + eye_in_water = a[5] == "1"; + spectator = a[6] == "1"; + removed = a[7] == "1"; + mode = a[8].parse().expect("mode"); + } + "volume" => { + let source: usize = a[1].parse().expect("source"); + engine.source_volumes[source] = f(a[2]); + engine.refresh_category_volume(source, &mut backend); + } + "tick" => { + let light = |b: [i32; 3]| light(mode, b[0], b[1], b[2]); + let ctx = AmbientContext { + sounds: ¤t, + position, + eye_y: position[1] + f64::from(eye), + underwater: eye_in_water, + spectator, + light: &light, + }; + ambience.tick( + &ctx, + &mut Bound { + engine: &mut engine, + backend: &mut backend, + }, + ); + let tick = TickContext { + player_underwater: ambience.was_underwater(), + player_removed: removed, + }; + engine.tick(false, &tick, &mut backend); + } + _ => panic!("{line}"), + } + writeln!( + out, + " rand={} mood={:08x} underwater={} delay={}", + ambience.random.clone().next_long(), + ambience.moodiness.to_bits(), + ambience.was_underwater(), + ambience.underwater_delay() + ) + .expect("write"); + for (event, id) in ambience.loops() { + let i = engine.instance(*id).expect("loop"); + let Ticking::BiomeLoop { fade, direction } = i.ticking else { + panic!("loop kind"); + }; + writeln!( + out, + " loop {event} fade={fade} direction={direction} stopped={} active={}", + i.stopped, + engine.is_active(*id) + ) + .expect("write"); + } + let mut playing: Vec = engine + .active_instances() + .into_iter() + .map(|id| { + let i = engine.instance(id).expect("instance"); + format!( + " playing {} volume={:08x} looping={} relative={} at={:016x},{:016x},{:016x} stopped={}", + i.identifier, + i.volume.to_bits(), + i.looping, + i.relative, + i.position[0].to_bits(), + i.position[1].to_bits(), + i.position[2].to_bits(), + i.tickable() && i.stopped + ) + }) + .collect(); + playing.sort(); + for p in playing { + writeln!(out, "{p}").expect("write"); + } + flush(&mut engine, &mut out); + } +} diff --git a/crates/horizon-client/src/ambience.rs b/crates/horizon-client/src/ambience.rs index 860a080a6..e6014cedc 100644 --- a/crates/horizon-client/src/ambience.rs +++ b/crates/horizon-client/src/ambience.rs @@ -128,6 +128,14 @@ impl Ambience { pub fn was_underwater(&self) -> bool { self.was_underwater } + /// `BiomeAmbientSoundsHandler.loopSounds`. + pub fn loops(&self) -> &[(String, InstanceId)] { + &self.loops + } + /// `UnderwaterAmbientSoundHandler.tickDelay`. + pub fn underwater_delay(&self) -> i32 { + self.underwater_delay + } /// A new player (leaving or changing worlds): fresh handlers. pub fn clear(&mut self, sounds: &mut impl Sounds) { for (_, id) in self.loops.drain(..) { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAmbientOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAmbientOracle.java new file mode 100644 index 000000000..af8b82be6 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAmbientOracle.java @@ -0,0 +1,216 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.lang.reflect.Method; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.Camera; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.resources.sounds.*; +import net.minecraft.client.sounds.ChannelAccess; +import net.minecraft.client.sounds.SoundEngine; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; +import net.minecraft.resources.Identifier; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.tags.FluidTags; +import net.minecraft.tags.TagKey; +import net.minecraft.util.RandomSource; +import net.minecraft.world.attribute.*; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LightLayer; +import net.minecraft.world.level.material.Fluid; +import net.minecraft.world.phys.Vec3; + +/** + * Runs the local player's real ambient sound path over the real SoundEngine + * (VanillaSoundRig): LocalPlayer.updateIsUnderwater (enter/exit sounds through + * ClientLevel.playLocalSound and the UnderLiquidAmbientSoundInstance), the + * UnderwaterAmbientSoundHandler and the BiomeAmbientSoundsHandler, then + * SoundManager.tick, once per client tick. Inputs: the AMBIENT_SOUNDS value + * (a constant attribute layer), the player's position, eye height, whether + * its eyes are in water, spectator and removed flags, and the level's sky and + * block brightness (a hash of the position). Prints the level random's next + * long (without drawing it), the handlers' state and every playing instance. + */ +public final class VanillaAmbientOracle { + public static final class Actor extends LocalPlayer { + boolean eyeInWater, spectator; + + Actor() { + super(null, null, null, null, null, null, false, null, null); + } + + @Override + public boolean isEyeInFluid(final TagKey type) { + return type == FluidTags.WATER && eyeInWater; + } + + @Override + public boolean isSpectator() { + return spectator; + } + } + + public static final class Lvl extends ClientLevel { + int mode; + + Lvl() { + super(null, null, null, null, 0, 0, null, false, 0L, 0); + } + + @Override + public int getBrightness(final LightLayer layer, final BlockPos pos) { + return light(mode, pos.getX(), pos.getY(), pos.getZ())[layer == LightLayer.SKY ? 0 : 1]; + } + } + + /** The scripted brightness: (sky, block) for a light mode and block. */ + static int[] light(int mode, int x, int y, int z) { + int h = x * 73856093 ^ y * 19349663 ^ z * 83492791; + return switch (mode) { + case 0 -> new int[]{15, 0}; + case 1 -> new int[]{0, 0}; + case 2 -> new int[]{0, (h >>> 4) & 15}; + default -> new int[]{(h & 3) == 0 ? (h >>> 8) & 15 : 0, (h >>> 12) & 15}; + }; + } + + static float f(String hex) { + return Float.intBitsToFloat(Integer.parseUnsignedInt(hex, 16)); + } + + static double d(String hex) { + return Double.longBitsToDouble(Long.parseUnsignedLong(hex, 16)); + } + + static Holder event(String id) { + return Holder.direct(SoundEvent.createVariableRangeEvent(Identifier.parse(id))); + } + + /** "loop|- mood|- addition..." with mood "sound,delay,extent,offsetbits" and additions "sound,chancebits". */ + static AmbientSounds sounds(String[] a) { + Optional> loop = a[1].equals("-") ? Optional.empty() : Optional.of(event(a[1])); + Optional mood = Optional.empty(); + if (!a[2].equals("-")) { + String[] m = a[2].split(","); + mood = Optional.of(new AmbientMoodSettings(event(m[0]), Integer.parseInt(m[1]), Integer.parseInt(m[2]), d(m[3]))); + } + var additions = new ArrayList(); + for (int i = 3; i < a.length; i++) { + String[] p = a[i].split(","); + additions.add(new AmbientAdditionsSettings(event(p[0]), d(p[1]))); + } + return new AmbientSounds(loop, mood, additions); + } + + /** LegacyRandomSource's next nextLong(), read from its state. */ + static long peek(RandomSource random) throws Exception { + long s = ((java.util.concurrent.atomic.AtomicLong) VanillaSoundRig.get(random, + Class.forName("net.minecraft.world.level.levelgen.LegacyRandomSource"), "seed")).get(); + long m = 0x5DEECE66DL, mask = (1L << 48) - 1; + long s1 = (s * m + 0xBL) & mask; + long s2 = (s1 * m + 0xBL) & mask; + return ((long) (int) (s1 >>> 16) << 32) + (int) (s2 >>> 16); + } + + static String bits(double v) { + return String.format("%016x", Double.doubleToRawLongBits(v)); + } + + @SuppressWarnings("unchecked") + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + var rig = new VanillaSoundRig(Path.of(args[0])); + var mc = VanillaSoundRig.make(Minecraft.class); + VanillaSoundRig.set(mc, Minecraft.class, "soundManager", rig.manager); + var renderer = VanillaSoundRig.make(GameRenderer.class); + VanillaSoundRig.set(renderer, GameRenderer.class, "mainCamera", VanillaSoundRig.make(Camera.class)); + VanillaSoundRig.set(VanillaSoundRig.get(renderer, GameRenderer.class, "mainCamera"), Camera.class, "position", Vec3.ZERO); + VanillaSoundRig.set(mc, Minecraft.class, "gameRenderer", renderer); + Method update = LocalPlayer.class.getDeclaredMethod("updateIsUnderwater"); + update.setAccessible(true); + var instanceToChannel = VanillaSoundRig.field(SoundEngine.class, "instanceToChannel"); + Lvl level = null; + Actor actor = null; + UnderwaterAmbientSoundHandler underwater = null; + BiomeAmbientSoundsHandler biome = null; + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2])))) { + for (String line : Files.readAllLines(Path.of(args[1]))) { + out.println(line); + String[] a = line.split(" "); + switch (a[0]) { + case "start" -> { + // A new level and player: fresh handlers on a seeded level random. + rig.manager.stop(); + level = VanillaSoundRig.make(Lvl.class); + VanillaSoundRig.set(level, Level.class, "random", RandomSource.create(Long.parseLong(a[1]))); + VanillaSoundRig.set(level, ClientLevel.class, "minecraft", mc); + VanillaSoundRig.set(level, ClientLevel.class, "environmentAttributes", EnvironmentAttributeSystem.builder().build()); + actor = VanillaSoundRig.make(Actor.class); + VanillaSoundRig.set(actor, Entity.class, "level", level); + VanillaSoundRig.set(actor, Entity.class, "position", Vec3.ZERO); + VanillaSoundRig.set(actor, LocalPlayer.class, "minecraft", mc); + underwater = new UnderwaterAmbientSoundHandler(actor, rig.manager); + biome = new BiomeAmbientSoundsHandler(actor, rig.manager); + } + case "sounds" -> { + AmbientSounds value = sounds(a); + var system = EnvironmentAttributeSystem.builder() + .addConstantLayer(EnvironmentAttributes.AMBIENT_SOUNDS, base -> value) + .build(); + VanillaSoundRig.set(level, ClientLevel.class, "environmentAttributes", system); + } + case "player" -> { + // player x y z eyeHeight eyeInWater spectator removed lightMode + VanillaSoundRig.set(actor, Entity.class, "position", new Vec3(d(a[1]), d(a[2]), d(a[3]))); + VanillaSoundRig.set(actor, Entity.class, "eyeHeight", f(a[4])); + actor.eyeInWater = a[5].equals("1"); + actor.spectator = a[6].equals("1"); + VanillaSoundRig.set(actor, Entity.class, "removalReason", a[7].equals("1") ? Entity.RemovalReason.DISCARDED : null); + level.mode = Integer.parseInt(a[8]); + } + case "volume" -> { + rig.volume(SoundSource.values()[Integer.parseInt(a[1])], f(a[2])); + rig.manager.refreshCategoryVolume(SoundSource.values()[Integer.parseInt(a[1])]); + } + case "tick" -> { + update.invoke(actor); + underwater.tick(); + biome.tick(); + rig.manager.tick(false); + } + default -> throw new IllegalArgumentException(line); + } + out.printf(" rand=%d mood=%08x underwater=%s delay=%d%n", peek(level.getRandom()), Float.floatToRawIntBits(biome.getMoodiness()), + actor.isUnderWater(), (int) VanillaSoundRig.get(underwater, UnderwaterAmbientSoundHandler.class, "tickDelay")); + var loops = (Map, BiomeAmbientSoundsHandler.LoopSoundInstance>) VanillaSoundRig.get(biome, + BiomeAmbientSoundsHandler.class, "loopSounds"); + for (var e : loops.entrySet()) { + var loop = e.getValue(); + out.printf(" loop %s fade=%d direction=%d stopped=%s active=%s%n", e.getKey().value().location(), + (int) VanillaSoundRig.get(loop, BiomeAmbientSoundsHandler.LoopSoundInstance.class, "fade"), + (int) VanillaSoundRig.get(loop, BiomeAmbientSoundsHandler.LoopSoundInstance.class, "fadeDirection"), loop.isStopped(), + rig.manager.isActive(loop)); + } + var playing = new ArrayList(); + for (SoundInstance i : ((Map) instanceToChannel.get(rig.engine)).keySet()) { + float volume = (float) VanillaSoundRig.get(i, AbstractSoundInstance.class, "volume"); + playing.add(String.format(" playing %s volume=%08x looping=%s relative=%s at=%s,%s,%s stopped=%s", i.getIdentifier(), + Float.floatToRawIntBits(volume), i.isLooping(), i.isRelative(), bits(i.getX()), bits(i.getY()), bits(i.getZ()), + i instanceof TickableSoundInstance t && t.isStopped())); + } + Collections.sort(playing); + for (String p : playing) out.println(p); + rig.flush(out); + } + } + System.exit(0); + } +} diff --git a/tools/test_ambient_sound_parity.py b/tools/test_ambient_sound_parity.py new file mode 100644 index 000000000..8fffae013 --- /dev/null +++ b/tools/test_ambient_sound_parity.py @@ -0,0 +1,168 @@ +#!/usr/bin/env python3 +"""Compare the local player's ambient sounds with the vanilla 26.3 client. + +The oracle runs the real `LocalPlayer.updateIsUnderwater` (enter/exit sounds +seeded from the level random, the `UnderLiquidAmbientSoundInstance`), +`UnderwaterAmbientSoundHandler` and `BiomeAmbientSoundsHandler` over the real +`SoundEngine` (see VanillaSoundRig), then `SoundManager.tick`, once per client +tick. The `AMBIENT_SOUNDS` value (loops, moods and additions from the biomes +and dimensions of the data pack plus faster custom moods), the player's +position, eye height, eyes in water, spectator and removed flags and the +level's brightness are script inputs. Every step prints the level random's +next long (so every draw is compared), moodiness, the underwater state and +delay, the handler's loop instances (fade, direction, stopped, active), each +playing instance and the subtitle notifications. Horizon's `Ambience` and +`SoundEngine` replay the scripts. +""" +import json +import random +import struct + +try: + from . import audio_harness as h +except ImportError: + import audio_harness as h + + +def dbits(v): + return struct.pack('>d', v).hex() + + +def settings(): + """Every AMBIENT_SOUNDS value in the data pack.""" + data = h.RESOURCES / 'data/minecraft' + values = [] + for path in sorted(list((data / 'worldgen/biome').glob('*.json')) + list((data / 'dimension_type').glob('*.json'))): + v = json.loads(path.read_text()).get('attributes', {}).get('minecraft:audio/ambient_sounds') + if v is None: + continue + additions = v.get('additions', []) + if isinstance(additions, dict): + additions = [additions] + mood = v.get('mood') + values.append(dict(loop=v.get('loop'), mood=None if mood is None else (mood['sound'], mood['tick_delay'], mood['block_search_extent'], mood['offset']), + additions=[(a['sound'], a['tick_chance']) for a in additions])) + return values + + +class Script: + def __init__(self): + self.lines = [] + + def add(self, *parts): + self.lines.append(' '.join(map(str, parts))) + + def sounds(self, value): + mood = '-' if value['mood'] is None else '{},{},{},{}'.format(value['mood'][0], value['mood'][1], value['mood'][2], dbits(value['mood'][3])) + self.add('sounds', value['loop'] or '-', mood, *[f'{s},{dbits(c)}' for s, c in value['additions']]) + + def player(self, at=(0.5, 64.0, 0.5), eye=1.62, water=0, spectator=0, removed=0, mode=0): + self.add('player', *map(dbits, at), h.bits(eye), water, spectator, removed, mode) + + def tick(self, n=1): + for _ in range(n): + self.add('tick') + + +def scripted(s, values): + by_loop = [v for v in values if v['loop']] + cave = next(v for v in values if v['mood'] and v['mood'][0] == 'minecraft:ambient.cave' and not v['loop']) + s.add('start', 1) + s.sounds(cave) + s.player(mode=1) + s.tick(6100) + s.player((100.25, -20.0, -7.75), mode=2) + s.tick(400) + s.player((3.5, 12.0, 3.5), mode=3) + s.tick(400) + # Biome loops cross-fading, back and forth. + s.add('start', 2) + for v in by_loop: + s.sounds(v) + s.tick(30) + s.sounds(by_loop[0]) + s.tick(20) + s.sounds(by_loop[1]) + s.tick(5) + s.sounds(by_loop[0]) + s.tick(60) + s.sounds(dict(loop=None, mood=None, additions=[])) + s.tick(60) + # Water: enter, the loop's fade, sub-sounds, exit, re-entering mid-fade, spectators. + s.add('start', 3) + s.sounds(cave) + s.player(water=1, mode=0) + s.tick(300) + s.player(water=0) + s.tick(10) + s.player(water=1) + s.tick(3) + s.player(water=0) + s.tick(2) + s.player(water=1) + s.tick(60) + s.player(water=1, spectator=1) + s.tick(5) + s.player(water=0, spectator=1) + s.tick(5) + s.player(water=1, removed=1) + s.tick(5) + s.player(water=0) + s.tick(25) + # Silent ambient category: loops never start and linger. + s.add('start', 4) + s.add('volume', 8, h.bits(0.0)) + s.sounds(by_loop[0]) + s.tick(50) + s.add('volume', 8, h.bits(1.0)) + s.sounds(by_loop[1]) + s.tick(50) + s.sounds(by_loop[0]) + s.tick(50) + + +def fuzz(s, rng, values, steps): + s.add('start', rng.getrandbits(63)) + for _ in range(steps): + op = rng.random() + if op < 0.05: + v = rng.choice(values + [dict(loop=None, mood=None, additions=[])]) + if rng.random() < 0.5 and v['mood']: + v = dict(v, mood=(v['mood'][0], rng.choice([20, 60, 150]), rng.choice([1, 4, 8, 16]), rng.choice([0.0, 2.0, 5.5]))) + s.sounds(v) + elif op < 0.12: + at = (rng.uniform(-3e4, 3e4) if rng.random() < 0.2 else rng.uniform(-200, 200), rng.uniform(-64, 320), rng.uniform(-200, 200)) + s.player(at, rng.choice([1.62, 1.27, 0.4, 0.2]), int(rng.random() < 0.4), int(rng.random() < 0.05), int(rng.random() < 0.03), rng.randrange(4)) + elif op < 0.13: + s.add('volume', rng.choice([0, 8]), h.bits(rng.choice([0.0, 1.0, 0.5]))) + else: + s.tick(rng.randrange(1, 40)) + + +def fixtures(): + values = settings() + s = Script() + scripted(s, values) + rng = random.Random(0x414d4249) + for _ in range(40): + fuzz(s, rng, values, 150) + return s.lines + + +def main(): + lines = fixtures() + matched, report = h.run_harness( + 'ambient', 'VanillaAmbientOracle', 'ambient_fixture', ''.join(l + '\n' for l in lines), + extra_sources=[h.lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java', + h.lab.ROOT / 'crates/horizon-client/src/ambience.rs', + h.lab.ROOT / 'crates/horizon-client/examples/audio_common/mod.rs'], + java_args=[h.RESOURCES], rust_args=[h.RESOURCES], + scope='Real LocalPlayer.updateIsUnderwater, UnderwaterAmbientSoundHandler and BiomeAmbientSoundsHandler (loop cross-fades, additions, ' + 'cave mood sampling, moodiness and the mood sound position) with UnderLiquidAmbientSoundInstance/UnderLiquidSubSound/LoopSoundInstance ' + 'ticking in the real SoundEngine: every level random draw, handler state, playing instance and notification per tick. The ' + 'AMBIENT_SOUNDS value, eyes-in-water state and brightness are inputs. BubbleColumnAmbientSoundHandler is not compared.') + print(f'{matched:,} ambient lines match the pinned client ({len(lines):,} steps): {report}', flush=True) + + +if __name__ == '__main__': + main() From d088140c0d2b0a4cda495160258cd85f4f437a6a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:02:40 +0200 Subject: [PATCH 17/28] Compare beacon beams with BeaconRenderer Move the beam geometry into block_entity_render::beacon_beam so the block entity render harness can replay it against vanilla submit calls (positions, UVs and colours of the solid beam and glow per section). Co-Authored-By: Claude Opus 5.5 --- .../examples/block_entity_render_fixture.rs | 46 +++++++++- .../horizon-client/src/block_entity_render.rs | 86 +++++++++++++++++++ crates/horizon-client/src/game/beacon.rs | 83 +++--------------- .../VanillaBlockEntityRenderOracle.java | 10 +++ tools/test_block_entity_render_parity.py | 21 ++++- 5 files changed, 169 insertions(+), 77 deletions(-) diff --git a/crates/horizon-client/examples/block_entity_render_fixture.rs b/crates/horizon-client/examples/block_entity_render_fixture.rs index df8a694a6..f29cebc0c 100644 --- a/crates/horizon-client/examples/block_entity_render_fixture.rs +++ b/crates/horizon-client/examples/block_entity_render_fixture.rs @@ -3,7 +3,7 @@ //! through `BlockEntityRenderer` at the block origin and writes the quads //! (texture, sprite-local UVs, baked colour, light) and sign text calls. #![forbid(unsafe_code)] -use glam::{DVec3, Mat4, Quat}; +use glam::{DVec3, Mat4, Quat, Vec3}; use horizon_client::{ assets::Assets, banner::{self, Banners}, @@ -125,6 +125,50 @@ fn main() -> Result<()> { { let case: Value = serde_json::from_str(line)?; let block = case["block"].as_str().unwrap_or_default(); + if block == "minecraft:beacon" { + // BeaconRenderer: the beam sections from the case, as Horizon's beacon keeps them. + let int = |v: &Value| v.as_i64().unwrap_or(0); + let pos = [ + int(&case["pos"][0]), + int(&case["pos"][1]), + int(&case["pos"][2]), + ]; + let partial = case["partial"].as_f64().unwrap_or(0.0) as f32; + let time = int(&case["gameTime"]).rem_euclid(40) as f32 + partial; + let cam = &case["camera"]; + let dx = cam[0].as_f64().unwrap_or(0.0) - (pos[0] as f64 + 0.5); + let dz = cam[2].as_f64().unwrap_or(0.0) - (pos[2] as f64 + 0.5); + let scale = ((dx * dx + dz * dz).sqrt() as f32 / 96.0).max(1.0); + let sections: Vec<(u32, i32)> = case["beam"] + .as_array() + .into_iter() + .flatten() + .map(|s| (int(&s[0]) as u32 & 0xFF_FFFF, int(&s[1]) as i32)) + .collect(); + let texture = "entity/beacon/beacon_beam"; + let rect = sprites.get(texture).copied().ok_or("no beam sprite")?; + let mut verts = Vec::new(); + horizon_client::block_entity_render::beacon_beam( + Vec3::ZERO, + §ions, + time, + scale, + rect, + &mut verts, + ); + let quads: Vec = verts + .chunks(4) + .map(|q| { + let v: Vec = q + .iter() + .map(|v| json!([v.pos[0], v.pos[1], v.pos[2], v.uv[0] - rect.u0, v.uv[1]])) + .collect(); + json!({"texture": texture, "v": v, "color": q[0].color, "light": q[0].light, "custom": true}) + }) + .collect(); + writeln!(out, "{}", json!({"quads": quads, "texts": []}))?; + continue; + } let Some(state) = find_state(registry, block) else { writeln!(out, "{}", json!({"skip": "unknown block state"}))?; continue; diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 1f6f805ba..4e2a7704b 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -1560,3 +1560,89 @@ mod tests { assert_eq!(out[2].uv, [0.5, 0.5]); } } + +/// `BeaconRenderer.submit`: for each beam section (ARGB colour, height) the +/// rotating solid beam and its translucent glow, the last section 2048 +/// blocks tall. `origin` is the beacon block's corner relative to the camera, +/// `time` the animation time (game time mod 40 plus partial tick) and `scale` +/// the radius scale. The sprite's v range rides in the light bytes (the +/// entity shader wraps v for layer 6). +pub fn beacon_beam( + origin: Vec3, + sections: &[(u32, i32)], + time: f32, + scale: f32, + s: Rect, + out: &mut Vec, +) { + let q = |v: f32| (v * 65535.0).round().clamp(0.0, 65535.0) as u32; + let wrap = q(s.v0) | q(s.v1 - s.v0) << 16; + let o = origin + Vec3::new(0.5, 0.0, 0.5); + let mut start = 0i32; + for (i, &(color, height)) in sections.iter().enumerate() { + let height = if i == sections.len() - 1 { + 2048 + } else { + height + }; + let end = start + height; + let scroll = if height < 0 { time } else { -time }; + let v_off = frac(scroll * 0.2 - (scroll * 0.1).floor()); + let abgr = + |a: u32| a << 24 | (color & 255) << 16 | (color >> 8 & 255) << 8 | (color >> 16 & 255); + // Solid beam: radius 0.2 * scale, rotated with time. + let r = 0.2 * scale; + let rot = glam::Mat3::from_rotation_y((time * 2.25 - 45.0).to_radians()); + let corners = [ + rot * Vec3::new(0.0, 0.0, r), + rot * Vec3::new(r, 0.0, 0.0), + rot * Vec3::new(-r, 0.0, 0.0), + rot * Vec3::new(0.0, 0.0, -r), + ]; + let v2 = -1.0 + v_off; + let v1 = height as f32 * (0.5 / r) + v2; + beam_part(out, o, start, end, corners, [v1, v2], abgr(255), s, wrap); + // Glow: radius 0.25 * scale, translucent. + let g = 0.25 * scale; + let corners = [ + Vec3::new(-g, 0.0, -g), + Vec3::new(g, 0.0, -g), + Vec3::new(-g, 0.0, g), + Vec3::new(g, 0.0, g), + ]; + let v1 = height as f32 + v2; + beam_part(out, o, start, end, corners, [v1, v2], abgr(32), s, wrap); + start = end; + } +} +/// `BeaconRenderer.renderPart`: four quads between the corners (wn, en, ws, es). +#[allow(clippy::too_many_arguments)] +fn beam_part( + out: &mut Vec, + o: Vec3, + start: i32, + end: i32, + [wn, en, ws, es]: [Vec3; 4], + [v1, v2]: [f32; 2], + color: u32, + s: Rect, + wrap: u32, +) { + for (a, b) in [(wn, en), (es, ws), (en, es), (ws, wn)] { + let at = |c: Vec3, y: i32| o + c + Vec3::new(0.0, y as f32, 0.0); + for (p, uv) in [ + (at(a, end), [s.u1, v1]), + (at(a, start), [s.u1, v2]), + (at(b, start), [s.u0, v2]), + (at(b, end), [s.u0, v1]), + ] { + out.push(Vertex { + pos: p.to_array(), + uv, + layer: 6, + color, + light: wrap, + }); + } + } +} diff --git a/crates/horizon-client/src/game/beacon.rs b/crates/horizon-client/src/game/beacon.rs index 89216e7e1..943fb9e9d 100644 --- a/crates/horizon-client/src/game/beacon.rs +++ b/crates/horizon-client/src/game/beacon.rs @@ -522,9 +522,6 @@ impl Game<'_> { else { return; }; - // The sprite's v range rides in the light bytes (entity shader overlay 6). - let q = |v: f32| (v * 65535.0).round().clamp(0.0, 65535.0) as u32; - let wrap = q(s.v0) | q(s.v1 - s.v0) << 16; let time = (self.world.game_time.rem_euclid(40)) as f32 + alpha as f32; let scoping = self.scoping(); for (k, e) in &self.world.block_entities { @@ -539,75 +536,17 @@ impl Game<'_> { } else { (distance / 96.0).max(1.0) }; - let o = (base - camera).as_vec3(); - let mut start = 0i32; - for (i, &(color, height)) in b.sections.iter().enumerate() { - let height = if i == b.sections.len() - 1 { - 2048 - } else { - height - }; - let end = start + height; - let scroll = -time; - let v_off = (scroll * 0.2 - (scroll * 0.1).floor()).rem_euclid(1.0); - let rgb = |a: u32| { - a << 24 | (color & 255) << 16 | (color >> 8 & 255) << 8 | (color >> 16 & 255) - }; - // Solid beam: radius 0.2, rotated with time. - let r = 0.2 * scale; - let rot = glam::Mat3::from_rotation_y((time * 2.25 - 45.0).to_radians()); - let corners = [ - rot * glam::Vec3::new(0.0, 0.0, r), - rot * glam::Vec3::new(r, 0.0, 0.0), - rot * glam::Vec3::new(-r, 0.0, 0.0), - rot * glam::Vec3::new(0.0, 0.0, -r), - ]; - let v2 = -1.0 + v_off; - let v1 = height as f32 * (0.5 / r) + v2; - beam_part(out, o, start, end, corners, [v1, v2], rgb(255), s, wrap); - // Glow: radius 0.25, translucent. - let g = 0.25 * scale; - let corners = [ - glam::Vec3::new(-g, 0.0, -g), - glam::Vec3::new(g, 0.0, -g), - glam::Vec3::new(-g, 0.0, g), - glam::Vec3::new(g, 0.0, g), - ]; - let v1 = height as f32 + v2; - beam_part(out, o, start, end, corners, [v1, v2], rgb(32), s, wrap); - start = end; - } - } - } -} -/// `renderPart`: four quads between the corners (wn, en, ws, es). -#[allow(clippy::too_many_arguments)] -fn beam_part( - out: &mut Vec, - o: glam::Vec3, - start: i32, - end: i32, - [wn, en, ws, es]: [glam::Vec3; 4], - [v1, v2]: [f32; 2], - color: u32, - s: horizon_client::hud::Rect, - wrap: u32, -) { - for (a, b) in [(wn, en), (es, ws), (en, es), (ws, wn)] { - let at = |c: glam::Vec3, y: i32| o + c + glam::Vec3::new(0.0, y as f32, 0.0); - for (p, uv) in [ - (at(a, end), [s.u1, v1]), - (at(a, start), [s.u1, v2]), - (at(b, start), [s.u0, v2]), - (at(b, end), [s.u0, v1]), - ] { - out.push(Vertex { - pos: p.to_array(), - uv, - layer: 6, - color, - light: wrap, - }); + let origin = (glam::DVec3::new(f64::from(k.0), f64::from(k.1), f64::from(k.2)) + - camera) + .as_vec3(); + horizon_client::block_entity_render::beacon_beam( + origin, + &b.sections, + time, + scale, + s, + out, + ); } } } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityRenderOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityRenderOracle.java index 5f42922af..7088eaab8 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityRenderOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityRenderOracle.java @@ -329,6 +329,16 @@ public final class VanillaBlockEntityRenderOracle { var cam = c.getAsJsonArray("camera"); var cameraPos = new Vec3(cam.get(0).getAsDouble(), cam.get(1).getAsDouble(), cam.get(2).getAsDouble()); var rs = (BlockEntityRenderState) renderer.createRenderState(); + if (rs instanceof BeaconRenderState beacon) { + // BeaconRenderer.extract reads Minecraft.getInstance().player (scoping); its level-free part: + BlockEntityRenderState.extractBase(be, rs, null); + beacon.animationTime = Math.floorMod(c.get("gameTime").getAsLong(), 40) + partial; + var sections = new ArrayList(); + for (var e : c.getAsJsonArray("beam")) sections.add(new BeaconRenderState.Section(e.getAsJsonArray().get(0).getAsInt(), e.getAsJsonArray().get(1).getAsInt())); + beacon.sections = sections; + float distance = (float) cameraPos.subtract(Vec3.atCenterOf(pos)).horizontalDistance(); + beacon.beamRadiusScale = Math.max(1.0F, distance / 96.0F); + } else if (rs instanceof SignRenderState sign) { // AbstractSignRenderer.extractRenderState reads Minecraft.getInstance(); its level-free part: var signBe = (SignBlockEntity) be; diff --git a/tools/test_block_entity_render_parity.py b/tools/test_block_entity_render_parity.py index 672138543..35932ba16 100644 --- a/tools/test_block_entity_render_parity.py +++ b/tools/test_block_entity_render_parity.py @@ -115,7 +115,11 @@ def cases(): for prefix in ['', 'exposed_', 'weathered_', 'oxidized_', 'waxed_']: for pose in ['standing', 'running', 'sitting', 'star']: add(f'minecraft:{prefix}copper_golem_statue[facing={rng.choice(HORIZONTAL)},copper_golem_pose={pose}]') - for block in ['end_portal', 'end_gateway', 'beacon', 'campfire[facing=north]', 'spawner', + for _ in range(8): + add('minecraft:beacon', gameTime=rng.randint(0, 10 ** 6), + camera=[rng.uniform(-300, 300), 70.0, rng.uniform(-300, 300)], + beam=[[0xFF000000 | rng.randint(0, 0xFFFFFF), rng.randint(1, 30)] for _ in range(rng.randint(1, 3))]) + for block in ['end_portal', 'end_gateway', 'campfire[facing=north]', 'spawner', 'trial_spawner', 'vault', 'suspicious_sand', 'oak_shelf[facing=east]']: add('minecraft:' + block) return out @@ -144,18 +148,20 @@ def mix(normal): def vanilla_quads(submits): quads, other = [], [] for s in submits: - if s['type'] != 'submitModel': + custom = s['type'] == 'submitCustomGeometry' + if s['type'] != 'submitModel' and not custom: other.append(s) continue verts = s['vertices'] for i in range(0, len(verts), 4): q = verts[i:i + 4] tint = q[0][3] & 0xFFFFFFFF - b = mix(q[0][8:11]) + # Custom geometry (beacon beams) is unlit; models get the entity shader's mix light. + b = 1.0 if custom else mix(q[0][8:11]) ch = lambda shift: int(((tint >> shift) & 255) * b) quads.append({'texture': s['texture'], 'v': [v[:3] + v[4:6] for v in q], 'rgb': [ch(16), ch(8), ch(0)], 'alpha': tint >> 24, 'light': q[0][7], - 'overlay': q[0][6], 'type': s['renderType']}) + 'overlay': q[0][6], 'type': s['renderType'], 'custom': custom}) return quads, other @@ -210,6 +216,13 @@ def compare_case(v, r, tol): if bad: problems.append(f'{a["texture"]} vertices {a["v"]} != {b["v"]}') break + if a['custom']: + # Horizon packs the beam sprite's v range into the light bytes (its shader wraps v). + got = b['color'] + if [got & 255, (got >> 8) & 255, (got >> 16) & 255, got >> 24] != a['rgb'] + [a['alpha']]: + problems.append(f'{a["texture"]} colour {a["rgb"]}/{a["alpha"]} != {got:#x}') + break + continue if a['overlay'] != NO_OVERLAY: problems.append(f'overlay {a["overlay"]}') got = b['color'] From b93f72c0da6b33ea1cbd42993dc6ae81b4a6b473 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:03:51 +0200 Subject: [PATCH 18/28] Play bubble column inside sounds as BubbleColumnAmbientSoundHandler does Co-Authored-By: Claude Opus 5.5 --- .../examples/ambient_fixture.rs | 26 ++++- crates/horizon-client/src/ambience.rs | 94 +++++++++++++++++-- crates/horizon-client/src/game/music.rs | 26 +++++ crates/horizon-client/src/sound_engine.rs | 1 + .../parity/VanillaAmbientOracle.java | 33 +++++++ tools/test_ambient_sound_parity.py | 36 ++++++- 6 files changed, 204 insertions(+), 12 deletions(-) diff --git a/crates/horizon-client/examples/ambient_fixture.rs b/crates/horizon-client/examples/ambient_fixture.rs index 70a50fd87..666235008 100644 --- a/crates/horizon-client/examples/ambient_fixture.rs +++ b/crates/horizon-client/examples/ambient_fixture.rs @@ -4,7 +4,7 @@ #[path = "audio_common/mod.rs"] mod common; use common::{Fake, d, f, flush}; -use horizon_client::ambience::{Ambience, AmbientContext, AmbientSounds, Mood}; +use horizon_client::ambience::{Ambience, AmbientContext, AmbientSounds, Mood, bubble_column_in}; use horizon_client::sound_engine::{Bound, SoundEngine, TickContext, Ticking}; use horizon_client::sound_events::{SoundRegistry, normalize}; use horizon_core::random::RandomSource; @@ -56,6 +56,8 @@ fn main() { let mut current = AmbientSounds::default(); let (mut position, mut eye, mut eye_in_water, mut spectator, mut removed, mut mode) = ([0.0f64; 3], 0.0f32, false, false, false, 0); + let mut height = 1.8f32; + let mut columns: Vec<([i32; 3], bool)> = Vec::new(); let input = std::fs::read_to_string(&args[2]).expect("input"); let mut out = std::io::BufWriter::new(std::fs::File::create(&args[3]).expect("output")); for line in input.lines() { @@ -72,6 +74,8 @@ fn main() { current = AmbientSounds::default(); (position, eye, eye_in_water, spectator, removed, mode) = ([0.0; 3], 0.0, false, false, false, 0); + height = 1.8; + columns.clear(); } "sounds" => current = sounds(&a), "player" => { @@ -81,6 +85,15 @@ fn main() { spectator = a[6] == "1"; removed = a[7] == "1"; mode = a[8].parse().expect("mode"); + height = f(a[9]); + columns = a[10..] + .iter() + .map(|c| { + let p: Vec<&str> = c.split(',').collect(); + let n = |i: usize| p[i].parse::().expect("column"); + ([n(0), n(1), n(2)], p[3] == "1") + }) + .collect(); } "volume" => { let source: usize = a[1].parse().expect("source"); @@ -96,6 +109,17 @@ fn main() { underwater: eye_in_water, spectator, light: &light, + bubble_column: bubble_column_in( + [ + position[0] - f64::from(0.3f32), + position[1], + position[2] - f64::from(0.3f32), + position[0] + f64::from(0.3f32), + position[1] + f64::from(height), + position[2] + f64::from(0.3f32), + ], + |b| columns.iter().find(|c| c.0 == b).map(|c| c.1), + ), }; ambience.tick( &ctx, diff --git a/crates/horizon-client/src/ambience.rs b/crates/horizon-client/src/ambience.rs index e6014cedc..f3cbeb0e1 100644 --- a/crates/horizon-client/src/ambience.rs +++ b/crates/horizon-client/src/ambience.rs @@ -3,7 +3,7 @@ //! `minecraft:audio/ambient_sounds` attribute, `UnderwaterAmbientSoundHandler` //! and `LocalPlayer.updateIsUnderwater` (enter/exit sounds and the //! `UnderLiquidAmbientSoundInstance` loop), played through the sound engine. -use crate::sound_engine::{AMBIENT, InstanceId, SoundEngine, SoundInstance, Sounds}; +use crate::sound_engine::{AMBIENT, InstanceId, PLAYERS, SoundEngine, SoundInstance, Sounds}; use horizon_core::random::{LegacyRandom, RandomSource}; use serde_json::Value; use std::{collections::HashMap, fs, path::Path}; @@ -94,6 +94,51 @@ pub struct AmbientContext<'a> { pub spectator: bool, /// `Level.getBrightness` (sky, block) at a block. pub light: &'a dyn Fn([i32; 3]) -> (u8, u8), + /// The bubble column in the player's box (its `drag` property), from + /// `bubble_column_in`. + pub bubble_column: Option, +} +/// `BubbleColumnAmbientSoundHandler`'s lookup: the first bubble column +/// (x fastest, then y, then z) in the player's bounding box inflated by +/// (0, -0.4F, 0) and deflated by 1.0E-6, as `drag_down`. `state` gives the +/// bubble column at a block (None for anything else). +pub fn bubble_column_in(bb: [f64; 6], state: impl Fn([i32; 3]) -> Option) -> Option { + // AABB keeps min <= max on every construction. + let make = |a: [f64; 6]| { + [ + a[0].min(a[3]), + a[1].min(a[4]), + a[2].min(a[5]), + a[0].max(a[3]), + a[1].max(a[4]), + a[2].max(a[5]), + ] + }; + let inflate = |b: [f64; 6], x: f64, y: f64, z: f64| { + make([b[0] - x, b[1] - y, b[2] - z, b[3] + x, b[4] + y, b[5] + z]) + }; + let b = inflate(make(bb), 0.0, f64::from(-0.4f32), 0.0); + let b = inflate(b, -1.0E-6, -1.0E-6, -1.0E-6); + let (x0, y0, z0) = ( + b[0].floor() as i32, + b[1].floor() as i32, + b[2].floor() as i32, + ); + let (x1, y1, z1) = ( + b[3].floor() as i32, + b[4].floor() as i32, + b[5].floor() as i32, + ); + for z in z0..=z1 { + for y in y0..=y1 { + for x in x0..=x1 { + if let Some(drag) = state([x, y, z]) { + return Some(drag); + } + } + } + } + None } /// The local player's ambient sound handlers. pub struct Ambience { @@ -107,6 +152,9 @@ pub struct Ambience { underwater_delay: i32, /// `LocalPlayer.wasUnderwater`. was_underwater: bool, + /// `BubbleColumnAmbientSoundHandler.wasInBubbleColumn` / `firstTick`. + was_in_bubble_column: bool, + first_tick: bool, } impl Default for Ambience { fn default() -> Self { @@ -122,6 +170,8 @@ impl Ambience { moodiness: 0.0, underwater_delay: 0, was_underwater: false, + was_in_bubble_column: false, + first_tick: true, } } /// `LocalPlayer.isUnderWater`. @@ -145,11 +195,13 @@ impl Ambience { self.moodiness = 0.0; self.underwater_delay = 0; self.was_underwater = false; + self.was_in_bubble_column = false; + self.first_tick = true; } - /// `ClientLevel.playLocalSound(x, y, z, sound, AMBIENT, 1, 1, false)`. - fn play_local(&mut self, event: &str, at: [f64; 3], sounds: &mut impl Sounds) { + /// `ClientLevel.playLocalSound(x, y, z, sound, source, 1, 1, false)`. + fn play_local(&mut self, event: &str, source: usize, at: [f64; 3], sounds: &mut impl Sounds) { let seed = self.random.next_long(); - let instance = SoundInstance::at(event, AMBIENT, 1.0, 1.0, LegacyRandom::new(seed), at); + let instance = SoundInstance::at(event, source, 1.0, 1.0, LegacyRandom::new(seed), at); sounds.play_instance(instance, false); } /// `LocalPlayer.updateIsUnderwater`, then the `ambientSoundHandlers` @@ -159,7 +211,12 @@ impl Ambience { self.was_underwater = ctx.underwater; if !ctx.spectator { if !old && ctx.underwater { - self.play_local("minecraft:ambient.underwater.enter", ctx.position, sounds); + self.play_local( + "minecraft:ambient.underwater.enter", + AMBIENT, + ctx.position, + sounds, + ); let instance = SoundInstance::under_liquid_loop( "minecraft:ambient.underwater.loop", SoundEngine::unseeded(), @@ -167,12 +224,36 @@ impl Ambience { sounds.play_instance(instance, false); } if old && !ctx.underwater { - self.play_local("minecraft:ambient.underwater.exit", ctx.position, sounds); + self.play_local( + "minecraft:ambient.underwater.exit", + AMBIENT, + ctx.position, + sounds, + ); } } self.tick_underwater(sounds); + self.tick_bubble_column(ctx, sounds); self.tick_biome(ctx, sounds); } + /// `BubbleColumnAmbientSoundHandler.tick`: entering a column plays its + /// inside sound (`LocalPlayer.playSound`, on PLAYERS). + fn tick_bubble_column(&mut self, ctx: &AmbientContext, sounds: &mut impl Sounds) { + if let Some(drag_down) = ctx.bubble_column { + if !self.was_in_bubble_column && !self.first_tick && !ctx.spectator { + let event = if drag_down { + "minecraft:block.bubble_column.whirlpool_inside" + } else { + "minecraft:block.bubble_column.upwards_inside" + }; + self.play_local(event, PLAYERS, ctx.position, sounds); + } + self.was_in_bubble_column = true; + } else { + self.was_in_bubble_column = false; + } + self.first_tick = false; + } /// `UnderwaterAmbientSoundHandler.tick`. fn tick_underwater(&mut self, sounds: &mut impl Sounds) { self.underwater_delay -= 1; @@ -317,6 +398,7 @@ mod tests { underwater, spectator: false, light, + bubble_column: None, } } diff --git a/crates/horizon-client/src/game/music.rs b/crates/horizon-client/src/game/music.rs index 699996e11..463dbce1c 100644 --- a/crates/horizon-client/src/game/music.rs +++ b/crates/horizon-client/src/game/music.rs @@ -101,6 +101,31 @@ impl Game<'_> { let l = world.light(b[0], b[1], b[2]); (l >> 4, l & 15) }; + let (half, height) = ( + f64::from(p.dimensions.width / 2.0), + f64::from(p.dimensions.height), + ); + let registry = &self.res.assets.registry; + let facts = &self.res.facts; + let bubble_column = horizon_client::ambience::bubble_column_in( + [ + feet[0] - half, + feet[1], + feet[2] - half, + feet[0] + half, + feet[1] + height, + feet[2] + half, + ], + |b| { + let state = world.block(b[0], b[1], b[2]); + (&*facts.get(state).name == "minecraft:bubble_column").then(|| { + registry + .state(state) + .and_then(|s| s.properties.get("drag")) + .is_some_and(|d| d == "true") + }) + }, + ); let ctx = horizon_client::ambience::AmbientContext { sounds: &sounds, position: feet, @@ -108,6 +133,7 @@ impl Game<'_> { underwater, spectator: self.spectator(), light: &light, + bubble_column, }; self.ambience.tick(&ctx, &mut self.audio); } diff --git a/crates/horizon-client/src/sound_engine.rs b/crates/horizon-client/src/sound_engine.rs index 2a47b5db2..288e85faf 100644 --- a/crates/horizon-client/src/sound_engine.rs +++ b/crates/horizon-client/src/sound_engine.rs @@ -17,6 +17,7 @@ use std::collections::HashMap; pub const MASTER: usize = 0; pub const MUSIC: usize = 1; pub const RECORDS: usize = 2; +pub const PLAYERS: usize = 7; pub const AMBIENT: usize = 8; pub const UI: usize = 10; /// The pool sizes `Library.init` derives from OpenAL Soft's default 255 mono diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAmbientOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAmbientOracle.java index af8b82be6..d20c5f892 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAmbientOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAmbientOracle.java @@ -24,6 +24,10 @@ import net.minecraft.world.attribute.*; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.Level; import net.minecraft.world.level.LightLayer; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.BubbleColumnBlock; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.phys.Vec3; @@ -59,6 +63,7 @@ public final class VanillaAmbientOracle { public static final class Lvl extends ClientLevel { int mode; + final Map columns = new HashMap<>(); Lvl() { super(null, null, null, null, 0, 0, null, false, 0L, 0); @@ -68,6 +73,17 @@ public final class VanillaAmbientOracle { public int getBrightness(final LightLayer layer, final BlockPos pos) { return light(mode, pos.getX(), pos.getY(), pos.getZ())[layer == LightLayer.SKY ? 0 : 1]; } + + @Override + public BlockState getBlockState(final BlockPos pos) { + Boolean drag = columns.get(pos); + return drag == null ? Blocks.AIR.defaultBlockState() : Blocks.BUBBLE_COLUMN.defaultBlockState().setValue(BubbleColumnBlock.DRAG_DOWN, drag); + } + + @Override + public boolean hasChunksAt(final int x0, final int y0, final int z0, final int x1, final int y1, final int z1) { + return true; + } } /** The scripted brightness: (sky, block) for a light mode and block. */ @@ -81,6 +97,11 @@ public final class VanillaAmbientOracle { }; } + /** The player's box (EntityDimensions.makeBoundingBox, width 0.6F). */ + static AABB box(Vec3 at, float height) { + return new AABB(at.x - 0.3F, at.y, at.z - 0.3F, at.x + 0.3F, at.y + height, at.z + 0.3F); + } + static float f(String hex) { return Float.intBitsToFloat(Integer.parseUnsignedInt(hex, 16)); } @@ -141,6 +162,7 @@ public final class VanillaAmbientOracle { Actor actor = null; UnderwaterAmbientSoundHandler underwater = null; BiomeAmbientSoundsHandler biome = null; + BubbleColumnAmbientSoundHandler bubble = null; try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2])))) { for (String line : Files.readAllLines(Path.of(args[1]))) { out.println(line); @@ -156,8 +178,11 @@ public final class VanillaAmbientOracle { actor = VanillaSoundRig.make(Actor.class); VanillaSoundRig.set(actor, Entity.class, "level", level); VanillaSoundRig.set(actor, Entity.class, "position", Vec3.ZERO); + VanillaSoundRig.set(actor, Entity.class, "bb", box(Vec3.ZERO, 1.8F)); + VanillaSoundRig.set(level, Lvl.class, "columns", new HashMap()); VanillaSoundRig.set(actor, LocalPlayer.class, "minecraft", mc); underwater = new UnderwaterAmbientSoundHandler(actor, rig.manager); + bubble = new BubbleColumnAmbientSoundHandler(actor); biome = new BiomeAmbientSoundsHandler(actor, rig.manager); } case "sounds" -> { @@ -175,6 +200,13 @@ public final class VanillaAmbientOracle { actor.spectator = a[6].equals("1"); VanillaSoundRig.set(actor, Entity.class, "removalReason", a[7].equals("1") ? Entity.RemovalReason.DISCARDED : null); level.mode = Integer.parseInt(a[8]); + var at = new Vec3(d(a[1]), d(a[2]), d(a[3])); + VanillaSoundRig.set(actor, Entity.class, "bb", box(at, f(a[9]))); + level.columns.clear(); + for (int i = 10; i < a.length; i++) { + String[] c = a[i].split(","); + level.columns.put(new BlockPos(Integer.parseInt(c[0]), Integer.parseInt(c[1]), Integer.parseInt(c[2])), c[3].equals("1")); + } } case "volume" -> { rig.volume(SoundSource.values()[Integer.parseInt(a[1])], f(a[2])); @@ -183,6 +215,7 @@ public final class VanillaAmbientOracle { case "tick" -> { update.invoke(actor); underwater.tick(); + bubble.tick(); biome.tick(); rig.manager.tick(false); } diff --git a/tools/test_ambient_sound_parity.py b/tools/test_ambient_sound_parity.py index 8fffae013..8906d2d7a 100644 --- a/tools/test_ambient_sound_parity.py +++ b/tools/test_ambient_sound_parity.py @@ -3,7 +3,8 @@ The oracle runs the real `LocalPlayer.updateIsUnderwater` (enter/exit sounds seeded from the level random, the `UnderLiquidAmbientSoundInstance`), -`UnderwaterAmbientSoundHandler` and `BiomeAmbientSoundsHandler` over the real +`UnderwaterAmbientSoundHandler`, `BubbleColumnAmbientSoundHandler` and +`BiomeAmbientSoundsHandler` over the real `SoundEngine` (see VanillaSoundRig), then `SoundManager.tick`, once per client tick. The `AMBIENT_SOUNDS` value (loops, moods and additions from the biomes and dimensions of the data pack plus faster custom moods), the player's @@ -56,8 +57,9 @@ class Script: mood = '-' if value['mood'] is None else '{},{},{},{}'.format(value['mood'][0], value['mood'][1], value['mood'][2], dbits(value['mood'][3])) self.add('sounds', value['loop'] or '-', mood, *[f'{s},{dbits(c)}' for s, c in value['additions']]) - def player(self, at=(0.5, 64.0, 0.5), eye=1.62, water=0, spectator=0, removed=0, mode=0): - self.add('player', *map(dbits, at), h.bits(eye), water, spectator, removed, mode) + def player(self, at=(0.5, 64.0, 0.5), eye=1.62, water=0, spectator=0, removed=0, mode=0, height=1.8, columns=()): + self.add('player', *map(dbits, at), h.bits(eye), water, spectator, removed, mode, h.bits(height), + *[f'{x},{y},{z},{d}' for x, y, z, d in columns]) def tick(self, n=1): for _ in range(n): @@ -119,6 +121,25 @@ def scripted(s, values): s.tick(50) s.sounds(by_loop[0]) s.tick(50) + # Bubble columns: entering, staying, the first tick, spectators, small boxes. + s.add('start', 5) + column = [(0, 64, 0, 1), (0, 65, 0, 1)] + s.player((0.5, 64.0, 0.5), water=1, columns=column) + s.tick(3) + s.player((3.5, 64.0, 0.5), water=1, columns=column) + s.tick(2) + s.player((0.5, 64.0, 0.5), water=1, columns=column) + s.tick(2) + s.player((0.5, 64.0, 0.5), water=1, columns=[(0, 64, 0, 0), (1, 64, 0, 1)]) + s.tick(2) + s.player((3.5, 64.0, 0.5)) + s.tick(2) + s.player((0.9, 64.5, 0.5), water=1, height=0.6, columns=[(1, 64, 0, 0), (0, 64, 0, 1)]) + s.tick(2) + s.player((3.5, 64.0, 0.5)) + s.tick(1) + s.player((0.5, 63.7, 0.5), spectator=1, columns=column) + s.tick(2) def fuzz(s, rng, values, steps): @@ -132,7 +153,12 @@ def fuzz(s, rng, values, steps): s.sounds(v) elif op < 0.12: at = (rng.uniform(-3e4, 3e4) if rng.random() < 0.2 else rng.uniform(-200, 200), rng.uniform(-64, 320), rng.uniform(-200, 200)) - s.player(at, rng.choice([1.62, 1.27, 0.4, 0.2]), int(rng.random() < 0.4), int(rng.random() < 0.05), int(rng.random() < 0.03), rng.randrange(4)) + columns = [] + if rng.random() < 0.3: + bx, by, bz = int(at[0] // 1), int(at[1] // 1), int(at[2] // 1) + columns = [(bx + rng.randrange(-1, 2), by + rng.randrange(-1, 3), bz + rng.randrange(-1, 2), rng.randrange(2)) for _ in range(rng.randrange(1, 4))] + s.player(at, rng.choice([1.62, 1.27, 0.4, 0.2]), int(rng.random() < 0.4), int(rng.random() < 0.05), int(rng.random() < 0.03), rng.randrange(4), + rng.choice([1.8, 1.5, 0.6]), columns) elif op < 0.13: s.add('volume', rng.choice([0, 8]), h.bits(rng.choice([0.0, 1.0, 0.5]))) else: @@ -160,7 +186,7 @@ def main(): scope='Real LocalPlayer.updateIsUnderwater, UnderwaterAmbientSoundHandler and BiomeAmbientSoundsHandler (loop cross-fades, additions, ' 'cave mood sampling, moodiness and the mood sound position) with UnderLiquidAmbientSoundInstance/UnderLiquidSubSound/LoopSoundInstance ' 'ticking in the real SoundEngine: every level random draw, handler state, playing instance and notification per tick. The ' - 'AMBIENT_SOUNDS value, eyes-in-water state and brightness are inputs. BubbleColumnAmbientSoundHandler is not compared.') + 'AMBIENT_SOUNDS value, eyes-in-water state and brightness are inputs. BubbleColumnAmbientSoundHandler runs on a scripted block world.') print(f'{matched:,} ambient lines match the pinned client ({len(lines):,} steps): {report}', flush=True) From 538347007a61cb4a1c58e6542dd7da4af58ce492 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:04:04 +0200 Subject: [PATCH 19/28] Add auto-jump and compare it with LocalPlayer.updateAutoJump Horizon had the Auto-Jump option but never jumped. MotionWorld::move_self now runs LocalPlayer.updateAutoJump after the player's own move (behind canAutoJump: option, autoJumpTime, ground, shift, input, block jump factor), the next aiStep presses jump for one tick (input.makeJump) without toggling creative flight, and the game feeds the option each tick. tools/test_auto_jump_parity.py runs the real updateAutoJump on a LocalPlayer shell in an independently built copy of the resident test scene with real block states (10,568 cases, 1,200 jumps). Co-Authored-By: Claude Opus 5.5 --- .../examples/auto_jump_probe.rs | 111 +++++++++ crates/horizon-client/src/auto_jump.rs | 227 ++++++++++++++++++ crates/horizon-client/src/game.rs | 2 + crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/motion.rs | 85 ++++++- .../parity/VanillaAutoJumpOracle.java | 159 ++++++++++++ tools/test_auto_jump_parity.py | 162 +++++++++++++ 7 files changed, 745 insertions(+), 2 deletions(-) create mode 100644 crates/horizon-client/examples/auto_jump_probe.rs create mode 100644 crates/horizon-client/src/auto_jump.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAutoJumpOracle.java create mode 100644 tools/test_auto_jump_parity.py diff --git a/crates/horizon-client/examples/auto_jump_probe.rs b/crates/horizon-client/examples/auto_jump_probe.rs new file mode 100644 index 000000000..f0f474c04 --- /dev/null +++ b/crates/horizon-client/examples/auto_jump_probe.rs @@ -0,0 +1,111 @@ +#![forbid(unsafe_code)] +//! Runs tools/test_auto_jump_parity.py's cases through the local player's +//! `MotionWorld::update_auto_jump` over the client's resident test scene +//! (actual resources, collision registry and block-collision scan). +use horizon_client::{ + assets::Assets, + collisions, + motion::{MotionResources, MotionWorld, PlayerMotion}, + world::World, +}; +use horizon_core::geometry::Vec3; +use serde_json::Value; +use std::{ + fs, + io::{BufRead, BufReader, BufWriter, Write}, + path::PathBuf, +}; +type Result = std::result::Result>; + +fn fl(v: &Value) -> f32 { + f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) +} +fn db(v: &Value) -> f64 { + f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) +} + +fn main() -> Result<()> { + let args: Vec<_> = std::env::args().skip(1).collect(); + let [root, input, output, scene_json] = &args[..] else { + return Err("usage: auto_jump_probe RESOURCES INPUT OUTPUT SCENE_JSON".into()); + }; + let root = PathBuf::from(root); + let assets = Assets::load(&root)?; + let mut scene = World::test_scene(&assets, 1)?; + let binding = collisions::load(&root, assets.registry)?; + let resources = MotionResources::load(&root, &assets)?; + fs::write( + scene_json, + serde_json::to_vec(&serde_json::json!({ + "radius": 1, "resident_chunks": scene.chunks.len(), "model_gallery": assets.model_gallery, + }))?, + )?; + let mut out = BufWriter::new(fs::File::create(output)?); + for (n, line) in BufReader::new(fs::File::open(input)?).lines().enumerate() { + let c: Value = serde_json::from_str(&line?)?; + writeln!(out, "== {n}")?; + let mut restore = Vec::new(); + for b in c["blocks"].as_array().unwrap() { + let (x, y, z) = ( + b[0].as_i64().unwrap() as i32, + b[1].as_i64().unwrap() as i32, + b[2].as_i64().unwrap() as i32, + ); + let mut state = assets + .registry + .default_state(b[3].as_str().unwrap()) + .ok_or("missing fixture block")?; + if let Some(properties) = b[4].as_object() + && !properties.is_empty() + { + let mut definition = assets.registry.state(state).unwrap().clone(); + for (name, value) in properties { + definition + .properties + .insert(name.clone(), value.as_str().unwrap().into()); + } + state = assets.registry.id(&definition).ok_or("missing fixture state")?; + } + restore.push((x, y, z, scene.block(x, y, z))); + scene.set(x, y, z, state)?; + } + let p = &c["player"]; + let position = Vec3::new(db(&p["pos"][0]), db(&p["pos"][1]), db(&p["pos"][2])); + let mut player = PlayerMotion::new(&resources, position)?; + player.ground.on_ground = p["ground"].as_bool().unwrap(); + player.shift_key_down = p["shift"].as_bool().unwrap(); + player.yaw = fl(&p["yr"]); + player.pitch = fl(&p["xr"]); + let key = player.attributes.key("minecraft:movement_speed").ok_or("speed")?; + let handle = player + .attributes + .get_instance(Some(key)) + .map_err(|e| format!("{e:?}"))? + .ok_or("speed instance")?; + let speed = f64::from(fl(&p["speed"])); + player + .attributes + .edit(&handle, |a, o| a.set_base_value(speed, o)) + .map_err(|e| format!("{e:?}"))?; + player.move_vector = [fl(&p["move"][0]), fl(&p["move"][1])]; + player.dimensions.width = fl(&p["width"]); + player.dimensions.height = fl(&p["height"]); + player.status.jump_boost = p["boost"].as_i64().map(|a| a as i32); + player.auto_jump_enabled = p["enabled"].as_bool().unwrap(); + player.auto_jump_time = p["time"].as_i64().unwrap() as i32; + MotionWorld { + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + } + .update_auto_jump(fl(&c["xa"]), fl(&c["za"]))?; + writeln!(out, "jump {}", player.auto_jump_time)?; + for (x, y, z, state) in restore.into_iter().rev() { + scene.set(x, y, z, state)?; + } + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-client/src/auto_jump.rs b/crates/horizon-client/src/auto_jump.rs new file mode 100644 index 000000000..123c84ce6 --- /dev/null +++ b/crates/horizon-client/src/auto_jump.rs @@ -0,0 +1,227 @@ +//! Auto-jump (`LocalPlayer.updateAutoJump` and `canAutoJump`): after the +//! local player's own move, look ahead along the movement for a step that +//! the player can clear with a jump and is not walled in above; if found, the +//! next `aiStep` presses jump for one tick (`autoJumpTime = 1`). +use horizon_core::{ + geometry::{Aabb, Axis, Vec3, VoxelShape, trig}, + position::BlockPos, +}; + +/// `Float.MIN_VALUE`, the "no obstacle" marker. +const NO_OBSTACLE: f32 = f32::from_bits(1); + +/// What `updateAutoJump` reads from the player. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct AutoJumper { + pub position: Vec3, + /// `getBoundingBox().maxY`. + pub max_y: f64, + pub x_rot: f32, + pub y_rot: f32, + /// `getSpeed()`. + pub speed: f32, + /// `input.getMoveVector()` (x: strafe, y: forward). + pub move_vector: [f32; 2], + /// `getBbWidth()`, `getBbHeight()`. + pub width: f32, + pub height: f32, + /// The jump boost amplifier, when the effect is active. + pub jump_boost: Option, +} + +/// The level queries, with the player's collision context. +pub trait AutoJumpWorld { + type Error; + /// `getBlockState(p).getCollisionShape(level, p, CollisionContext.of(player))`. + fn collision_shape(&mut self, p: BlockPos) -> Result; + /// `level.getCollisions(player, bounds)` flattened with `toAabbs`, in order. + fn collision_boxes(&mut self, bounds: Aabb) -> Result, Self::Error>; +} + +/// `LocalPlayer.canAutoJump`. `staying_on_surface` is +/// `isStayingOnGroundSurface()` (the shift key). +#[allow(clippy::too_many_arguments)] +pub fn can_auto_jump( + enabled: bool, + auto_jump_time: i32, + on_ground: bool, + staying_on_surface: bool, + passenger: bool, + move_vector: [f32; 2], + block_jump_factor: f32, +) -> bool { + enabled + && auto_jump_time <= 0 + && on_ground + && !staying_on_surface + && !passenger + && move_vector[0] * move_vector[0] + move_vector[1] * move_vector[1] > 0.0 + && f64::from(block_jump_factor) >= 1.0 +} + +/// `Vec3.directionFromRotation(rotX, rotY)`. +pub fn direction_from_rotation(rot_x: f32, rot_y: f32) -> Vec3 { + let rad = trig::DEG_TO_RAD; + let pi = std::f32::consts::PI; + let y_cos = trig::cos(f64::from(-rot_y * rad - pi)); + let y_sin = trig::sin(f64::from(-rot_y * rad - pi)); + let x_cos = -trig::cos(f64::from(-rot_x * rad)); + let x_sin = trig::sin(f64::from(-rot_x * rad)); + Vec3::new( + f64::from(y_sin * x_cos), + f64::from(x_sin), + f64::from(y_cos * x_cos), + ) +} + +/// `AABB.intersects(Vec3, Vec3)`: the box overlaps the segment's bounds. +fn intersects_segment(b: Aabb, from: Vec3, to: Vec3) -> bool { + b.intersects(Aabb::new(from, to)) +} + +/// `LocalPlayer.updateAutoJump(xa, za)` once `canAutoJump` holds: whether +/// it sets `autoJumpTime = 1`. `xa`/`za` are the float horizontal +/// displacement of the move. +pub fn update_auto_jump( + world: &mut W, + p: &AutoJumper, + xa: f32, + za: f32, +) -> Result { + let move_begin = p.position; + let move_end = move_begin.add_vector(Vec3::new(f64::from(xa), 0.0, f64::from(za))); + let mut move_diff = Vec3::new(f64::from(xa), 0.0, f64::from(za)); + let current_speed = p.speed; + let mut move_dist_sq = move_diff.length_squared() as f32; + if move_dist_sq <= 0.001 { + let input_xa = current_speed * p.move_vector[0]; + let input_za = current_speed * p.move_vector[1]; + let sin = trig::sin(f64::from(p.y_rot * trig::DEG_TO_RAD)); + let cos = trig::cos(f64::from(p.y_rot * trig::DEG_TO_RAD)); + move_diff = Vec3::new( + f64::from(input_xa * cos - input_za * sin), + move_diff.y, + f64::from(input_za * cos + input_xa * sin), + ); + move_dist_sq = move_diff.length_squared() as f32; + if move_dist_sq <= 0.001 { + return Ok(false); + } + } + // Mth.invSqrt: 1.0F / (float) Math.sqrt(x). + let inverted = 1.0 / move_dist_sq.sqrt(); + let move_dir = move_diff.scale(f64::from(inverted)); + let facing = direction_from_rotation(p.x_rot, p.y_rot); + let facing_vs_moving = (facing.x * move_dir.x + facing.z * move_dir.z) as f32; + if facing_vs_moving < -0.15 { + return Ok(false); + } + let mut ceiling = BlockPos::containing(Vec3::new(move_begin.x, p.max_y, move_begin.z)); + if !world.collision_shape(ceiling)?.is_empty() { + return Ok(false); + } + ceiling = ceiling.offset(0, 1, 0); + if !world.collision_shape(ceiling)?.is_empty() { + return Ok(false); + } + let mut jump_height = 1.2f32; + if let Some(amplifier) = p.jump_boost { + jump_height += (amplifier + 1) as f32 * 0.75; + } + let look_ahead = crate::camera::java_max(current_speed * 7.0, 1.0 / inverted); + let seg_begin = move_begin; + let seg_end = move_end.add_vector(move_dir.scale(f64::from(look_ahead))); + let (width, height) = (p.width, p.height); + let test_box = Aabb::new( + seg_begin, + seg_end.add_vector(Vec3::new(0.0, f64::from(height), 0.0)), + ) + .inflate(Vec3::new(f64::from(width), 0.0, f64::from(width))); + let lift = Vec3::new(0.0, f64::from(0.51f32), 0.0); + let seg_begin = seg_begin.add_vector(lift); + let seg_end = seg_end.add_vector(lift); + let right_dir = move_dir.cross(Vec3::new(0.0, 1.0, 0.0)); + let right_offset = right_dir.scale(f64::from(width * 0.5)); + let left_begin = seg_begin.subtract(right_offset); + let left_end = seg_end.subtract(right_offset); + let right_begin = seg_begin.add_vector(right_offset); + let right_end = seg_end.add_vector(right_offset); + let mut obstacle = NO_OBSTACLE; + for b in world.collision_boxes(test_box)? { + if intersects_segment(b, left_begin, left_end) || intersects_segment(b, right_begin, right_end) + { + obstacle = b.max_position().y as f32; + let obstacle_pos = BlockPos::containing(b.center()); + let mut steps = 1i32; + while (steps as f32) < jump_height { + let above = obstacle_pos.offset(0, steps, 0); + let shape = world.collision_shape(above)?; + if !shape.is_empty() { + obstacle = shape.max(Axis::Y) as f32 + above.y as f32; + if f64::from(obstacle) - p.position.y > f64::from(jump_height) { + return Ok(false); + } + } + if steps > 1 { + ceiling = ceiling.offset(0, 1, 0); + if !world.collision_shape(ceiling)?.is_empty() { + return Ok(false); + } + } + steps += 1; + } + break; + } + } + if obstacle != NO_OBSTACLE { + let y_delta = (f64::from(obstacle) - p.position.y) as f32; + if !(y_delta <= 0.5) && !(y_delta > jump_height) { + return Ok(true); + } + } + Ok(false) +} + +#[cfg(test)] +mod tests { + use super::*; + struct Step; + impl AutoJumpWorld for Step { + type Error = (); + fn collision_shape(&mut self, p: BlockPos) -> Result { + Ok(if p.x == 1 && p.y == 0 { + VoxelShape::block() + } else { + VoxelShape::empty() + }) + } + fn collision_boxes(&mut self, bounds: Aabb) -> Result, ()> { + let b = Aabb::new(Vec3::new(1.0, 0.0, -5.0), Vec3::new(2.0, 1.0, 5.0)); + Ok(if b.intersects(bounds) { vec![b] } else { Vec::new() }) + } + } + #[test] + fn walking_into_a_one_block_step_jumps() { + let p = AutoJumper { + position: Vec3::new(0.6, 0.0, 0.5), + max_y: 1.8, + x_rot: 0.0, + y_rot: -90.0, + speed: 0.1, + move_vector: [0.0, 1.0], + width: 0.6, + height: 1.8, + jump_boost: None, + }; + assert!(update_auto_jump(&mut Step, &p, 0.1, 0.0).unwrap()); + // Moving away from the step does not. + assert!(!update_auto_jump(&mut Step, &p, -0.1, 0.0).unwrap()); + } + #[test] + fn sneaking_or_standing_still_cannot_auto_jump() { + assert!(can_auto_jump(true, 0, true, false, false, [0.0, 1.0], 1.0)); + assert!(!can_auto_jump(true, 0, true, true, false, [0.0, 1.0], 1.0)); + assert!(!can_auto_jump(true, 0, true, false, false, [0.0, 0.0], 1.0)); + assert!(!can_auto_jump(true, 0, true, false, false, [0.0, 1.0], 0.5)); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 6a1413d2c..d9f77d66b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2517,6 +2517,8 @@ impl Game<'_> { player.yaw = self.yaw; let spectator = self.mode == horizon_client::command::args::GameMode::Spectator; player.may_fly = self.creative || spectator; + // LocalPlayer.sendPosition: autoJumpEnabled follows the option. + player.auto_jump_enabled = self.settings.auto_jump; player.invulnerable = self.creative || spectator; player.spectator = spectator; player.pitch = self.pitch; diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 5bb313406..7be5053b8 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -7,6 +7,7 @@ pub mod animate_tick; pub mod assets; pub mod attribute_updates; pub mod audio; +pub mod auto_jump; pub mod banner; pub mod biome; pub mod block_entity_nbt; diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index e9e64229e..a5d78e165 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -147,6 +147,13 @@ pub struct PlayerMotion { pub flying: bool, /// The jump key last tick (LocalPlayer.aiStep's wasJumping). pub was_jumping: bool, + /// `LocalPlayer.autoJumpEnabled` (the Auto-Jump option) and + /// `autoJumpTime`; `was_auto_jump` is this tick's `wasAutoJump`. + pub auto_jump_enabled: bool, + pub auto_jump_time: i32, + pub was_auto_jump: bool, + /// `input.getMoveVector()` this tick (before `modifyInput`). + pub move_vector: [f32; 2], /// A usable glider (elytra) is worn; the game sets it each tick. pub glider: bool, /// The view pitch (xRot), for gliding. @@ -230,6 +237,10 @@ impl PlayerMotion { spectator: false, flying: false, was_jumping: false, + auto_jump_enabled: false, + auto_jump_time: 0, + was_auto_jump: false, + move_vector: [0.0, 0.0], glider: false, pitch: 0.0, fall_flying: false, @@ -473,7 +484,7 @@ impl MotionWorld<'_, '_, '_> { self.player.ground.on_ground = false; } else if !self.player.may_fly { self.player.flying = false; - } else if !was_jumping && jumping { + } else if !was_jumping && jumping && !self.player.was_auto_jump { if self.player.jump_trigger_time == 0 { self.player.jump_trigger_time = 7; } else { @@ -545,9 +556,18 @@ impl MotionWorld<'_, '_, '_> { } pub fn controlled_simulation_tick(&mut self, keys: crate::sprint::Keys) -> Result<()> { self.update_local_crouching()?; + let mut keys = keys; + // LocalPlayer.aiStep: a pending auto-jump presses jump for this tick + // (input.makeJump) and keeps the jump from toggling flight. + self.player.was_auto_jump = self.player.auto_jump_time > 0; + if self.player.was_auto_jump { + self.player.auto_jump_time -= 1; + keys.jump = true; + } self.player.sprint_input_tick(keys)?; self.player.shift_key_down = keys.shift; let direction = keys.direction(); + self.player.move_vector = direction; let sneak = if direction[0] * direction[0] + direction[1] * direction[1] != 0.0 && self.player.moving_slowly() { @@ -668,8 +688,69 @@ impl MotionWorld<'_, '_, '_> { let movement = self.player.velocity; self.move_self(movement) } + /// `LocalPlayer.move`: the move, then `updateAutoJump` with the float + /// horizontal displacement. pub fn move_self(&mut self, movement: Vec3) -> Result<()> { - entity_move::move_entity(self, MoverType::SelfMovement, movement) + let before = self.player.position; + entity_move::move_entity(self, MoverType::SelfMovement, movement)?; + let dx = (self.player.position.x - before.x) as f32; + let dz = (self.player.position.z - before.z) as f32; + self.update_auto_jump(dx, dz) + } + /// `LocalPlayer.updateAutoJump` behind `canAutoJump`. + pub fn update_auto_jump(&mut self, xa: f32, za: f32) -> Result<()> { + let p = &*self.player; + // canAutoJump; MotionWorld drives an unmounted player (not a passenger). + let ready = crate::auto_jump::can_auto_jump( + p.auto_jump_enabled, + p.auto_jump_time, + p.ground.on_ground, + p.shift_key_down, + false, + p.move_vector, + 1.0, + ); + if !ready || f64::from(self.block_jump_factor()?) < 1.0 { + return Ok(()); + } + // Player.getSpeed: the movement speed attribute as it is now. + let speed = self.player.attribute("minecraft:movement_speed")? as f32; + let p = &*self.player; + let jumper = crate::auto_jump::AutoJumper { + position: p.position, + max_y: p.bounds().max_position().y, + x_rot: p.pitch, + y_rot: p.yaw, + speed, + move_vector: p.move_vector, + width: p.dimensions.width, + height: p.dimensions.height, + jump_boost: p.status.jump_boost, + }; + if crate::auto_jump::update_auto_jump(self, &jumper, xa, za)? { + self.player.auto_jump_time = 1; + } + Ok(()) + } +} +impl crate::auto_jump::AutoJumpWorld for MotionWorld<'_, '_, '_> { + type Error = Box; + fn collision_shape(&mut self, p: BlockPos) -> Result { + let context = self.context(); + let state = self.block(p); + let binding = self.collision_binding; + Ok(binding.collision_shape_with_context(&mut self.collisions(), state, p, &context)?) + } + fn collision_boxes(&mut self, bounds: Aabb) -> Result> { + let context = self.context(); + let mut scene = self.collisions(); + let mut boxes = Vec::new(); + for hit in horizon_world::block_collision_scan::BlockCollisionScan::new( + &mut scene, context, bounds, false, 1_000_000, + )? { + boxes.extend_from_slice(hit?.shape.boxes()); + } + Ok(boxes) } } // Current resident movement domain: dry, standing, no vehicles or gliding. diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAutoJumpOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAutoJumpOracle.java new file mode 100644 index 000000000..dc5554197 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAutoJumpOracle.java @@ -0,0 +1,159 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.io.*; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.player.ClientInput; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.*; +import net.minecraft.world.effect.*; +import net.minecraft.world.entity.*; +import net.minecraft.world.entity.player.Input; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.*; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.Property; +import net.minecraft.world.phys.*; +import net.minecraft.world.phys.shapes.VoxelShape; +import static dev.horizonlab.parity.VanillaRegistryCollisionScanOracle.*; + +/** + * Runs the real LocalPlayer.updateAutoJump (with canAutoJump, getBlockJumpFactor, + * CollisionGetter.getCollisions/BlockCollisions and the player's collision + * context) on a LocalPlayer shell standing in an independently constructed copy + * of the client's resident test scene, with each case's blocks placed. + */ +public final class VanillaAutoJumpOracle { + static Object unsafe; + static Method allocate; + + @SuppressWarnings("unchecked") + static T make(Class type) throws Exception { + return (T) allocate.invoke(unsafe, type); + } + + static Field field(Class type, String name) throws Exception { + Field f = type.getDeclaredField(name); + f.setAccessible(true); + return f; + } + + static float f(JsonElement v) { + return Float.intBitsToFloat(Integer.parseUnsignedInt(v.getAsString(), 16)); + } + + static double d(JsonElement v) { + return Double.longBitsToDouble(Long.parseUnsignedLong(v.getAsString(), 16)); + } + + static Map chunks; + + static final class AutoLevel extends net.minecraft.server.level.ServerLevel { + AutoLevel() { + super(null, null, null, null, null, null, false, 0L, List.of(), false); + } + + @Override public BlockState getBlockState(BlockPos p) { return chunks.get(key(p.getX() >> 4, p.getZ() >> 4)).getBlockState(p); } + @Override public BlockGetter getChunkForCollisions(int x, int z) { return chunks.get(key(x, z)); } + @Override public List getEntityCollisions(Entity entity, AABB bounds) { return List.of(); } + } + + static final class Jumper extends LocalPlayer { + boolean ground; + net.minecraft.world.entity.ai.attributes.AttributeMap attributes; + + Jumper() { + super(null, null, null, null, null, Input.EMPTY, false, null, null); + } + + @Override public boolean onGround() { return ground; } + @Override public net.minecraft.world.entity.ai.attributes.AttributeMap getAttributes() { return attributes; } + @Override public ItemStack getMainHandItem() { return ItemStack.EMPTY; } + @Override public ItemStack getItemBySlot(EquipmentSlot slot) { return ItemStack.EMPTY; } + } + + static > BlockState with(BlockState state, Property key, String value) { + return state.setValue(key, key.getValue(value).orElseThrow()); + } + + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + var u = Class.forName("sun.misc.Unsafe"); + unsafe = field(u, "theUnsafe").get(null); + allocate = u.getMethod("allocateInstance", Class.class); + Path resources = Path.of(args[2]); + VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(resources.resolve("block-tags.json"))).getAsJsonObject()); + var description = JsonParser.parseString(Files.readString(Path.of(args[3]))).getAsJsonObject(); + var trace = new Trace(); + trace.out = new PrintWriter(OutputStream.nullOutputStream()); + trace.fail = -1; + chunks = VanillaSceneCollisionOracle.scene(description, trace); + AutoLevel level = make(AutoLevel.class); + var update = LocalPlayer.class.getDeclaredMethod("updateAutoJump", float.class, float.class); + update.setAccessible(true); + var enabled = field(LocalPlayer.class, "autoJumpEnabled"); + var time = field(LocalPlayer.class, "autoJumpTime"); + var moveVector = field(ClientInput.class, "moveVector"); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8)); + var lines = Files.lines(Path.of(args[0]))) { + int n = 0; + for (var line : (Iterable) lines::iterator) { + var c = JsonParser.parseString(line).getAsJsonObject(); + out.println("== " + n++); + var restore = new ArrayList(); + for (var e : c.getAsJsonArray("blocks")) { + var b = e.getAsJsonArray(); + var pos = new BlockPos(b.get(0).getAsInt(), b.get(1).getAsInt(), b.get(2).getAsInt()); + BlockState state = VanillaSceneCollisionOracle.state(b.get(3).getAsString()); + for (var p : b.get(4).getAsJsonObject().entrySet()) { + state = with(state, Objects.requireNonNull(state.getBlock().getStateDefinition().getProperty(p.getKey())), p.getValue().getAsString()); + } + restore.add(new Object[] {pos, level.getBlockState(pos)}); + VanillaSceneCollisionOracle.put(chunks, pos.getX(), pos.getY(), pos.getZ(), state); + } + var p = c.getAsJsonObject("player"); + Jumper player = make(Jumper.class); + field(Entity.class, "level").set(player, level); + var position = new Vec3(d(p.getAsJsonArray("pos").get(0)), d(p.getAsJsonArray("pos").get(1)), d(p.getAsJsonArray("pos").get(2))); + field(Entity.class, "position").set(player, position); + field(Entity.class, "blockPosition").set(player, BlockPos.containing(position)); + player.mainSupportingBlockPos = Optional.empty(); + var dimensions = EntityDimensions.scalable(f(p.get("width")), f(p.get("height"))); + field(Entity.class, "dimensions").set(player, dimensions); + player.setBoundingBox(dimensions.makeBoundingBox(position)); + player.ground = p.get("ground").getAsBoolean(); + field(Entity.class, "yRot").setFloat(player, f(p.get("yr"))); + field(Entity.class, "xRot").setFloat(player, f(p.get("xr"))); + // Player.getSpeed reads the movement speed attribute. + player.attributes = new net.minecraft.world.entity.ai.attributes.AttributeMap(Player.createAttributes().build()); + player.attributes.getInstance(net.minecraft.world.entity.ai.attributes.Attributes.MOVEMENT_SPEED).setBaseValue(f(p.get("speed"))); + var input = new ClientInput(); + boolean shift = p.get("shift").getAsBoolean(); + input.keyPresses = new Input(false, false, false, false, false, shift, false); + var move = p.getAsJsonArray("move"); + moveVector.set(input, new Vec2(f(move.get(0)), f(move.get(1)))); + player.input = input; + var effects = new HashMap, MobEffectInstance>(); + if (!p.get("boost").isJsonNull()) { + effects.put(MobEffects.JUMP_BOOST, new MobEffectInstance(MobEffects.JUMP_BOOST, 100, p.get("boost").getAsInt())); + } + field(LivingEntity.class, "activeEffects").set(player, effects); + enabled.setBoolean(player, p.get("enabled").getAsBoolean()); + time.setInt(player, p.get("time").getAsInt()); + update.invoke(player, f(c.get("xa")), f(c.get("za"))); + out.println("jump " + time.getInt(player)); + Collections.reverse(restore); + for (var r : restore) { + var pos = (BlockPos) r[0]; + VanillaSceneCollisionOracle.put(chunks, pos.getX(), pos.getY(), pos.getZ(), (BlockState) r[1]); + } + } + } + System.exit(0); + } +} diff --git a/tools/test_auto_jump_parity.py b/tools/test_auto_jump_parity.py new file mode 100644 index 000000000..da0c16b7b --- /dev/null +++ b/tools/test_auto_jump_parity.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +"""Compare auto-jump with the pinned client: the real LocalPlayer.updateAutoJump +(and canAutoJump) on a player standing in an independently built copy of the +client's resident test scene, against MotionWorld::update_auto_jump over the +client's actual resources, collision registry and block-collision scan, for +steps, slabs, stairs, fences, walls, snow, carpets, honey, low ceilings and +overhangs approached from every angle with varied speeds, input vectors, +sizes, jump boost and the canAutoJump preconditions.""" +import json +import math +import os +from pathlib import Path +import platform +import random +import struct +import subprocess + +try: + from . import lab, oracle_harness as harness, test_rust_parity as base, test_model_baking_parity as baking, \ + test_native_client as client +except ImportError: + import lab, oracle_harness as harness, test_rust_parity as base, test_model_baking_parity as baking + import test_native_client as client + + +def fbits(v): + return struct.pack('>f', v).hex() + + +def dbits(v): + return struct.pack('>d', v).hex() + + +BLOCKS = [ + ('stone', {}), ('stone', {}), ('stone', {}), + ('stone_slab', {'type': 'bottom'}), ('stone_slab', {'type': 'top'}), ('stone_slab', {'type': 'double'}), + ('oak_stairs', {'facing': 'north', 'half': 'bottom'}), ('oak_stairs', {'facing': 'east', 'half': 'bottom'}), + ('oak_stairs', {'facing': 'south', 'half': 'top'}), ('oak_stairs', {'facing': 'west', 'half': 'bottom', 'shape': 'outer_left'}), + ('oak_fence', {}), ('oak_fence', {'north': 'true', 'south': 'true'}), ('oak_fence_gate', {}), + ('cobblestone_wall', {}), ('cobblestone_wall', {'up': 'true', 'east': 'tall'}), + ('snow', {'layers': '1'}), ('snow', {'layers': '4'}), ('snow', {'layers': '8'}), + ('white_carpet', {}), ('honey_block', {}), ('soul_sand', {}), ('farmland', {}), ('dirt_path', {}), + ('chest', {}), ('enchanting_table', {}), ('oak_trapdoor', {}), ('oak_trapdoor', {'half': 'top'}), + ('oak_trapdoor', {'open': 'true', 'facing': 'east'}), ('daylight_detector', {}), ('glass', {}), ('iron_bars', {}), + ('lantern', {}), ('cake', {}), ('anvil', {}), ('hopper', {}), ('oak_leaves', {}), ('cobweb', {}), ('ladder', {}), + ('red_bed', {'part': 'foot'}), +] + +ORIGIN = (20, 4, -4) + + +def placed(rng, count): + blocks = {} + ox, oy, oz = ORIGIN + for _ in range(count): + x, y, z = ox + rng.randint(-3, 3), oy + rng.choice([0, 0, 0, 1, 1, 2, 3]), oz + rng.randint(-3, 3) + name, props = rng.choice(BLOCKS) + blocks[(x, y, z)] = [x, y, z, 'minecraft:' + name, props] + return list(blocks.values()) + + +DIMS = [(0.6, 1.8), (0.6, 1.8), (0.6, 1.5), (0.6, 0.6), (0.3, 0.9), (1.2, 3.6), (0.6000000238418579, 1.7999999523162842)] + + +def player(rng, x, y, z, yaw): + w, h = rng.choice(DIMS) + return dict(pos=[dbits(x), dbits(y), dbits(z)], ground=rng.random() < 0.9, shift=rng.random() < 0.08, + yr=fbits(yaw), xr=fbits(rng.choice([0.0, 30.0, -45.0, 90.0, rng.uniform(-90, 90)])), + speed=fbits(rng.choice([0.1, 0.13000001, 0.03, 0.0, 0.2, rng.uniform(0, 0.3)])), + move=[fbits(v) for v in rng.choice([(0.0, 1.0), (0.0, 1.0), (1.0, 0.0), (-1.0, 0.0), (0.70710677, 0.70710677), + (0.0, -1.0), (0.0, 0.0), (0.3, 0.3)])], + width=fbits(w), height=fbits(h), boost=rng.choice([None] * 6 + [0, 1, 4, 255]), + enabled=rng.random() < 0.93, time=rng.choice([0] * 12 + [1, -3, 2])) + + +def cases(rng): + ox, oy, oz = ORIGIN + # Walk straight at each block from the four sides, at several speeds. + for name, props in BLOCKS: + for yaw, (dx, dz) in [(0.0, (0, 1)), (90.0, (-1, 0)), (180.0, (0, -1)), (-90.0, (1, 0)), (45.0, (-0.7, 0.7))]: + for step in (0.1, 0.215, 0.03, 0.0): + for lift in (0, 1): + blocks = [[ox, oy + lift, oz, 'minecraft:' + name, props]] + if lift: + blocks.append([ox, oy, oz, 'minecraft:stone', {}]) + x = ox + 0.5 - dx * 1.1 + z = oz + 0.5 - dz * 1.1 + p = player(rng, x, float(oy), z, yaw) + p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[fbits(0.0), fbits(1.0)], + width=fbits(0.6), height=fbits(1.8), xr=fbits(0.0)) + yield dict(blocks=blocks, player=p, xa=fbits(dx * step), za=fbits(dz * step)) + # Ceilings above the player and above the step. + for ceiling in range(2, 6): + for step_height in (0, 1): + blocks = [[ox, oy + step_height, oz, 'minecraft:stone', {}], [ox - 1, oy + ceiling, oz, 'minecraft:stone', {}], + [ox, oy + ceiling + step_height, oz, 'minecraft:stone_slab', {'type': 'top'}]] + p = player(rng, ox - 0.5, float(oy), oz + 0.5, -90.0) + p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[fbits(0.0), fbits(1.0)], + width=fbits(0.6), height=fbits(1.8)) + yield dict(blocks=blocks, player=p, xa=fbits(0.2), za=fbits(0.0)) + for _ in range(9000): + blocks = placed(rng, rng.choice([1, 2, 4, 8, 16, 30])) + x = ox + rng.uniform(-2, 3) + z = oz + rng.uniform(-2, 3) + y = float(oy) + rng.choice([0.0, 0.0, 0.0, 0.5, 1.0, 0.0625, 0.9375]) + yaw = rng.choice([0.0, 90.0, 180.0, -90.0, 45.0, rng.uniform(-360, 360)]) + p = player(rng, x, y, z, yaw) + move = rng.choice([0.0, 0.0, 0.01, 0.1, 0.215, 0.3, rng.uniform(0, 0.4)]) + angle = rng.uniform(0, 6.283) + + yield dict(blocks=blocks, player=p, xa=fbits(math.cos(angle) * move), za=fbits(math.sin(angle) * move)) + + +def main(): + lock, jars, _ = base.verify_artifacts() + libraries = baking.client_libraries() + build = lab.LOCAL / 'rust-auto-jump-parity' + build.mkdir(exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version'] + resources_before = client.resource_fingerprint(resources) + oracle = 'VanillaAutoJumpOracle' + parity = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity' + sources = [Path(__file__).resolve(), lab.ROOT / 'tools/oracle_harness.py', lab.ROOT / 'tools/lab.py', + parity / (oracle + '.java'), parity / 'VanillaSceneCollisionOracle.java', + parity / 'VanillaRegistryCollisionScanOracle.java', lab.ROOT / 'Cargo.lock', + lab.ROOT / 'crates/horizon-client/examples/auto_jump_probe.rs', + lab.ROOT / 'crates/horizon-client/src/auto_jump.rs', lab.ROOT / 'crates/horizon-client/src/motion.rs'] + tested = base.source_hashes(sources) + fixtures = list(cases(random.Random(0x4155544f))) + inputs = build / 'cases.jsonl' + inputs.write_text(''.join(json.dumps(f, separators=(',', ':')) + '\n' for f in fixtures)) + input_hash = lab.digest(inputs, 'sha256') + classes, dependencies, _ = harness.compile_oracle(build, oracle, jars, libraries, lock['minecraft']['java_major']) + binary = harness.build_probe(build, 'auto_jump_probe') + harness.run_logged([binary, resources, inputs, build / 'rust.txt', build / 'scene.json'], build, 'rust', timeout=3600) + harness.java_run(build, classes, dependencies, oracle, [inputs, build / 'client.txt', resources, build / 'scene.json'], 'client') + matched = harness.compare(build / 'client.txt', build / 'rust.txt', 2 * len(fixtures)) + base.ensure_sources_unchanged(sources, tested) + if input_hash != lab.digest(inputs, 'sha256') or resources_before != client.resource_fingerprint(resources): + raise AssertionError('Fixtures or resources changed during validation') + jumps = sum(1 for line in (build / 'rust.txt').read_text().splitlines() if line == 'jump 1') + lab.write_json(report, dict( + schema=1, minecraft=lock['minecraft']['version'], manifest_sha1=lock['minecraft']['manifest_sha1'], + platform=platform.platform(), rustc=subprocess.check_output(['rustc', '--version'], text=True).strip(), + java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], fixtures=len(fixtures), + auto_jumps=jumps, sources_sha256=tested, input_sha256=input_hash, resources=resources_before, + client_jar_sha256=lab.digest(jars['client'], 'sha256'), matched_output_lines=matched, + output_sha256=lab.digest(build / 'rust.txt', 'sha256'), + scope='The actual LocalPlayer.updateAutoJump with canAutoJump (option, autoJumpTime, onGround, ' + 'isStayingOnGroundSurface, passenger, input move vector, getBlockJumpFactor over the real level) on a ' + 'LocalPlayer shell in an independently constructed copy of the resident test scene with each case\'s ' + 'real block states placed; collisions through CollisionGetter.getCollisions/BlockCollisions with the ' + 'player\'s EntityCollisionContext and real collision shapes, jump boost from a real MobEffectInstance. ' + 'Rust runs MotionWorld::update_auto_jump over the client\'s loaded resources, collision registry and ' + 'block-collision scan. Entity collisions (none in the scene) and the riding/minecart paths are not exercised.')) + print(f'{len(fixtures):,} auto-jump cases ({jumps:,} jumps) match the pinned client: {report}', flush=True) + + +if __name__ == '__main__': + main() From 1357e2f01b0475b06cff6870ece1497892beab69 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:10:06 +0200 Subject: [PATCH 20/28] Choose situational music exactly as Minecraft.getSituationalMusic does Situation captures the screen music, the menu without a player, End boss music, creative abilities and underwater selection and the music volume; the harness calls the real getSituationalMusic/getMusicVolume with a real camera attribute probe for every dimension and biome. Co-Authored-By: Claude Opus 5.5 --- .../examples/situational_music_fixture.rs | 47 +++++++ crates/horizon-client/src/game/music.rs | 53 ++++--- crates/horizon-client/src/music.rs | 45 ++++++ .../parity/VanillaSituationalMusicOracle.java | 130 ++++++++++++++++++ tools/test_situational_music_parity.py | 45 ++++++ 5 files changed, 300 insertions(+), 20 deletions(-) create mode 100644 crates/horizon-client/examples/situational_music_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSituationalMusicOracle.java create mode 100644 tools/test_situational_music_parity.py diff --git a/crates/horizon-client/examples/situational_music_fixture.rs b/crates/horizon-client/examples/situational_music_fixture.rs new file mode 100644 index 000000000..ae47426bb --- /dev/null +++ b/crates/horizon-client/examples/situational_music_fixture.rs @@ -0,0 +1,47 @@ +//! `getSituationalMusic`/`getMusicVolume` through Horizon's `Situation` for +//! `tools/test_situational_music_parity.py`: +//! `situational_music_fixture ROOT INPUT OUTPUT`. +use horizon_client::music::{BackgroundMusic, Music, MusicTables, Situation}; +use horizon_client::sound_events::normalize; +use std::io::Write; + +fn main() { + let args: Vec = std::env::args().collect(); + let tables = MusicTables::load(std::path::Path::new(&args[1])); + let input = std::fs::read_to_string(&args[2]).expect("input"); + let mut out = std::io::BufWriter::new(std::fs::File::create(&args[3]).expect("output")); + for line in input.lines() { + let f: Vec<&str> = line.split(' ').collect(); + let in_world = f[1] == "1"; + let (background, probe_volume) = if in_world { + (tables.background(f[2], f[3]), tables.volume(f[2], f[3])) + } else { + (BackgroundMusic::default(), 1.0) + }; + let situation = Situation { + screen_music: (f[0] == "win").then(Music::credits), + in_world, + in_end: f[2] == "minecraft:the_end", + boss_music: f[4].contains("music"), + background: &background, + probe_volume, + creative: f[5] == "1" && f[6] == "1", + underwater: f[7] == "1", + }; + let music = situation.music().map_or("-".to_owned(), |m| { + format!( + "{},{},{},{}", + normalize(&m.sound), + m.min_delay, + m.max_delay, + m.replace_current_music + ) + }); + writeln!( + out, + "{line} music={music} volume={:08x}", + situation.volume().to_bits() + ) + .expect("write"); + } +} diff --git a/crates/horizon-client/src/game/music.rs b/crates/horizon-client/src/game/music.rs index 463dbce1c..59c14f998 100644 --- a/crates/horizon-client/src/game/music.rs +++ b/crates/horizon-client/src/game/music.rs @@ -1,7 +1,11 @@ //! `Minecraft.getSituationalMusic` and `getMusicVolume` for the music manager, //! the local player's ambient sound handlers and the sound engine tick. use super::Game; -use horizon_client::{blocks::Fluid, music::Music, sound_engine::TickContext}; +use horizon_client::{ + blocks::Fluid, + music::{BackgroundMusic, Music, Situation}, + sound_engine::TickContext, +}; impl Game<'_> { /// `Minecraft.tick` -> `MusicManager.tick`, once per client tick. @@ -32,26 +36,35 @@ impl Game<'_> { } /// `getSituationalMusic` and `getMusicVolume`. fn situational_music(&self) -> (Option, f32) { - // Title screen: no player, Musics.MENU at full volume. - if self.title.is_some() { - return (Some(Music::menu()), 1.0); - } - let Some(eye) = self.eye_position() else { - return (Some(Music::menu()), 1.0); + let empty = BackgroundMusic::default(); + // The title screen has no player (and no level for the camera probe). + let eye = if self.title.is_some() { + None + } else { + self.eye_position() }; - let biome = self.biome_at(eye); - let dimension = self.dim.id(); - let tables = &self.res.music; - let volume = tables.volume(dimension, biome); - // Minecraft.getSituationalMusic: the boss overlay's music in the End. - if self.dim == super::Dim::End && self.boss_music() { - return (Some(Music::end_boss()), volume); - } - let music = tables - .background(dimension, biome) - .select(self.creative, self.ambience.was_underwater()) - .cloned(); - (music, volume) + let (background, probe_volume) = match eye { + Some(eye) => { + let (dimension, biome) = (self.dim.id(), self.biome_at(eye)); + let tables = &self.res.music; + ( + tables.background(dimension, biome), + tables.volume(dimension, biome), + ) + } + None => (empty, 1.0), + }; + let situation = Situation { + screen_music: None, + in_world: eye.is_some(), + in_end: self.dim == super::Dim::End, + boss_music: self.boss_music(), + background: &background, + probe_volume, + creative: self.creative, + underwater: self.ambience.was_underwater(), + }; + (situation.music(), situation.volume()) } /// `BiomeManager.getNoiseBiomeAtPosition`: the quart cell holding a position. fn biome_at(&self, p: [f64; 3]) -> &str { diff --git a/crates/horizon-client/src/music.rs b/crates/horizon-client/src/music.rs index 08dbea125..caa8edb3e 100644 --- a/crates/horizon-client/src/music.rs +++ b/crates/horizon-client/src/music.rs @@ -107,6 +107,51 @@ impl Layer { } } } +/// What `Minecraft.getSituationalMusic` and `getMusicVolume` read. +#[derive(Clone, Debug)] +pub struct Situation<'a> { + /// `Screen.getBackgroundMusic` of the open screen. + pub screen_music: Option, + /// `Minecraft.player != null`. + pub in_world: bool, + /// The player's level is the End. + pub in_end: bool, + /// `BossHealthOverlay.shouldPlayMusic`: a boss bar asks for music. + pub boss_music: bool, + /// `BACKGROUND_MUSIC` at the camera. + pub background: &'a BackgroundMusic, + /// `MUSIC_VOLUME` at the camera (1 without a level). + pub probe_volume: f32, + /// `abilities.instabuild && abilities.mayfly`. + pub creative: bool, + /// `LocalPlayer.isUnderWater`. + pub underwater: bool, +} +impl Situation<'_> { + /// `Minecraft.getSituationalMusic`. + pub fn music(&self) -> Option { + if let Some(music) = &self.screen_music { + return Some(music.clone()); + } + if !self.in_world { + return Some(Music::menu()); + } + if self.in_end && self.boss_music { + return Some(Music::end_boss()); + } + self.background + .select(self.creative, self.underwater) + .cloned() + } + /// `Minecraft.getMusicVolume`. + pub fn volume(&self) -> f32 { + if self.screen_music.is_some() { + 1.0 + } else { + self.probe_volume + } + } +} /// Music attributes by dimension type and biome. #[derive(Clone, Debug, Default)] pub struct MusicTables { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSituationalMusicOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSituationalMusicOracle.java new file mode 100644 index 000000000..e3bf5e6df --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSituationalMusicOracle.java @@ -0,0 +1,130 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.SharedConstants; +import net.minecraft.client.Camera; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.Hud; +import net.minecraft.client.gui.components.BossHealthOverlay; +import net.minecraft.client.gui.components.LerpingBossEvent; +import net.minecraft.client.gui.screens.WinScreen; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.core.*; +import net.minecraft.core.registries.Registries; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.RegistryDataLoader; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.Bootstrap; +import net.minecraft.server.RegistryLayer; +import net.minecraft.server.packs.PackType; +import net.minecraft.server.packs.repository.ServerPacksSource; +import net.minecraft.server.packs.resources.MultiPackResourceManager; +import net.minecraft.sounds.Music; +import net.minecraft.tags.TagLoader; +import net.minecraft.world.BossEvent; +import net.minecraft.world.attribute.*; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Abilities; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.phys.Vec3; + +/** + * Calls the real Minecraft.getSituationalMusic and getMusicVolume on shells + * holding the open screen (none or the credits' WinScreen), the boss overlay's + * events, the player (its level's dimension, abilities and underwater state) + * and a real camera EnvironmentAttributeProbe over the dimension and biome's + * attribute layers from the vanilla data pack. Lines: "screen player + * dimension biome boss instabuild mayfly underwater". + */ +public final class VanillaSituationalMusicOracle { + static String music(Music m) { + return m == null ? "-" : m.sound().value().location() + "," + m.minDelay() + "," + m.maxDelay() + "," + m.replaceCurrentMusic(); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private static void addBiome(EnvironmentAttributeSystem.Builder b, EnvironmentAttribute attr, Biome biome) { + b.addPositionalLayer(attr, (base, pos, w) -> biome.getAttributes().applyModifier(attr, base)); + } + + static LerpingBossEvent bar(boolean darken, boolean music) { + return new LerpingBossEvent(UUID.randomUUID(), Component.empty(), 1.0F, BossEvent.BossBarColor.PINK, BossEvent.BossBarOverlay.PROGRESS, + darken, music, false); + } + + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + var repo = ServerPacksSource.createVanillaTrustedRepository(); + repo.reload(); + repo.setSelected(List.of("vanilla")); + var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected()); + var layers = RegistryLayer.createRegistryAccess(); + var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC)); + var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags); + RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join(); + staticTags.forEach(Registry.PendingTags::apply); + var dimensions = world.lookupOrThrow(Registries.DIMENSION_TYPE); + var biomes = world.lookupOrThrow(Registries.BIOME); + + Minecraft mc = VanillaSoundRig.make(Minecraft.class); + Gui gui = VanillaSoundRig.make(Gui.class); + Hud hud = VanillaSoundRig.make(Hud.class); + BossHealthOverlay overlay = VanillaSoundRig.make(BossHealthOverlay.class); + Map events = new LinkedHashMap<>(); + VanillaSoundRig.set(overlay, BossHealthOverlay.class, "events", events); + VanillaSoundRig.set(hud, Hud.class, "bossOverlay", overlay); + VanillaSoundRig.set(gui, Gui.class, "hud", hud); + VanillaSoundRig.set(mc, Minecraft.class, "gui", gui); + GameRenderer renderer = VanillaSoundRig.make(GameRenderer.class); + Camera camera = VanillaSoundRig.make(Camera.class); + VanillaSoundRig.set(renderer, GameRenderer.class, "mainCamera", camera); + VanillaSoundRig.set(mc, Minecraft.class, "gameRenderer", renderer); + WinScreen credits = VanillaSoundRig.make(WinScreen.class); + try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) { + for (String line : Files.readAllLines(Path.of(args[0]), StandardCharsets.UTF_8)) { + String[] f = line.split(" "); + VanillaSoundRig.set(gui, Gui.class, "screen", f[0].equals("win") ? credits : null); + events.clear(); + if (f[4].contains("dark")) events.put(UUID.randomUUID(), bar(true, false)); + if (f[4].contains("music")) events.put(UUID.randomUUID(), bar(false, true)); + var probe = new EnvironmentAttributeProbe(); + VanillaSoundRig.set(camera, Camera.class, "attributeProbe", probe); + if (f[1].equals("1")) { + DimensionType dim = dimensions.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.parse(f[2]))).value(); + Biome biome = biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(f[3]))).value(); + var b = EnvironmentAttributeSystem.builder(); + b.addConstantLayer(dim.attributes()); + for (EnvironmentAttribute attr : biome.getAttributes().keySet()) addBiome(b, attr, biome); + ClientLevel level = VanillaSoundRig.make(ClientLevel.class); + VanillaSoundRig.set(level, ClientLevel.class, "environmentAttributes", b.build()); + VanillaSoundRig.set(level, Level.class, "dimension", f[2].equals("minecraft:the_end") ? Level.END + : f[2].equals("minecraft:the_nether") ? Level.NETHER : Level.OVERWORLD); + VanillaSoundRig.set(probe, EnvironmentAttributeProbe.class, "level", level); + VanillaSoundRig.set(probe, EnvironmentAttributeProbe.class, "position", new Vec3(0.5, 64.0, 0.5)); + LocalPlayer player = VanillaSoundRig.make(LocalPlayer.class); + VanillaSoundRig.set(player, Entity.class, "level", level); + var abilities = new Abilities(); + abilities.instabuild = f[5].equals("1"); + abilities.mayfly = f[6].equals("1"); + VanillaSoundRig.set(player, Player.class, "abilities", abilities); + VanillaSoundRig.set(player, Player.class, "wasUnderwater", f[7].equals("1")); + mc.player = player; + } else { + mc.player = null; + } + w.printf("%s music=%s volume=%08x%n", line, music(mc.getSituationalMusic()), Float.floatToRawIntBits(mc.getMusicVolume())); + } + } + System.exit(0); + } +} diff --git a/tools/test_situational_music_parity.py b/tools/test_situational_music_parity.py new file mode 100644 index 000000000..3ba6b0102 --- /dev/null +++ b/tools/test_situational_music_parity.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +"""Compare the situational music choice with the vanilla 26.3 client. + +The oracle calls the real `Minecraft.getSituationalMusic` and +`getMusicVolume` with the open screen (none or the credits), the boss +overlay's bars (none, darkening, music), the player (absent, or in a dimension +with creative abilities and an underwater state) and a real camera +`EnvironmentAttributeProbe` over the dimension and biome attribute layers of +the vanilla data pack. Horizon's `Situation` with `MusicTables` answers the +same, for every dimension type x biome and every combination of the rest. +""" +import itertools + +try: + from . import audio_harness as h +except ImportError: + import audio_harness as h + + +def fixtures(): + data = h.RESOURCES / 'data/minecraft' + biomes = sorted('minecraft:' + p.stem for p in (data / 'worldgen/biome').glob('*.json')) + dimensions = ['minecraft:overworld', 'minecraft:the_nether', 'minecraft:the_end'] + lines = [] + for screen, boss in itertools.product(['none', 'win'], ['none', 'dark', 'music', 'dark+music']): + lines.append(f'{screen} 0 minecraft:overworld minecraft:plains {boss} 0 0 0') + for d, b in itertools.product(dimensions, biomes): + for screen, boss, instabuild, mayfly, water in itertools.product(['none', 'win'], ['none', 'dark', 'music'], '01', '01', '01'): + lines.append(f'{screen} 1 {d} {b} {boss} {instabuild} {mayfly} {water}') + return lines + + +def main(): + lines = fixtures() + matched, report = h.run_harness( + 'situational-music', 'VanillaSituationalMusicOracle', 'situational_music_fixture', ''.join(l + '\n' for l in lines), + extra_sources=[h.lab.ROOT / 'crates/horizon-client/src/music.rs'], rust_args=[h.RESOURCES], + scope='Real Minecraft.getSituationalMusic/getMusicVolume: screen music (credits), menu without a player, End boss music from ' + 'the boss overlay, BACKGROUND_MUSIC and MUSIC_VOLUME through a real camera EnvironmentAttributeProbe, creative abilities ' + '(instabuild && mayfly) and underwater selection, for every dimension x biome.') + print(f'{matched:,} situational music lines match the pinned client: {report}', flush=True) + + +if __name__ == '__main__': + main() From 17ac24f4dbdd7238e3330348d4cbc3b64affd99e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:12:23 +0200 Subject: [PATCH 21/28] Drive toggle sprint/sneak as vanilla's key handlers do and compare ToggleKeys holds the sneak, sprint, attack and use ToggleKeyMappings with the dispatch of KeyboardHandler.keyPress (releases always reach them; presses and SDL key repeats only without a screen), MouseHandler.onButton, Gui.setScreen (releaseAll / restoreToggleStatesOnScreenClosed) and LocalPlayer.respawn (resetToggleKeys, which Horizon lacked). Presses behind a screen no longer flip a toggled key. tools/test_toggle_keys_parity.py drives the real Options mappings through the real static KeyMapping functions (8,000 sequences). Co-Authored-By: Claude Opus 5.5 --- .../examples/toggle_keys_probe.rs | 56 ++++++++++ crates/horizon-client/src/game.rs | 60 +++++------ crates/horizon-client/src/game/screens.rs | 3 + crates/horizon-client/src/keymapping.rs | 101 +++++++++++++++++ .../parity/VanillaToggleKeysOracle.java | 102 ++++++++++++++++++ tools/test_toggle_keys_parity.py | 76 +++++++++++++ 6 files changed, 366 insertions(+), 32 deletions(-) create mode 100644 crates/horizon-client/examples/toggle_keys_probe.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaToggleKeysOracle.java create mode 100644 tools/test_toggle_keys_parity.py diff --git a/crates/horizon-client/examples/toggle_keys_probe.rs b/crates/horizon-client/examples/toggle_keys_probe.rs new file mode 100644 index 000000000..01ef5fd4d --- /dev/null +++ b/crates/horizon-client/examples/toggle_keys_probe.rs @@ -0,0 +1,56 @@ +#![forbid(unsafe_code)] +//! Runs tools/test_toggle_keys_parity.py's event sequences through +//! `ToggleKeys`, the sneak/sprint/attack/use toggle mappings. +use horizon_client::{ + Result, + keymapping::{KeyAction, ToggleKeys}, +}; +use serde_json::Value; +use std::{ + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, +}; + +fn main() -> Result<()> { + let args: Vec = std::env::args().collect(); + let input = BufReader::new(File::open(&args[1])?); + let mut out = BufWriter::new(File::create(&args[2])?); + for (n, line) in input.lines().enumerate() { + let c: Value = serde_json::from_str(&line?)?; + writeln!(out, "== {n}")?; + let mut keys = ToggleKeys::default(); + let mut options = [false; 4]; + for op in c["ops"].as_array().unwrap() { + let name = op[0].as_str().unwrap(); + let slot = || op[1].as_u64().unwrap() as usize; + match name { + "option" => options[slot()] = op[2].as_bool().unwrap(), + "key" => { + let action = match op[2].as_i64().unwrap() { + 0 => KeyAction::Release, + 1 => KeyAction::Press, + _ => KeyAction::Repeat, + }; + keys.key(slot(), action, op[3].as_bool().unwrap(), options[slot()]); + } + "button" => keys.button( + slot(), + op[2].as_bool().unwrap(), + op[3].as_bool().unwrap(), + options[slot()], + ), + "open" => keys.screen_opened(options), + "close" => keys.screen_closed(options), + "respawn" => keys.respawn(), + other => panic!("{other}"), + } + let mut line = name.to_string(); + for k in &keys.0 { + line += &format!(" {} {}", k.is_down, k.pending_clicks()); + } + writeln!(out, "{line}")?; + } + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index d9f77d66b..54876c5bf 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -108,7 +108,7 @@ use horizon_client::{ gfx::{Frame, Renderer}, hud::{HudAtlas, HudBatch, rgba}, items::{ItemStack, Items}, - keymapping::KeyState, + keymapping::KeyAction, light::LightTables, mesher::{MeshTables, Vertex}, mobs::{Mob, MobType, MobTypes}, @@ -567,7 +567,7 @@ struct Game<'a> { /// `Options.smoothCamera` (cinematic camera), not persisted. smooth_camera: bool, /// Sneak, sprint, attack and use as ToggleKeyMappings. - toggles: [KeyState; 4], + toggles: horizon_client::keymapping::ToggleKeys, /// A world screen with the pointer captured was open last frame. was_playing: bool, /// Minecraft.pause: a single-player screen that pauses the game is open. @@ -2745,7 +2745,7 @@ impl Game<'_> { /// Keep the held-key state of toggled sneak and sprint in step with their mapping. fn sync_toggle(&mut self, slot: usize) { let key = [KeyCode::ShiftLeft, KeyCode::ControlLeft][slot]; - if self.toggles[slot].is_down { + if self.toggles.is_down(slot) { self.keys.insert(key); } else { self.keys.remove(&key); @@ -2765,20 +2765,15 @@ impl Game<'_> { self.settings.toggle_attack, self.settings.toggle_use, ]; - for (slot, option) in options.into_iter().enumerate() { - if playing { - if self.toggles[slot].should_restore_state_on_screen_closed(option) { - self.toggles[slot].set_down(true, option); - } - } else { - self.toggles[slot].release(option); - } - match slot { - 0 | 1 => self.sync_toggle(slot), - 2 => self.left = self.toggles[2].is_down, - _ => self.right = self.toggles[3].is_down, - } + if playing { + self.toggles.screen_closed(options); + } else { + self.toggles.screen_opened(options); } + self.sync_toggle(0); + self.sync_toggle(1); + self.left = self.toggles.is_down(2); + self.right = self.toggles.is_down(3); } /// `MouseHandler.handleAccumulatedMovement` and `Entity.turn`, once per frame. fn apply_mouse_look(&mut self) { @@ -7681,15 +7676,16 @@ impl Game<'_> { if pressed && self.attack() { return Ok(()); } - self.toggles[2].set_down(pressed, self.settings.toggle_attack); - self.left = self.toggles[2].is_down; + self.toggles + .button(2, pressed, false, self.settings.toggle_attack); + self.left = self.toggles.is_down(2); if pressed { self.destroy_delay = 0; } } MouseButton::Right => { - self.toggles[3].set_down(pressed, self.settings.toggle_use); - self.right = self.toggles[3].is_down; + self.toggles.button(3, pressed, false, self.settings.toggle_use); + self.right = self.toggles.is_down(3); if pressed { self.use_item()?; self.use_delay = 4; @@ -8141,18 +8137,23 @@ impl ApplicationHandler for Game<'_> { } None => return Ok(()), }; - // Sneak and sprint are ToggleKeyMappings: a press flips them when toggling. + // Sneak and sprint are ToggleKeyMappings: a press (or a key + // repeat) flips them when toggling; only releases reach them + // behind a screen (KeyboardHandler.keyPress). let toggle = match key { KeyCode::ShiftLeft => Some((0, self.settings.toggle_crouch)), KeyCode::ControlLeft => Some((1, self.settings.toggle_sprint)), _ => None, }; if let Some((slot, option)) = toggle { - if !event.repeat { - self.toggles[slot] - .set_down(event.state == ElementState::Pressed, option); - self.sync_toggle(slot); - } + let action = match (event.state, event.repeat) { + (ElementState::Released, _) => KeyAction::Release, + (_, false) => KeyAction::Press, + (_, true) => KeyAction::Repeat, + }; + let screen_open = self.screen != Screen::Playing || self.title.is_some(); + self.toggles.key(slot, action, screen_open, option); + self.sync_toggle(slot); if event.state != ElementState::Pressed { return Ok(()); } @@ -8460,12 +8461,7 @@ pub fn run() -> Result<()> { focused: true, mouse: MouseLook::default(), smooth_camera: false, - toggles: [ - KeyState::toggle(true, true), - KeyState::toggle(true, true), - KeyState::toggle(true, false), - KeyState::toggle(false, false), - ], + toggles: Default::default(), was_playing: false, pause: false, debug: false, diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index b98c4ac7f..d82c1d0d6 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -213,9 +213,12 @@ impl Game<'_> { match hit { Some(0) if self.remote.is_some() => { self.ui.death_text = None; + self.toggles.respawn(); self.remote_respawn(); } Some(0) => { + // LocalPlayer.respawn: KeyMapping.resetToggleKeys. + self.toggles.respawn(); self.respawn_out_of_end()?; self.player = None; self.screen = Screen::Playing; diff --git a/crates/horizon-client/src/keymapping.rs b/crates/horizon-client/src/keymapping.rs index 157e59cb8..e598fbf71 100644 --- a/crates/horizon-client/src/keymapping.rs +++ b/crates/horizon-client/src/keymapping.rs @@ -74,6 +74,10 @@ impl KeyState { pub fn reset(&mut self) { self.is_down = false; } + /// Clicks not yet consumed. + pub fn pending_clicks(&self) -> i32 { + self.click_count + } /// `shouldRestoreStateOnScreenClosed` (clears the remembered release). pub fn should_restore_state_on_screen_closed(&mut self, needs_toggle: bool) -> bool { let Some(restore) = self.toggle else { @@ -85,6 +89,90 @@ impl KeyState { } } +/// A keyboard event (`KeyEvent.Action`): SDL reports a held key's repeats +/// as their own action. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum KeyAction { + Release, + Press, + Repeat, +} + +/// Sneak. +pub const SNEAK: usize = 0; +/// Sprint. +pub const SPRINT: usize = 1; +/// Attack (mouse). +pub const ATTACK: usize = 2; +/// Use (mouse). +pub const USE: usize = 3; + +/// The `ToggleKeyMapping`s `Options` builds: sneak and sprint (keyboard, +/// restored after a screen), attack (mouse, restored) and use (mouse, not +/// restored), and the handlers that drive them. `needs_toggle` is each +/// mapping's toggle option, read at every event as vanilla does. +#[derive(Clone, Debug)] +pub struct ToggleKeys(pub [KeyState; 4]); +impl Default for ToggleKeys { + fn default() -> Self { + Self([ + KeyState::toggle(true, true), + KeyState::toggle(true, true), + KeyState::toggle(true, false), + KeyState::toggle(false, false), + ]) + } +} +impl ToggleKeys { + pub fn is_down(&self, slot: usize) -> bool { + self.0[slot].is_down + } + /// `KeyboardHandler.keyPress` for a key bound to `slot`: a release sets + /// the mapping up (`KeyMapping.set(key, false)`); a press or a repeat + /// with no screen open sets it down and clicks it. + pub fn key(&mut self, slot: usize, action: KeyAction, screen_open: bool, needs_toggle: bool) { + match action { + KeyAction::Release => self.0[slot].set_down(false, needs_toggle), + KeyAction::Press | KeyAction::Repeat if !screen_open => { + self.0[slot].set_down(true, needs_toggle); + self.0[slot].click(); + } + _ => {} + } + } + /// `MouseHandler.onButton` for a button bound to `slot`: only without a + /// screen or overlay. + pub fn button(&mut self, slot: usize, pressed: bool, screen_open: bool, needs_toggle: bool) { + if !screen_open { + self.0[slot].set_down(pressed, needs_toggle); + if pressed { + self.0[slot].click(); + } + } + } + /// `Gui.setScreen` with a screen: `KeyMapping.releaseAll`. + pub fn screen_opened(&mut self, needs_toggle: [bool; 4]) { + for (key, option) in self.0.iter_mut().zip(needs_toggle) { + key.release(option); + } + } + /// `Gui.setScreen(null)` in a level: + /// `KeyMapping.restoreToggleStatesOnScreenClosed`. + pub fn screen_closed(&mut self, needs_toggle: [bool; 4]) { + for (key, option) in self.0.iter_mut().zip(needs_toggle) { + if key.should_restore_state_on_screen_closed(option) { + key.set_down(true, option); + } + } + } + /// `LocalPlayer.respawn`: `KeyMapping.resetToggleKeys`. + pub fn respawn(&mut self) { + for key in &mut self.0 { + key.reset(); + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -99,6 +187,19 @@ mod tests { assert!(!k.is_down); } #[test] + fn screens_block_presses_but_not_releases() { + let mut keys = ToggleKeys::default(); + keys.key(SNEAK, KeyAction::Press, true, false); + assert!(!keys.is_down(SNEAK)); + keys.key(SNEAK, KeyAction::Press, false, false); + assert!(keys.is_down(SNEAK)); + keys.key(SNEAK, KeyAction::Release, true, false); + assert!(!keys.is_down(SNEAK)); + keys.key(SPRINT, KeyAction::Press, false, true); + keys.respawn(); + assert!(!keys.is_down(SPRINT)); + } + #[test] fn screen_release_restores_toggled_state() { let mut k = KeyState::toggle(true, true); k.set_down(true, true); diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaToggleKeysOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaToggleKeysOracle.java new file mode 100644 index 000000000..ae3e34519 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaToggleKeysOracle.java @@ -0,0 +1,102 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import com.mojang.blaze3d.platform.InputConstants; +import java.io.*; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.*; + +/** + * Drives the real Options key mappings (keyShift, keySprint, keyAttack and + * keyUse are ToggleKeyMappings reading toggleCrouch/toggleSprint/toggleAttack/ + * toggleUse) through the real static KeyMapping.set/click, releaseAll, + * restoreToggleStatesOnScreenClosed and resetToggleKeys, dispatched as + * KeyboardHandler.keyPress, MouseHandler.onButton, Gui.setScreen and + * LocalPlayer.respawn call them, and prints each mapping's down state and + * pending clicks after every event. + */ +public final class VanillaToggleKeysOracle { + static Field field(Class type, String name) throws Exception { + Field f = type.getDeclaredField(name); + f.setAccessible(true); + return f; + } + + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + var u = Class.forName("sun.misc.Unsafe"); + var unsafe = field(u, "theUnsafe").get(null); + Minecraft shell = (Minecraft) u.getMethod("allocateInstance", Class.class).invoke(unsafe, Minecraft.class); + field(Minecraft.class, "fixerUpper").set(shell, net.minecraft.util.datafix.DataFixers.getDataFixer()); + field(Minecraft.class, "instance").set(null, shell); + Options options = new Options(shell, Files.createTempDirectory("opts").toFile()); + KeyMapping[] mappings = {options.keyShift, options.keySprint, options.keyAttack, options.keyUse}; + List> toggles = List.of(options.toggleCrouch(), options.toggleSprint(), options.toggleAttack(), options.toggleUse()); + Field keyField = field(KeyMapping.class, "key"); + Field clicks = field(KeyMapping.class, "clickCount"); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8)); + var lines = Files.lines(Path.of(args[0]))) { + int n = 0; + for (var line : (Iterable) lines::iterator) { + var c = JsonParser.parseString(line).getAsJsonObject(); + out.println("== " + n++); + // A fresh session: everything up, no pending clicks or remembered releases. + for (int i = 0; i < 4; i++) { + toggles.get(i).set(false); + } + KeyMapping.resetToggleKeys(); + KeyMapping.releaseAll(); + KeyMapping.restoreToggleStatesOnScreenClosed(); + for (var m : mappings) { + while (m.consumeClick()) { + } + } + for (var e : c.getAsJsonArray("ops")) { + var op = e.getAsJsonArray(); + String name = op.get(0).getAsString(); + switch (name) { + case "option" -> toggles.get(op.get(1).getAsInt()).set(op.get(2).getAsBoolean()); + case "key" -> { + // KeyboardHandler.keyPress: action 0 releases; a press (1) or an SDL + // repeat (-1) sets and clicks only with no screen open. + var key = (InputConstants.Key) keyField.get(mappings[op.get(1).getAsInt()]); + int action = op.get(2).getAsInt(); + boolean screen = op.get(3).getAsBoolean(); + if (action == 0) { + KeyMapping.set(key, false); + } else if (!screen) { + KeyMapping.set(key, true); + KeyMapping.click(key); + } + } + case "button" -> { + // MouseHandler.onButton: only with no screen or overlay. + var key = (InputConstants.Key) keyField.get(mappings[op.get(1).getAsInt()]); + boolean pressed = op.get(2).getAsBoolean(); + if (!op.get(3).getAsBoolean()) { + KeyMapping.set(key, pressed); + if (pressed) { + KeyMapping.click(key); + } + } + } + case "open" -> KeyMapping.releaseAll(); + case "close" -> KeyMapping.restoreToggleStatesOnScreenClosed(); + case "respawn" -> KeyMapping.resetToggleKeys(); + default -> throw new IllegalArgumentException(name); + } + var sb = new StringBuilder(name); + for (var m : mappings) { + sb.append(' ').append(m.isDown()).append(' ').append(clicks.getInt(m)); + } + out.println(sb); + } + } + } + System.exit(0); + } +} diff --git a/tools/test_toggle_keys_parity.py b/tools/test_toggle_keys_parity.py new file mode 100644 index 000000000..a5d2b0500 --- /dev/null +++ b/tools/test_toggle_keys_parity.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Compare toggle sprint/sneak (and toggle attack/use) with the pinned client: +the real Options ToggleKeyMappings driven by the real static KeyMapping +functions as keyboard presses, SDL key repeats and releases, mouse buttons, +screens opening and closing over the game (releaseAll and +restoreToggleStatesOnScreenClosed), respawning (resetToggleKeys) and toggle +options changing mid-sequence, event by event.""" +import json +import random + +try: + from . import lab, oracle_harness as harness +except ImportError: + import lab, oracle_harness as harness + + +def op(rng, screen): + kind = rng.choice(['key', 'key', 'key', 'key', 'button', 'button', 'open', 'close', 'option', 'option', 'respawn']) + if kind == 'key': + return ['key', rng.choice([0, 1]), rng.choice([1, 1, 0, 0, -1]), screen] + if kind == 'button': + return ['button', rng.choice([2, 3]), rng.random() < 0.5, screen] + if kind == 'option': + return ['option', rng.randrange(4), rng.random() < 0.6] + return [kind] + + +def cases(rng): + # Every short sequence of the main events for sneak with toggle off and on. + events = [['key', 0, 1, False], ['key', 0, 0, False], ['key', 0, -1, False], ['key', 0, 1, True], ['key', 0, 0, True], + ['open'], ['close'], ['respawn'], ['option', 0, True], ['option', 0, False]] + for a in events: + for b in events: + for c in events: + for toggled in (False, True): + yield dict(ops=[['option', 0, toggled], a, b, c, ['key', 0, 1, False], ['open'], ['close']]) + for _ in range(6000): + screen = False + ops = [['option', i, rng.random() < 0.5] for i in range(4)] + for _ in range(rng.randrange(1, 60)): + o = op(rng, screen) + if o[0] == 'open': + screen = True + elif o[0] == 'close': + screen = False + elif o[0] in ('key', 'button'): + o[3] = screen + ops.append(o) + yield dict(ops=ops) + + +def make_cases(build): + path = build / 'cases.jsonl' + count = 0 + with path.open('w') as out: + for case in cases(random.Random(0x544f474c)): + out.write(json.dumps(case, separators=(',', ':')) + '\n') + count += 1 + return path, count + + +def main(): + scope = ('The real Options keyShift/keySprint/keyAttack/keyUse ToggleKeyMappings with their real toggle options and ' + 'shouldRestore flags, driven through the real static KeyMapping.set/click (every mapping bound to the key), ' + 'releaseAll, restoreToggleStatesOnScreenClosed and resetToggleKeys, dispatched as KeyboardHandler.keyPress ' + '(release always; press and SDL repeat only without a screen), MouseHandler.onButton (only without a screen), ' + 'Gui.setScreen and LocalPlayer.respawn call them. Compares down state and pending clicks after every event. ' + 'The screen-consumed keyPressed/keyReleased branches and KeyMapping.setAll (an InputQuirks platform quirk) are ' + 'not exercised; KeyboardInput then reads isDown as the sprint and local input harnesses compare.') + harness.differential( + 'rust-toggle-keys-parity', 'VanillaToggleKeysOracle', 'toggle_keys_probe', make_cases, scope, + sources=[lab.ROOT / 'crates/horizon-client/src/keymapping.rs']) + + +if __name__ == '__main__': + main() From f77a22177a9dda3789ecf511a3e646d25fff49fa Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:13:40 +0200 Subject: [PATCH 22/28] Click recipe book buttons at forUI volume and test the mixer Recipe book widgets play SimpleSoundInstance.forUI(UI_BUTTON_CLICK, 1.0F), whose volume is 0.25. Unit tests cover the mixer distance gain and the stopped/looping source states. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/audio.rs | 44 +++++++++++++++++++ crates/horizon-client/src/game/recipe_book.rs | 10 ++--- crates/horizon-client/src/sound_events.rs | 4 +- 3 files changed, 52 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index 773bf064d..5d99c4858 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -552,3 +552,47 @@ impl Sounds for Audio { self.bound().update_category_volume(source, gain); } } + +#[cfg(test)] +mod tests { + use super::*; + + fn channel(samples: Vec, linear: Option, at: [f32; 3], looping: bool) -> Channel { + Channel { + samples: Some((Arc::new(samples), 48_000)), + position: 0.0, + state: State::Playing, + gain: 1.0, + pitch: 1.0, + linear, + looping, + at, + relative: false, + } + } + + #[test] + fn linear_attenuation_reaches_zero_at_the_max_distance() { + assert_eq!(distance_gain(None, 100.0), 1.0); + assert_eq!(distance_gain(Some(16.0), 0.0), 1.0); + assert_eq!(distance_gain(Some(16.0), 8.0), 0.5); + assert_eq!(distance_gain(Some(16.0), 16.0), 0.0); + assert_eq!(distance_gain(Some(16.0), 40.0), 0.0); + } + + #[test] + fn sources_play_attenuated_then_stop_or_loop() { + let mut m = Mixer::default(); + m.channels + .insert(1, channel(vec![1.0; 4], Some(16.0), [8.0, 0.0, 0.0], false)); + m.channels + .insert(2, channel(vec![1.0; 4], None, [0.0; 3], true)); + let mut data = [0.0f32; 16]; + mix(&mut m, &mut data, 2, 48_000); + assert_eq!(m.channels[&1].state, State::Stopped); + assert_eq!(m.channels[&2].state, State::Playing); + // Mono sum of the two at the first frame: the far one is half as loud. + let first = data[0] + data[1]; + assert!(first > 1.4 && first < 3.1, "{first}"); + } +} diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 60fc4ec50..95470203d 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -490,7 +490,7 @@ impl Game<'_> { if !open { self.recipe_ui.overlay = None; } - self.audio.play("minecraft:ui.button.click", None, 1.0, 1.0); + self.audio.play("minecraft:ui.button.click", None, 0.25, 1.0); return true; } if !self.book_open(book_type) || self.spectator() { @@ -518,12 +518,12 @@ impl Game<'_> { if self.recipe_ui.page + 1 < pages && inside(cursor, xo + 93.0, yo + 137.0, 12.0, 17.0) { self.recipe_ui.page += 1; - self.audio.play("minecraft:ui.button.click", None, 1.0, 1.0); + self.audio.play("minecraft:ui.button.click", None, 0.25, 1.0); return true; } if self.recipe_ui.page > 0 && inside(cursor, xo + 38.0, yo + 137.0, 12.0, 17.0) { self.recipe_ui.page -= 1; - self.audio.play("minecraft:ui.button.click", None, 1.0, 1.0); + self.audio.play("minecraft:ui.button.click", None, 0.25, 1.0); return true; } } @@ -570,7 +570,7 @@ impl Game<'_> { let filtering = !self.book_filtering(book_type); self.level.recipe_book.filtering[book_type.index()] = filtering; self.recipe_ui.page = 0; - self.audio.play("minecraft:ui.button.click", None, 1.0, 1.0); + self.audio.play("minecraft:ui.button.click", None, 0.25, 1.0); return true; } // Tabs. @@ -581,7 +581,7 @@ impl Game<'_> { self.recipe_ui.tab = Some(tab); self.recipe_ui.page = 0; } - self.audio.play("minecraft:ui.button.click", None, 1.0, 1.0); + self.audio.play("minecraft:ui.button.click", None, 0.25, 1.0); return true; } } diff --git a/crates/horizon-client/src/sound_events.rs b/crates/horizon-client/src/sound_events.rs index 6a5e179c2..4f1af3670 100644 --- a/crates/horizon-client/src/sound_events.rs +++ b/crates/horizon-client/src/sound_events.rs @@ -20,7 +20,9 @@ pub enum Sampled { Product(Vec), } impl Sampled { - /// `SampledFloat.sample`: constants draw nothing. + /// `SampledFloat.sample`: constants draw nothing (sounds.json only has + /// constants, but the random stays part of the call as in vanilla). + #[allow(clippy::only_used_in_recursion)] pub fn sample(&self, random: &mut impl RandomSource) -> f32 { match self { Self::Constant(v) => *v, From 635acffda91c254efcf0b6f25c3c7001f3dc9c68 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:16:37 +0200 Subject: [PATCH 23/28] Draw every item through the resolved item model pipeline The client now resolves stacks with horizon-assets' ItemModelResolver into an ItemStackRenderState equivalent (item_render): baked cuboid layers with their display and local transforms, tints and foil, and the special model renderers (chests, shulker boxes, banners, heads, shields, tridents, decorated pots, conduits, bells, books, copper golem statues) posed from the entity model layers. GUI icons are submitted under the GuiItemAtlas pose with ITEMS_3D/ITEMS_FLAT lighting, back faces culled and clipped to the slot; dropped items follow ItemEntityRenderer (bounding box hover, spin and seeded cluster copies); item frames, first-person and mob, player and armour stand hands, worn skulls and head items submit the same state in the world. The client atlas also runs the atlas sprite sources (directory, single, filter, unstitch, paletted_permutations), so armour trim sprites exist. The ad-hoc icon, held-banner, shield, potion-layer and glint paths are gone. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/atlas_sources.rs | 464 ++++++++++ crates/horizon-client/src/game.rs | 610 +------------ .../horizon-client/src/game/armor_stands.rs | 120 +++ crates/horizon-client/src/game/banners.rs | 159 ---- crates/horizon-client/src/game/creatures.rs | 1 - crates/horizon-client/src/game/frames.rs | 113 +-- crates/horizon-client/src/game/item_draw.rs | 373 ++++++++ crates/horizon-client/src/game/mob_blocks.rs | 121 +-- crates/horizon-client/src/game/packs.rs | 6 +- crates/horizon-client/src/game/perspective.rs | 2 + crates/horizon-client/src/game/shield.rs | 129 --- crates/horizon-client/src/game/stations.rs | 94 -- crates/horizon-client/src/hud.rs | 53 ++ crates/horizon-client/src/item_render.rs | 815 ++++++++++++++++++ crates/horizon-client/src/item_render/gui.rs | 245 ++++++ .../horizon-client/src/item_render/special.rs | 597 +++++++++++++ crates/horizon-client/src/lib.rs | 2 + crates/horizon-client/src/mobs/anim.rs | 1 + crates/horizon-client/src/mobs/render.rs | 163 +--- crates/horizon-client/src/packs.rs | 2 +- 20 files changed, 2817 insertions(+), 1253 deletions(-) create mode 100644 crates/horizon-client/src/atlas_sources.rs create mode 100644 crates/horizon-client/src/game/item_draw.rs create mode 100644 crates/horizon-client/src/item_render.rs create mode 100644 crates/horizon-client/src/item_render/gui.rs create mode 100644 crates/horizon-client/src/item_render/special.rs diff --git a/crates/horizon-client/src/atlas_sources.rs b/crates/horizon-client/src/atlas_sources.rs new file mode 100644 index 000000000..1eea24666 --- /dev/null +++ b/crates/horizon-client/src/atlas_sources.rs @@ -0,0 +1,464 @@ +//! Atlas sprite sources (`SpriteSourceList`): the `atlases/*.json` +//! definitions listing which sprites an atlas holds. `directory`, `single`, +//! `filter`, `unstitch` and `paletted_permutations` sources run in order +//! against the resource tree; a later source replaces an earlier sprite of +//! the same id and a filter removes the matching ones. +use crate::packs::pattern::Pattern; +use horizon_assets::palette::apply_palette; +use serde_json::Value; +use std::{ + collections::BTreeMap, + fs, + path::{Path, PathBuf}, +}; + +/// One region of an `unstitch` source, in units of the divisors. +#[derive(Clone, Debug, PartialEq)] +pub struct Region { + pub sprite: String, + pub x: f64, + pub y: f64, + pub width: f64, + pub height: f64, +} +#[derive(Clone, Debug)] +pub enum SpriteSource { + Directory { + source: String, + prefix: String, + }, + Single { + resource: String, + sprite: Option, + }, + Filter { + namespace: Option, + path: Option, + }, + Unstitch { + resource: String, + regions: Vec, + divisor_x: f64, + divisor_y: f64, + }, + PalettedPermutations { + textures: Vec, + palette_key: String, + permutations: BTreeMap, + separator: String, + }, +} +/// Where a listed sprite's pixels come from. +#[derive(Clone, Debug, PartialEq)] +pub enum SpriteOrigin { + /// A whole texture (`textures/.png`), by texture identifier. + File(String), + /// `Unstitcher.RegionInstance`: part of a texture. + Region { + texture: String, + region: Region, + divisor_x: f64, + divisor_y: f64, + }, + /// `PalettedSpriteSupplier`: a texture with its colours remapped. + Paletted { + texture: String, + palette_key: String, + palette: String, + }, +} + +/// `Identifier.parse` default namespace. +pub fn qualified(id: &str) -> String { + if id.contains(':') { + id.to_owned() + } else { + format!("minecraft:{id}") + } +} +fn string(v: &Value, key: &str) -> Option { + v.get(key)?.as_str().map(str::to_owned) +} +fn number(v: &Value, key: &str, default: f64) -> Option { + match v.get(key) { + None => Some(default), + Some(n) => n.as_f64(), + } +} + +/// `SpriteSources.FILE_CODEC`: the `sources` list of an atlas definition. +/// A malformed source fails the whole file, as the codec does. +pub fn decode(text: &str) -> Option> { + let json: Value = serde_json::from_str(text).ok()?; + json.get("sources")? + .as_array()? + .iter() + .map(decode_source) + .collect() +} +fn decode_source(s: &Value) -> Option { + Some(match qualified(s.get("type")?.as_str()?).as_str() { + "minecraft:directory" => SpriteSource::Directory { + source: string(s, "source")?, + prefix: string(s, "prefix")?, + }, + "minecraft:single" => SpriteSource::Single { + resource: qualified(&string(s, "resource")?), + sprite: match s.get("sprite") { + None => None, + Some(v) => Some(qualified(v.as_str()?)), + }, + }, + "minecraft:filter" => { + let p = s.get("pattern")?; + let pattern = |key: &str| -> Option> { + match p.get(key) { + None => Some(None), + Some(v) => Pattern::new(v.as_str()?).map(Some), + } + }; + SpriteSource::Filter { + namespace: pattern("namespace")?, + path: pattern("path")?, + } + } + "minecraft:unstitch" => { + let regions = s + .get("regions")? + .as_array()? + .iter() + .map(|r| { + Some(Region { + sprite: qualified(&string(r, "sprite")?), + x: r.get("x")?.as_f64()?, + y: r.get("y")?.as_f64()?, + width: r.get("width")?.as_f64()?, + height: r.get("height")?.as_f64()?, + }) + }) + .collect::>>()?; + if regions.is_empty() { + return None; + } + SpriteSource::Unstitch { + resource: qualified(&string(s, "resource")?), + regions, + divisor_x: number(s, "divisor_x", 1.0)?, + divisor_y: number(s, "divisor_y", 1.0)?, + } + } + "minecraft:paletted_permutations" => SpriteSource::PalettedPermutations { + textures: s + .get("textures")? + .as_array()? + .iter() + .map(|t| t.as_str().map(qualified)) + .collect::>()?, + palette_key: qualified(&string(s, "palette_key")?), + permutations: s + .get("permutations")? + .as_object()? + .iter() + .map(|(k, v)| Some((k.clone(), qualified(v.as_str()?)))) + .collect::>()?, + separator: match s.get("separator") { + None => "_".to_owned(), + Some(v) => v.as_str()?.to_owned(), + }, + }, + _ => return None, + }) +} + +/// The texture files of a resource tree: `namespace:path` for every +/// `assets//textures/.png`. +pub fn list_textures(root: &Path) -> Vec { + let mut out = Vec::new(); + let Ok(namespaces) = fs::read_dir(root.join("assets")) else { + return out; + }; + for ns in namespaces.flatten() { + let namespace = ns.file_name().to_string_lossy().into_owned(); + let base = ns.path().join("textures"); + let mut stack = vec![base.clone()]; + while let Some(dir) = stack.pop() { + let Ok(entries) = fs::read_dir(&dir) else { + continue; + }; + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() { + stack.push(p); + } else if p.extension().is_some_and(|x| x == "png") + && let Ok(rel) = p.strip_prefix(&base) + { + let rel = rel.with_extension("").to_string_lossy().replace('\\', "/"); + out.push(format!("{namespace}:{rel}")); + } + } + } + } + out.sort(); + out +} +/// The file of a texture identifier. +pub fn texture_path(root: &Path, texture: &str, directory: &str) -> PathBuf { + let (namespace, path) = texture.split_once(':').unwrap_or(("minecraft", texture)); + root.join(format!("assets/{namespace}/{directory}/{path}.png")) +} + +/// `SpriteSourceList.list`: every sprite id of the atlas and its origin. +/// `textures` are the available texture identifiers ([`list_textures`]). +pub fn list(sources: &[SpriteSource], textures: &[String]) -> BTreeMap { + let mut out = BTreeMap::new(); + let exists = |t: &str| textures.binary_search_by(|x| x.as_str().cmp(t)).is_ok(); + for source in sources { + match source { + SpriteSource::Directory { source, prefix } => { + // FileToIdConverter("textures/" + source, ".png"). + let dir = format!("{source}/"); + for t in textures { + let (namespace, path) = t.split_once(':').unwrap_or(("minecraft", t)); + if let Some(rest) = path.strip_prefix(&dir) { + out.insert( + format!("{namespace}:{prefix}{rest}"), + SpriteOrigin::File(t.clone()), + ); + } + } + } + SpriteSource::Single { resource, sprite } => { + if exists(resource) { + out.insert( + sprite.clone().unwrap_or_else(|| resource.clone()), + SpriteOrigin::File(resource.clone()), + ); + } + } + SpriteSource::Filter { namespace, path } => { + out.retain(|id: &String, _| { + let (ns, p) = id.split_once(':').unwrap_or(("minecraft", id)); + !(namespace.as_ref().is_none_or(|m| m.is_match(ns)) + && path.as_ref().is_none_or(|m| m.is_match(p))) + }); + } + SpriteSource::Unstitch { + resource, + regions, + divisor_x, + divisor_y, + } => { + if exists(resource) { + for region in regions { + out.insert( + region.sprite.clone(), + SpriteOrigin::Region { + texture: resource.clone(), + region: region.clone(), + divisor_x: *divisor_x, + divisor_y: *divisor_y, + }, + ); + } + } + } + SpriteSource::PalettedPermutations { + textures: bases, + palette_key, + permutations, + separator, + } => { + for base in bases { + if !exists(base) { + continue; + } + for (suffix, palette) in permutations { + out.insert( + format!("{base}{separator}{suffix}"), + SpriteOrigin::Paletted { + texture: base.clone(), + palette_key: palette_key.clone(), + palette: palette.clone(), + }, + ); + } + } + } + } + } + out +} + +/// An RGBA image. +pub type Image = (u32, u32, Vec); + +fn argb(rgba: &[u8]) -> Vec { + rgba.as_chunks::<4>() + .0 + .iter() + .map(|p| u32::from_be_bytes([p[3], p[0], p[1], p[2]])) + .collect() +} +/// The pixels of a generated sprite (`Region` or `Paletted`); `None` for a +/// plain file, which loads as itself. +pub fn generate( + origin: &SpriteOrigin, + load: &dyn Fn(&str, &str) -> Option, +) -> Option { + match origin { + SpriteOrigin::File(_) => None, + SpriteOrigin::Region { + texture, + region, + divisor_x, + divisor_y, + } => { + let (w, h, pixels) = load(texture, "textures")?; + let x_scale = f64::from(w) / divisor_x; + let y_scale = f64::from(h) / divisor_y; + let x = (region.x * x_scale).floor() as i64; + let y = (region.y * y_scale).floor() as i64; + let width = (region.width * x_scale).floor() as i64; + let height = (region.height * y_scale).floor() as i64; + if width <= 0 || height <= 0 { + return None; + } + let mut out = vec![0u8; (width * height * 4) as usize]; + for row in 0..height { + for col in 0..width { + let (sx, sy) = (x + col, y + row); + if sx < 0 || sy < 0 || sx >= i64::from(w) || sy >= i64::from(h) { + continue; + } + let s = ((sy * i64::from(w) + sx) * 4) as usize; + let d = ((row * width + col) * 4) as usize; + out[d..d + 4].copy_from_slice(&pixels[s..s + 4]); + } + } + Some((width as u32, height as u32, out)) + } + SpriteOrigin::Paletted { + texture, + palette_key, + palette, + } => { + let (w, h, pixels) = load(texture, "textures")?; + let (_, _, key) = load(palette_key, "textures/palettes")?; + let (_, _, target) = load(palette, "textures/palettes")?; + let mut mapped = argb(&pixels); + apply_palette(&mut mapped, &argb(&key), &argb(&target))?; + let out = mapped + .iter() + .flat_map(|p| { + let [a, r, g, b] = p.to_be_bytes(); + [r, g, b, a] + }) + .collect(); + Some((w, h, out)) + } + } +} + +/// Every atlas definition of a resource tree (`atlases/*.json` in every +/// namespace), by atlas id. +pub fn atlases(root: &Path) -> BTreeMap> { + let mut out = BTreeMap::new(); + let Ok(namespaces) = fs::read_dir(root.join("assets")) else { + return out; + }; + for ns in namespaces.flatten() { + let namespace = ns.file_name().to_string_lossy().into_owned(); + let Ok(files) = fs::read_dir(ns.path().join("atlases")) else { + continue; + }; + for f in files.flatten() { + let path = f.path(); + if path.extension().is_none_or(|e| e != "json") { + continue; + } + let name = path.file_stem().unwrap_or_default().to_string_lossy(); + if let Some(sources) = fs::read_to_string(&path).ok().and_then(|t| decode(&t)) { + out.insert(format!("{namespace}:{name}"), sources); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn textures() -> Vec { + let mut t: Vec = [ + "minecraft:item/apple", + "minecraft:item/stick", + "minecraft:trims/items/boots_trim", + "minecraft:block/stone", + "minecraft:entity/sheet", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + t.sort(); + t + } + #[test] + fn sources_run_in_order() { + let sources = decode( + r#"{"sources":[ + {"type":"directory","source":"item","prefix":"item/"}, + {"type":"minecraft:single","resource":"block/stone","sprite":"item/stone"}, + {"type":"filter","pattern":{"path":"stick"}}, + {"type":"unstitch","resource":"entity/sheet","divisor_x":2,"regions":[{"sprite":"a","x":1,"y":0,"width":1,"height":1}]}, + {"type":"paletted_permutations","textures":["trims/items/boots_trim"],"palette_key":"trims/color_palettes/trim_palette","permutations":{"quartz":"trims/color_palettes/quartz"}} + ]}"#, + ) + .unwrap(); + let listed = list(&sources, &textures()); + let ids: Vec<&str> = listed.keys().map(String::as_str).collect(); + assert_eq!( + ids, + [ + "minecraft:a", + "minecraft:item/apple", + "minecraft:item/stone", + "minecraft:trims/items/boots_trim_quartz" + ] + ); + assert_eq!( + listed["minecraft:item/stone"], + SpriteOrigin::File("minecraft:block/stone".into()) + ); + } + #[test] + fn malformed_sources_fail_the_file() { + assert!(decode(r#"{"sources":[{"type":"directory","source":"item"}]}"#).is_none()); + assert!( + decode(r#"{"sources":[{"type":"unstitch","resource":"x","regions":[]}]}"#).is_none() + ); + assert!(decode(r#"{"sources":[{"type":"horizon"}]}"#).is_none()); + } + #[test] + fn unstitch_cuts_by_divisor() { + let pixels: Vec = (0..16u8).flat_map(|i| [i, i, i, 255]).collect(); + let load = |_: &str, _: &str| Some((4u32, 4u32, pixels.clone())); + let origin = SpriteOrigin::Region { + texture: "t".into(), + region: Region { + sprite: "s".into(), + x: 1.0, + y: 1.0, + width: 1.0, + height: 1.0, + }, + divisor_x: 2.0, + divisor_y: 2.0, + }; + let (w, h, out) = generate(&origin, &load).unwrap(); + assert_eq!((w, h), (2, 2)); + assert_eq!(out[0], 10); + assert_eq!(out[4], 11); + assert_eq!(out[8], 14); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b81c403fd..8a768c811 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -35,6 +35,7 @@ mod ghasts; mod golems; mod growth; mod health_hud; +mod item_draw; mod jukebox; mod lan; mod lan_actions; @@ -290,16 +291,6 @@ enum Screen { /// WorldOptionsScreen (game/lan_screen.rs). WorldOptions, } -#[derive(Clone)] -enum Icon { - Flat(String), - Cube { - top: String, - left: String, - right: String, - tint: u32, - }, -} struct Mining { pos: [i32; 3], progress: f32, @@ -493,7 +484,6 @@ pub struct Resources { biomes: Arc, environment: Environment, atlas: HudAtlas, - icons: HashMap>, layer_names: HashMap, mob_types: HashMap>, mob_data: horizon_client::mobs::MobData, @@ -514,8 +504,8 @@ pub struct Resources { threads: usize, player_arm: Option, player_type: Option>, - /// firstperson_righthand display transforms per item: (rotation, translation, scale). - displays: HashMap>, + /// Item definitions, baked item models and special renderers. + item_renderer: Arc, /// Enchantments, workstation recipes and brewing (game/stations.rs). stations: horizon_client::stations::StationData, } @@ -979,37 +969,6 @@ impl Game<'_> { } Some(stack) } - /// The block's particle texture (approximated by its first model face) and tint. - /// The `particle` texture of a block's first blockstate model (for models without faces). - fn model_particle(&self, block: &str) -> Option { - let root = &self.options.resources; - let read = |path: String| -> Option { - serde_json::from_slice(&std::fs::read(root.join(path)).ok()?).ok() - }; - let states = read(format!("assets/minecraft/blockstates/{block}.json"))?; - let mut model = states["variants"] - .as_object()? - .values() - .next() - .and_then(|v| v["model"].as_str().or_else(|| v[0]["model"].as_str()))? - .to_owned(); - for _ in 0..8 { - let m = read(format!( - "assets/minecraft/models/{}.json", - model.trim_start_matches("minecraft:") - ))?; - if let Some(p) = m["textures"]["particle"].as_str() { - let p = if let Some(alias) = p.strip_prefix('#') { - m["textures"][alias].as_str()? - } else { - p - }; - return Some(p.trim_start_matches("minecraft:").to_owned()); - } - model = m["parent"].as_str()?.to_owned(); - } - None - } fn particle_sprite(&self, state: BlockStateId) -> Option<(String, u32)> { let models = self .res @@ -2150,7 +2109,15 @@ impl Game<'_> { 0.5 + 0.5 * self.world.random.next_int_bound(2).unwrap_or(0) as f32, pitch, ); - if let Some(Icon::Flat(sprite)) = self.icon(&stack.item) { + // `ItemParticleOption`: the particle material of a random layer of + // the stack resolved for the ground (`BreakingItemParticle`). + let state = self.resolve_item( + &stack, + horizon_assets::item_model::DisplayContext::Ground, + None, + 0, + ); + if let Some(sprite) = state.pick_particle(&mut self.world.random) { let (yaw, pitch) = ( f64::from(self.yaw).to_radians(), f64::from(self.pitch).to_radians(), @@ -2834,231 +2801,11 @@ impl Game<'_> { } window.set_cursor_visible(!self.captured); } - fn icon(&mut self, item: &str) -> Option { - if let Some(icon) = self.res.icons.get(item) { - return icon.clone(); - } - let icon = self.resolve_icon(item); - self.res.icons.insert(item.to_owned(), icon.clone()); - icon - } - fn resolve_icon(&self, item: &str) -> Option { - let root = &self.options.resources; - let name = item.trim_start_matches("minecraft:"); - let info = self.res.items.get(item); - let model_name = info.map_or(name.to_owned(), |i| { - i.model.trim_start_matches("minecraft:").to_owned() - }); - let def: serde_json::Value = serde_json::from_slice( - &std::fs::read(root.join(format!("assets/minecraft/items/{model_name}.json"))).ok()?, - ) - .ok()?; - // Find the first plain model reference in the item model definition. - fn first_model(v: &serde_json::Value) -> Option { - match v { - serde_json::Value::Object(o) => { - if o.get("type").and_then(|t| t.as_str()) == Some("minecraft:model") { - return o.get("model").and_then(|m| m.as_str()).map(str::to_owned); - } - // A display_context select: the inventory shows the `gui` case. - if o.get("property").and_then(|t| t.as_str()) - == Some("minecraft:display_context") - && let Some(case) = - o.get("cases").and_then(|c| c.as_array()).and_then(|cases| { - cases.iter().find(|c| match &c["when"] { - serde_json::Value::String(w) => w == "gui", - serde_json::Value::Array(ws) => ws.iter().any(|w| w == "gui"), - _ => false, - }) - }) - { - return first_model(&case["model"]); - } - for key in [ - "model", "fallback", "on_false", "on_true", "cases", "entries", "tints", - ] { - if let Some(m) = o.get(key).and_then(first_model) { - return Some(m); - } - } - o.values().find_map(first_model) - } - serde_json::Value::Array(a) => a.iter().find_map(first_model), - _ => None, - } - } - let Some(model) = first_model(&def["model"]) else { - // Special item models (chests, beds, banners...): show the block's particle texture. - let block = self - .res - .assets - .registry - .default_state(item) - .or_else(|| info.and_then(|i| i.block))?; - let (sprite, tint) = self - .particle_sprite(block) - .or_else(|| self.model_particle(name).map(|s| (s, 0xFFFFFF)))?; - return Some(Icon::Cube { - top: sprite.clone(), - left: sprite.clone(), - right: sprite, - tint, - }); - }; - let path = model.trim_start_matches("minecraft:").to_owned(); - let mut current = path.clone(); - let mut textures = serde_json::Map::new(); - for _ in 0..16 { - let text = - std::fs::read(root.join(format!("assets/minecraft/models/{current}.json"))).ok()?; - let m: serde_json::Value = serde_json::from_slice(&text).ok()?; - if let Some(t) = m["textures"].as_object() { - for (k, v) in t { - textures.entry(k.clone()).or_insert(v.clone()); - } - } - match m["parent"].as_str() { - Some(p) - if p.ends_with("item/generated") - || p.ends_with("item/handheld") - || p.contains("handheld") => - { - let layer = textures.get("layer0")?.as_str()?; - return Some(Icon::Flat( - layer.trim_start_matches("minecraft:").to_owned(), - )); - } - Some(p) => current = p.trim_start_matches("minecraft:").to_owned(), - None => break, - } - } - if path.starts_with("block/") { - let block = self - .res - .assets - .registry - .default_state(&format!("minecraft:{name}")) - .or_else(|| info.and_then(|i| i.block))?; - let models = self - .res - .assets - .model_catalog - .collect(block, horizon_core::position::BlockPos::new(0, 0, 0)) - .ok()?; - let mut faces: HashMap = HashMap::new(); - for (_, m) in &models { - for f in &m.faces { - faces - .entry(f.quad.facing as usize) - .or_insert((f.layer, f.quad.tint_index)); - } - } - use horizon_assets::model::Direction as D; - let get = |d: D| { - faces - .get(&(d as usize)) - .and_then(|(l, _)| self.res.layer_names.get(l)) - .cloned() - }; - let top = get(D::Up)?; - let tinted = faces.get(&(D::Up as usize)).is_some_and(|(_, t)| *t >= 0); - let tint = if tinted { - if name.contains("leaves") || name == "vine" { - 0x48B518 - } else { - 0x91BD59 - } - } else { - 0xFFFFFF - }; - return Some(Icon::Cube { - left: get(D::South).unwrap_or(top.clone()), - right: get(D::East).unwrap_or(top.clone()), - top, - tint, - }); - } - textures - .get("layer0") - .or_else(|| textures.get("all")) - .or_else(|| textures.get("texture")) - .and_then(|t| t.as_str()) - .map(|t| Icon::Flat(t.trim_start_matches("minecraft:").to_owned())) - } fn draw_item(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) { - // Special-model items: the shield and banners draw their own 3D icon. - let banner = if &*stack.item == "minecraft:shield" { - let passes = shield::shield_passes(&self.res.stations.banners, stack); - shield::draw_shield_icon(batch, &self.res.atlas, x, y, &passes); - true - } else { - self.draw_banner_icon(batch, stack, x, y) - }; - let icon = if banner { None } else { self.icon(&stack.item) }; + // `GuiGraphics.renderItem`: the resolved item model (tints, foil and + // special renderers included), then the decorations. + self.draw_item_model(batch, stack, x, y); let atlas = &self.res.atlas; - match icon { - None if banner => {} - Some(Icon::Flat(name)) => batch.sprite_scaled(atlas, &name, x, y, 16.0, 16.0, u32::MAX), - Some(Icon::Cube { - top, - left, - right, - tint, - }) => { - let color = |b: f32| { - let c = |s: u32| (((tint >> s) & 255) as f32 * b) as u8; - rgba(c(16), c(8), c(0), 255) - }; - let (cx, top_y) = (x + 8.0, y + 1.0); - let quad = |batch: &mut HudBatch, name: &str, p: [[f32; 2]; 4], c: u32| { - if let Some(r) = atlas.sprites.get(name).copied() { - batch.quad( - p, - [[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]], - c, - ); - } - }; - let (w, h) = (7.0, 3.6); - quad( - batch, - &top, - [ - [cx, top_y], - [cx + w, top_y + h], - [cx, top_y + 2.0 * h], - [cx - w, top_y + h], - ], - color(1.0), - ); - let side = 8.0; - quad( - batch, - &left, - [ - [cx - w, top_y + h], - [cx, top_y + 2.0 * h], - [cx, top_y + 2.0 * h + side], - [cx - w, top_y + h + side], - ], - color(0.8), - ); - quad( - batch, - &right, - [ - [cx, top_y + 2.0 * h], - [cx + w, top_y + h], - [cx + w, top_y + h + side], - [cx, top_y + 2.0 * h + side], - ], - color(0.6), - ); - } - None => batch.fill(atlas, x + 2.0, y + 2.0, 12.0, 12.0, rgba(200, 0, 200, 255)), - } - self.draw_potion_layers(batch, stack, x, y); - self.draw_glint(batch, stack, x, y); if stack.count > 1 { let text = stack.count.to_string(); let w = HudBatch::text_width(atlas, &text); @@ -4234,147 +3981,8 @@ impl Game<'_> { /// ItemEntityRenderer: items bob and spin; blocks render as small cubes. fn entity_geometry(&mut self, camera: glam::DVec3, alpha: f64) -> Vec { let mut out = Vec::new(); - let items = self.dropped.clone(); - for item in &items { - let p = item.previous; - let q = item.position; - let pos = glam::DVec3::new( - p.x + (q.x - p.x) * alpha, - p.y + (q.y - p.y) * alpha, - p.z + (q.z - p.z) * alpha, - ) - camera; - if pos.length_squared() > 64.0 * 64.0 { - continue; - } - let age = item.age as f32 + alpha as f32; - let bob = (age / 10.0 + item.bob_offset).sin() * 0.1 + 0.1; - let spin = age / 20.0 + item.bob_offset; - let light = self.world.light( - q.x.floor() as i32, - (q.y + 0.1).floor() as i32, - q.z.floor() as i32, - ); - let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); - let center = pos.as_vec3() + glam::Vec3::new(0.0, bob + 0.125, 0.0); - let rot = glam::Mat3::from_rotation_y(spin); - let icon = self.icon(&item.stack.item); - let atlas = &self.res.atlas; - let mut quad = |corners: [glam::Vec3; 4], name: &str, shade: f32, tint: u32| { - let Some(r) = atlas.sprites.get(name).copied() else { - return; - }; - let uv = [[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]]; - let c = |sft: u32| (((tint >> sft) & 255) as f32 * shade) as u32; - let color = 0xFF00_0000 | c(0) << 16 | c(8) << 8 | c(16); - for (corner, uv) in corners.iter().zip(uv) { - let v = center + rot * *corner; - out.push(Vertex { - pos: v.to_array(), - uv, - layer: 0, - color, - light: packed, - }); - } - }; - let copies = match item.stack.count { - 0..=1 => 1, - 2..=16 => 2, - 17..=32 => 3, - _ => 4, - }; - for k in 0..copies { - let o = glam::Vec3::new(k as f32 * 0.03, k as f32 * 0.03, k as f32 * 0.05); - match &icon { - Some(Icon::Cube { - top, - left, - right, - tint, - }) => { - let h = 0.125; - let v = |x: f32, y: f32, z: f32| glam::Vec3::new(x * h, y * h, z * h) + o; - quad( - [ - v(-1., 1., 1.), - v(1., 1., 1.), - v(1., 1., -1.), - v(-1., 1., -1.), - ], - top, - 1.0, - *tint, - ); - quad( - [ - v(-1., -1., -1.), - v(1., -1., -1.), - v(1., -1., 1.), - v(-1., -1., 1.), - ], - top, - 0.5, - *tint, - ); - quad( - [ - v(-1., -1., 1.), - v(1., -1., 1.), - v(1., 1., 1.), - v(-1., 1., 1.), - ], - left, - 0.8, - 0xFFFFFF, - ); - quad( - [ - v(1., -1., -1.), - v(-1., -1., -1.), - v(-1., 1., -1.), - v(1., 1., -1.), - ], - left, - 0.8, - 0xFFFFFF, - ); - quad( - [ - v(1., -1., 1.), - v(1., -1., -1.), - v(1., 1., -1.), - v(1., 1., 1.), - ], - right, - 0.6, - 0xFFFFFF, - ); - quad( - [ - v(-1., -1., -1.), - v(-1., -1., 1.), - v(-1., 1., 1.), - v(-1., 1., -1.), - ], - right, - 0.6, - 0xFFFFFF, - ); - } - Some(Icon::Flat(name)) => { - let h = 0.25; - let v = |x: f32, y: f32| glam::Vec3::new(x * h, y * h + 0.125, 0.0) + o; - quad( - [v(-1., -1.), v(1., -1.), v(1., 1.), v(-1., 1.)], - name, - 1.0, - 0xFFFFFF, - ); - } - None => {} - } - } - } + // `ItemEntityRenderer`. + self.dropped_item_geometry(camera, alpha, &mut out); // Mobs and their projectiles. self.mob_geometry(camera, alpha, &mut out); self.player_model_geometry(camera, alpha, &mut out); @@ -6507,67 +6115,6 @@ impl Game<'_> { self.hand_item = held; } } - fn display_transform(&mut self, item: &str) -> Option<([f32; 3], [f32; 3], [f32; 3])> { - if let Some(d) = self.res.displays.get(item) { - return *d; - } - let root = &self.options.resources; - let name = item.trim_start_matches("minecraft:"); - let model_name = self.res.items.get(item).map_or(name.to_owned(), |i| { - i.model.trim_start_matches("minecraft:").to_owned() - }); - let mut found = None; - let def: Option = - std::fs::read(root.join(format!("assets/minecraft/items/{model_name}.json"))) - .ok() - .and_then(|b| serde_json::from_slice(&b).ok()); - let mut current = def.and_then(|d| { - fn first(v: &serde_json::Value) -> Option { - match v { - serde_json::Value::Object(o) => { - if o.get("type").and_then(|t| t.as_str()) == Some("minecraft:model") { - return o.get("model").and_then(|m| m.as_str()).map(str::to_owned); - } - o.values().find_map(first) - } - serde_json::Value::Array(a) => a.iter().find_map(first), - _ => None, - } - } - first(&d["model"]) - }); - if item.ends_with("_banner") { - // The banner item model is a special renderer over this base model. - current = Some("minecraft:item/template_banner".to_owned()); - } - for _ in 0..16 { - let Some(m) = current.take() else { break }; - let path = m.trim_start_matches("minecraft:").to_owned(); - let Some(model) = - std::fs::read(root.join(format!("assets/minecraft/models/{path}.json"))) - .ok() - .and_then(|b| serde_json::from_slice::(&b).ok()) - else { - break; - }; - let d = &model["display"]["firstperson_righthand"]; - if d.is_object() { - let v = |k: &str, default: f32| -> [f32; 3] { - let a = d[k].as_array(); - std::array::from_fn(|i| { - a.and_then(|a| a.get(i)) - .and_then(|x| x.as_f64()) - .map_or(default, |x| x as f32) - }) - }; - found = Some((v("rotation", 0.0), v("translation", 0.0), v("scale", 1.0))); - break; - } - current = model["parent"].as_str().map(str::to_owned); - } - self.res.displays.insert(item.to_owned(), found); - found - } /// FirstPersonHandsAndItemsRenderer: the right arm or held item in view /// space, converted to camera-relative world space. fn hand_geometry(&mut self, alpha: f64) -> Vec { @@ -6663,115 +6210,39 @@ impl Game<'_> { ); } Some(stack) => { - let display = self - .display_transform(&stack.item) - .unwrap_or(([0.0; 3], [0.0; 3], [1.0; 3])); - let icon = self.icon(&stack.item); // applyItemArmTransform + swingArm (applyItemArmAttackTransform) let x = -0.4 * (sqrt_attack * std::f32::consts::PI).sin(); let y = 0.2 * (sqrt_attack * std::f32::consts::TAU).sin(); let z = -0.2 * (attack * std::f32::consts::PI).sin(); let y_swing_rot = (attack * attack * std::f32::consts::PI).sin(); let xz_swing_rot = (sqrt_attack * std::f32::consts::PI).sin(); - let (rot, trans, scale) = display; let m = to_world - * glam::Mat4::from_translation(glam::Vec3::new(0.56, -0.52 + inverse_height * -0.6, -0.72)) + * glam::Mat4::from_translation(glam::Vec3::new( + 0.56, + -0.52 + inverse_height * -0.6, + -0.72, + )) * glam::Mat4::from_translation(glam::Vec3::new(x, y, z)) * glam::Mat4::from_rotation_y(deg(45.0 + y_swing_rot * -20.0)) * glam::Mat4::from_rotation_z(deg(xz_swing_rot * -20.0)) * glam::Mat4::from_rotation_x(deg(xz_swing_rot * -80.0)) - * glam::Mat4::from_rotation_y(deg(-45.0)) - // ItemTransform.apply: translation is in sixteenths, rotation XYZ, then scale. - * glam::Mat4::from_translation(glam::Vec3::from(trans) / 16.0) - * glam::Mat4::from_quat(glam::Quat::from_euler(glam::EulerRot::XYZ, deg(rot[0]), deg(rot[1]), deg(rot[2]))) - * glam::Mat4::from_scale(glam::Vec3::from(scale)) - * glam::Mat4::from_translation(glam::Vec3::splat(-0.5)); - if self.held_banner_geometry(m, &stack, packed, &mut out) { - return out; - } - let atlas = &self.res.atlas; - let quad = |corners: [glam::Vec3; 4], - name: &str, - shade: f32, - tint: u32, - out: &mut Vec| { - let Some(r) = atlas.sprites.get(name).copied() else { - return; - }; - let uv = [[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]]; - let c = |sft: u32| (((tint >> sft) & 255) as f32 * shade) as u32; - let color = 0xFF00_0000 | c(0) << 16 | c(8) << 8 | c(16); - for (p, uv) in corners.iter().zip(uv) { - out.push(Vertex { - pos: m.transform_point3(*p).to_array(), - uv, - layer: 0, - color, - light: packed, - }); - } - }; - let v = glam::Vec3::new; - match icon { - Some(Icon::Cube { - top, - left, - right, - tint, - }) => { - quad( - [v(0., 1., 1.), v(1., 1., 1.), v(1., 1., 0.), v(0., 1., 0.)], - &top, - 1.0, - tint, - &mut out, - ); - quad( - [v(0., 0., 1.), v(1., 0., 1.), v(1., 1., 1.), v(0., 1., 1.)], - &left, - 0.8, - 0xFFFFFF, - &mut out, - ); - quad( - [v(1., 0., 0.), v(0., 0., 0.), v(0., 1., 0.), v(1., 1., 0.)], - &left, - 0.8, - 0xFFFFFF, - &mut out, - ); - quad( - [v(1., 0., 1.), v(1., 0., 0.), v(1., 1., 0.), v(1., 1., 1.)], - &right, - 0.6, - 0xFFFFFF, - &mut out, - ); - quad( - [v(0., 0., 0.), v(0., 0., 1.), v(0., 1., 1.), v(0., 1., 0.)], - &right, - 0.6, - 0xFFFFFF, - &mut out, - ); - } - Some(Icon::Flat(name)) => { - // Generated item models are a sprite on the z = 8/16 plane. - quad( - [ - v(0., 0., 0.5), - v(1., 0., 0.5), - v(1., 1., 0.5), - v(0., 1., 0.5), - ], - &name, - 1.0, - 0xFFFFFF, - &mut out, - ); - } - None => {} - } + * glam::Mat4::from_rotation_y(deg(-45.0)); + // `ItemInHandRenderer.renderItem`: the player as owner, seeded by + // its id plus the display context ordinal. + let owner = self.player_owner(Some(&stack)); + let context = horizon_assets::item_model::DisplayContext::FirstPersonRightHand; + let state = self.resolve_item(&stack, context, Some(&owner), 4); + let light = self.world.light( + eye[0].floor() as i32, + eye[1].floor() as i32, + eye[2].floor() as i32, + ); + self.submit_item_world( + &state, + m, + horizon_client::block_entity_render::vertex_light(light), + &mut out, + ); } } out @@ -8386,7 +7857,7 @@ pub fn run() -> Result<()> { biomes, environment, atlas, - icons: HashMap::new(), + item_renderer: Arc::new(horizon_client::item_render::ItemRenderer::load(&root)?), layer_names, providers: Providers::load(&root), block_entity_render: horizon_client::block_entity_render::BlockEntityRenderer::load( @@ -8424,7 +7895,6 @@ pub fn run() -> Result<()> { player_type: perspective::player_type(&root), player_arm: horizon_client::mobs::load_model(&root, "minecraft:player#main") .and_then(|m| m.children.into_iter().find(|c| c.name == "right_arm")), - displays: HashMap::new(), }; let inventory = vec![None; 36]; let now = Instant::now(); diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index 5fff87c9d..abf17b545 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -415,6 +415,8 @@ impl Game<'_> { pose[5] = deg(rot[2]); } } + // Item layers pose from the hidden arms too (`visible` only skips drawing). + let posed = poses.clone(); let mut hide = |name: &str| { if poses.has(name) { let pose = poses.get(name); @@ -446,6 +448,7 @@ impl Game<'_> { 0, out, ); + self.armor_stand_items(a, model, base, &posed, packed, out); // HumanoidArmorLayer: head, chest, legs, feet. for (slot, layer) in [ (5usize, "helmet"), @@ -562,3 +565,120 @@ impl Game<'_> { true } } +impl Game<'_> { + /// `ItemInHandLayer` and `CustomHeadLayer` of an armour stand: the hand + /// items in the third-person contexts, and a non-armour head item on the + /// head (`translateToHead`: down a quarter, turned, 0.625 scale). + fn armor_stand_items( + &self, + a: &ArmorStand, + model: &Part, + base: glam::Mat4, + poses: &Poses, + light: u32, + out: &mut Vec, + ) { + use horizon_assets::item_model::DisplayContext; + use horizon_client::mobs::render::part_matrix; + let owner = super::item_draw::owner_at( + [a.position.x, a.position.y, a.position.z], + a.yaw, + "minecraft:armor_stand", + ); + // `useBabyOffset`: small stands use the baby hand offsets. + let (ox, oy, oz) = if a.small { + (0.0, 1.0, -4.5) + } else { + (1.0, 2.0, -10.0) + }; + for (slot, left, context) in [ + (0usize, false, DisplayContext::ThirdPersonRightHand), + (1, true, DisplayContext::ThirdPersonLeftHand), + ] { + let Some(stack) = &a.equipment[slot] else { + continue; + }; + let arm = if left { "left_arm" } else { "right_arm" }; + let Some(hand) = part_matrix(model, base, poses, arm, 0.0) else { + continue; + }; + let pose = hand + * glam::Mat4::from_rotation_x((-90.0f32).to_radians()) + * glam::Mat4::from_rotation_y(std::f32::consts::PI) + * glam::Mat4::from_translation(glam::Vec3::new( + if left { -ox } else { ox } / 16.0, + oy / 16.0, + oz / 16.0, + )); + let seed = a.id as i32 + if left { 1 } else { 2 }; + let state = self.resolve_item(stack, context, Some(&owner), seed); + self.submit_item_world(&state, pose, light, out); + } + // `CustomHeadLayer`: a worn skull draws the skull model. + if let Some(stack) = &a.equipment[5] + && let Some(kind) = skull_kind(&stack.item) + && let Some(head) = part_matrix(model, base, poses, "head", 0.0) + { + let pose = head * glam::Mat4::from_scale(glam::Vec3::splat(1.1875)); + let special = horizon_assets::item_model::SpecialModel { + kind: if kind == "player" { + horizon_assets::item_model::SpecialKind::PlayerHead + } else { + horizon_assets::item_model::SpecialKind::Head { + kind: kind.to_owned(), + texture: None, + animation: 0.0, + } + }, + }; + let mut sink = horizon_client::item_render::WorldSink { + out, + light, + lights: Some(horizon_client::block_entity_render::diffuse_lights( + self.dim == super::Dim::Nether, + )), + }; + self.res.item_renderer.submit_special( + &special, + &serde_json::Value::Null, + false, + pose, + &self.res.atlas.sprites, + &self.item_host(), + &mut sink, + ); + return; + } + // A head item that is not worn armour. + if let Some(stack) = &a.equipment[5] + && self + .res + .items + .get(&stack.item) + .is_none_or(|i| i.equip_asset.is_none()) + && let Some(head) = part_matrix(model, base, poses, "head", 0.0) + { + let pose = head + * glam::Mat4::from_translation(glam::Vec3::new(0.0, -0.25, 0.0)) + * glam::Mat4::from_rotation_y(std::f32::consts::PI) + * glam::Mat4::from_scale(glam::Vec3::new(0.625, -0.625, -0.625)); + // `updateForLiving`: seeded by the entity id plus HEAD's ordinal. + let state = + self.resolve_item(stack, DisplayContext::Head, Some(&owner), a.id as i32 + 5); + self.submit_item_world(&state, pose, light, out); + } + } +} +/// `AbstractSkullBlock.getType` of a skull item. +fn skull_kind(item: &str) -> Option<&'static str> { + Some(match item { + "minecraft:skeleton_skull" => "skeleton", + "minecraft:wither_skeleton_skull" => "wither_skeleton", + "minecraft:zombie_head" => "zombie", + "minecraft:creeper_head" => "creeper", + "minecraft:dragon_head" => "dragon", + "minecraft:piglin_head" => "piglin", + "minecraft:player_head" => "player", + _ => return None, + }) +} diff --git a/crates/horizon-client/src/game/banners.rs b/crates/horizon-client/src/game/banners.rs index b9f701a0c..d767dc9b8 100644 --- a/crates/horizon-client/src/game/banners.rs +++ b/crates/horizon-client/src/game/banners.rs @@ -2,14 +2,10 @@ //! banner item to the block when placed and back to the dropped item when //! broken (`copy_components` in the banner loot tables). use super::Game; -use glam::{EulerRot, Mat4, Quat, Vec3}; use horizon_client::{ banner::{self, BannerLayer}, - block_entity_render::{Paint, draw_part}, containers::{Banner, BlockEntity}, - hud::{HudBatch, rgba}, items::ItemStack, - mesher::Vertex, }; impl Game<'_> { @@ -34,161 +30,6 @@ impl Game<'_> { b.name = stack.custom_name().map(str::to_owned); } } - /// A banner in a slot: `item/template_banner`'s `gui` transform on the - /// banner model (pole, bar and flag with every layer), flat-lit and - /// depth-sorted. False when the stack is not a banner. - pub(super) fn draw_banner_icon( - &self, - batch: &mut HudBatch, - stack: &ItemStack, - x: f32, - y: f32, - ) -> bool { - let Some(base) = banner::banner_color(&stack.item) else { - return false; - }; - let Some((main, flag)) = self.res.block_entity_render.banner_models() else { - return true; - }; - let banners = &self.res.stations.banners; - let sprites = &self.res.atlas.sprites; - // display.gui, then the item's special transformation (a banner is - // modelled upside down and 2/3 size around the block centre). - let m = Mat4::from_translation(Vec3::new(0.0, -3.25 / 16.0, 0.0)) - * Mat4::from_quat(Quat::from_euler( - EulerRot::XYZ, - 30f32.to_radians(), - 20f32.to_radians(), - 0.0, - )) - * Mat4::from_scale(Vec3::splat(0.5325)) - * Mat4::from_translation(Vec3::new(0.0, -0.5, 0.0)) - * Mat4::from_scale(Vec3::new(2.0 / 3.0, -2.0 / 3.0, -2.0 / 3.0)); - let wave = |name: &str, p: &mut [f32; 9]| { - if name == "flag" { - p[3] = (-0.0125 + 0.01) * std::f32::consts::PI; - } - }; - let none = |_: &str, _: &mut [f32; 9]| {}; - let mut passes: Vec<(&str, u32, bool, String)> = vec![ - ("entity/banner/banner_base", 0xFFFFFF, true, String::new()), - ( - "entity/banner/base", - banner::dye_rgb(base), - false, - String::new(), - ), - ]; - for layer in banner::layers(stack).iter().take(16) { - passes.push(( - "", - banner::dye_rgb(&layer.color), - false, - banners.banner_texture(&layer.pattern), - )); - } - // (depth, pass, screen corners, uv, colour) - let mut faces: Vec<(f32, usize, [[f32; 2]; 4], [[f32; 2]; 4], u32)> = Vec::new(); - for (index, (fixed, tint, with_pole, dynamic)) in passes.iter().enumerate() { - let name = if fixed.is_empty() { - dynamic.as_str() - } else { - fixed - }; - let Some(sprite) = sprites.get(name).copied() else { - continue; - }; - let paint = Paint { - sprite, - tint: 0xFFFFFF, - light: 0, - lights: (Vec3::ZERO, Vec3::ZERO), - }; - let mut verts: Vec = Vec::new(); - if *with_pole { - draw_part(main, "root", m, &none, paint, &mut verts); - } - draw_part(flag, "root", m, &wave, paint, &mut verts); - for quad in verts.as_chunks::<4>().0 { - let p = |i: usize| Vec3::from(quad[i].pos); - let normal = (p(1) - p(0)).cross(p(2) - p(0)).normalize_or_zero(); - // Faces turned away from the viewer are culled. - if normal.z <= 0.0 { - continue; - } - let depth = (0..4).map(|i| p(i).z).sum::() / 4.0; - let shade = (0.6 + 0.4 * normal.z).min(1.0); - let c = |s: u32| (((tint >> s) & 255) as f32 * shade) as u8; - faces.push(( - depth, - index, - std::array::from_fn(|i| { - [ - x + 8.0 + quad[i].pos[0] * 16.0, - y + 8.0 - quad[i].pos[1] * 16.0, - ] - }), - std::array::from_fn(|i| quad[i].uv), - rgba(c(16), c(8), c(0), 255), - )); - } - } - faces.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); - for (_, _, corners, uv, color) in faces { - batch.quad(corners, uv, color); - } - true - } - /// A banner in the first-person hand: the standing banner model under the - /// item's `firstperson_righthand` transform (`m`) and its special - /// transformation. False when the stack is not a banner. - pub(super) fn held_banner_geometry( - &self, - m: Mat4, - stack: &ItemStack, - packed: u32, - out: &mut Vec, - ) -> bool { - let Some(base) = banner::banner_color(&stack.item) else { - return false; - }; - let Some((main, flag)) = self.res.block_entity_render.banner_models() else { - return true; - }; - let m = m - * Mat4::from_translation(Vec3::new(0.5, 0.0, 0.5)) - * Mat4::from_scale(Vec3::new(2.0 / 3.0, -2.0 / 3.0, -2.0 / 3.0)); - let wave = |name: &str, p: &mut [f32; 9]| { - if name == "flag" { - p[3] = (-0.0125 + 0.01) * std::f32::consts::PI; - } - }; - let none = |_: &str, _: &mut [f32; 9]| {}; - let lights = horizon_client::block_entity_render::diffuse_lights(false); - let sprites = &self.res.atlas.sprites; - let paint = |name: &str, tint: u32| { - sprites.get(name).map(|&sprite| Paint { - sprite, - tint, - light: packed, - lights, - }) - }; - if let Some(p) = paint("entity/banner/banner_base", 0xFFFFFF) { - draw_part(main, "root", m, &none, p, out); - draw_part(flag, "root", m, &wave, p, out); - } - if let Some(p) = paint("entity/banner/base", banner::dye_rgb(base)) { - draw_part(flag, "root", m, &wave, p, out); - } - for layer in banner::layers(stack).iter().take(16) { - let texture = self.res.stations.banners.banner_texture(&layer.pattern); - if let Some(p) = paint(&texture, banner::dye_rgb(&layer.color)) { - draw_part(flag, "root", m, &wave, p, out); - } - } - true - } /// The layers a banner dropped at `pos` carries. pub(super) fn attach_banner_layers(&mut self, pos: [i32; 3], stack: &mut ItemStack) { if !stack.item.ends_with("_banner") { diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 26c1bf86f..792a07539 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -718,7 +718,6 @@ impl Game<'_> { self.mobs.append(&mut mobs); self.sync_riders(); self.tick_skeleton_traps(); - self.cache_mob_icons(); self.tick_apparition(); self.villager_reputation_tick(); self.villager_pickups(); diff --git a/crates/horizon-client/src/game/frames.rs b/crates/horizon-client/src/game/frames.rs index 269a4958c..5d80a424b 100644 --- a/crates/horizon-client/src/game/frames.rs +++ b/crates/horizon-client/src/game/frames.rs @@ -2,7 +2,7 @@ //! `ItemFrame.survives`, `interact` (put an item in, then rotate it), //! `hurtServer` (take the item out, then break the frame) and //! `ItemFrameRenderer` (the frame model and the item at a 45 degree step). -use super::{Game, Hit, Icon, view_vector}; +use super::{Game, Hit, view_vector}; use horizon_assets::{bake::bake_model, model::CuboidModel, resolve::ModelLibrary}; use horizon_client::{entities::ItemFrame, items::ItemStack, mesher::Vertex}; use horizon_core::{ @@ -300,17 +300,10 @@ impl Game<'_> { } /// ItemFrameRenderer: the frame model, then the item half size on its face. pub(super) fn frame_geometry(&mut self, camera: glam::DVec3, out: &mut Vec) { - let icons: Vec> = (0..self.item_frames.len()) - .map(|i| { - self.item_frames[i] - .item - .clone() - .and_then(|s| self.icon(&s.item)) - }) - .collect(); let sprites = &self.res.atlas.sprites; let mut maps: Vec<(i32, glam::Mat4, u32)> = Vec::new(); - for (f, icon) in self.item_frames.iter().zip(icons) { + let mut items: Vec<(ItemStack, u32, glam::Mat4, u8)> = Vec::new(); + for f in &self.item_frames { let map = f.item.as_ref().and_then(super::maps::map_id); let s = f.step(); // Pose: to the block centre, then X/Y rotation by facing. @@ -391,89 +384,33 @@ impl Game<'_> { maps.push((id, m.as_mat4(), item_light)); continue; } - let Some(icon) = icon else { continue }; - // GlowItemFrame items render full bright. - let item_light = if f.glow { 240 | 240 << 8 } else { packed }; + let Some(stack) = f.item.clone() else { + continue; + }; + // `GlowItemFrame` items render full bright (15728880). + let item_light = if f.glow { 0xFF } else { light }; let depth = if f.invisible { 0.5 } else { 0.4375 }; let m = pose * glam::DMat4::from_translation(glam::DVec3::new(0.0, 0.0, depth)) * glam::DMat4::from_rotation_z((f64::from(f.rotation) * 45.0).to_radians()) * glam::DMat4::from_scale(glam::DVec3::splat(0.5)); - let full = |r: &horizon_client::hud::Rect| { - [[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]] - }; - match icon { - // A flat item faces out of the frame (towards -z here). - Icon::Flat(sprite) => { - if let Some(r) = sprites.get(&sprite) { - let z = -0.03125; - quad( - &m, - [ - [0.5, -0.5, z], - [-0.5, -0.5, z], - [-0.5, 0.5, z], - [0.5, 0.5, z], - ], - full(r), - item_light, - ); - } - } - Icon::Cube { - top, left, right, .. - } => { - let h = 0.25; - let face = |name: &str| sprites.get(name).copied(); - if let (Some(t), Some(l), Some(r)) = (face(&top), face(&left), face(&right)) { - let c = |x: f64, y: f64, z: f64| [x * h, y * h, z * h - h]; - quad( - &m, - [ - c(-1., 1., -1.), - c(1., 1., -1.), - c(1., 1., 1.), - c(-1., 1., 1.), - ], - full(&t), - item_light, - ); - quad( - &m, - [ - c(1., -1., -1.), - c(-1., -1., -1.), - c(-1., 1., -1.), - c(1., 1., -1.), - ], - full(&l), - item_light, - ); - quad( - &m, - [ - c(-1., -1., -1.), - c(-1., -1., 1.), - c(-1., 1., 1.), - c(-1., 1., -1.), - ], - full(&r), - item_light, - ); - quad( - &m, - [ - c(1., -1., 1.), - c(1., -1., -1.), - c(1., 1., -1.), - c(1., 1., 1.), - ], - full(&r), - item_light, - ); - } - } - } + items.push((stack, f.id, m.as_mat4(), item_light)); + } + // `extractRenderState`: FIXED, seeded by the frame entity. + for (stack, id, m, light) in items { + let owner = super::item_draw::owner_at([0.0; 3], 0.0, "minecraft:item_frame"); + let state = self.resolve_item( + &stack, + horizon_assets::item_model::DisplayContext::Fixed, + Some(&owner), + id as i32, + ); + self.submit_item_world( + &state, + m, + horizon_client::block_entity_render::vertex_light(light), + out, + ); } for (id, m, light) in maps { self.map_vertices(id, m, light, out); diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs new file mode 100644 index 000000000..d5a4db677 --- /dev/null +++ b/crates/horizon-client/src/game/item_draw.rs @@ -0,0 +1,373 @@ +//! Items drawn through the resolved item model pipeline +//! (`horizon_client::item_render`): GUI icons (`GuiGraphics.renderItem`), +//! dropped items (`ItemEntityRenderer`) and items posed in the world (hands, +//! frames, armour stands). This binds the resolver's host services +//! (`ItemEnv`) and the special renderers' registries to the game. +use super::{Dim, Game}; +use horizon_assets::item_model::{ + Components, DisplayContext, GlobalPos, ItemEnv, LevelState, OwnerState, StackView, +}; +use horizon_client::{ + block_entity_render::{diffuse_lights, vertex_light}, + hud::HudBatch, + item_render::{self, ItemRenderState, SpecialHost, WorldSink}, + items::ItemStack, + mesher::Vertex, +}; +use serde_json::Value; +use winit::keyboard::KeyCode; + +/// The game's answers to what the resolver cannot read from the stack. +pub(super) struct Env<'a, 'g> { + game: &'a Game<'g>, +} +impl ItemEnv for Env<'_, '_> { + fn potion_effect_color(&self, contents: &Value) -> Option { + // `PotionContents.getColorOr`: the effect mix when any effect is visible. + let id = contents["potion"].as_str(); + let effects = id + .and_then(horizon_client::brewing::potion) + .is_some_and(|p| !p.effects.is_empty()); + effects.then(|| (0xFF00_0000 | horizon_client::brewing::potion_color(id)) as i32) + } + fn grass_color(&self, temperature: f64, downfall: f64) -> i32 { + self.game + .res + .item_renderer + .grass_color(temperature, downfall) + } + fn bundle_fullness(&self, _stack: &StackView, components: &Components) -> f32 { + // `BundleContents.weight`: count / max stack size, summed. + let Some(items) = components + .get("minecraft:bundle_contents") + .and_then(Value::as_array) + else { + return 0.0; + }; + let prototypes = &self.game.res.item_renderer.models.prototypes; + let mut total = 0.0f64; + for item in items { + let id = item["id"].as_str().unwrap_or(""); + let count = item["count"].as_i64().unwrap_or(1) as f64; + let max = prototypes + .get(id) + .and_then(|c| c.get("minecraft:max_stack_size")) + .and_then(Value::as_i64) + .unwrap_or(1) as f64; + total += count / max; + } + total as f32 + } + fn has_shift_down(&self) -> bool { + self.game.keys.contains(&KeyCode::ShiftLeft) + || self.game.keys.contains(&KeyCode::ShiftRight) + } + fn local_time(&self, pattern: &str, _locale: &str, _time_zone: Option<&str>) -> String { + local_time(pattern) + } + fn random_float(&self) -> f32 { + let nanos = self.game.started.elapsed().subsec_nanos(); + (nanos % 1_000_000) as f32 / 1_000_000.0 + } +} +/// The days since 1970-01-01 as a civil (year, month, day) date. +fn civil(days: i64) -> (i64, u32, u32) { + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = (doy - (153 * mp + 2) / 5 + 1) as u32; + let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; + (yoe + era * 400 + i64::from(m <= 2), m, d) +} +/// `DateTimeFormatter.ofPattern(pattern).format(now)` for the month, day, +/// year and time letters item models use (UTC: no time zone database). +pub(super) fn local_time(pattern: &str) -> String { + let secs = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs() as i64); + let (y, mo, d) = civil(secs.div_euclid(86_400)); + let s = secs.rem_euclid(86_400); + let (h, mi, se) = (s / 3600, s / 60 % 60, s % 60); + let mut out = String::new(); + let chars: Vec = pattern.chars().collect(); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + let mut n = 1; + while i + n < chars.len() && chars[i + n] == c { + n += 1; + } + let num = |v: i64| format!("{v:0n$}"); + match c { + 'M' => out += &num(i64::from(mo)), + 'd' => out += &num(i64::from(d)), + 'y' | 'u' => out += &if n == 2 { num(y % 100) } else { num(y) }, + 'H' => out += &num(h), + 'm' => out += &num(mi), + 's' => out += &num(se), + '\'' => { + // Quoted literal text. + let end = chars[i + 1..].iter().position(|&x| x == '\''); + if let Some(e) = end { + out.extend(&chars[i + 1..i + 1 + e]); + i += e + 2; + continue; + } + n = 1; + } + other => out.extend(std::iter::repeat_n(other, n)), + } + i += n; + } + out +} + +/// Banner and shield pattern textures from the banner pattern registry. +pub(super) struct Host<'a> { + banners: &'a horizon_client::banner::Banners, +} +impl SpecialHost for Host<'_> { + fn banner_texture(&self, pattern: &str) -> Option { + self.banners + .pattern(pattern) + .map(|_| self.banners.banner_texture(pattern)) + } + fn shield_texture(&self, pattern: &str) -> Option { + self.banners + .pattern(pattern) + .map(|_| self.banners.shield_texture(pattern)) + } +} + +/// `ItemOwner` of an entity holding or showing an item. +pub(super) fn owner_at(position: [f64; 3], yaw: f32, entity_type: &str) -> OwnerState { + OwnerState { + position, + visual_rotation_y_degrees: yaw, + entity_type: entity_type.to_owned(), + ..Default::default() + } +} +/// `UseDuration` of a stack: 72000 for drawn items, the consume time for food. +fn use_duration(components: &Components) -> i32 { + if let Some(c) = components.get("minecraft:consumable") { + let seconds = c["consume_seconds"].as_f64().unwrap_or(1.6); + return (seconds * 20.0) as i32; + } + let item_model = components + .get("minecraft:item_model") + .and_then(Value::as_str) + .unwrap_or(""); + match item_model { + "minecraft:bow" + | "minecraft:crossbow" + | "minecraft:trident" + | "minecraft:spyglass" + | "minecraft:goat_horn" + | "minecraft:brush" => 72_000, + _ => 0, + } +} + +impl Game<'_> { + pub(super) fn item_env(&self) -> Env<'_, '_> { + Env { game: self } + } + pub(super) fn item_host(&self) -> Host<'_> { + Host { + banners: &self.res.stations.banners, + } + } + /// The client level as item models read it. + pub(super) fn item_level(&self) -> LevelState { + let dimension = match self.dim { + Dim::Overworld => "minecraft:overworld", + Dim::Nether => "minecraft:the_nether", + Dim::End => "minecraft:the_end", + }; + let sky = self + .dim_environment() + .sample(self.world.day_time, None, None); + LevelState { + dimension: dimension.to_owned(), + game_time: self.world.game_time, + sun_angle: sky.sun_angle, + moon_phase: (self.world.day_time.div_euclid(24_000)).rem_euclid(8) as i32, + respawn: self.spawn.map(|s| GlobalPos { + dimension: "minecraft:overworld".to_owned(), + pos: [s.x.floor() as i32, s.y.floor() as i32, s.z.floor() as i32], + }), + runs_normally: true, + } + } + /// The local player as `ItemOwner`; `stack` is the stack drawn, to tell + /// whether it is the one in use. + pub(super) fn player_owner(&self, stack: Option<&ItemStack>) -> OwnerState { + let position = self + .player + .as_ref() + .map_or([0.0; 3], |p| [p.position.x, p.position.y, p.position.z]); + let mut owner = owner_at(position, self.yaw, "minecraft:player"); + owner.main_arm_left = self.settings.main_hand_left; + owner.is_local_player = true; + owner.is_view_entity = true; + if let (Some((slot, ticks)), Some(stack)) = (self.using, stack) + && self.inventory.get(slot).and_then(Option::as_ref) == Some(stack) + { + let view = item_render::stack_view(stack); + let duration = use_duration(&self.res.item_renderer.models.components(&view)); + owner.using_this_item = true; + owner.use_duration = duration; + owner.use_item_remaining_ticks = duration - ticks as i32; + owner.crossbow_charge_duration = 25; + } + owner.is_selected = + stack.is_some() && self.inventory.get(self.selected).and_then(Option::as_ref) == stack; + owner.is_carried = owner.is_selected; + owner + } + /// `ItemModelResolver.updateForTopItem`. + pub(super) fn resolve_item( + &self, + stack: &ItemStack, + display: DisplayContext, + owner: Option<&OwnerState>, + seed: i32, + ) -> ItemRenderState { + let level = self.item_level(); + self.res.item_renderer.resolve( + &item_render::stack_view(stack), + display, + owner, + Some(&level), + seed, + &self.item_env(), + ) + } + /// `GuiGraphics.renderItem(player, level, stack, x, y, 0)`. + pub(super) fn draw_item_model(&self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) { + let owner = self.player_owner(Some(stack)); + let state = self.resolve_item(stack, DisplayContext::Gui, Some(&owner), 0); + item_render::gui::draw( + &state, + &self.res.item_renderer, + &self.res.atlas.sprites, + &self.item_host(), + batch, + x, + y, + self.started.elapsed().as_secs_f32(), + ); + } + /// Submit a resolved item under `pose` (camera-relative) at `light` + /// (packed lightmap coordinates). + pub(super) fn submit_item_world( + &self, + state: &ItemRenderState, + pose: glam::Mat4, + light: u32, + out: &mut Vec, + ) { + let mut sink = WorldSink { + out, + light, + lights: Some(diffuse_lights(self.dim == Dim::Nether)), + }; + state.submit( + &self.res.item_renderer, + &self.res.atlas.sprites, + &self.item_host(), + pose, + &mut sink, + ); + } + /// [`Self::submit_item_world`] without the level's diffuse shading. + pub(super) fn submit_item_unlit( + &self, + state: &ItemRenderState, + pose: glam::Mat4, + light: u32, + out: &mut Vec, + ) { + let mut sink = WorldSink { + out, + light, + lights: None, + }; + state.submit( + &self.res.item_renderer, + &self.res.atlas.sprites, + &self.item_host(), + pose, + &mut sink, + ); + } + /// `ItemEntityRenderer.submit` for every dropped item. + pub(super) fn dropped_item_geometry( + &self, + camera: glam::DVec3, + alpha: f64, + out: &mut Vec, + ) { + for item in &self.dropped { + let (p, q) = (item.previous, item.position); + let pos = glam::DVec3::new( + p.x + (q.x - p.x) * alpha, + p.y + (q.y - p.y) * alpha, + p.z + (q.z - p.z) * alpha, + ) - camera; + if pos.length_squared() > 64.0 * 64.0 { + continue; + } + // `extractItemGroupRenderState`: GROUND, seeded by the entity id. + let owner = owner_at([q.x, q.y, q.z], 0.0, "minecraft:item"); + let state = self.resolve_item( + &item.stack, + DisplayContext::Ground, + Some(&owner), + item.id as i32, + ); + if state.is_empty() { + continue; + } + let age = item.age as f32 + alpha as f32; + let (lo, _) = state.bounding_box(); + let min_offset_y = -lo.y + 0.0625; + let bob = (age / 10.0 + item.bob_offset).sin() * 0.1 + 0.1; + let spin = item_render::item_spin(age, item.bob_offset); + let pose = glam::Mat4::from_translation(pos.as_vec3()) + * glam::Mat4::from_translation(glam::Vec3::new(0.0, bob + min_offset_y, 0.0)) + * glam::Mat4::from_rotation_y(spin); + let packed = self.world.light( + q.x.floor() as i32, + (q.y + 0.1).floor() as i32, + q.z.floor() as i32, + ); + let seed = i64::from(self.res.item_renderer.item_id(&item.stack.item)) + + i64::from(item.stack.damage); + for copy in item_render::cluster_poses( + &state, + pose, + item_render::rendered_amount(item.stack.count), + seed, + ) { + self.submit_item_world(&state, copy, vertex_light(packed), out); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn civil_dates_follow_the_gregorian_calendar() { + assert_eq!(civil(0), (1970, 1, 1)); + assert_eq!(civil(19_716), (2023, 12, 25)); + assert_eq!(civil(11_016), (2000, 2, 29)); + } +} diff --git a/crates/horizon-client/src/game/mob_blocks.rs b/crates/horizon-client/src/game/mob_blocks.rs index b7570ea27..d2fe1f8af 100644 --- a/crates/horizon-client/src/game/mob_blocks.rs +++ b/crates/horizon-client/src/game/mob_blocks.rs @@ -1,8 +1,9 @@ //! Blocks mobs carry: block items in a hand (`ItemInHandLayer`) and the //! block an enderman holds (`CarriedBlockLayer`), drawn as shaded cubes like //! dropped block items. -use super::{Game, Icon}; +use super::Game; use horizon_client::{ + items::ItemStack, mesher::Vertex, mobs::{Mob, Species, render}, }; @@ -176,22 +177,6 @@ impl Game<'_> { render::draw(flag, m, &flag_poses, r, color, light, 0, out); } } - /// Resolve the icons of the items mobs hold, so drawing can look them up. - pub(super) fn cache_mob_icons(&mut self) { - let items: Vec = self - .mobs - .iter() - .filter(|m| m.extra.main_hand.is_some() || m.extra.off_hand.is_some()) - .flat_map(|m| [m.extra.main_hand.clone(), m.extra.off_hand.clone()]) - .flatten() - .map(|i| i.to_string()) - .collect(); - for item in items { - if !self.res.icons.contains_key(&item) { - let _ = self.icon(&item); - } - } - } fn push_cube( &self, t: glam::Mat4, @@ -232,40 +217,7 @@ impl Game<'_> { ) { let overlay = u32::from(mob.hurt_time > 0); self.captain_banner_geometry(mob, camera, alpha, light, out); - for (item, left) in [(&mob.extra.main_hand, false), (&mob.extra.off_hand, true)] { - let Some(item) = item else { continue }; - let Some(Icon::Cube { - top, - left: z, - right: x, - tint, - }) = self.res.icons.get(&**item).cloned().flatten() - else { - continue; - }; - let Some(t) = - render::held_block_transform(mob, alpha as f32, camera, &self.res.mob_data, left) - else { - continue; - }; - let slot = if left { - horizon_client::mobs::gear::OFF - } else { - horizon_client::mobs::gear::MAIN - }; - let glint = horizon_client::mobs::gear::enchanted(mob, slot); - let overlay = if glint { 7 } else { overlay }; - self.push_cube( - t, - &Cube { - sprites: [&top, &z, &x], - tint, - }, - light, - overlay, - out, - ); - } + self.held_item_geometry(mob, camera, alpha, light, true, out); if mob.species() == Species::Enderman && let Some(state) = mob.extra.carried && let Some((sprite, tint)) = self.particle_sprite(state) @@ -292,4 +244,71 @@ impl Game<'_> { ); } } + /// `ItemInHandLayer`: both hands through the item model pipeline; `lit` + /// applies the level's diffuse lighting (off for GUI previews, which + /// light the projected quads themselves). + pub(super) fn held_item_geometry( + &self, + mob: &Mob, + camera: glam::DVec3, + alpha: f64, + light: u32, + lit: bool, + out: &mut Vec, + ) { + let overlay = u32::from(mob.hurt_time > 0); + for (item, left) in [(&mob.extra.main_hand, false), (&mob.extra.off_hand, true)] { + let Some(item) = item else { continue }; + let Some(t) = + render::held_item_transform(mob, alpha as f32, camera, &self.res.mob_data, left) + else { + continue; + }; + let slot = if left { + horizon_client::mobs::gear::OFF + } else { + horizon_client::mobs::gear::MAIN + }; + let mut stack = ItemStack::new(item, 1); + if horizon_client::mobs::gear::enchanted(mob, slot) { + // The gear's enchantments are not tracked, only that it has some. + stack.enchant("minecraft:unbreaking", 1); + } + if &**item == "minecraft:crossbow" && mob.extra.flag2 { + stack.data_mut().charged = vec![ItemStack::new("minecraft:arrow", 1)]; + } + let mut owner = super::item_draw::owner_at( + [mob.position.x, mob.position.y, mob.position.z], + mob.body_yaw, + &mob.kind.id, + ); + if !left && mob.extra.using_item > 0 { + owner.using_this_item = true; + owner.use_duration = 72_000; + owner.use_item_remaining_ticks = 72_000 - mob.extra.using_item; + owner.crossbow_charge_duration = 25; + } + let context = if left { + horizon_assets::item_model::DisplayContext::ThirdPersonLeftHand + } else { + horizon_assets::item_model::DisplayContext::ThirdPersonRightHand + }; + // `updateForLiving`: seeded by the entity id plus the context ordinal. + let seed = mob.id as i32 + if left { 1 } else { 2 }; + let state = self.resolve_item(&stack, context, Some(&owner), seed); + let start = out.len(); + if lit { + self.submit_item_world(&state, t, light, out); + } else { + self.submit_item_unlit(&state, t, light, out); + } + if overlay != 0 { + for v in &mut out[start..] { + if v.layer == 0 { + v.layer = overlay; + } + } + } + } + } } diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index a1f4b8c25..fe438915d 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -123,8 +123,10 @@ impl Game<'_> { ); } self.res.atlas = atlas; - self.res.icons.clear(); - self.res.displays.clear(); + match horizon_client::item_render::ItemRenderer::load(&root) { + Ok(r) => self.res.item_renderer = std::sync::Arc::new(r), + Err(e) => eprintln!("Horizon: item model reload failed: {e}"), + } } else { eprintln!( "Horizon: resource pack atlas size changed; restart to apply GUI textures" diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index c175733bb..9d4ae7fa6 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -242,6 +242,7 @@ impl Game<'_> { &self.player_armor_layers(), out, ); + self.held_item_geometry(m, camera, alpha, packed, true, out); } /// `extractEntityInInventoryFollowsMouse`: the player in the box /// `[x0, x1) x [y0, y1)`, `size` pixels per block, turned toward the @@ -295,6 +296,7 @@ impl Game<'_> { &self.player_armor_layers(), &mut verts, ); + self.held_item_geometry(&m, camera, 1.0, 240 | 240 << 8, false, &mut verts); let height = if m.extra.crouching { 1.5 } else { 1.8 }; // PictureInPictureRenderer: the box centre, (size, size, -size); // then the translation and Rz(pi) * Rx(y_angle * 20 degrees). diff --git a/crates/horizon-client/src/game/shield.rs b/crates/horizon-client/src/game/shield.rs index 7857c047e..2821738c5 100644 --- a/crates/horizon-client/src/game/shield.rs +++ b/crates/horizon-client/src/game/shield.rs @@ -244,132 +244,3 @@ impl Game<'_> { } } } - -/// The shield in a slot: `ShieldSpecialRenderer`'s plate and handle boxes -/// under item/shield's `gui` display transform, flat-lit and depth-sorted. -pub(super) fn draw_shield_icon( - batch: &mut horizon_client::hud::HudBatch, - atlas: &horizon_client::hud::HudAtlas, - x: f32, - y: f32, - passes: &[(String, u32)], -) { - // display.gui: rotation [15, -25, -5], translation [2, 3, 0], scale 0.65. - let (sx, cx) = 15f32.to_radians().sin_cos(); - let (sy, cy) = (-25f32).to_radians().sin_cos(); - let (sz, cz) = (-5f32).to_radians().sin_cos(); - // Quaternionf.rotationXYZ: Rx * Ry * Rz. - let rotate = |[x, y, z]: [f32; 3]| { - let (x, y) = (x * cz - y * sz, x * sz + y * cz); - let (x, z) = (x * cy + z * sy, -x * sy + z * cy); - let (y, z) = (y * cx - z * sx, y * sx + z * cx); - [x, y, z] - }; - // Model pixels -> slot pixels: S(1,-1,-1), T(-0.5), S(0.65), R, T, and - // the GUI's (16, -16, 16) around the slot centre. - let place = |[px, py, pz]: [f32; 3]| { - let q = [px / 16.0 - 0.5, -py / 16.0 - 0.5, -pz / 16.0 - 0.5].map(|v| v * 0.65); - let [qx, qy, qz] = rotate(q); - [ - x + 8.0 + (qx + 2.0 / 16.0) * 16.0, - y + 8.0 - (qy + 3.0 / 16.0) * 16.0, - qz, - ] - }; - // ShieldModel: plate texOffs(0, 0) box(-6, -11, -2, 12, 22, 1) and - // handle texOffs(26, 0) box(-1, -3, -1, 2, 6, 6). - let mut faces: Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], f32)> = Vec::new(); - for (tu, tv, from, size) in [ - (0.0, 0.0, [-6.0, -11.0, -2.0], [12.0, 22.0, 1.0]), - (26.0, 0.0, [-1.0, -3.0, -1.0], [2.0, 6.0, 6.0]), - ] { - let [w, h, d] = size; - let (x0, y0, z0) = (from[0], from[1], from[2]); - let (x1, y1, z1) = (x0 + w, y0 + h, z0 + d); - let t0 = [x0, y0, z0]; - let t1 = [x1, y0, z0]; - let t2 = [x1, y1, z0]; - let t3 = [x0, y1, z0]; - let l0 = [x0, y0, z1]; - let l1 = [x1, y0, z1]; - let l2 = [x1, y1, z1]; - let l3 = [x0, y1, z1]; - let (u0, u1, u2) = (tu, tu + d, tu + d + w); - let (u22, u3, u4) = (tu + d + w + w, tu + d + w + d, tu + d + w + d + w); - let (v0, v1, v2) = (tv, tv + d, tv + d + h); - // ModelPart.Cube's polygons: (vertices, u0, v0, u1, v1, normal). - for (verts, a, b, c, e, n) in [ - ([l1, l0, t0, t1], u1, v0, u2, v1, [0.0, -1.0, 0.0]), - ([t2, t3, l3, l2], u2, v1, u22, v0, [0.0, 1.0, 0.0]), - ([t0, l0, l3, t3], u0, v1, u1, v2, [-1.0, 0.0, 0.0]), - ([t1, t0, t3, t2], u1, v1, u2, v2, [0.0, 0.0, -1.0]), - ([l1, t1, t2, l2], u2, v1, u3, v2, [1.0, 0.0, 0.0]), - ([l0, l1, l2, l3], u3, v1, u4, v2, [0.0, 0.0, 1.0]), - ] { - let normal = rotate([n[0], -n[1], -n[2]]); - if normal[2] <= 0.0 { - continue; - } - let p = verts.map(place); - let depth = p.iter().map(|q| q[2]).sum::() / 4.0; - let texels = [[c, b], [a, b], [a, e], [c, e]]; - // Flat item lighting: faces toward the viewer are brightest. - let shade = (0.6 + 0.4 * normal[2]).min(1.0); - faces.push((depth, p.map(|q| [q[0], q[1]]), texels, shade)); - } - } - // Every pass redraws the same boxes; equal depths keep the pass order. - let mut quads = Vec::new(); - for (index, (name, tint)) in passes.iter().enumerate() { - let Some(r) = atlas.sprites.get(name).copied() else { - continue; - }; - for (depth, p, texels, shade) in &faces { - let uv = texels.map(|[u, v]| { - [ - r.u0 + (r.u1 - r.u0) * u / 64.0, - r.v0 + (r.v1 - r.v0) * v / 64.0, - ] - }); - let c = |s: u32| (((tint >> s) & 255) as f32 * shade) as u8; - quads.push(( - *depth, - index, - *p, - uv, - horizon_client::hud::rgba(c(16), c(8), c(0), 255), - )); - } - } - quads.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); - for (_, _, p, uv, color) in quads { - batch.quad(p, uv, color); - } -} -/// The textures a shield draws: the plain or patterned base, then the -/// banner layers (`ShieldSpecialRenderer.submit`). -pub(super) fn shield_passes( - banners: &horizon_client::banner::Banners, - stack: &ItemStack, -) -> Vec<(String, u32)> { - let data = stack.data(); - let layers = data.map_or(&[][..], |d| &d.banner_patterns[..]); - let base = data.and_then(|d| d.base_color.as_deref()); - if layers.is_empty() && base.is_none() { - return vec![("entity/shield/shield_base_nopattern".into(), 0xFFFFFF)]; - } - let mut passes = vec![ - ("entity/shield/shield_base".into(), 0xFFFFFF), - ( - "entity/shield/base".into(), - horizon_client::banner::dye_rgb(base.unwrap_or("white")), - ), - ]; - for layer in layers.iter().take(16) { - passes.push(( - banners.shield_texture(&layer.pattern), - horizon_client::banner::dye_rgb(&layer.color), - )); - } - passes -} diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 90892be56..e75db5b6f 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -1991,100 +1991,6 @@ impl Game<'_> { self.draw_tooltip_lines(batch, &[(text, u32::MAX)], self.cursor.0, self.cursor.1); } } - /// Potion items: `layer0` tinted with the potion colour under the bottle - /// (`minecraft:potion` item tint source). - pub(super) fn draw_potion_layers( - &self, - batch: &mut HudBatch, - stack: &ItemStack, - x: f32, - y: f32, - ) { - let (overlay, base) = match &*stack.item { - "minecraft:potion" => ("item/potion_overlay", "item/potion"), - "minecraft:splash_potion" => ("item/potion_overlay", "item/splash_potion"), - "minecraft:lingering_potion" => ("item/potion_overlay", "item/lingering_potion"), - "minecraft:tipped_arrow" => ("item/tipped_arrow_head", "item/tipped_arrow_base"), - _ => return, - }; - let c = brewing::potion_color(stack.potion()); - let atlas = &self.res.atlas; - batch.sprite_scaled( - atlas, - overlay, - x, - y, - 16.0, - 16.0, - rgba( - (c >> 16 & 255) as u8, - (c >> 8 & 255) as u8, - (c & 255) as u8, - 255, - ), - ); - batch.sprite_scaled(atlas, base, x, y, 16.0, 16.0, u32::MAX); - } - /// The enchantment glint over an item icon: a shimmering purple tint. - pub(super) fn draw_glint(&self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) { - if !self.res.stations.enchantments.has_glint(stack) { - return; - } - // ItemRenderer glint: the enchanted_glint texture scrolls diagonally over the - // item's shape. Approximated with a grid of item-texture quads whose vertex - // colours carry a purple base tint plus a moving bright band. - let t = self.started.elapsed().as_secs_f32(); - let glint = |gx: f32, gy: f32| -> u32 { - let d = ((gx + gy) / 32.0 - t * 0.35).rem_euclid(1.0); - let band = (1.0 - (d - 0.5).abs() * 6.0).max(0.0); - let a = 45.0 + 110.0 * band; - rgba( - (170.0 + 70.0 * band) as u8, - (90.0 + 110.0 * band) as u8, - 255, - a as u8, - ) - }; - match self.res.icons.get(&*stack.item).cloned().flatten() { - Some(super::Icon::Flat(name)) => { - let Some(r) = self.res.atlas.sprites.get(&name).copied() else { - return; - }; - const N: usize = 4; - let cell = 16.0 / N as f32; - let (du, dv) = ((r.u1 - r.u0) / N as f32, (r.v1 - r.v0) / N as f32); - for row in 0..N { - for col in 0..N { - let (x0, y0) = (col as f32 * cell, row as f32 * cell); - let (u0, v0) = (r.u0 + du * col as f32, r.v0 + dv * row as f32); - let corners = [ - (x0, y0, u0, v0), - (x0 + cell, y0, u0 + du, v0), - (x0 + cell, y0 + cell, u0 + du, v0 + dv), - (x0, y0 + cell, u0, v0 + dv), - ]; - for i in [0usize, 1, 2, 0, 2, 3] { - let (cx, cy, u, v) = corners[i]; - batch.vertices.push(horizon_client::hud::HudVertex { - pos: [x + cx, y + cy], - uv: [u + 2.0, v], - color: glint(cx, cy), - }); - } - } - } - } - Some(super::Icon::Cube { .. }) => batch.fill( - &self.res.atlas, - x + 1.0, - y + 1.0, - 14.0, - 14.0, - glint(8.0, 8.0) & 0x7FFF_FFFF, - ), - None => {} - } - } // ---------------------------------------------------------------- brewing stand diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index ed1a91c15..bc78f3ccd 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -62,6 +62,58 @@ fn walk(dir: &Path, out: &mut Vec) { } } } +/// A packed atlas image: sprite name, size and RGBA pixels. +type PackedImage = (String, u32, u32, Vec); +/// Sprites the atlas definitions (`atlases/*.json`) add beyond the texture +/// files already packed: generated ones (`paletted_permutations` such as the +/// armour trim sprites, `unstitch` regions) and files listed under another id. +fn atlas_sprites(root: &Path, packed: &[PackedImage]) -> Vec { + use crate::atlas_sources::{self, SpriteOrigin}; + let have: std::collections::HashSet<&str> = packed.iter().map(|i| i.0.as_str()).collect(); + let textures = atlas_sources::list_textures(root); + let load = |texture: &str, directory: &str| { + decode(&atlas_sources::texture_path(root, texture, directory)).ok() + }; + let mut out: Vec = Vec::new(); + let mut added = std::collections::HashSet::new(); + for (atlas, sources) in atlas_sources::atlases(root) { + // The other atlases' renamed files (GUI sprites, particles...) are + // looked up by their texture paths here. + let item_models = atlas == "minecraft:blocks" || atlas == "minecraft:items"; + for (id, origin) in atlas_sources::list(&sources, &textures) { + if !item_models && matches!(origin, SpriteOrigin::File(_)) { + continue; + } + let name = id.strip_prefix("minecraft:").unwrap_or(&id).to_owned(); + if have.contains(name.as_str()) || added.contains(&name) { + continue; + } + let image = match &origin { + SpriteOrigin::File(texture) => { + let path = texture.strip_prefix("minecraft:").unwrap_or(texture); + // Packed under its own name already: only a renamed file is new. + if path == name { + continue; + } + load(texture, "textures").map(|(w, h, p)| { + // Animated strips keep their first frame, like the packed files. + if h > w && (path.starts_with("block/") || path.starts_with("item/")) { + (w, w, p[..(w * w * 4) as usize].to_vec()) + } else { + (w, h, p) + } + }) + } + generated => atlas_sources::generate(generated, &load), + }; + if let Some((w, h, pixels)) = image { + added.insert(name.clone()); + out.push((name, w, h, pixels)); + } + } + } + out +} impl HudAtlas { /// A font glyph's atlas cell (8x8 GUI pixels) and advance. pub fn glyph(&self, ch: char) -> Option<(Rect, f32)> { @@ -131,6 +183,7 @@ impl HudAtlas { .flat_map(|h| h.join().unwrap_or_default()) .collect() }); + images.extend(atlas_sprites(root, &images)); images.push(("horizon/white".into(), 4, 4, vec![255; 64])); // Map textures (game/maps.rs) are written into these slots at run time. for i in 0..MAP_SLOTS { diff --git a/crates/horizon-client/src/item_render.rs b/crates/horizon-client/src/item_render.rs new file mode 100644 index 000000000..bd5c47179 --- /dev/null +++ b/crates/horizon-client/src/item_render.rs @@ -0,0 +1,815 @@ +//! Item rendering through the resolved item model pipeline: the +//! `ItemModelResolver` of `horizon-assets` fills an [`ItemRenderState`] +//! (`ItemStackRenderState`: layers of baked quads or special renderers, each +//! with its display transform, local transform, tints and foil), and +//! [`ItemRenderState::submit`] turns it into the quads `ItemFeatureRenderer` +//! and the special model renderers submit, in pose space. A sink then draws +//! them: [`gui`] into the HUD batch with the GUI item lighting, [`WorldSink`] +//! into entity vertices with the level's lighting. +pub mod gui; +mod special; + +use crate::{ + block_entity_render::{ModelPart, diffuse}, + hud::Rect, + mesher::Vertex, +}; +use glam::{Mat3, Mat4, Vec3}; +use horizon_assets::{ + animation::AnimationMetadata, + item_bake::{BakedItemModel, SpriteLookup, SpriteMask, bake_item_model}, + item_model::{ + ClientItem, Components, Context, DisplayContext, FoilType, ItemEnv, ItemModels, + LayerContent, LevelState, OwnerState, SpecialModel, StackView, + }, + model::{CuboidModel, Direction}, + palette::PalettedPermutations, + resolve::{MISSING_MODEL, ModelLibrary}, +}; +use horizon_world::nbt::Tag; +use serde_json::Value; +use std::{ + collections::{BTreeMap, HashMap}, + fs, + path::{Path, PathBuf}, + sync::{Arc, Mutex}, +}; + +/// One quad as submitted for drawing: pose-space corners, atlas UVs, the +/// transformed unit normal, ARGB colour (tint, `-1` white) and its glint. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ItemQuad { + pub pos: [Vec3; 4], + pub uv: [[f32; 2]; 4], + pub normal: Vec3, + pub color: u32, + pub foil: Foil, + /// `MaterialInfo.lightEmission` (block light floor). + pub light_emission: u8, +} +/// Which glint render type a quad uses. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Foil { + None, + /// `GLINT_TEXTURING` over the sprite's UVs (`itemGlintRenderType`, + /// `entitySolidGlint`). + Standard, + /// `itemGlintSpecialRenderType`: compasses and clocks, a sheeted decal. + Special, +} +/// Where submitted quads go. +pub trait ItemSink { + fn quad(&mut self, quad: ItemQuad); +} +impl ItemSink for Vec { + fn quad(&mut self, quad: ItemQuad) { + self.push(quad); + } +} + +/// Data special renderers read from the game (registries, skins). +pub trait SpecialHost { + /// The banner atlas texture of a banner pattern (`entity/banner/`). + fn banner_texture(&self, pattern: &str) -> Option; + /// The shield atlas texture of a banner pattern (`entity/shield/`). + fn shield_texture(&self, pattern: &str) -> Option; + /// The skin texture of a `minecraft:profile` component, if loaded. + fn player_skin(&self, _profile: &Value) -> Option { + None + } +} +/// A host with no registries: patterns and skins fall back to defaults. +pub struct NoHost; +impl SpecialHost for NoHost { + fn banner_texture(&self, _: &str) -> Option { + None + } + fn shield_texture(&self, _: &str) -> Option { + None + } +} + +/// The geometry of one layer. +#[derive(Clone, Debug)] +pub enum LayerGeometry { + Quads(Arc), + Special { + model: SpecialModel, + argument: Value, + }, +} +/// `ItemStackRenderState.LayerRenderState`. +#[derive(Clone, Debug)] +pub struct LayerRender { + pub geometry: LayerGeometry, + pub tints: Vec, + pub foil: FoilType, + /// `applyTransform`: the display transform, then the local transform. + pub matrix: Mat4, + /// `particleMaterial` (atlas sprite name). + pub particle: String, + pub uses_block_light: bool, + /// Untransformed extents (quad corners or the special model's parts). + pub extents: Arc>, +} +/// `ItemStackRenderState`. +#[derive(Clone, Debug)] +pub struct ItemRenderState { + pub display: DisplayContext, + pub layers: Vec, + pub oversized_in_gui: bool, + pub animated: bool, +} +impl ItemRenderState { + pub fn is_empty(&self) -> bool { + self.layers.is_empty() + } + /// `pickParticleMaterial`: a random layer's particle sprite. + pub fn pick_particle( + &self, + random: &mut impl horizon_core::random::RandomSource, + ) -> Option { + if self.layers.is_empty() { + return None; + } + let i = random.next_int_bound(self.layers.len() as i32).unwrap_or(0) as usize; + self.layers.get(i).map(|l| l.particle.clone()) + } + /// `usesBlockLight` of the first layer (GUI lighting choice). + pub fn uses_block_light(&self) -> bool { + self.layers.first().is_some_and(|l| l.uses_block_light) + } + /// `getModelBoundingBox`: the transformed extents of every layer, as + /// (min, max); a zero box at the origin when there are none. + pub fn bounding_box(&self) -> (Vec3, Vec3) { + let mut lo = Vec3::splat(f32::INFINITY); + let mut hi = Vec3::splat(f32::NEG_INFINITY); + for layer in &self.layers { + for p in layer.extents.iter() { + let q = layer.matrix.transform_point3(*p); + lo = lo.min(q); + hi = hi.max(q); + } + } + if lo.x > hi.x { + (Vec3::ZERO, Vec3::ZERO) + } else { + (lo, hi) + } + } + /// `ItemStackRenderState.submit` under `pose`. + pub fn submit( + &self, + renderer: &ItemRenderer, + sprites: &HashMap, + host: &dyn SpecialHost, + pose: Mat4, + sink: &mut dyn ItemSink, + ) { + for layer in &self.layers { + let m = pose * layer.matrix; + match &layer.geometry { + LayerGeometry::Quads(baked) => { + submit_quads(baked, layer, self.display, m, sprites, sink); + } + LayerGeometry::Special { model, argument } => special::submit( + renderer, + model, + argument, + layer.foil != FoilType::None, + m, + sprites, + host, + sink, + ), + } + } + } +} + +/// The atlas name of a sprite identifier (`minecraft:item/apple` -> `item/apple`). +pub fn sprite_name(sprite: &str) -> &str { + sprite.strip_prefix("minecraft:").unwrap_or(sprite) +} +/// `Direction.getUnitVec3f`. +pub fn direction_vector(d: Direction) -> Vec3 { + match d { + Direction::Down => Vec3::NEG_Y, + Direction::Up => Vec3::Y, + Direction::North => Vec3::NEG_Z, + Direction::South => Vec3::Z, + Direction::West => Vec3::NEG_X, + Direction::East => Vec3::X, + } +} +/// `PoseStack.Pose.transformNormal`: the normal matrix, renormalized. +pub fn transform_normal(m: Mat4, n: Vec3) -> Vec3 { + let normal = Mat3::from_mat4(m).inverse().transpose(); + (normal * n).normalize_or_zero() +} +/// An `ARGB` int as the `u32` colour of an [`ItemQuad`]. +pub fn argb(color: i32) -> u32 { + color as u32 +} + +/// `ItemFeatureRenderer.prepareMainSubmit` for one cuboid layer. +fn submit_quads( + baked: &BakedItemModel, + layer: &LayerRender, + display: DisplayContext, + m: Mat4, + sprites: &HashMap, + sink: &mut dyn ItemSink, +) { + let foil = match layer.foil { + FoilType::None => Foil::None, + FoilType::Standard => Foil::Standard, + FoilType::Special => Foil::Special, + }; + let _ = display; + for q in &baked.quads { + let Some(r) = sprites + .get(sprite_name(&q.material.sprite)) + .or_else(|| sprites.get("misc/missingno")) + .or_else(|| sprites.get("horizon/missingno")) + .copied() + else { + continue; + }; + // `getLayerColorSafe`: an untinted quad, or a tint index past the + // tints, draws white. + let color = if q.tint_index >= 0 { + layer + .tints + .get(q.tint_index as usize) + .copied() + .unwrap_or(-1) + } else { + -1 + }; + let pos = q.positions.map(|p| m.transform_point3(Vec3::from(p))); + let uv = + q.uv.map(|[u, v]| [r.u0 + (r.u1 - r.u0) * u, r.v0 + (r.v1 - r.v0) * v]); + sink.quad(ItemQuad { + pos, + uv, + normal: transform_normal(m, direction_vector(q.facing)), + color: argb(color), + foil, + light_emission: q.light_emission, + }); + } +} + +// --------------------------------------------------------------------------- +// Sprites for baking +// --------------------------------------------------------------------------- + +/// The alpha masks of item and block sprites, read from the texture files +/// (every unique animation frame) and the items atlas's palette sprites. +struct FileSprites { + root: PathBuf, + permutations: Vec, + cache: Mutex>>, +} +impl SpriteLookup for FileSprites { + fn mask(&self, sprite: &str) -> Option { + if let Ok(cache) = self.cache.lock() + && let Some(hit) = cache.get(sprite) + { + return hit.clone(); + } + let mask = self.load(sprite); + if let Ok(mut cache) = self.cache.lock() { + cache.insert(sprite.to_owned(), mask.clone()); + } + mask + } +} +fn argb_pixels(rgba: &[u8]) -> Vec { + rgba.as_chunks::<4>() + .0 + .iter() + .map(|p| u32::from_be_bytes([p[3], p[0], p[1], p[2]])) + .collect() +} +impl FileSprites { + fn png(&self, sprite: &str, directory: &str) -> PathBuf { + crate::atlas_sources::texture_path(&self.root, sprite, directory) + } + fn image(&self, sprite: &str, directory: &str) -> Option<(usize, usize, Vec)> { + let (w, h, rgba) = crate::hud::decode(&self.png(sprite, directory)).ok()?; + Some((w as usize, h as usize, argb_pixels(&rgba))) + } + fn load(&self, sprite: &str) -> Option { + let png = self.png(sprite, "textures"); + let (iw, ih, argb) = match self.image(sprite, "textures") { + Some(image) => image, + None => { + let p = self.permutations.iter().find_map(|s| s.find(sprite))?; + let (w, h, mut pixels) = self.image(p.base, "textures")?; + let (_, _, key) = self.image(p.palette_key, "textures/palettes")?; + let (_, _, target) = self.image(p.palette, "textures/palettes")?; + horizon_assets::palette::apply_palette(&mut pixels, &key, &target)?; + (w, h, pixels) + } + }; + let alpha: Vec = argb.iter().map(|p| (p >> 24) as u8).collect(); + let animation = fs::read_to_string(png.with_extension("png.mcmeta")) + .ok() + .and_then(|m| serde_json::from_str::(&m).ok()) + .and_then(|m| m.get("animation").map(Value::to_string)) + .and_then(|a| AnimationMetadata::from_json(&a).ok()); + let (w, h) = match &animation { + Some(a) => { + let [w, h] = a.frame_size(iw as i32, ih as i32); + (w as usize, h as usize) + } + None => (iw, ih), + }; + if w == 0 || h == 0 { + return None; + } + let columns = iw / w; + let total = columns * (ih / h); + let clip = animation.and_then(|a| a.clip(total as u32).ok().flatten()); + let frames: Vec = match clip { + Some(clip) => { + let mut unique = Vec::new(); + for (index, _) in clip.sequence() { + if !unique.contains(&(*index as usize)) { + unique.push(*index as usize); + } + } + unique + } + None => vec![0], + }; + let frames = frames + .into_iter() + .map(|f| { + let (fx, fy) = (f % columns * w, f / columns * h); + (0..h) + .flat_map(|y| (0..w).map(move |x| (x, y))) + .map(|(x, y)| alpha[(fy + y) * iw + fx + x] == 0) + .collect() + }) + .collect(); + Some(SpriteMask { + width: w, + height: h, + frames, + }) + } +} + +// --------------------------------------------------------------------------- +// The renderer +// --------------------------------------------------------------------------- + +/// The baked item models and everything resolution needs. +pub struct ItemRenderer { + pub models: ItemModels, + library: ModelLibrary, + sprites: FileSprites, + baked: Mutex>>, + extents: Mutex>>>, + /// Entity model layers of the special renderers. + parts: HashMap, + /// `colormap/grass.png` as ARGB. + grass: Vec, + /// `minecraft:item` registry ids (`Item.getId`). + item_ids: HashMap, +} + +/// Every `models/**.json` of a namespace directory, by identifier. +fn load_models(root: &Path) -> BTreeMap { + let mut out = BTreeMap::new(); + let Ok(namespaces) = fs::read_dir(root.join("assets")) else { + return out; + }; + for ns in namespaces.flatten() { + let namespace = ns.file_name().to_string_lossy().into_owned(); + let base = ns.path().join("models"); + let mut stack = vec![base.clone()]; + while let Some(dir) = stack.pop() { + let Ok(entries) = fs::read_dir(&dir) else { + continue; + }; + for e in entries.flatten() { + let path = e.path(); + if path.is_dir() { + stack.push(path); + } else if path.extension().is_some_and(|x| x == "json") + && let Ok(rel) = path.strip_prefix(&base) + && let Ok(text) = fs::read_to_string(&path) + && let Ok(model) = CuboidModel::from_json(&text) + { + let rel = rel.with_extension("").to_string_lossy().replace('\\', "/"); + out.insert(format!("{namespace}:{rel}"), model); + } + } + } + } + out +} +/// Every `items/*.json` client item definition, by identifier. +fn load_definitions(root: &Path) -> BTreeMap { + let mut out = BTreeMap::new(); + let Ok(namespaces) = fs::read_dir(root.join("assets")) else { + return out; + }; + for ns in namespaces.flatten() { + let namespace = ns.file_name().to_string_lossy().into_owned(); + let Ok(files) = fs::read_dir(ns.path().join("items")) else { + continue; + }; + for f in files.flatten() { + let path = f.path(); + if path.extension().is_none_or(|e| e != "json") { + continue; + } + let name = path.file_stem().unwrap_or_default().to_string_lossy(); + if let Some(item) = fs::read_to_string(&path) + .ok() + .and_then(|t| ClientItem::from_json(&t).ok()) + { + out.insert(format!("{namespace}:{name}"), item); + } + } + } + out +} + +impl ItemRenderer { + /// Load item definitions, item prototypes (`items.json`), every model, + /// the special renderers' entity models and the grass colormap. + pub fn load(root: &Path) -> crate::Result { + let prototypes: BTreeMap = + serde_json::from_slice(&fs::read(root.join("items.json"))?)?; + let models = ItemModels { + definitions: load_definitions(root), + prototypes, + }; + let library = ModelLibrary::with_item_generator(load_models(root)) + .map_err(|e| format!("item models: {e:?}"))?; + let permutations = PalettedPermutations::from_atlas( + &fs::read_to_string(root.join("assets/minecraft/atlases/items.json")) + .unwrap_or_default(), + ); + let parts = special::load_parts(root); + let grass = crate::hud::decode(&root.join("assets/minecraft/textures/colormap/grass.png")) + .map(|(_, _, rgba)| argb_pixels(&rgba).into_iter().map(|p| p as i32).collect()) + .unwrap_or_default(); + let item_ids = horizon_protocol::registry::Builtin::find(root) + .and_then(|p| horizon_protocol::registry::Builtin::load(&p).ok()) + .and_then(|b| { + let ids = b.get("minecraft:item")?; + let mut out = HashMap::new(); + for i in 0.. { + let Some(name) = ids.name(i) else { break }; + out.insert(name.to_owned(), i); + } + Some(out) + }) + .unwrap_or_default(); + Ok(Self { + item_ids, + models, + library, + sprites: FileSprites { + root: root.to_path_buf(), + permutations, + cache: Mutex::default(), + }, + baked: Mutex::default(), + extents: Mutex::default(), + parts, + grass, + }) + } + /// `ModelBakery` item baking, cached per model. + pub fn bake(&self, model: &str) -> Arc { + if let Ok(cache) = self.baked.lock() + && let Some(hit) = cache.get(model) + { + return hit.clone(); + } + let baked = bake_item_model(&self.library, &self.sprites, model) + .or_else(|_| bake_item_model(&self.library, &self.sprites, MISSING_MODEL)) + .map(Arc::new) + .unwrap_or_else(|_| { + Arc::new(BakedItemModel { + quads: Vec::new(), + uses_block_light: false, + particle: horizon_assets::model::Material { + sprite: horizon_assets::item_bake::MISSING_SPRITE.to_owned(), + force_translucent: false, + }, + transforms: Default::default(), + }) + }); + if let Ok(mut cache) = self.baked.lock() { + cache.insert(model.to_owned(), baked.clone()); + } + baked + } + /// `CuboidItemModelWrapper.computeExtents`: the distinct quad corners. + fn quad_extents(&self, model: &str, baked: &BakedItemModel) -> Arc> { + if let Ok(cache) = self.extents.lock() + && let Some(hit) = cache.get(model) + { + return hit.clone(); + } + let mut out: Vec = Vec::new(); + for q in &baked.quads { + for p in q.positions { + let p = Vec3::from(p); + if !out.contains(&p) { + out.push(p); + } + } + } + let out = Arc::new(out); + if let Ok(mut cache) = self.extents.lock() { + cache.insert(model.to_owned(), out.clone()); + } + out + } + fn special_extents(&self, model: &SpecialModel) -> Arc> { + let key = model.to_json().to_string(); + if let Ok(cache) = self.extents.lock() + && let Some(hit) = cache.get(&key) + { + return hit.clone(); + } + let out = Arc::new(special::extents(self, model)); + if let Ok(mut cache) = self.extents.lock() { + cache.insert(key, out.clone()); + } + out + } + /// `ItemModelResolver.updateForTopItem`. + pub fn resolve( + &self, + stack: &StackView, + display: DisplayContext, + owner: Option<&OwnerState>, + level: Option<&LevelState>, + seed: i32, + env: &dyn ItemEnv, + ) -> ItemRenderState { + let ctx = Context { + display, + owner, + level, + seed, + }; + let resolved = self.models.resolve(stack, &ctx, env); + let mut animated = false; + let layers = resolved + .layers + .into_iter() + .map(|layer| { + let (geometry, baked, extents) = match layer.content { + LayerContent::Model { model } => { + let baked = self.bake(&model); + let extents = self.quad_extents(&model, &baked); + (LayerGeometry::Quads(baked.clone()), baked, extents) + } + LayerContent::Missing => { + let baked = self.bake(MISSING_MODEL); + let extents = self.quad_extents(MISSING_MODEL, &baked); + (LayerGeometry::Quads(baked.clone()), baked, extents) + } + LayerContent::Special { + base, + model, + argument, + } => { + let baked = self.bake(&base); + let extents = self.special_extents(&model); + (LayerGeometry::Special { model, argument }, baked, extents) + } + }; + if layer.foil != FoilType::None { + animated = true; + } + LayerRender { + geometry, + tints: layer.tints, + foil: layer.foil, + matrix: glam_matrix(&baked.layer_matrix(display, &layer.transform)), + uses_block_light: baked.uses_block_light, + particle: sprite_name(&baked.particle.sprite).to_owned(), + extents, + } + }) + .collect(); + ItemRenderState { + display, + layers, + oversized_in_gui: resolved.oversized_in_gui, + animated, + } + } + /// `GrassColor.get` over the loaded colormap. + pub fn grass_color(&self, temperature: f64, downfall: f64) -> i32 { + let rain = downfall * temperature; + let x = ((1.0 - temperature) * 255.0) as i64; + let y = ((1.0 - rain) * 255.0) as i64; + let index = (y << 8 | x) as usize; + self.grass.get(index).copied().unwrap_or(-65281) + } + /// Submit a special model renderer directly (worn skulls of + /// `CustomHeadLayer`, which draw the skull model, not the item). + #[allow(clippy::too_many_arguments)] + pub fn submit_special( + &self, + model: &SpecialModel, + argument: &Value, + has_foil: bool, + pose: Mat4, + sprites: &HashMap, + host: &dyn SpecialHost, + sink: &mut dyn ItemSink, + ) { + special::submit(self, model, argument, has_foil, pose, sprites, host, sink); + } + /// `Item.getId` (0 when the registry report is missing). + pub fn item_id(&self, item: &str) -> i32 { + self.item_ids.get(item).copied().unwrap_or(0) + } + pub(crate) fn part(&self, key: &str) -> Option<&ModelPart> { + self.parts.get(key) + } +} +/// A `horizon-assets` (row-major, JOML-exact) matrix as glam's. +pub fn glam_matrix(m: &horizon_assets::math::Mat4) -> Mat4 { + Mat4::from_cols_array_2d(&m.rows()).transpose() +} + +// --------------------------------------------------------------------------- +// Stacks +// --------------------------------------------------------------------------- + +/// An NBT value as the JSON its component codec reads. +pub fn tag_json(tag: &Tag) -> Value { + match tag { + Tag::End => Value::Null, + Tag::Byte(v) => Value::from(*v), + Tag::Short(v) => Value::from(*v), + Tag::Int(v) => Value::from(*v), + Tag::Long(v) => Value::from(*v), + Tag::Float(bits) => serde_json::Number::from_f64(f64::from(f32::from_bits(*bits))) + .map_or(Value::Null, Value::Number), + Tag::Double(bits) => { + serde_json::Number::from_f64(f64::from_bits(*bits)).map_or(Value::Null, Value::Number) + } + Tag::ByteArray(a) => Value::Array(a.iter().map(|b| Value::from(*b as i8)).collect()), + Tag::String(s) => Value::String(s.to_string_lossy()), + Tag::List(l) => Value::Array(l.iter().map(tag_json).collect()), + Tag::Compound(c) => Value::Object( + c.iter() + .map(|(k, v)| (k.to_string_lossy(), tag_json(v))) + .collect(), + ), + Tag::IntArray(a) => Value::Array(a.iter().map(|v| Value::from(*v)).collect()), + Tag::LongArray(a) => Value::Array(a.iter().map(|v| Value::from(*v)).collect()), + } +} +/// The resolver's view of a client stack: its item, count and component patch. +pub fn stack_view(stack: &crate::items::ItemStack) -> StackView { + let mut view = StackView::new(&stack.item, stack.count as i32); + if let Some(Tag::Compound(c)) = crate::item_data::components_tag(stack.damage, stack.data()) { + for (k, v) in &c { + let key = k.to_string_lossy(); + match key.strip_prefix('!') { + Some(removed) => view.patch.insert(removed.to_owned(), None), + None => view.patch.insert(key, Some(tag_json(v))), + }; + } + } + view +} + +// --------------------------------------------------------------------------- +// World drawing +// --------------------------------------------------------------------------- + +/// Entity vertices for submitted quads: the `item`/`entity` shader's +/// `minecraft_mix_light` with the level's diffuse lights on the vertex +/// colour, the packed lightmap coordinates (raised by light emission) and +/// overlay 7 for the glint. +pub struct WorldSink<'a> { + pub out: &'a mut Vec, + /// Packed light (`block_entity_render::vertex_light`). + pub light: u32, + /// The level's diffuse lights; `None` leaves the colour unshaded. + pub lights: Option<(Vec3, Vec3)>, +} +impl ItemSink for WorldSink<'_> { + fn quad(&mut self, q: ItemQuad) { + let brightness = self.lights.map_or(1.0, |l| diffuse(q.normal, l)); + let [a, r, g, b] = q.color.to_be_bytes(); + let c = |v: u8| (f32::from(v) * brightness) as u32; + let color = u32::from(a) << 24 | c(b) << 16 | c(g) << 8 | c(r); + // `LightCoordsUtil.lightCoordsWithEmission`: block light at least the emission. + let emission = u32::from(q.light_emission) * 16; + let light = if (self.light >> 8 & 0xFF) < emission { + (self.light & 0xFF) | emission << 8 + } else { + self.light + }; + let overlay = if q.foil == Foil::None { 0 } else { 7 }; + for (p, uv) in q.pos.iter().zip(q.uv) { + self.out.push(Vertex { + pos: p.to_array(), + uv, + layer: overlay, + color, + light, + }); + } + } +} + +/// `ItemEntity.getSpin`. +pub fn item_spin(age_in_ticks: f32, bob_offset: f32) -> f32 { + age_in_ticks / 20.0 + bob_offset +} +/// `ItemClusterRenderState.getRenderedAmount`. +pub fn rendered_amount(count: u32) -> u32 { + match count { + 0..=1 => 1, + 2..=16 => 2, + 17..=32 => 3, + 33..=48 => 4, + _ => 5, + } +} +/// `ItemEntityRenderer.submitMultipleFromCount`: the poses of each copy of +/// a stack (`seed` is `ItemClusterRenderState.getSeedForItemStack`). +pub fn cluster_poses(state: &ItemRenderState, pose: Mat4, amount: u32, seed: i64) -> Vec { + use horizon_core::random::{LegacyRandom, RandomSource}; + let mut out = Vec::new(); + if amount == 0 { + return out; + } + let mut random = LegacyRandom::new(seed); + let (lo, hi) = state.bounding_box(); + let depth = hi.z - lo.z; + let mut next = || random.next_float() * 2.0 - 1.0; + if depth > 0.0625 { + out.push(pose); + for _ in 1..amount { + let (x, y, z) = (next() * 0.15, next() * 0.15, next() * 0.15); + out.push(pose * Mat4::from_translation(Vec3::new(x, y, z))); + } + } else { + let offset = depth * 1.5; + let mut p = pose + * Mat4::from_translation(Vec3::new(0.0, 0.0, -(offset * (amount - 1) as f32 / 2.0))); + out.push(p); + p *= Mat4::from_translation(Vec3::new(0.0, 0.0, offset)); + for _ in 1..amount { + let (x, y) = (next() * 0.15 * 0.5, next() * 0.15 * 0.5); + out.push(p * Mat4::from_translation(Vec3::new(x, y, 0.0))); + p *= Mat4::from_translation(Vec3::new(0.0, 0.0, offset)); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rendered_amounts_follow_the_count_bands() { + let bands: Vec = [0, 1, 2, 16, 17, 32, 33, 48, 49, 64] + .iter() + .map(|c| rendered_amount(*c)) + .collect(); + assert_eq!(bands, [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]); + } + #[test] + fn nbt_components_read_as_json() { + let tag = Tag::compound([ + ("a", Tag::Int(3)), + ("b", Tag::List(vec![Tag::String("x".into())])), + ("c", Tag::Float(1.5f32.to_bits())), + ]); + assert_eq!( + tag_json(&tag), + serde_json::json!({"a": 3, "b": ["x"], "c": 1.5}) + ); + } + #[test] + fn normals_follow_the_inverse_transpose() { + let m = Mat4::from_scale(Vec3::new(2.0, 1.0, 1.0)); + assert_eq!(transform_normal(m, Vec3::X), Vec3::X); + let r = Mat4::from_rotation_y(std::f32::consts::FRAC_PI_2); + assert!((transform_normal(r, Vec3::Z) - Vec3::X).length() < 1e-6); + } +} diff --git a/crates/horizon-client/src/item_render/gui.rs b/crates/horizon-client/src/item_render/gui.rs new file mode 100644 index 000000000..0000b2613 --- /dev/null +++ b/crates/horizon-client/src/item_render/gui.rs @@ -0,0 +1,245 @@ +//! `GuiGraphics.renderItem` drawn into the HUD batch: the item's layers are +//! submitted under the GUI item pose (`translate(x + 8, y + 8)`, +//! `scale(16, -16, 16)`), lit with `Lighting.Entry.ITEMS_3D` or `ITEMS_FLAT` +//! (`minecraft_mix_light` on the transformed normals), back faces culled, +//! drawn far to near, and clipped to the item's 16x16 slot unless the model +//! is oversized in the GUI (`GuiItemAtlas` draws each item into a scissored +//! 16x16 slot; oversized items get a picture-in-picture of their bounds). +use super::{Foil, ItemQuad, ItemRenderState, ItemRenderer, SpecialHost}; +use crate::hud::{HudBatch, Rect}; +use glam::{EulerRot, Mat4, Vec2, Vec3}; +use std::{collections::HashMap, f32::consts::PI}; + +/// `Lighting.DIFFUSE_LIGHT_0` and `DIFFUSE_LIGHT_1`. +fn diffuse_lights() -> (Vec3, Vec3) { + ( + Vec3::new(0.2, 1.0, -0.7).normalize(), + Vec3::new(-0.2, 1.0, 0.7).normalize(), + ) +} +/// `Lighting.Entry.ITEMS_FLAT`: `rotationY(-PI/8).rotateX(3PI/4)`. +pub fn items_flat_lights() -> (Vec3, Vec3) { + let m = Mat4::from_rotation_y(-PI / 8.0) * Mat4::from_rotation_x(PI * 3.0 / 4.0); + let (a, b) = diffuse_lights(); + (m.transform_vector3(a), m.transform_vector3(b)) +} +/// JOML `rotateYXZ(y, x, z)`. +fn rotate_yxz(y: f32, x: f32, z: f32) -> Mat4 { + Mat4::from_euler(EulerRot::YXZ, y, x, z) +} +/// `Lighting.Entry.ITEMS_3D`. +pub fn items_3d_lights() -> (Vec3, Vec3) { + let m = Mat4::from_scale(Vec3::new(1.0, -1.0, 1.0)) + * rotate_yxz(1.082_104_1, 3.237_585_8, 0.0) + * rotate_yxz(-PI / 8.0, PI * 3.0 / 4.0, 0.0); + let (a, b) = diffuse_lights(); + (m.transform_vector3(a), m.transform_vector3(b)) +} + +/// A GUI-space vertex: position, atlas UV. +#[derive(Clone, Copy, Debug)] +struct Point { + p: Vec2, + uv: [f32; 2], +} +fn lerp(a: Point, b: Point, t: f32) -> Point { + Point { + p: a.p + (b.p - a.p) * t, + uv: [ + a.uv[0] + (b.uv[0] - a.uv[0]) * t, + a.uv[1] + (b.uv[1] - a.uv[1]) * t, + ], + } +} +/// Sutherland-Hodgman against one half plane `dot(p, n) <= limit`. +fn clip_edge(poly: &[Point], axis: usize, limit: f32, keep_below: bool) -> Vec { + let inside = |p: &Point| { + let v = p.p[axis]; + if keep_below { v <= limit } else { v >= limit } + }; + let mut out = Vec::with_capacity(poly.len() + 2); + for i in 0..poly.len() { + let (a, b) = (poly[i], poly[(i + 1) % poly.len()]); + let (ia, ib) = (inside(&a), inside(&b)); + if ia { + out.push(a); + } + if ia != ib { + let t = (limit - a.p[axis]) / (b.p[axis] - a.p[axis]); + out.push(lerp(a, b, t)); + } + } + out +} +/// A triangle clipped to `[x0, x1] x [y0, y1]`, as a fan. +fn clip_triangle(tri: [Point; 3], rect: [f32; 4]) -> Vec { + let mut poly = tri.to_vec(); + for (axis, limit, below) in [ + (0, rect[0], false), + (0, rect[2], true), + (1, rect[1], false), + (1, rect[3], true), + ] { + if poly.is_empty() { + break; + } + poly = clip_edge(&poly, axis, limit, below); + } + poly +} + +/// RGBA vertex colour of a lit quad: `minecraft_mix_light` on the tint. +fn lit_color(q: &ItemQuad, lights: (Vec3, Vec3)) -> u32 { + let light = crate::block_entity_render::diffuse(q.normal, lights); + let [a, r, g, b] = q.color.to_be_bytes(); + let c = |v: u8| (f32::from(v) * light) as u8; + crate::hud::rgba(c(r), c(g), c(b), a) +} +/// The glint's moving sheen at a GUI position (a stand-in for the +/// `GLINT_TEXTURING`-scrolled `enchanted_glint_item` texture added on top). +fn glint_color(p: Vec2, time: f32) -> u32 { + let d = ((p.x + p.y) / 32.0 - time * 0.35).rem_euclid(1.0); + let band = (1.0 - (d - 0.5).abs() * 6.0).max(0.0); + crate::hud::rgba( + (170.0 + 70.0 * band) as u8, + (90.0 + 110.0 * band) as u8, + 255, + (45.0 + 110.0 * band) as u8, + ) +} + +fn emit(batch: &mut HudBatch, fan: &[Point], color: impl Fn(Vec2) -> u32, glint: bool) { + let shift = if glint { 2.0 } else { 0.0 }; + for i in 1..fan.len().saturating_sub(1) { + let (a, b, c) = (fan[0], fan[i], fan[i + 1]); + let corners = [a, b, c, c]; + // `HudBatch.quad` draws (0, 1, 2) and (0, 2, 3): the second is empty. + batch.quad( + corners.map(|v| v.p.to_array()), + corners.map(|v| [v.uv[0] + shift, v.uv[1]]), + color(a.p), + ); + if glint { + // Per-vertex colours are flat per quad in the HUD batch: use the + // fan centre for the sheen. + let n = batch.vertices.len(); + for v in &mut batch.vertices[n - 6..] { + v.color = color(Vec2::from(v.pos)); + } + } + } +} + +/// Submit, light, cull, sort and clip one item's quads into `batch` at GUI +/// position `(x, y)`. +#[allow(clippy::too_many_arguments)] +pub fn draw( + state: &ItemRenderState, + renderer: &ItemRenderer, + sprites: &HashMap, + host: &dyn SpecialHost, + batch: &mut HudBatch, + x: f32, + y: f32, + time: f32, +) { + if state.is_empty() { + return; + } + let pose = Mat4::from_translation(Vec3::new(x + 8.0, y + 8.0, 0.0)) + * Mat4::from_scale(Vec3::new(16.0, -16.0, 16.0)); + let mut quads: Vec = Vec::new(); + state.submit(renderer, sprites, host, pose, &mut quads); + let lights = if state.uses_block_light() { + items_3d_lights() + } else { + items_flat_lights() + }; + // Back-face culling: front faces wind counter-clockwise on screen with y up. + let mut visible: Vec<(f32, usize)> = quads + .iter() + .enumerate() + .filter(|(_, q)| { + let p = q.pos.map(|v| Vec2::new(v.x, -v.y)); + let area: f32 = (0..4) + .map(|i| { + let (a, b) = (p[i], p[(i + 1) % 4]); + a.x * b.y - b.x * a.y + }) + .sum(); + area > 0.0 + }) + .map(|(i, q)| (q.pos.iter().map(|v| v.z).sum::() / 4.0, i)) + .collect(); + // Far to near; the depth buffer of the item atlas, approximated per quad. + visible.sort_by(|a, b| a.0.total_cmp(&b.0)); + let rect = if state.oversized_in_gui { + [ + f32::NEG_INFINITY, + f32::NEG_INFINITY, + f32::INFINITY, + f32::INFINITY, + ] + } else { + [x, y, x + 16.0, y + 16.0] + }; + for (_, i) in visible { + let q = &quads[i]; + let points: [Point; 4] = std::array::from_fn(|k| Point { + p: Vec2::new(q.pos[k].x, q.pos[k].y), + uv: q.uv[k], + }); + let color = lit_color(q, lights); + for tri in [ + [points[0], points[1], points[2]], + [points[0], points[2], points[3]], + ] { + let fan = clip_triangle(tri, rect); + if fan.len() < 3 { + continue; + } + emit(batch, &fan, |_| color, false); + if q.foil != Foil::None { + emit(batch, &fan, |p| glint_color(p, time), true); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn flat_lights_match_joml() { + // new Matrix4f().rotationY(-PI/8).rotateX(3PI/4).transformDirection(L0). + let (l0, _) = items_flat_lights(); + let l = Vec3::new(0.2, 1.0, -0.7).normalize(); + let (s, c) = ((3.0 * PI / 4.0).sin(), (3.0 * PI / 4.0).cos()); + let rx = Vec3::new(l.x, c * l.y - s * l.z, s * l.y + c * l.z); + let (s, c) = ((-PI / 8.0).sin(), (-PI / 8.0).cos()); + let ry = Vec3::new(c * rx.x + s * rx.z, rx.y, -s * rx.x + c * rx.z); + assert!((l0 - ry).length() < 1e-6); + } + #[test] + fn triangles_clip_to_the_slot() { + let p = |x: f32, y: f32| Point { + p: Vec2::new(x, y), + uv: [x, y], + }; + let fan = clip_triangle( + [p(-4.0, 0.0), p(8.0, 0.0), p(8.0, 8.0)], + [0.0, 0.0, 16.0, 16.0], + ); + assert!(fan.iter().all(|v| v.p.x >= 0.0)); + // UVs follow the cut affinely. + assert!(fan.iter().all(|v| (v.uv[0] - v.p.x).abs() < 1e-6)); + assert!( + clip_triangle( + [p(20.0, 0.0), p(30.0, 0.0), p(30.0, 5.0)], + [0.0, 0.0, 16.0, 16.0] + ) + .is_empty() + ); + } +} diff --git a/crates/horizon-client/src/item_render/special.rs b/crates/horizon-client/src/item_render/special.rs new file mode 100644 index 000000000..fe9f0cfa8 --- /dev/null +++ b/crates/horizon-client/src/item_render/special.rs @@ -0,0 +1,597 @@ +//! `SpecialModelRenderer`s: items drawn with entity models (chests, shulker +//! boxes, banners, heads, shields, tridents, decorated pots, conduits, bells, +//! books and copper golem statues). Each submits its model at the layer pose +//! as vanilla's `submit` does (no block-entity placement transform) and +//! reports `getExtents` over the same posed parts. +use super::{Foil, ItemQuad, ItemRenderer, ItemSink, SpecialHost, argb}; +use crate::{block_entity_render::ModelPart, hud::Rect}; +use glam::{Mat4, Quat, Vec3}; +use horizon_assets::item_model::{SpecialKind, SpecialModel}; +use serde_json::Value; +use std::{collections::HashMap, f32::consts::PI, path::Path}; + +/// Entity model layers the special renderers bake (`ModelLayers`). +const LAYERS: [(&str, &str); 22] = [ + ("chest", "minecraft:chest#main"), + ("double_chest_left", "minecraft:double_chest_left#main"), + ("double_chest_right", "minecraft:double_chest_right#main"), + ("shulker_box", "minecraft:shulker_box#main"), + ("standing_banner", "minecraft:standing_banner#main"), + ("standing_banner_flag", "minecraft:standing_banner#flag"), + ("wall_banner", "minecraft:wall_banner#main"), + ("wall_banner_flag", "minecraft:wall_banner#flag"), + ("skeleton", "minecraft:skeleton_skull#main"), + ("wither_skeleton", "minecraft:wither_skeleton_skull#main"), + ("zombie", "minecraft:zombie_head#main"), + ("creeper", "minecraft:creeper_head#main"), + ("dragon", "minecraft:dragon_skull#main"), + ("piglin", "minecraft:piglin_head#main"), + ("player", "minecraft:player_head#main"), + ("bell", "minecraft:bell#main"), + ("book", "minecraft:book#main"), + ("conduit_shell", "minecraft:conduit#shell"), + ("decorated_pot_base", "minecraft:decorated_pot_base#main"), + ("decorated_pot_sides", "minecraft:decorated_pot_sides#main"), + ("shield", "minecraft:shield#main"), + ("trident", "minecraft:trident#main"), +]; +const COPPER_GOLEM_LAYERS: [(&str, &str); 4] = [ + ("copper_golem", "minecraft:copper_golem#main"), + ( + "copper_golem_running", + "minecraft:copper_golem_running#main", + ), + ( + "copper_golem_sitting", + "minecraft:copper_golem_sitting#main", + ), + ("copper_golem_star", "minecraft:copper_golem_star#main"), +]; + +pub(super) fn load_parts(root: &Path) -> HashMap { + let Ok(all) = std::fs::read(root.join("entity-models.json")) + .map_err(|_| ()) + .and_then(|b| serde_json::from_slice::(&b).map_err(|_| ())) + else { + return HashMap::new(); + }; + LAYERS + .iter() + .chain(COPPER_GOLEM_LAYERS.iter()) + .filter_map(|(key, layer)| { + all.get(*layer) + .map(|v| ((*key).to_owned(), ModelPart::parse(v))) + }) + .collect() +} + +/// A pose override for a named part (`setupAnim`). +type Adjust<'a> = &'a dyn Fn(&str, &mut [f32; 9]); +fn none(_: &str, _: &mut [f32; 9]) {} + +/// `ModelPart.translateAndRotate`. +fn part_matrix(parent: Mat4, p: &[f32; 9]) -> Mat4 { + parent + * Mat4::from_translation(Vec3::new(p[0], p[1], p[2]) / 16.0) + * Mat4::from_quat(Quat::from_euler(glam::EulerRot::ZYX, p[5], p[4], p[3])) + * Mat4::from_scale(Vec3::new(p[6], p[7], p[8])) +} +/// `ModelPart.render` of `part` (named `name`) as item quads. +#[allow(clippy::too_many_arguments)] +fn draw( + part: &ModelPart, + name: &str, + parent: Mat4, + adjust: Adjust, + sprite: Rect, + color: u32, + foil: Foil, + sink: &mut dyn ItemSink, +) { + let mut p = part.pose; + adjust(name, &mut p); + let m = part_matrix(parent, &p); + for poly in &part.polygons { + let pos = poly.map(|v| m.transform_point3(Vec3::new(v[0], v[1], v[2]) / 16.0)); + let normal = (pos[1] - pos[0]).cross(pos[2] - pos[0]).normalize_or_zero(); + let normal = if normal == Vec3::ZERO { + (pos[2] - pos[1]) + .cross(pos[3] - pos[1]) + .normalize_or(Vec3::Y) + } else { + normal + }; + sink.quad(ItemQuad { + pos, + uv: poly.map(|v| { + [ + sprite.u0 + (sprite.u1 - sprite.u0) * v[3], + sprite.v0 + (sprite.v1 - sprite.v0) * v[4], + ] + }), + normal, + color, + foil, + light_emission: 0, + }); + } + for (child_name, child) in &part.children { + draw(child, child_name, m, adjust, sprite, color, foil, sink); + } +} +/// `ModelPart.getExtentsForGui` from an identity pose. +fn extents_of(part: &ModelPart, name: &str, parent: Mat4, adjust: Adjust, out: &mut Vec) { + if part.polygons.is_empty() && part.children.is_empty() { + return; + } + let mut p = part.pose; + adjust(name, &mut p); + let m = part_matrix(parent, &p); + for poly in &part.polygons { + for v in poly { + let q = m.transform_point3(Vec3::new(v[0], v[1], v[2]) / 16.0); + if !out.contains(&q) { + out.push(q); + } + } + } + for (child_name, child) in &part.children { + extents_of(child, child_name, m, adjust, out); + } +} +fn child<'a>(part: &'a ModelPart, name: &str) -> Option<&'a ModelPart> { + part.child(name) +} + +/// A texture identifier relative to `textures/` (`minecraft:entity/x` or a +/// full `minecraft:textures/entity/x.png`) as its atlas sprite name. +fn texture_sprite(id: &str) -> String { + let path = id.strip_prefix("minecraft:").unwrap_or(id); + let path = path.strip_prefix("textures/").unwrap_or(path); + path.strip_suffix(".png").unwrap_or(path).to_owned() +} +fn mapped(directory: &str, id: &str) -> String { + format!( + "entity/{directory}/{}", + id.strip_prefix("minecraft:").unwrap_or(id) + ) +} +/// `DyeColor.getTextureDiffuseColor` as ARGB. +fn dye(name: &str) -> u32 { + 0xFF00_0000 | crate::banner::dye_rgb(name) +} + +/// The chest model of a chest type, with `ChestModel.setupAnim(openness)`. +fn chest_model(chest_type: &str) -> &'static str { + match chest_type { + "left" => "double_chest_left", + "right" => "double_chest_right", + _ => "chest", + } +} +fn skull_layer(kind: &str) -> &'static str { + match kind { + "skeleton" => "skeleton", + "wither_skeleton" => "wither_skeleton", + "zombie" => "zombie", + "creeper" => "creeper", + "dragon" => "dragon", + "piglin" => "piglin", + _ => "player", + } +} +/// `SkullBlockRenderer.SKIN_BY_TYPE`. +fn skull_texture(kind: &str) -> &'static str { + match kind { + "skeleton" => "entity/skeleton/skeleton", + "wither_skeleton" => "entity/skeleton/wither_skeleton", + "zombie" => "entity/zombie/zombie", + "creeper" => "entity/creeper/creeper", + "dragon" => "entity/enderdragon/dragon", + "piglin" => "entity/piglin/piglin", + _ => "entity/player/wide/steve", + } +} +/// `SkullModelBase.setupAnim` for a head at `animation` (yRot = xRot = 0). +fn skull_pose(kind: &str, animation: f32) -> impl Fn(&str, &mut [f32; 9]) + '_ { + move |name: &str, p: &mut [f32; 9]| match (kind, name) { + (_, "head") => { + p[3] = 0.0; + p[4] = 0.0; + } + ("dragon", "jaw") => p[3] = (((animation * PI * 0.2) as f64).sin() as f32 + 1.0) * 0.2, + ("piglin", "left_ear") => { + p[5] = -((((animation * PI * 0.2 * 1.2) as f64).cos() + 2.5) as f32) * 0.2; + } + ("piglin", "right_ear") => { + p[5] = ((((animation * PI * 0.2) as f64).cos() + 2.5) as f32) * 0.2; + } + _ => {} + } +} +fn shulker_pose(progress: f32) -> impl Fn(&str, &mut [f32; 9]) { + move |name: &str, p: &mut [f32; 9]| { + if name == "lid" { + p[0] = 0.0; + p[1] = 24.0 - progress * 0.5 * 16.0; + p[2] = 0.0; + p[4] = 270.0 * progress * (PI / 180.0); + } + } +} +fn chest_pose(open: f32) -> impl Fn(&str, &mut [f32; 9]) { + move |name: &str, p: &mut [f32; 9]| { + if name == "lid" || name == "lock" { + p[3] = -(open * (PI / 2.0)); + } + } +} +/// `BannerFlagModel.setupAnim(0)`. +fn flag_pose(name: &str, p: &mut [f32; 9]) { + if name == "flag" { + p[3] = (-0.0125 + 0.01 * (2.0 * PI * 0.0f32).cos()) * PI; + } +} +/// `BookModel.setupAnim`. +fn book_pose(openness: f32, flip1: f32, flip2: f32) -> impl Fn(&str, &mut [f32; 9]) { + move |name: &str, p: &mut [f32; 9]| match name { + "left_lid" => p[4] = PI + openness, + "right_lid" => p[4] = -openness, + "left_pages" => { + p[4] = openness; + p[0] = openness.sin(); + } + "right_pages" => { + p[4] = -openness; + p[0] = openness.sin(); + } + "flip_page1" => { + p[4] = openness - openness * 2.0 * flip1; + p[0] = openness.sin(); + } + "flip_page2" => { + p[4] = openness - openness * 2.0 * flip2; + p[0] = openness.sin(); + } + _ => {} + } +} +/// `CopperGolemStatueModel.setupAnim`. +fn statue_pose(name: &str, p: &mut [f32; 9]) { + if name == "root" { + p[1] = 0.0; + p[5] = PI; + } +} +fn statue_layer(pose: &str) -> &'static str { + match pose { + "running" => "copper_golem_running", + "sitting" => "copper_golem_sitting", + "star" => "copper_golem_star", + _ => "copper_golem", + } +} + +/// `SpecialModelRenderer.getExtents`. +pub(super) fn extents(renderer: &ItemRenderer, model: &SpecialModel) -> Vec { + let mut out = Vec::new(); + let id = Mat4::IDENTITY; + let mut add = |key: &str, adjust: Adjust| { + if let Some(part) = renderer.part(key) { + extents_of(part, "root", id, adjust, &mut out); + } + }; + match &model.kind { + SpecialKind::Bell => add("bell", &none), + SpecialKind::Banner { .. } => { + // `BannerRenderer.getExtents`: the standing models only. + add("standing_banner", &none); + add("standing_banner_flag", &flag_pose); + } + SpecialKind::Book { + open_angle, + page1, + page2, + } => add( + "book", + &book_pose(open_angle * (PI / 180.0), *page1, *page2), + ), + SpecialKind::Conduit => add("conduit_shell", &none), + SpecialKind::Chest { + openness, + chest_type, + .. + } => add(chest_model(chest_type), &chest_pose(*openness)), + SpecialKind::CopperGolemStatue { pose, .. } => add(statue_layer(pose), &statue_pose), + SpecialKind::DecoratedPot => { + if let Some(base) = renderer.part("decorated_pot_base") { + // `neck`, `top` and `bottom` are posed from an identity stack. + for name in ["neck", "top", "bottom"] { + if let Some(part) = child(base, name) { + extents_of(part, name, id, &none, &mut out); + } + } + } + } + SpecialKind::EndCube { .. } => {} + SpecialKind::Head { + kind, animation, .. + } => add(skull_layer(kind), &skull_pose(kind, *animation)), + SpecialKind::PlayerHead => add("player", &none), + SpecialKind::ShulkerBox { openness, .. } => add("shulker_box", &shulker_pose(*openness)), + SpecialKind::Shield => add("shield", &none), + SpecialKind::Trident => add("trident", &none), + } + out +} + +/// Banner pattern layers of a `minecraft:banner_patterns` value: the +/// pattern identifier (or inline asset) and the dye. +fn pattern_layers(v: &Value) -> Vec<(String, String)> { + v.as_array() + .into_iter() + .flatten() + .filter_map(|layer| { + let pattern = match &layer["pattern"] { + Value::String(s) => s.clone(), + Value::Object(o) => format!("#asset:{}", o.get("asset_id")?.as_str()?), + _ => return None, + }; + let color = layer["color"].as_str()?.to_owned(); + Some((pattern, color)) + }) + .collect() +} +fn pattern_texture(host: &dyn SpecialHost, banner: bool, pattern: &str) -> Option { + if let Some(asset) = pattern.strip_prefix("#asset:") { + let path = asset.strip_prefix("minecraft:").unwrap_or(asset); + return Some(format!( + "entity/{}/{path}", + if banner { "banner" } else { "shield" } + )); + } + if banner { + host.banner_texture(pattern) + } else { + host.shield_texture(pattern) + } +} +/// `DecoratedPotPatterns.getPatternFromItem` for one side's sherd item. +fn pot_side(item: Option<&str>) -> String { + let item = item.map(|i| i.strip_prefix("minecraft:").unwrap_or(i)); + match item.and_then(|i| i.strip_suffix("_pottery_sherd")) { + Some(name) => format!("entity/decorated_pot/{name}_pottery_pattern"), + None => "entity/decorated_pot/decorated_pot_side".to_owned(), + } +} +/// `PotDecorations` as [back, left, right, front] item ids, from the list +/// codec or a keyed object. +fn pot_sides(v: &Value) -> [Option; 4] { + let id = |s: &Value| match s { + Value::String(s) => Some(s.clone()), + Value::Object(o) => o.get("id").and_then(Value::as_str).map(str::to_owned), + _ => None, + }; + match v { + Value::Array(a) => std::array::from_fn(|i| a.get(i).and_then(id)), + Value::Object(o) => ["back", "left", "right", "front"].map(|k| o.get(k).and_then(id)), + _ => Default::default(), + } +} + +/// `SpecialModelRenderer.submit`. +#[allow(clippy::too_many_arguments)] +pub(super) fn submit( + renderer: &ItemRenderer, + model: &SpecialModel, + argument: &Value, + has_foil: bool, + pose: Mat4, + sprites: &HashMap, + host: &dyn SpecialHost, + sink: &mut dyn ItemSink, +) { + let white = argb(-1); + let mut part = |key: &str, adjust: Adjust, texture: &str, color: u32, foil: Foil| { + if let (Some(p), Some(r)) = (renderer.part(key), sprites.get(texture).copied()) { + draw(p, "root", pose, adjust, r, color, foil, sink); + } + }; + match &model.kind { + SpecialKind::Bell => part("bell", &none, "entity/bell/bell_body", white, Foil::None), + SpecialKind::Book { + open_angle, + page1, + page2, + } => part( + "book", + &book_pose(open_angle * (PI / 180.0), *page1, *page2), + "entity/enchantment/enchanting_table_book", + white, + Foil::None, + ), + SpecialKind::Conduit => { + part( + "conduit_shell", + &none, + "entity/conduit/base", + white, + Foil::None, + ); + } + SpecialKind::Chest { + texture, + openness, + chest_type, + } => part( + chest_model(chest_type), + &chest_pose(*openness), + &mapped("chest", texture), + white, + Foil::None, + ), + SpecialKind::ShulkerBox { texture, openness } => part( + "shulker_box", + &shulker_pose(*openness), + &mapped("shulker", texture), + white, + Foil::None, + ), + SpecialKind::CopperGolemStatue { texture, pose: p } => part( + statue_layer(p), + &statue_pose, + &texture_sprite(texture), + white, + Foil::None, + ), + SpecialKind::Head { + kind, + texture, + animation, + } => { + let skin = texture + .as_deref() + .map(|t| format!("entity/{}", t.strip_prefix("minecraft:").unwrap_or(t))) + .unwrap_or_else(|| skull_texture(kind).to_owned()); + part( + skull_layer(kind), + &skull_pose(kind, *animation), + &skin, + white, + Foil::None, + ); + } + SpecialKind::PlayerHead => { + let skin = (!argument.is_null()) + .then(|| host.player_skin(argument)) + .flatten() + .unwrap_or_else(|| "entity/player/wide/steve".to_owned()); + part("player", &none, &skin, white, Foil::None); + } + SpecialKind::Trident => { + let foil = if has_foil { Foil::Standard } else { Foil::None }; + part("trident", &none, "entity/trident/trident", white, foil); + } + SpecialKind::Banner { color, wall } => { + let (main, flag) = if *wall { + ("wall_banner", "wall_banner_flag") + } else { + ("standing_banner", "standing_banner_flag") + }; + part(main, &none, "entity/banner/banner_base", white, Foil::None); + part( + flag, + &flag_pose, + "entity/banner/banner_base", + white, + Foil::None, + ); + // `submitPatterns`: the base layer in the banner's colour, then up to 16 layers. + part( + flag, + &flag_pose, + "entity/banner/base", + dye(color), + Foil::None, + ); + for (pattern, color) in pattern_layers(argument).into_iter().take(16) { + if let Some(t) = pattern_texture(host, true, &pattern) { + part(flag, &flag_pose, &t, dye(&color), Foil::None); + } + } + } + SpecialKind::Shield => { + let patterns = pattern_layers(&argument["minecraft:banner_patterns"]); + let base_color = argument["minecraft:base_color"].as_str(); + let has_patterns = !patterns.is_empty() || base_color.is_some(); + let base = if has_patterns { + "entity/shield/shield_base" + } else { + "entity/shield/shield_base_nopattern" + }; + let foil = if has_foil && !has_patterns { + Foil::Standard + } else { + Foil::None + }; + part("shield", &none, base, white, foil); + if has_patterns { + part( + "shield", + &none, + "entity/shield/base", + dye(base_color.unwrap_or("white")), + Foil::None, + ); + for (pattern, color) in patterns.into_iter().take(16) { + if let Some(t) = pattern_texture(host, false, &pattern) { + part("shield", &none, &t, dye(&color), Foil::None); + } + } + if has_foil { + // `patternedShieldGlint`: the glint alone over the model. + part("shield", &none, base, white, Foil::Standard); + } + } + } + SpecialKind::DecoratedPot => { + let sides = pot_sides(argument); + if let Some(base) = renderer.part("decorated_pot_base") + && let Some(r) = sprites + .get("entity/decorated_pot/decorated_pot_base") + .copied() + { + for name in ["neck", "top", "bottom"] { + if let Some(p) = child(base, name) { + draw(p, name, pose, &none, r, white, Foil::None, sink); + } + } + } + if let Some(side_parts) = renderer.part("decorated_pot_sides") { + for (i, name) in ["back", "left", "right", "front"].into_iter().enumerate() { + let texture = pot_side(sides[i].as_deref()); + if let (Some(p), Some(r)) = (child(side_parts, name), sprites.get(&texture)) { + draw(p, name, pose, &none, *r, white, Foil::None, sink); + } + } + } + } + // `EndCubeSpecialRenderer` draws the end portal/gateway effect; no + // bundled item uses it. + SpecialKind::EndCube { .. } => {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pot_sides_read_both_shapes() { + let list = serde_json::json!(["minecraft:brick", "minecraft:angler_pottery_sherd"]); + let sides = pot_sides(&list); + assert_eq!( + pot_side(sides[0].as_deref()), + "entity/decorated_pot/decorated_pot_side" + ); + assert_eq!( + pot_side(sides[1].as_deref()), + "entity/decorated_pot/angler_pottery_pattern" + ); + assert_eq!( + pot_side(sides[3].as_deref()), + "entity/decorated_pot/decorated_pot_side" + ); + } + #[test] + fn texture_ids_map_to_sprites() { + assert_eq!( + texture_sprite("minecraft:textures/entity/copper_golem/copper_golem.png"), + "entity/copper_golem/copper_golem" + ); + assert_eq!( + mapped("chest", "minecraft:christmas"), + "entity/chest/christmas" + ); + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index e5080ea4a..835dbd637 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -5,6 +5,7 @@ pub mod advancements; pub mod ambience; pub mod animate_tick; pub mod assets; +pub mod atlas_sources; pub mod attribute_updates; pub mod audio; pub mod banner; @@ -44,6 +45,7 @@ pub mod hud; pub mod hunger; pub mod input; pub mod item_data; +pub mod item_render; pub mod items; pub mod java_text; pub mod key_names; diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index 8644e25a4..27f441adc 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -101,6 +101,7 @@ impl AnimState { pub fn end_tick(&mut self, _swinging: bool) {} } /// Part poses for one draw, keyed by part name. +#[derive(Clone)] pub struct Poses { map: HashMap, dummy: [f32; 9], diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 1ca00218a..7dce44559 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -915,7 +915,6 @@ fn render_visible( for (part, uv, color) in extra { draw(part, base, &poses, *uv, *color, light, overlay, out); } - held_items(m, &model, base, &poses, atlas, light, out); let mut all_layers = layers(m); // WardenRenderer: the translucent emissive layers fade with the animations. if m.species() == Species::Warden { @@ -1013,57 +1012,6 @@ pub fn part_matrix( .iter() .find_map(|c| part_matrix(c, m, poses, name, x_offset)) } -/// ItemModel thirdperson_righthand display transform by item model parent. -fn item_display(item: &str) -> ([f32; 3], [f32; 3], [f32; 3]) { - let name = item.trim_start_matches("minecraft:"); - if name == "bow" { - ([-80.0, 260.0, -40.0], [-1.0, -2.0, 2.5], [0.9; 3]) - } else if name == "crossbow" { - ([-90.0, 0.0, -60.0], [2.0, 0.1, -3.0], [0.9; 3]) - } else if name == "fishing_rod" - || name == "carrot_on_a_stick" - || name == "warped_fungus_on_a_stick" - { - ([0.0, 90.0, 55.0], [0.0, 4.0, 2.5], [0.85; 3]) - } else if [ - "_sword", - "_axe", - "_pickaxe", - "_shovel", - "_hoe", - "trident", - "mace", - "stick", - "bone", - "blaze_rod", - ] - .iter() - .any(|t| name.ends_with(t)) - { - ([0.0, -90.0, 55.0], [0.0, 4.0, 0.5], [0.85; 3]) - } else { - ([0.0, 0.0, 0.0], [0.0, 3.0, 1.0], [0.55; 3]) - } -} -/// The sprite drawn for a held item (bow pull frames while charging). -fn item_sprite(m: &Mob, item: &str) -> String { - let name = item.trim_start_matches("minecraft:"); - if name == "bow" && m.extra.using_item > 0 { - let pull = m.extra.using_item as f32 * 0.05; - let frame = if pull >= 0.9 { - 2 - } else if pull >= 0.65 { - 1 - } else { - 0 - }; - return format!("item/bow_pulling_{frame}"); - } - if name == "crossbow" && m.extra.flag2 { - return "item/crossbow_arrow".into(); - } - format!("item/{name}") -} /// The hand of a mob in model space, up to the item's own transform /// (`ItemInHandLayer.submitArmWithItem`). fn hand_base( @@ -1122,10 +1070,10 @@ pub fn part_transform( anim::setup(m, &s, &mut poses, &data.animations); part_matrix(&model, base, &poses, part, 0.0) } -/// Where a mob holds a block item (`block/block` thirdperson display: turned -/// 75 and 45 degrees, at 0.375 scale), as the hand transform for `left`, or -/// `None` when the mob shows no held items. -pub fn held_block_transform( +/// The pose a mob's held item is submitted under (`ItemInHandLayer`: +/// `translateToHand`, then the hand offset; the item model adds its own +/// display transform), or `None` when the mob shows no held items. +pub fn held_item_transform( m: &Mob, alpha: f32, camera: glam::DVec3, @@ -1145,106 +1093,5 @@ pub fn held_block_transform( .unwrap_or_else(|| m.kind.model.clone()); let mut poses = Poses::new(&model); anim::setup(m, &s, &mut poses, &data.animations); - let mut t = hand_base(m, &model, base, &poses, left)?; - let ry = if left { -45.0f32 } else { 45.0 }; - t *= glam::Mat4::from_translation(glam::Vec3::new(0.0, 2.5, 0.0) / 16.0); - t *= glam::Mat4::from_quat(glam::Quat::from_euler( - glam::EulerRot::XYZ, - 75.0f32.to_radians(), - ry.to_radians(), - 0.0, - )); - t *= glam::Mat4::from_scale(glam::Vec3::splat(0.375)); - t *= glam::Mat4::from_translation(glam::Vec3::splat(-0.5)); - Some(t) -} -/// ItemInHandLayer: items in the mob's hands. -fn held_items( - m: &Mob, - model: &Part, - base: glam::Mat4, - poses: &Poses, - atlas: Atlas, - light: u32, - out: &mut Vec, -) { - if !super::illager::shows_item(m) { - return; - } - for (item, left) in [(&m.extra.main_hand, false), (&m.extra.off_hand, true)] { - let Some(item) = item else { continue }; - let Some(mut t) = hand_base(m, model, base, poses, left) else { - continue; - }; - let Some(uv) = atlas(&item_sprite(m, item)) else { - continue; - }; - // ItemTransform.apply (mirrored for the left hand). - let (rot, tr, sc) = item_display(item); - let (ry, rz, tx) = if left { - (-rot[1], -rot[2], -tr[0]) - } else { - (rot[1], rot[2], tr[0]) - }; - t *= glam::Mat4::from_translation(glam::Vec3::new(tx, tr[1], tr[2]) / 16.0); - t *= glam::Mat4::from_quat(glam::Quat::from_euler( - glam::EulerRot::XYZ, - rot[0].to_radians(), - ry.to_radians(), - rz.to_radians(), - )); - t *= glam::Mat4::from_scale(glam::Vec3::from(sc)); - t *= glam::Mat4::from_translation(glam::Vec3::splat(-0.5)); - let glint = super::gear::enchanted( - m, - if left { - super::gear::OFF - } else { - super::gear::MAIN - }, - ); - draw_item_plane_with(t, uv, light, if glint { 7 } else { 0 }, out); - } -} -/// A generated item model: the sprite on two faces 1/16 apart. -pub fn draw_item_plane(t: glam::Mat4, uv: [f32; 4], light: u32, out: &mut Vec) { - draw_item_plane_with(t, uv, light, 0, out); -} -/// `draw_item_plane` with an entity shader overlay (7: enchantment glint). -pub fn draw_item_plane_with( - t: glam::Mat4, - uv: [f32; 4], - light: u32, - overlay: u32, - out: &mut Vec, -) { - let (u0, v0, u1, v1) = (uv[0], uv[1], uv[2], uv[3]); - let south = 8.5 / 16.0; - let north = 7.5 / 16.0; - let quads = [ - [ - ([0.0, 0.0, south], [u0, v1]), - ([1.0, 0.0, south], [u1, v1]), - ([1.0, 1.0, south], [u1, v0]), - ([0.0, 1.0, south], [u0, v0]), - ], - [ - ([1.0, 0.0, north], [u1, v1]), - ([0.0, 0.0, north], [u0, v1]), - ([0.0, 1.0, north], [u0, v0]), - ([1.0, 1.0, north], [u1, v0]), - ], - ]; - for q in quads { - for (p, uv) in q { - let pos = t.transform_point3(glam::Vec3::from(p)); - out.push(Vertex { - pos: pos.to_array(), - uv, - layer: overlay, - color: 0xFFFF_FFFF, - light, - }); - } - } + hand_base(m, &model, base, &poses, left) } diff --git a/crates/horizon-client/src/packs.rs b/crates/horizon-client/src/packs.rs index 5e0e35515..b5205922b 100644 --- a/crates/horizon-client/src/packs.rs +++ b/crates/horizon-client/src/packs.rs @@ -3,7 +3,7 @@ //! and High Contrast packs, `pack.mcmeta` metadata and format compatibility, //! and an overlay resource root that layers the enabled packs over the //! vanilla resources (later packs win), so every loader sees one tree. -mod pattern; +pub mod pattern; use crate::{text::Text, zip::Zip}; use pattern::Pattern; use std::{ From e6ef8c502b390fe1b45958750c52423b0cf1f2bb Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:16:57 +0200 Subject: [PATCH 24/28] Check spawn placements and spawn predicates exactly as SpawnPlacements does mobs::spawn_rules ports SpawnPlacements over a SpawnLevel trait the game's MobWorld implements: the placement types with per-type isValidSpawn (leaves, ice, magma for fire-immune types) and isValidEmptySpawnBlock with each type's dangerous and immune blocks, and every registered predicate in vanilla's draw order: the dimension's monster light test and block light limit, thunder, peaceful, spawn reasons, guardians' sky from below water, drowned, bats, ghasts, ocelots, slimes (surface chance and slime chunks), strays under powder snow, striders, turtles, polar bears, tropical fish, nautiluses, silverfish and endermites near players, patrols and the spawnable-on tags. Divergences fixed on the way: nether monsters ignored light, hoglins and piglins had extra checks, slimes spawned outside slime chunks, ocelots and ghasts skipped their odds, bats ignored the surface and their draw order, and several predicates read the wrong blocks. tools/test_spawn_rules_parity.py: 18,669 cases over 87 entity types match. Co-Authored-By: Claude Opus 5.5 --- .../examples/spawn_rules_fixture.rs | 232 +++++++ crates/horizon-client/src/game/creatures.rs | 2 + crates/horizon-client/src/mobs.rs | 5 + crates/horizon-client/src/mobs/spawn_rules.rs | 589 ++++++++++++++++++ crates/horizon-client/src/mobs/spawning.rs | 167 +---- .../parity/VanillaSpawnRulesOracle.java | 204 ++++++ tools/test_spawn_rules_parity.py | 182 ++++++ 7 files changed, 1227 insertions(+), 154 deletions(-) create mode 100644 crates/horizon-client/examples/spawn_rules_fixture.rs create mode 100644 crates/horizon-client/src/mobs/spawn_rules.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSpawnRulesOracle.java create mode 100644 tools/test_spawn_rules_parity.py diff --git a/crates/horizon-client/examples/spawn_rules_fixture.rs b/crates/horizon-client/examples/spawn_rules_fixture.rs new file mode 100644 index 000000000..8e4fff1c3 --- /dev/null +++ b/crates/horizon-client/examples/spawn_rules_fixture.rs @@ -0,0 +1,232 @@ +//! Spawn placement and spawn predicate answers for differential tests against +//! vanilla (tools/test_spawn_rules_parity.py): reads the column-world cases of +//! `VanillaSpawnRulesOracle` and prints `mobs::spawn_rules`' answers. +//! +//! usage: spawn_rules_fixture RESOURCES INPUT OUTPUT +use horizon_client::{ + assets::Assets, + blocks::BlockFacts, + items::Items, + mobs::{ + MobTypes, + data::MobData, + spawn_rules::{self, Dimension, Reason, SpawnLevel}, + }, +}; +use horizon_core::random::{LegacyRandom, RandomSource}; +use horizon_world::{chunk::BlockState, registry::BlockStateId}; +use std::{ + collections::{BTreeMap, HashMap, HashSet}, + fmt::Write as _, + fs, + path::Path, +}; + +struct Column<'a> { + facts: &'a BlockFacts, + data: &'a MobData, + block_tags: &'a HashMap>, + air: BlockStateId, + blocks: HashMap, + x0: i32, + z0: i32, + sky: i32, + light: i32, + darken: i32, + thunder: bool, + sea: i32, + surface: i32, + seed: i64, + peaceful: bool, + dimension: Dimension, + biome: String, + slime: f32, + /// A player position and whether it is survival or adventure. + player: Option<([f64; 3], bool)>, +} +impl SpawnLevel for Column<'_> { + fn state(&self, x: i32, y: i32, z: i32) -> BlockStateId { + if x != self.x0 || z != self.z0 { + return self.air; + } + self.blocks.get(&y).copied().unwrap_or(self.air) + } + fn facts(&self) -> &BlockFacts { + self.facts + } + fn mob_data(&self) -> &MobData { + self.data + } + fn block_tag(&self, tag: &str, block: &str) -> bool { + self.block_tags.get(tag).is_some_and(|s| s.contains(block)) + } + fn biome_tag(&self, tag: &str, _: i32, _: i32, _: i32) -> bool { + self.data + .biome_tags + .get(tag) + .is_some_and(|s| s.contains(&self.biome)) + } + fn sky_light(&self, _: i32, _: i32, _: i32) -> i32 { + self.sky + } + fn block_light(&self, _: i32, _: i32, _: i32) -> i32 { + self.light + } + fn sky_darken(&self) -> i32 { + self.darken + } + fn thundering(&self) -> bool { + self.thunder + } + fn sea_level(&self) -> i32 { + self.sea + } + fn world_surface(&self, _: i32, _: i32) -> i32 { + self.surface + } + fn peaceful(&self) -> bool { + self.peaceful + } + fn dimension(&self) -> Dimension { + self.dimension + } + fn surface_slime_chance(&self, _: i32, _: i32, _: i32) -> f32 { + self.slime + } + fn world_seed(&self) -> i64 { + self.seed + } + fn player_near(&self, x: f64, y: f64, z: f64, distance: f64) -> bool { + self.player.is_some_and(|(p, targetable)| { + let d = (p[0] - x).powi(2) + (p[1] - y).powi(2) + (p[2] - z).powi(2); + targetable && d < distance * distance + }) + } +} + +/// `name[key=value,...]`. +fn parse_state(spec: &str) -> BlockState { + let (name, props) = match spec.split_once('[') { + Some((n, rest)) => (n, rest.trim_end_matches(']')), + None => (spec, ""), + }; + let properties: BTreeMap = props + .split(',') + .filter(|p| !p.is_empty()) + .filter_map(|p| p.split_once('=')) + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect(); + BlockState { + name: name.to_owned(), + properties, + } +} + +fn reason(name: &str) -> Reason { + match name { + "chunk_generation" => Reason::ChunkGeneration, + "spawner" => Reason::Spawner, + "trial_spawner" => Reason::TrialSpawner, + "reinforcement" => Reason::Reinforcement, + "patrol" => Reason::Patrol, + "structure" => Reason::Structure, + "event" => Reason::Event, + "command" => Reason::Command, + _ => Reason::Natural, + } +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let root = Path::new( + args.get(1) + .ok_or("usage: spawn_rules_fixture RESOURCES INPUT OUTPUT")?, + ); + let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; + let assets = Assets::load(root)?; + let registry = assets.registry; + let facts = BlockFacts::load(root, registry)?; + let data = MobData::load(root, &facts); + let items = Items::tags_only(root)?; + let types = MobTypes::load(root)?; + let mut out = String::new(); + for raw in input.lines() { + if raw.trim().is_empty() { + continue; + } + let mut c = BTreeMap::new(); + let mut name = ""; + for token in raw.split_whitespace() { + match token.split_once('=') { + Some((k, v)) => { + c.insert(k, v); + } + None => name = token, + } + } + let get = |k: &str, d: &'static str| -> String { c.get(k).copied().unwrap_or(d).to_owned() }; + let Some(kind) = types.types.get(c["type"]) else { + let _ = writeln!(out, "{name} error unsupported {}", c["type"]); + continue; + }; + let y: i32 = get("y", "64").parse()?; + let (x0, z0): (i32, i32) = (get("x", "8").parse()?, get("z", "8").parse()?); + let mut blocks = HashMap::new(); + for (k, v) in &c { + if let Some(offset) = k.strip_prefix("at") { + let offset: i32 = offset.parse()?; + blocks.insert(y + offset, registry.resolve(&parse_state(v))?); + } + } + let player = c.get("player").map(|p| { + let f: Vec<&str> = p.split(',').collect(); + let at = |i: usize, base: i32| f64::from(base) + f[i].parse::().unwrap_or(0.0); + let mode = f.get(3).copied().unwrap_or("survival"); + ( + [at(0, x0), at(1, y), at(2, z0)], + mode == "survival" || mode == "adventure", + ) + }); + let level = Column { + facts: &facts, + data: &data, + block_tags: &items.block_tags, + air: facts.air, + blocks, + x0, + z0, + sky: get("sky", "15").parse()?, + light: get("light", "0").parse()?, + darken: get("darken", "0").parse()?, + thunder: get("thunder", "0") == "1", + sea: get("sea", "63").parse()?, + surface: get("surface", "0").parse()?, + seed: get("wseed", "0").parse()?, + peaceful: get("difficulty", "normal") == "peaceful", + dimension: match get("dim", "minecraft:overworld").as_str() { + "minecraft:the_nether" => Dimension::Nether, + "minecraft:the_end" => Dimension::End, + _ => Dimension::Overworld, + }, + biome: get("biome", "minecraft:plains"), + slime: get("slime", "0.0").parse()?, + player, + }; + let mut random = LegacyRandom::new(get("seed", "0").parse()?); + let s = kind.species; + let ok = spawn_rules::is_spawn_position_ok(s, &level, x0, y, z0); + let rules = spawn_rules::check_spawn_rules( + s, + &level, + reason(&get("reason", "natural")), + &mut random, + x0, + y, + z0, + ); + let next = random.next_int_bound(1000).unwrap_or(0); + let _ = writeln!(out, "{name} {ok} {rules} {next}"); + } + fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index afd148af7..8441baaf1 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -467,6 +467,8 @@ impl Game<'_> { block_tags: &self.res.items.block_tags, biomes: &self.res.biomes, mob_griefing: self.ui.rules.bool("mob_griefing"), + end: self.dim == Dim::End, + world_seed: self.level.seed, difficulty: self.local_difficulty( self.player .as_ref() diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index deda5984a..b45da996c 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -47,6 +47,7 @@ pub mod riders; pub mod shulker; pub mod sniffer; pub mod spawning; +pub mod spawn_rules; pub mod species; pub mod sulfur_cube; pub mod tame; @@ -903,6 +904,10 @@ pub struct MobWorld<'a> { pub mob_griefing: bool, /// `getCurrentDifficultyAt` near the player. pub difficulty: spawning::LocalDifficulty, + /// The End (its dimension type's monster spawn light rules). + pub end: bool, + /// The world seed (slime chunks). + pub world_seed: i64, } impl Mob { pub fn new(id: u32, kind: Arc, position: Vec3, yaw: f32) -> Self { diff --git a/crates/horizon-client/src/mobs/spawn_rules.rs b/crates/horizon-client/src/mobs/spawn_rules.rs new file mode 100644 index 000000000..f64918bd4 --- /dev/null +++ b/crates/horizon-client/src/mobs/spawn_rules.rs @@ -0,0 +1,589 @@ +//! `SpawnPlacements`: each entity type's placement type +//! (`SpawnPlacementTypes.isSpawnPositionOk`) and spawn predicate +//! (`checkSpawnRules`), read through [`SpawnLevel`] so the game's world and a +//! differential test world answer the same questions. Random draws follow +//! vanilla's order. +use super::{Species, data}; +use crate::blocks::{BlockFacts, Fluid}; +use horizon_core::random::{RandomSource, slime_chunk_random}; +use horizon_world::registry::BlockStateId; + +/// `EntitySpawnReason`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Reason { + Natural, + ChunkGeneration, + Spawner, + TrialSpawner, + Reinforcement, + Patrol, + Structure, + Event, + Command, + SpawnItemUse, + MobSummoned, + Conversion, + Breeding, + Triggered, + Jockey, + Dispenser, + Bucket, + Load, + DimensionTravel, +} +impl Reason { + pub fn is_spawner(self) -> bool { + matches!(self, Self::Spawner | Self::TrialSpawner) + } + pub fn ignores_light(self) -> bool { + self == Self::TrialSpawner + } +} +/// The dimension type's monster spawn light rules. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Dimension { + Overworld, + Nether, + End, +} +impl Dimension { + /// `monster_spawn_block_light_limit`. + fn block_light_limit(self) -> i32 { + match self { + Self::Nether => 15, + _ => 0, + } + } + /// `monster_spawn_light_level.sample`: uniform 0..=7 in the overworld. + fn light_test(self, random: &mut impl RandomSource) -> i32 { + match self { + Self::Overworld => random.next_int_bound(8).unwrap_or(0), + Self::Nether => 7, + Self::End => 15, + } + } +} + +/// What spawn checks read from a level. +pub trait SpawnLevel { + fn state(&self, x: i32, y: i32, z: i32) -> BlockStateId; + fn facts(&self) -> &BlockFacts; + fn mob_data(&self) -> &data::MobData; + fn block_tag(&self, tag: &str, block: &str) -> bool; + fn biome_tag(&self, tag: &str, x: i32, y: i32, z: i32) -> bool; + /// `getBrightness(LightLayer.SKY / BLOCK)`. + fn sky_light(&self, x: i32, y: i32, z: i32) -> i32; + fn block_light(&self, x: i32, y: i32, z: i32) -> i32; + fn sky_darken(&self) -> i32; + fn thundering(&self) -> bool; + fn sea_level(&self) -> i32; + /// `getHeight(WORLD_SURFACE, x, z)`: above the highest non-air block. + fn world_surface(&self, x: i32, z: i32) -> i32; + fn peaceful(&self) -> bool; + fn dimension(&self) -> Dimension; + /// The `gameplay/surface_slime_spawn_chance` environment attribute. + fn surface_slime_chance(&self, x: i32, y: i32, z: i32) -> f32; + fn world_seed(&self) -> i64; + /// `getNearestPlayer(x, y, z, distance, true) != null`: a survival or + /// adventure player that close. + fn player_near(&self, x: f64, y: f64, z: f64, distance: f64) -> bool; +} + +fn name(l: &L, x: i32, y: i32, z: i32) -> &str { + &l.facts().get(l.state(x, y, z)).name +} +fn fluid(l: &L, x: i32, y: i32, z: i32) -> Fluid { + l.facts().get(l.state(x, y, z)).fluid +} +fn flags(l: &L, x: i32, y: i32, z: i32) -> u16 { + l.mob_data().state(l.state(x, y, z)).flags +} +fn tag(l: &L, tag: &str, x: i32, y: i32, z: i32) -> bool { + l.block_tag(tag, name(l, x, y, z)) +} +/// `getRawBrightness(pos, darkening)`. +fn raw_brightness(l: &L, x: i32, y: i32, z: i32, darkening: i32) -> i32 { + l.block_light(x, y, z).max(l.sky_light(x, y, z) - darkening) +} +fn can_see_sky(l: &L, x: i32, y: i32, z: i32) -> bool { + l.sky_light(x, y, z) >= 15 +} +/// `LevelReader.canSeeSkyFromBelowWater`. +fn can_see_sky_from_below_water(l: &L, x: i32, y: i32, z: i32) -> bool { + let sea = l.sea_level(); + if y >= sea { + return can_see_sky(l, x, y, z); + } + if !can_see_sky(l, x, sea, z) { + return false; + } + ((y + 1)..sea).all(|yy| { + let f = l.facts().get(l.state(x, yy, z)); + f.dampening == 0 || f.fluid != Fluid::None + }) +} + +/// `EntityType.fireImmune`. +pub fn fire_immune(s: Species) -> bool { + use Species as S; + matches!( + s, + S::Blaze + | S::Ghast + | S::MagmaCube + | S::Shulker + | S::Strider + | S::Vex + | S::Warden + | S::Wither + | S::WitherSkeleton + | S::Zoglin + | S::ZombifiedPiglin + ) +} +/// `EntityType.isAllowedInPeaceful`. +pub fn allowed_in_peaceful(s: Species) -> bool { + use Species as S; + !matches!( + s, + S::Blaze + | S::Bogged + | S::Breeze + | S::CaveSpider + | S::Creaking + | S::Creeper + | S::Drowned + | S::ElderGuardian + | S::Enderman + | S::Endermite + | S::Evoker + | S::Ghast + | S::Giant + | S::Guardian + | S::Hoglin + | S::Husk + | S::Illusioner + | S::MagmaCube + | S::Parched + | S::Phantom + | S::PiglinBrute + | S::Pillager + | S::Ravager + | S::Silverfish + | S::Skeleton + | S::Slime + | S::Spider + | S::Stray + | S::Vex + | S::Vindicator + | S::Warden + | S::Witch + | S::Wither + | S::WitherSkeleton + | S::Zoglin + | S::Zombie + | S::ZombieVillager + | S::ZombifiedPiglin + ) +} +/// The block tag an entity type is `immuneTo`. +fn immune_tag(s: Species) -> Option<&'static str> { + use Species as S; + match s { + S::Fox => Some("minecraft:fox_immune_to"), + S::PolarBear => Some("minecraft:polar_bear_immune_to"), + S::SnowGolem => Some("minecraft:snow_golem_immune_to"), + S::Stray => Some("minecraft:stray_immune_to"), + S::Wither => Some("minecraft:wither_immune_to"), + S::WitherSkeleton => Some("minecraft:wither_skeleton_immune_to"), + _ => None, + } +} +/// `BlockState.isValidSpawn(level, pos, type)` for the block at a position. +pub fn is_valid_spawn(s: Species, l: &L, x: i32, y: i32, z: i32) -> bool { + if name(l, x, y, z) == "minecraft:magma_block" { + return fire_immune(s); + } + let bit = match s { + Species::Ocelot | Species::Parrot => data::VALID_SPAWN_LEAVES, + Species::PolarBear => data::VALID_SPAWN_ICE, + _ => data::VALID_SPAWN, + }; + flags(l, x, y, z) & bit != 0 +} +/// `NaturalSpawner.isValidEmptySpawnBlock` for an entity type. +pub fn is_valid_empty_spawn(s: Species, l: &L, x: i32, y: i32, z: i32) -> bool { + // The exported flag is the zombie's answer; only blocks a zombie finds + // dangerous can answer differently for another type. + if flags(l, x, y, z) & data::VALID_EMPTY_SPAWN != 0 { + return true; + } + let f = l.facts().get(l.state(x, y, z)); + let block = &*f.name; + let burning = l.block_tag("minecraft:fire", block) + || block == "minecraft:lava" + || block == "minecraft:magma_block" + || (block == "minecraft:campfire" || block == "minecraft:soul_campfire") && f.emission > 0 + || block == "minecraft:lava_cauldron"; + let other = matches!( + block, + "minecraft:wither_rose" + | "minecraft:sweet_berry_bush" + | "minecraft:cactus" + | "minecraft:powder_snow" + ); + if !burning && !other { + return false; + } + let immune = immune_tag(s).is_some_and(|t| l.block_tag(t, block)); + let dangerous = !immune && (burning && !fire_immune(s) || other); + !dangerous + && !f.full_collision + && f.fluid == Fluid::None + && !l.block_tag("minecraft:prevent_mob_spawning_inside", block) +} +/// `SpawnPlacements.isSpawnPositionOk`. +pub fn is_spawn_position_ok(s: Species, l: &L, x: i32, y: i32, z: i32) -> bool { + let id = format!("minecraft:{}", super::species::def(s).name); + match l.mob_data().placement(&id) { + data::Placement::OnGround => { + is_valid_spawn(s, l, x, y - 1, z) + && is_valid_empty_spawn(s, l, x, y, z) + && is_valid_empty_spawn(s, l, x, y + 1, z) + } + data::Placement::InWater => { + fluid(l, x, y, z) == Fluid::Water && flags(l, x, y + 1, z) & data::REDSTONE_CONDUCTOR == 0 + } + data::Placement::InLava => fluid(l, x, y, z) == Fluid::Lava, + data::Placement::NoRestrictions => true, + } +} +/// `Monster.isDarkEnoughToSpawn`. +pub fn is_dark_enough(l: &L, random: &mut impl RandomSource, x: i32, y: i32, z: i32) -> bool { + if l.sky_light(x, y, z) > random.next_int_bound(32).unwrap_or(0) { + return false; + } + let dim = l.dimension(); + let limit = dim.block_light_limit(); + if limit < 15 && l.block_light(x, y, z) > limit { + return false; + } + let darken = if l.thundering() { 10 } else { l.sky_darken() }; + let brightness = raw_brightness(l, x, y, z, darken); + brightness <= dim.light_test(random) +} +/// `Animal.isBrightEnoughToSpawn`. +fn bright(l: &L, x: i32, y: i32, z: i32) -> bool { + raw_brightness(l, x, y, z, 0) > 8 +} +/// `Mob.checkMobSpawnRules`. +fn mob_rules(s: Species, l: &L, reason: Reason, x: i32, y: i32, z: i32) -> bool { + reason.is_spawner() || is_valid_spawn(s, l, x, y - 1, z) +} +/// `Monster.checkMonsterSpawnRules`. +fn monster_rules( + s: Species, + l: &L, + reason: Reason, + random: &mut impl RandomSource, + x: i32, + y: i32, + z: i32, +) -> bool { + (reason.ignores_light() || is_dark_enough(l, random, x, y, z)) && mob_rules(s, l, reason, x, y, z) +} +/// `Animal.checkAnimalSpawnRules` with the given spawnable-on tag. +fn animal_rules(l: &L, reason: Reason, on: &str, x: i32, y: i32, z: i32) -> bool { + let bright = reason.ignores_light() || bright(l, x, y, z); + tag(l, on, x, y - 1, z) && bright +} +/// `WaterAnimal.checkSurfaceWaterAnimalSpawnRules`. +fn surface_water(l: &L, x: i32, y: i32, z: i32) -> bool { + let sea = l.sea_level(); + y >= sea - 13 + && y <= sea + && fluid(l, x, y - 1, z) == Fluid::Water + && name(l, x, y + 1, z) == "minecraft:water" +} + +/// `SpawnPlacements.checkSpawnRules`. +pub fn check_spawn_rules( + s: Species, + l: &L, + reason: Reason, + random: &mut impl RandomSource, + x: i32, + y: i32, + z: i32, +) -> bool { + use Species as S; + if !allowed_in_peaceful(s) && l.peaceful() { + return false; + } + let below = |l: &L| name(l, x, y - 1, z).to_owned(); + match s { + S::Axolotl => tag(l, "minecraft:axolotls_spawnable_on", x, y - 1, z), + S::Cod | S::Pufferfish | S::Salmon | S::Dolphin | S::Squid => surface_water(l, x, y, z), + S::Drowned => { + if fluid(l, x, y - 1, z) != Fluid::Water && !reason.is_spawner() { + return false; + } + let frequent = l.biome_tag("minecraft:more_frequent_drowned_spawns", x, y, z); + let can_spawn = !l.peaceful() + && (reason.ignores_light() || is_dark_enough(l, random, x, y, z)) + && (reason.is_spawner() || fluid(l, x, y, z) == Fluid::Water); + if !can_spawn || !reason.is_spawner() && reason != Reason::Reinforcement { + if frequent { + random.next_int_bound(15).unwrap_or(1) == 0 && can_spawn + } else { + random.next_int_bound(40).unwrap_or(1) == 0 && y < l.sea_level() - 5 && can_spawn + } + } else { + true + } + } + S::Guardian | S::ElderGuardian => { + (random.next_int_bound(20).unwrap_or(1) == 0 || !can_see_sky_from_below_water(l, x, y, z)) + && !l.peaceful() + && (reason.is_spawner() || fluid(l, x, y, z) == Fluid::Water) + && fluid(l, x, y - 1, z) == Fluid::Water + } + S::TropicalFish => { + fluid(l, x, y - 1, z) == Fluid::Water + && name(l, x, y + 1, z) == "minecraft:water" + && (l.biome_tag("minecraft:allows_tropical_fish_spawns_at_any_height", x, y, z) + || surface_water(l, x, y, z)) + } + S::Armadillo => tag(l, "minecraft:armadillo_spawnable_on", x, y - 1, z) && bright(l, x, y, z), + S::Bat => { + if y >= l.world_surface(x, z) || random.next_boolean() { + return false; + } + if raw_brightness(l, x, y, z, l.sky_darken()) > random.next_int_bound(4).unwrap_or(0) { + return false; + } + tag(l, "minecraft:bats_spawnable_on", x, y - 1, z) && mob_rules(s, l, reason, x, y, z) + } + S::Blaze | S::Breeze | S::Zoglin => mob_rules(s, l, reason, x, y, z), + S::Camel => tag(l, "minecraft:camels_spawnable_on", x, y - 1, z) && bright(l, x, y, z), + S::CamelHusk | S::Husk | S::Parched => { + monster_rules(s, l, reason, random, x, y, z) + && (reason.is_spawner() || can_see_sky(l, x, y, z)) + } + S::Chicken + | S::Cow + | S::Donkey + | S::HappyGhast + | S::Horse + | S::Llama + | S::Mule + | S::Pig + | S::Sheep + | S::Cat + | S::Panda + | S::TraderLlama => animal_rules(l, reason, "minecraft:animals_spawnable_on", x, y, z), + S::Endermite | S::Silverfish => { + if !mob_rules(s, l, reason, x, y, z) { + return false; + } + reason.is_spawner() + || !l.player_near(f64::from(x) + 0.5, f64::from(y) + 0.5, f64::from(z) + 0.5, 5.0) + } + S::IronGolem | S::SnowGolem | S::Villager | S::Phantom | S::Shulker + | S::WanderingTrader => mob_rules(s, l, reason, x, y, z), + S::Frog => tag(l, "minecraft:frogs_spawnable_on", x, y - 1, z) && bright(l, x, y, z), + S::Ghast => { + !l.peaceful() + && random.next_int_bound(20).unwrap_or(1) == 0 + && mob_rules(s, l, reason, x, y, z) + } + S::GlowSquid => { + y <= l.sea_level() - 33 + && raw_brightness(l, x, y, z, 0) == 0 + && name(l, x, y, z) == "minecraft:water" + } + S::Goat => tag(l, "minecraft:goats_spawnable_on", x, y - 1, z) && bright(l, x, y, z), + S::MagmaCube => !l.peaceful(), + S::SulfurCube => true, + S::Mooshroom => tag(l, "minecraft:mooshrooms_spawnable_on", x, y - 1, z) && bright(l, x, y, z), + S::Nautilus => { + let sea = l.sea_level(); + y >= sea - 25 + && y <= sea - 5 + && fluid(l, x, y - 1, z) == Fluid::Water + && name(l, x, y + 1, z) == "minecraft:water" + } + S::Ocelot => random.next_int_bound(3).unwrap_or(0) != 0, + S::Parrot => tag(l, "minecraft:parrots_spawnable_on", x, y - 1, z) && bright(l, x, y, z), + S::Hoglin | S::Piglin => below(l) != "minecraft:nether_wart_block", + S::Pillager => l.block_light(x, y, z) <= 8 && mob_rules(s, l, reason, x, y, z), + S::PolarBear => { + if l.biome_tag("minecraft:polar_bears_spawn_on_alternate_blocks", x, y, z) { + bright(l, x, y, z) + && tag(l, "minecraft:polar_bears_spawnable_on_alternate", x, y - 1, z) + } else { + animal_rules(l, reason, "minecraft:animals_spawnable_on", x, y, z) + } + } + S::Rabbit => tag(l, "minecraft:rabbits_spawnable_on", x, y - 1, z) && bright(l, x, y, z), + S::SkeletonHorse => { + if reason.is_spawner() { + reason.ignores_light() || bright(l, x, y, z) + } else { + animal_rules(l, reason, "minecraft:animals_spawnable_on", x, y, z) + } + } + S::Slime => slime_rules(s, l, reason, random, x, y, z), + S::Stray => { + let mut sky = y + 1; + while name(l, x, sky, z) == "minecraft:powder_snow" { + sky += 1; + } + monster_rules(s, l, reason, random, x, y, z) + && (reason.is_spawner() || can_see_sky(l, x, sky - 1, z)) + } + S::Strider => { + let mut up = y + 1; + while fluid(l, x, up, z) == Fluid::Lava { + up += 1; + } + l.facts().is_air(l.state(x, up, z)) + } + S::Turtle => { + y < l.sea_level() + 4 && tag(l, "minecraft:sand", x, y - 1, z) && bright(l, x, y, z) + } + S::Wolf => tag(l, "minecraft:wolves_spawnable_on", x, y - 1, z) && bright(l, x, y, z), + S::ZombifiedPiglin => !l.peaceful() && below(l) != "minecraft:nether_wart_block", + S::Fox => tag(l, "minecraft:foxes_spawnable_on", x, y - 1, z) && bright(l, x, y, z), + S::Bogged + | S::CaveSpider + | S::Creeper + | S::Enderman + | S::Giant + | S::Skeleton + | S::Spider + | S::Witch + | S::Wither + | S::WitherSkeleton + | S::Creaking + | S::Zombie + | S::ZombieHorse + | S::ZombieVillager + | S::Evoker + | S::Illusioner + | S::Ravager + | S::Vex + | S::Vindicator + | S::Warden => monster_rules(s, l, reason, random, x, y, z), + // Types without a SpawnPlacements registration. + _ => true, + } +} +/// `Slime.checkSlimeSpawnRules`. +fn slime_rules( + s: Species, + l: &L, + reason: Reason, + random: &mut impl RandomSource, + x: i32, + y: i32, + z: i32, +) -> bool { + if l.peaceful() { + return false; + } + if reason.is_spawner() { + return mob_rules(s, l, reason, x, y, z); + } + if l.biome_tag("minecraft:allows_surface_slime_spawns", x, y, z) && y > 50 && y < 70 { + let chance = l.surface_slime_chance(x, y, z); + if random.next_float() < chance + && raw_brightness(l, x, y, z, l.sky_darken()) <= random.next_int_bound(8).unwrap_or(0) + { + return mob_rules(s, l, reason, x, y, z); + } + } + let slime_chunk = slime_chunk_random(x >> 4, z >> 4, l.world_seed(), 987_234_911) + .next_int_bound(10) + .unwrap_or(1) + == 0; + if random.next_int_bound(10).unwrap_or(1) == 0 && slime_chunk && y < 40 { + return mob_rules(s, l, reason, x, y, z); + } + false +} + +impl SpawnLevel for super::MobWorld<'_> { + fn state(&self, x: i32, y: i32, z: i32) -> BlockStateId { + self.world.block(x, y, z) + } + fn facts(&self) -> &BlockFacts { + self.facts + } + fn mob_data(&self) -> &data::MobData { + self.data + } + fn block_tag(&self, tag: &str, block: &str) -> bool { + self.has_tag(tag, block) + } + fn biome_tag(&self, tag: &str, x: i32, y: i32, z: i32) -> bool { + let Some(chunk) = self.world.chunks.get(&(x >> 4, z >> 4)) else { + return false; + }; + let biome = &self.biomes.get(chunk.biome(x, y, z)).name; + self.data + .biome_tags + .get(tag.trim_start_matches('#')) + .is_some_and(|members| members.contains(biome)) + } + fn sky_light(&self, x: i32, y: i32, z: i32) -> i32 { + if self.nether || self.end { + return 0; + } + i32::from(self.world.light(x, y, z) >> 4) + } + fn block_light(&self, x: i32, y: i32, z: i32) -> i32 { + i32::from(self.world.light(x, y, z) & 15) + } + fn sky_darken(&self) -> i32 { + super::MobWorld::sky_darken(self) + } + fn thundering(&self) -> bool { + self.thundering + } + fn sea_level(&self) -> i32 { + if self.nether { 32 } else { 63 } + } + fn world_surface(&self, x: i32, z: i32) -> i32 { + let top = crate::chunk::MIN_Y + crate::chunk::HEIGHT; + (crate::chunk::MIN_Y..top) + .rev() + .find(|&y| !self.facts.is_air(self.world.block(x, y, z))) + .map_or(crate::chunk::MIN_Y, |y| y + 1) + } + fn peaceful(&self) -> bool { + self.difficulty.effective == 0.0 + } + fn dimension(&self) -> Dimension { + if self.nether { + Dimension::Nether + } else if self.end { + Dimension::End + } else { + Dimension::Overworld + } + } + fn surface_slime_chance(&self, _: i32, _: i32, _: i32) -> f32 { + let phase = self.day_time.div_euclid(24000).rem_euclid(8) as usize; + 0.5 * super::spawning::MOON_BRIGHTNESS[phase] + } + fn world_seed(&self) -> i64 { + self.world_seed + } + fn player_near(&self, x: f64, y: f64, z: f64, distance: f64) -> bool { + self.player.as_ref().is_some_and(|p| { + let d = (p.position.x - x).powi(2) + (p.position.y - y).powi(2) + (p.position.z - z).powi(2); + p.alive && !p.creative && !p.spectator && d < distance * distance + }) + } +} diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index 33c4b5dd9..cffe7e03d 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -2,8 +2,7 @@ //! species' spawn predicate (`checkAnimalSpawnRules`, `checkMonsterSpawnRules`, //! water animals, bats...), and `finalizeSpawn` (variants, colours, babies, //! equipment). -use super::{Mob, MobWorld, Species, data, farm::Climate}; -use crate::blocks::Fluid; +use super::{Mob, MobWorld, Species, farm::Climate}; use horizon_core::random::RandomSource; /// Biome facts finalizeSpawn and the spawn rules read. @@ -27,44 +26,11 @@ pub struct BiomeFacts { /// `spawns_coral_variant_zombie_nautilus` (the warm ocean). pub coral_nautilus: bool, } -/// SpawnPlacementTypes for the species. +/// `SpawnPlacements.isSpawnPositionOk` for the species. pub fn placement_ok(species: Species, w: &MobWorld, x: i32, y: i32, z: i32) -> bool { - let id = format!("minecraft:{}", super::species::def(species).name); - match w.data.placement(&id) { - data::Placement::OnGround => { - let below = w.data.state(w.world.block(x, y - 1, z)); - let valid = match species { - Species::Ocelot | Species::Parrot => below.flags & data::VALID_SPAWN_LEAVES != 0, - Species::PolarBear => below.flags & data::VALID_SPAWN_ICE != 0, - _ => below.flags & data::VALID_SPAWN != 0, - }; - valid && empty(w, x, y, z) && empty(w, x, y + 1, z) - } - data::Placement::InWater => { - w.fluid(x, y, z) == Fluid::Water - && w.data.state(w.world.block(x, y + 1, z)).flags & data::REDSTONE_CONDUCTOR == 0 - } - data::Placement::InLava => w.fluid(x, y, z) == Fluid::Lava, - data::Placement::NoRestrictions => true, - } + super::spawn_rules::is_spawn_position_ok(species, w, x, y, z) } -fn empty(w: &MobWorld, x: i32, y: i32, z: i32) -> bool { - w.data.state(w.world.block(x, y, z)).flags & data::VALID_EMPTY_SPAWN != 0 -} -/// Monster.isDarkEnoughToSpawn (overworld: sky light vs random(32), block light 0). -pub fn dark_enough(w: &MobWorld, random: &mut impl RandomSource, x: i32, y: i32, z: i32) -> bool { - let light = w.world.light(x, y, z); - let (sky, block) = (i32::from(light >> 4), i32::from(light & 15)); - if sky > random.next_int_bound(32).unwrap_or(0) { - return false; - } - if block > 0 { - return false; - } - let darken = if w.thundering { 10 } else { w.sky_darken() }; - (sky - darken).max(0) <= random.next_int_bound(8).unwrap_or(0) -} -/// The species' checkSpawnRules for natural spawns. +/// `SpawnPlacements.checkSpawnRules` for a natural spawn. pub fn spawn_rules_ok( species: Species, w: &MobWorld, @@ -73,122 +39,15 @@ pub fn spawn_rules_ok( y: i32, z: i32, ) -> bool { - use Species as S; - let below = w.block_name(x, y - 1, z).to_owned(); - let light = w.world.light(x, y, z); - let raw = i32::from(light >> 4).max(i32::from(light & 15)); - match species { - // Guardian.checkGuardianSpawnRules. - S::Guardian | S::ElderGuardian => { - let sky_from_below = || { - let sea = 63; - if y >= sea { - return w.can_see_sky(x, y, z); - } - if !w.can_see_sky(x, sea, z) { - return false; - } - ((y + 1)..sea).all(|yy| { - let f = w.facts.get(w.world.block(x, yy, z)); - !f.full_collision || f.fluid != Fluid::None - }) - }; - (random.next_int_bound(20).unwrap_or(1) == 0 || !sky_from_below()) - && w.fluid(x, y, z) == Fluid::Water - && w.fluid(x, y - 1, z) == Fluid::Water - } - // Animal.checkAnimalSpawnRules: animals_spawnable_on below and bright. - S::Pig - | S::Cow - | S::Sheep - | S::Chicken - | S::Horse - | S::Donkey - | S::Llama - | S::Camel - | S::Wolf - | S::Cat - | S::Fox - | S::Rabbit - | S::Goat - | S::Panda - | S::Armadillo - | S::Mooshroom - | S::Turtle - | S::Frog - | S::Bee => { - let tag = match species { - S::Mooshroom => "minecraft:mooshrooms_spawnable_on", - S::Camel => "minecraft:camels_spawnable_on", - S::Wolf => "minecraft:wolves_spawnable_on", - S::Fox => "minecraft:foxes_spawnable_on", - S::Rabbit => "minecraft:rabbits_spawnable_on", - S::Goat => "minecraft:goats_spawnable_on", - S::Armadillo => "minecraft:armadillo_spawnable_on", - S::Turtle => "minecraft:turtles_spawnable_on", - S::Frog => "minecraft:frogs_spawnable_on", - _ => "minecraft:animals_spawnable_on", - }; - w.has_tag(tag, &below) && raw > 8 - } - S::PolarBear => { - w.has_tag("minecraft:polar_bears_spawnable_on_alternate", &below) - || w.has_tag("minecraft:animals_spawnable_on", &below) && raw > 8 - } - S::Ocelot | S::Parrot => { - (w.has_tag("minecraft:parrots_spawnable_on", &below) - || below.contains("leaves") - || below == "minecraft:grass_block") - && raw > 8 - } - S::Bat => { - // Bat.checkBatSpawnRules: below sea level, dark. - if y >= 63 { - return false; - } - let block = i32::from(light & 15).max(i32::from(light >> 4)); - block <= random.next_int_bound(4).unwrap_or(0) - } - S::Slime => { - // Swamp at night by moon brightness, or slime chunks below y 40. - y < 40 && random.next_int_bound(10).unwrap_or(1) == 0 - } - // GlowSquid.checkGlowSquidSpawnRules: deep, pitch dark water. - S::GlowSquid => y <= 63 - 33 && light == 0 && w.block_name(x, y, z) == "minecraft:water", - S::Squid | S::Cod | S::Salmon | S::TropicalFish | S::Pufferfish | S::Dolphin => { - // WaterAnimal.checkSurfaceWaterAnimalSpawnRules: sea level - 13 ..= sea level. - (50..=63).contains(&y) - && w.fluid(x, y - 1, z) == Fluid::Water - && w.block_name(x, y + 1, z) == "minecraft:water" - } - S::Axolotl => w.block_name(x, y - 1, z) == "minecraft:clay", - S::Strider => w.fluid(x, y, z) == Fluid::Lava, - S::Ghast - | S::MagmaCube - | S::ZombifiedPiglin - | S::Piglin - | S::Hoglin - | S::Blaze - | S::WitherSkeleton - | S::Enderman - if w.nether => - { - !w.block_name(x, y - 1, z).contains("nether_wart_block") || species == S::Ghast - } - // Monster.checkSurfaceMonstersSpawnRules. - S::Husk | S::Stray | S::CamelHusk => { - dark_enough(w, random, x, y, z) && w.can_see_sky(x, y, z) - } - // AbstractNautilus.checkNautilusSpawnRules. - S::Nautilus => super::nautilus::spawn_rules_ok(w, x, y, z), - // SulfurCube.checkSulfurCubeSpawnRules: anywhere it fits. - S::SulfurCube => true, - S::Drowned => w.fluid(x, y, z) == Fluid::Water && dark_enough(w, random, x, y, z), - _ => { - // Monster.checkMonsterSpawnRules - !w.nether && dark_enough(w, random, x, y, z) || w.nether - } - } + super::spawn_rules::check_spawn_rules( + species, + w, + super::spawn_rules::Reason::Natural, + random, + x, + y, + z, + ) } /// Mob.finalizeSpawn for natural, chunk-generation and summoned mobs. /// `DifficultyInstance`: the local difficulty at a position. diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSpawnRulesOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSpawnRulesOracle.java new file mode 100644 index 000000000..c02da47a6 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSpawnRulesOracle.java @@ -0,0 +1,204 @@ +package dev.horizonlab.parity; + +import com.mojang.authlib.GameProfile; +import java.io.PrintWriter; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.SharedConstants; +import net.minecraft.core.*; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.RegistryDataLoader; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.Bootstrap; +import net.minecraft.server.RegistryLayer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.packs.PackType; +import net.minecraft.server.packs.repository.ServerPacksSource; +import net.minecraft.server.packs.resources.MultiPackResourceManager; +import net.minecraft.tags.TagLoader; +import net.minecraft.util.RandomSource; +import net.minecraft.world.Difficulty; +import net.minecraft.world.entity.*; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LightLayer; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.border.WorldBorder; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.levelgen.Heightmap; +import net.minecraft.world.level.material.FluidState; + +/** + * Original oracle: SpawnPlacements.isSpawnPositionOk and checkSpawnRules for an + * entity type at a position of a controlled column world. The stand-in + * ServerLevel answers block states from the case (air elsewhere), uniform sky + * and block light, the sky darkening, thunder, difficulty, dimension type, + * biome, sea level, WORLD_SURFACE height, world seed, the surface slime spawn + * chance and an optional nearby player. Each case prints the two answers and + * the next nextInt(1000) of its random, which pins the number of draws. + */ +public final class VanillaSpawnRulesOracle { + static Object unsafe; + static Method allocate, putObject, objectFieldOffset; + + static Object alloc(Class c) throws Exception { return allocate.invoke(unsafe, c); } + + static void put(Object target, Class owner, String field, Object value) throws Exception { + Field f = owner.getDeclaredField(field); + putObject.invoke(unsafe, target, (long) objectFieldOffset.invoke(unsafe, f), value); + } + + static final class Lvl extends ServerLevel { + Lvl() { super(null, null, null, null, null, null, false, 0L, List.of(), false); } + RegistryAccess registries; + Map column = new HashMap<>(); + int x0, z0, sky, block, darken, sea, surface; + boolean thunder; + long seed; + Difficulty difficulty; + DimensionType dimension; + Holder biome; + net.minecraft.world.attribute.EnvironmentAttributeSystem attributes; + List playerList = new ArrayList<>(); + WorldBorder border = new WorldBorder(); + int next = 1; + @Override public RegistryAccess registryAccess() { return registries; } + @Override public Difficulty getDifficulty() { return difficulty; } + @Override public long getGameTime() { return 0L; } + @Override public int getNextEntityId() { return next++; } + @Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags(); } + @Override public BlockState getBlockState(BlockPos pos) { + if (pos.getX() != x0 || pos.getZ() != z0) return Blocks.AIR.defaultBlockState(); + return column.getOrDefault(pos.getY(), Blocks.AIR.defaultBlockState()); + } + @Override public FluidState getFluidState(BlockPos pos) { return getBlockState(pos).getFluidState(); } + @Override public int getBrightness(LightLayer layer, BlockPos pos) { return layer == LightLayer.SKY ? sky : block; } + @Override public int getRawBrightness(BlockPos pos, int darkening) { return Math.max(block, sky - darkening); } + @Override public int getSkyDarken() { return darken; } + @Override public boolean isThundering() { return thunder; } + @Override public int getSeaLevel() { return sea; } + @Override public int getHeight(Heightmap.Types type, int x, int z) { return surface; } + @Override public long getSeed() { return seed; } + @Override public DimensionType dimensionType() { return dimension; } + @Override public Holder getBiome(BlockPos pos) { return biome; } + @Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { return attributes; } + @Override public WorldBorder getWorldBorder() { return border; } + @SuppressWarnings({"unchecked", "rawtypes"}) + @Override public List players() { return playerList; } + } + + static final class OraclePlayer extends Player { + final GameType mode; + OraclePlayer(Level level, GameType mode) { super(level, new GameProfile(new UUID(1L, 2L), "oracle")); this.mode = mode; } + @Override public GameType gameMode() { return mode; } + @Override public boolean isCreative() { return mode == GameType.CREATIVE; } + @Override public boolean isSpectator() { return mode == GameType.SPECTATOR; } + @Override public net.minecraft.world.item.component.ResolvableProfile getProfile() { return net.minecraft.world.item.component.ResolvableProfile.createResolved(this.getGameProfile()); } + } + + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); + unsafeField.setAccessible(true); + unsafe = unsafeField.get(null); + allocate = unsafe.getClass().getMethod("allocateInstance", Class.class); + putObject = unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class); + objectFieldOffset = unsafe.getClass().getMethod("objectFieldOffset", Field.class); + var repo = ServerPacksSource.createVanillaTrustedRepository(); + repo.reload(); + repo.setSelected(List.of("vanilla")); + var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected()); + var layers = RegistryLayer.createRegistryAccess(); + var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC)); + var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags); + RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join(); + staticTags.forEach(Registry.PendingTags::apply); + var access = layers.replaceFrom(RegistryLayer.WORLD, world).compositeAccess(); + + Lvl level = (Lvl) alloc(Lvl.class); + level.registries = access; + level.column = new HashMap<>(); + level.playerList = new ArrayList<>(); + level.border = new WorldBorder(); + put(level, Level.class, "random", RandomSource.create(0L)); + var biomes = access.lookupOrThrow(Registries.BIOME); + var dimensions = access.lookupOrThrow(Registries.DIMENSION_TYPE); + var blocks = access.lookupOrThrow(Registries.BLOCK); + + if (args.length > 2 && args[2].equals("facts")) { + try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) { + for (var type : BuiltInRegistries.ENTITY_TYPE) + w.println(BuiltInRegistries.ENTITY_TYPE.getKey(type) + " peaceful=" + type.isAllowedInPeaceful() + " fire_immune=" + type.fireImmune() + + " placement=" + SpawnPlacements.getPlacementType(type) + " heightmap=" + SpawnPlacements.getHeightmapType(type)); + } + System.exit(0); + } + + List lines = Files.readAllLines(Path.of(args[0])); + try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) { + for (String raw : lines) { + if (raw.isBlank()) continue; + Map c = new LinkedHashMap<>(); + for (String token : raw.trim().split("\\s+")) { + int eq = token.indexOf('='); + if (eq < 0) c.put("name", token); else c.put(token.substring(0, eq), token.substring(eq + 1)); + } + try { + int y = Integer.parseInt(c.getOrDefault("y", "64")); + level.x0 = Integer.parseInt(c.getOrDefault("x", "8")); + level.z0 = Integer.parseInt(c.getOrDefault("z", "8")); + level.column.clear(); + for (var e : c.entrySet()) { + if (e.getKey().startsWith("at")) { + int offset = Integer.parseInt(e.getKey().substring(2)); + level.column.put(y + offset, net.minecraft.commands.arguments.blocks.BlockStateParser.parseForBlock(blocks, e.getValue(), false).blockState()); + } + } + level.sky = Integer.parseInt(c.getOrDefault("sky", "15")); + level.block = Integer.parseInt(c.getOrDefault("light", "0")); + level.darken = Integer.parseInt(c.getOrDefault("darken", "0")); + level.thunder = c.getOrDefault("thunder", "0").equals("1"); + level.sea = Integer.parseInt(c.getOrDefault("sea", "63")); + level.surface = Integer.parseInt(c.getOrDefault("surface", "0")); + level.seed = Long.parseLong(c.getOrDefault("wseed", "0")); + level.difficulty = Difficulty.byName(c.getOrDefault("difficulty", "normal")); + level.dimension = dimensions.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.parse(c.getOrDefault("dim", "minecraft:overworld")))).value(); + level.biome = biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(c.getOrDefault("biome", "minecraft:plains")))); + level.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder() + .addConstantLayer(net.minecraft.world.attribute.EnvironmentAttributeMap.builder() + .set(net.minecraft.world.attribute.EnvironmentAttributes.SURFACE_SLIME_SPAWN_CHANCE, Float.parseFloat(c.getOrDefault("slime", "0.0"))) + .build()) + .build(); + level.playerList.clear(); + if (c.containsKey("player")) { + String[] p = c.get("player").split(","); + Player player = new OraclePlayer(level, GameType.byName(p.length > 3 ? p[3] : "survival")); + player.setPos(level.x0 + Double.parseDouble(p[0]), y + Double.parseDouble(p[1]), level.z0 + Double.parseDouble(p[2])); + level.playerList.add(player); + } + EntityType type = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(c.get("type"))); + EntitySpawnReason reason = EntitySpawnReason.valueOf(c.getOrDefault("reason", "natural").toUpperCase(Locale.ROOT)); + BlockPos pos = new BlockPos(level.x0, y, level.z0); + RandomSource random = RandomSource.create(Long.parseLong(c.getOrDefault("seed", "0"))); + boolean ok = SpawnPlacements.isSpawnPositionOk(type, level, pos); + boolean rules = SpawnPlacements.checkSpawnRules(type, level, reason, pos, random); + w.println(c.get("name") + " " + ok + " " + rules + " " + random.nextInt(1000)); + } catch (Throwable t) { + Throwable cause = t instanceof InvocationTargetException ite ? ite.getCause() : t; + StringBuilder line = new StringBuilder(c.get("name") + " error " + cause); + if (System.getenv("ORACLE_TRACE") != null) for (var frame : cause.getStackTrace()) line.append("\n at ").append(frame); + w.println(line); + } + } + } + System.exit(0); + } +} diff --git a/tools/test_spawn_rules_parity.py b/tools/test_spawn_rules_parity.py new file mode 100644 index 000000000..4050fae46 --- /dev/null +++ b/tools/test_spawn_rules_parity.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Compare spawn placement checks and spawn predicates with vanilla. + +Java (VanillaSpawnRulesOracle) runs SpawnPlacements.isSpawnPositionOk and +checkSpawnRules on a stand-in ServerLevel holding one column of blocks with +uniform light; Rust (spawn_rules_fixture) runs horizon_client::mobs::spawn_rules +on the same column. Every mob type is tried on surfaces, caves, water, lava, +the nether and the end, dangerous blocks, light levels, thunder, difficulty, +biomes, slime chunks, nearby players and several spawn reasons; each case +also prints the next draw of its random, pinning the number of draws. +""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + +# Living types that are not Horizon mob types or not mobs at all. +SKIPPED = {'player', 'mannequin', 'armor_stand', 'ender_dragon', 'giant', 'copper_golem'} + +SCENARIOS = { + 'grass-day': dict(b=dict(m1='minecraft:grass_block'), sky=15, surface=64), + 'grass-night': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, surface=64), + 'grass-dusk': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=7, surface=64), + 'grass-thunder': dict(b=dict(m1='minecraft:grass_block'), sky=15, thunder=1, surface=64), + 'grass-peaceful': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, difficulty='peaceful', surface=64), + 'grass-torch': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, light=9, surface=64), + 'cave-dark': dict(b=dict(m1='minecraft:stone'), sky=0, y=20, surface=80), + 'cave-lit1': dict(b=dict(m1='minecraft:stone'), sky=0, light=1, y=20, surface=80), + 'cave-lit8': dict(b=dict(m1='minecraft:deepslate'), sky=0, light=8, y=-20, surface=80), + 'cave-lit12': dict(b=dict(m1='minecraft:stone'), sky=0, light=12, y=20, surface=80), + 'cave-dim': dict(b=dict(m1='minecraft:stone'), sky=3, y=40, surface=80), + 'water-surface': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=15, y=60, surface=64, biome='minecraft:ocean'), + 'water-warm': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=15, y=58, surface=64, biome='minecraft:warm_ocean'), + 'water-deep': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=0, y=25, surface=64, biome='minecraft:deep_ocean'), + 'water-deep-lit': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=0, light=3, y=25, surface=64, biome='minecraft:lukewarm_ocean'), + 'water-mid': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=15, y=45, surface=64, biome='minecraft:cold_ocean'), + 'water-roofed': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water', p3='minecraft:stone'), sky=0, y=50, surface=64, biome='minecraft:ocean'), + 'water-river': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=0, y=50, surface=64, biome='minecraft:river', darken=11), + 'water-conductor': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:stone'), sky=15, y=60, surface=64), + 'water-seagrass': dict(b=dict(m1='minecraft:sand', p0='minecraft:water', p1='minecraft:water'), sky=15, y=55, surface=64, biome='minecraft:ocean'), + 'water-clay': dict(b=dict(m1='minecraft:clay', p0='minecraft:water', p1='minecraft:water'), sky=0, y=10, surface=64, biome='minecraft:lush_caves'), + 'lava-nether': dict(b=dict(m1='minecraft:lava', p0='minecraft:lava', p1='minecraft:lava'), sky=0, light=15, y=31, sea=32, dim='minecraft:the_nether', biome='minecraft:basalt_deltas'), + 'lava-open': dict(b=dict(m1='minecraft:lava', p0='minecraft:lava'), sky=0, light=15, y=31, sea=32, dim='minecraft:the_nether', biome='minecraft:nether_wastes'), + 'nether-dark': dict(b=dict(m1='minecraft:netherrack'), sky=0, light=0, y=70, sea=32, dim='minecraft:the_nether', biome='minecraft:nether_wastes'), + 'nether-lit7': dict(b=dict(m1='minecraft:netherrack'), sky=0, light=7, y=70, sea=32, dim='minecraft:the_nether', biome='minecraft:crimson_forest'), + 'nether-lit8': dict(b=dict(m1='minecraft:crimson_nylium'), sky=0, light=8, y=70, sea=32, dim='minecraft:the_nether', biome='minecraft:crimson_forest'), + 'nether-wart': dict(b=dict(m1='minecraft:nether_wart_block'), sky=0, light=0, y=70, sea=32, dim='minecraft:the_nether', biome='minecraft:crimson_forest'), + 'nether-soul': dict(b=dict(m1='minecraft:soul_sand'), sky=0, light=3, y=40, sea=32, dim='minecraft:the_nether', biome='minecraft:soul_sand_valley'), + 'nether-magma': dict(b=dict(m1='minecraft:magma_block'), sky=0, light=3, y=40, sea=32, dim='minecraft:the_nether', biome='minecraft:basalt_deltas'), + 'end': dict(b=dict(m1='minecraft:end_stone'), sky=0, light=0, y=60, dim='minecraft:the_end', biome='minecraft:the_end'), + 'end-lit': dict(b=dict(m1='minecraft:end_stone'), sky=0, light=14, y=60, dim='minecraft:the_end', biome='minecraft:end_highlands'), + 'ice-frozen': dict(b=dict(m1='minecraft:ice'), sky=15, y=63, surface=64, biome='minecraft:frozen_ocean'), + 'ice-plains': dict(b=dict(m1='minecraft:packed_ice'), sky=15, y=64, surface=64, biome='minecraft:snowy_plains'), + 'snow-block': dict(b=dict(m1='minecraft:snow_block'), sky=15, darken=11, y=70, surface=70, biome='minecraft:snowy_plains'), + 'snow-layer': dict(b=dict(m1='minecraft:grass_block[snowy=true]', p0='minecraft:snow'), sky=15, y=70, surface=71, biome='minecraft:snowy_taiga'), + 'powder-snow-stray': dict(b=dict(m1='minecraft:snow_block', p1='minecraft:powder_snow', p2='minecraft:powder_snow'), sky=15, darken=11, y=90, surface=93, biome='minecraft:frozen_peaks'), + 'sand-beach': dict(b=dict(m1='minecraft:sand'), sky=15, y=63, surface=64, biome='minecraft:beach'), + 'sand-desert': dict(b=dict(m1='minecraft:sand'), sky=15, darken=11, y=70, surface=70, biome='minecraft:desert'), + 'red-sand': dict(b=dict(m1='minecraft:red_sand'), sky=15, y=80, surface=80, biome='minecraft:badlands'), + 'leaves-jungle': dict(b=dict(m1='minecraft:jungle_leaves'), sky=15, y=90, surface=90, biome='minecraft:jungle'), + 'grass-jungle': dict(b=dict(m1='minecraft:grass_block'), sky=15, y=70, surface=70, biome='minecraft:jungle'), + 'mycelium': dict(b=dict(m1='minecraft:mycelium'), sky=15, y=70, surface=70, biome='minecraft:mushroom_fields'), + 'podzol': dict(b=dict(m1='minecraft:podzol'), sky=15, y=70, surface=70, biome='minecraft:old_growth_pine_taiga'), + 'mud-swamp': dict(b=dict(m1='minecraft:mud'), sky=15, y=62, surface=62, biome='minecraft:mangrove_swamp'), + 'stone-peaks': dict(b=dict(m1='minecraft:stone'), sky=15, y=160, surface=160, biome='minecraft:jagged_peaks'), + 'coarse-savanna': dict(b=dict(m1='minecraft:coarse_dirt'), sky=15, y=70, surface=70, biome='minecraft:savanna'), + 'slab-bottom': dict(b=dict(m1='minecraft:oak_slab[type=bottom]'), sky=0, y=40, surface=80), + 'slab-top': dict(b=dict(m1='minecraft:oak_slab[type=top]'), sky=0, y=40, surface=80), + 'glass': dict(b=dict(m1='minecraft:glass'), sky=0, y=40, surface=80), + 'glowstone': dict(b=dict(m1='minecraft:glowstone'), sky=0, light=15, y=40, surface=80), + 'fire': dict(b=dict(m1='minecraft:netherrack', p0='minecraft:fire'), sky=0, light=15, y=40, surface=80), + 'soul-fire': dict(b=dict(m1='minecraft:soul_soil', p0='minecraft:soul_fire'), sky=0, light=10, y=40, sea=32, dim='minecraft:the_nether', biome='minecraft:soul_sand_valley'), + 'wither-rose': dict(b=dict(m1='minecraft:grass_block', p0='minecraft:wither_rose'), sky=0, y=40, surface=80), + 'berry-bush': dict(b=dict(m1='minecraft:grass_block', p0='minecraft:sweet_berry_bush'), sky=15, y=70, surface=70, biome='minecraft:taiga'), + 'cactus': dict(b=dict(m1='minecraft:sand', p0='minecraft:cactus'), sky=0, y=70, surface=72, biome='minecraft:desert'), + 'powder-snow-feet': dict(b=dict(m1='minecraft:snow_block', p0='minecraft:powder_snow'), sky=15, darken=11, y=90, surface=91, biome='minecraft:snowy_slopes'), + 'campfire': dict(b=dict(m1='minecraft:stone', p0='minecraft:campfire[lit=true]'), sky=0, light=15, y=40, surface=80), + 'campfire-out': dict(b=dict(m1='minecraft:stone', p0='minecraft:campfire[lit=false]'), sky=0, y=40, surface=80), + 'rail': dict(b=dict(m1='minecraft:stone', p0='minecraft:rail'), sky=0, y=40, surface=80), + 'redstone-torch': dict(b=dict(m1='minecraft:stone', p0='minecraft:redstone_torch'), sky=0, light=7, y=40, surface=80), + 'tall-grass': dict(b=dict(m1='minecraft:grass_block', p0='minecraft:short_grass', p1='minecraft:air'), sky=15, darken=11, y=70, surface=70), + 'low-ceiling': dict(b=dict(m1='minecraft:stone', p1='minecraft:stone'), sky=0, y=40, surface=80), + 'swamp-surface': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, y=62, surface=63, biome='minecraft:swamp', slime=0.5), + 'swamp-full-moon': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=4, y=64, surface=65, biome='minecraft:swamp', slime=0.5), + 'swamp-new-moon': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, y=63, surface=64, biome='minecraft:swamp', slime=0.0), + 'bat-cave': dict(b=dict(m1='minecraft:stone'), sky=0, y=10, surface=80), + 'bat-surface': dict(b=dict(m1='minecraft:stone'), sky=0, y=79, surface=79), +} +REASONS = ['natural', 'natural', 'natural', 'chunk_generation', 'spawner', 'trial_spawner', 'reinforcement', 'patrol'] + + +def corpus(types): + rng = random.Random(0x5350574E) + cases = [] + for t in types: + n = t.split(':')[1] + for name, s in SCENARIOS.items(): + for k in range(3): + kv = {k2: v for k2, v in s.items() if k2 != 'b'} + kv.setdefault('y', 64) + for key, block in s['b'].items(): + kv['at' + ('-' if key[0] == 'm' else '') + key[1:]] = block + kv['reason'] = REASONS[k] if k == 0 else rng.choice(REASONS) + kv['seed'] = rng.randrange(-2**47, 2**47) + cases.append(f'{n}/{name}/{k} type={t} ' + ' '.join(f'{a}={b}' for a, b in kv.items())) + # Slime chunks: deep caves at many chunk positions and world seeds. + if n in ('slime', 'zombie'): + for k in range(600 if n == 'slime' else 60): + cases.append(f'{n}/slime-chunk/{k} type={t} at-1=minecraft:stone sky=0 y={rng.randrange(-60, 45)} ' + f'x={rng.randrange(-4000, 4000)} z={rng.randrange(-4000, 4000)} wseed={rng.randrange(-2**63, 2**63)} ' + f'seed={rng.randrange(-2**47, 2**47)} reason=natural surface=80') + # Nearby players (silverfish and endermite refuse to spawn next to a targetable one). + for k, player in enumerate(['1,0,1,survival', '1,0,1,creative', '4,0,4,survival', '3,1,3,adventure', '0,4.4,0,survival', + '2,2,2,spectator']): + cases.append(f'{n}/player/{k} type={t} at-1=minecraft:stone sky=0 y=20 surface=80 player={player} ' + f'seed={rng.randrange(-2**47, 2**47)} reason={rng.choice(REASONS)}') + return cases + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--prepare', action='store_true') + args = parser.parse_args() + build = lab.LOCAL / 'rust-spawn-rules-parity' + build.mkdir(parents=True, exist_ok=True) + if args.prepare: + lab.prepare() + lock, jars, libraries = base.verify_artifacts() + resources = lab.LOCAL / 'horizon-client/26.3' + entity_types = json.loads((resources / 'entity-types.json').read_text()) + types = sorted(t for t, v in entity_types.items() if 'attributes' in v and t.split(':')[1] not in SKIPPED) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSpawnRulesOracle.java' + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/spawn_rules_fixture.rs', + lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs'] + tested = base.source_hashes(sources) + inputs = build / 'inputs.txt' + cases = corpus(types) + inputs.write_text(''.join(line + '\n' for line in cases), encoding='utf-8') + classes = build / 'classes' + classes.mkdir(exist_ok=True) + deps = os.pathsep.join(map(str, libraries)) + + def run(command, name): + with (build / (name + '.log')).open('w', encoding='utf-8') as log: + base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT) + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'), + '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') + run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), + 'dev.horizonlab.parity.VanillaSpawnRulesOracle', inputs, build / 'server.txt'], 'server') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'spawn_rules_fixture'], 'compile-rust') + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release/examples/spawn_rules_fixture' + run([binary, resources, inputs, build / 'rust.txt'], 'rust') + vanilla = (build / 'server.txt').read_text().splitlines() + errors = [l for l in vanilla if ' error ' in l] + if errors: + raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}') + rust = (build / 'rust.txt').read_text().splitlines() + bad = [(a, b) for a, b in zip(vanilla, rust) if a != b] + if bad or len(vanilla) != len(rust): + report = '\n'.join(f' vanilla {a}\n rust {b}' for a, b in bad[:40]) + raise SystemExit(f'{len(bad)} of {len(vanilla)} cases differ (rust {len(rust)} lines):\n{report}') + base.ensure_sources_unchanged(sources, tested) + lab.write_json(build / 'report.json', { + 'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'cases': len(cases), + 'types': len(types), 'scenarios': sorted(SCENARIOS), 'sources_sha256': tested, + 'scope': 'SpawnPlacements.isSpawnPositionOk (placement types, isValidSpawn, isValidEmptySpawnBlock with per-type ' + 'dangerous blocks) and checkSpawnRules (every registered predicate, peaceful, spawn reasons) with the ' + 'random draw count.'}) + print(f'{len(cases):,} spawn rule cases over {len(types)} entity types match vanilla') + + +if __name__ == '__main__': + main() From 54119238878d06b13e002f1822adf308f50a1d7d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:23:05 +0200 Subject: [PATCH 25/28] Join guests as PlayerList.placeNewPlayer does and send vanilla's command tree Send the join packets in vanilla's order with the permission level entity event, recipe book, server data, ticking state and post effects; announce the newcomer only to the others; list players with every info action; use vanilla's level key order and border warning time; sync the game time every 20 ticks without clocks and the overworld clock only when it jumps. Build the command tree from the commands report for the player's permission level and server kind, with vanilla's suggestion providers (VanillaCommandSuggestionsExporter), and answer command suggestions. The tree matches what a vanilla integrated server sends node for node. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/examples/lan_flat.rs | 5 +- crates/horizon-client/src/game/lan.rs | 9 +- crates/horizon-client/src/game/lan_actions.rs | 46 +++ .../src/lan/command_suggestions.rs | 138 +++++++ crates/horizon-client/src/lan/commands.rs | 337 +++++++++++++++++ crates/horizon-client/src/lan/data.rs | 3 + crates/horizon-client/src/lan/guest.rs | 3 + crates/horizon-client/src/lan/hub.rs | 341 ++++++++++-------- crates/horizon-client/src/lan/mod.rs | 7 +- .../dev/horizonlab/parity/OfflineLanHost.java | 42 +++ .../VanillaCommandSuggestionsExporter.java | 39 ++ tools/generate_command_suggestions.py | 42 +++ tools/vanilla_client.py | 13 + 13 files changed, 880 insertions(+), 145 deletions(-) create mode 100644 crates/horizon-client/src/lan/command_suggestions.rs create mode 100644 crates/horizon-client/src/lan/commands.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/OfflineLanHost.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandSuggestionsExporter.java create mode 100644 tools/generate_command_suggestions.py diff --git a/crates/horizon-client/examples/lan_flat.rs b/crates/horizon-client/examples/lan_flat.rs index aa9fb70f8..63ea9f136 100644 --- a/crates/horizon-client/examples/lan_flat.rs +++ b/crates/horizon-client/examples/lan_flat.rs @@ -87,6 +87,7 @@ fn main() -> Result<(), Box> { dimension: "minecraft:overworld".into(), seed: 0, max_players: 8, + dedicated: false, }, ); let mut next_entity = 100u32; @@ -110,13 +111,15 @@ fn main() -> Result<(), Box> { world.day_time += 1; let mut ctx = TickCtx { world: &mut world, - host: &host, + host: Some(&host), entities: &[], next_entity: &mut next_entity, spawn: [8.5, 60.0, 8.5], difficulty: 2, difficulty_locked: false, clock_rate: 1.0, + tick_rate: 20.0, + tick_frozen: false, }; for event in hub.tick(&mut ctx) { match event { diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 664662249..8fb31db45 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -382,6 +382,7 @@ impl Game<'_> { dimension: self.dim.id().to_owned(), seed: self.level.seed, max_players: MAX_PLAYERS, + dedicated: false, }, ); let port = hub.lan.port; @@ -539,7 +540,7 @@ impl Game<'_> { let events = { let mut ctx = TickCtx { world: &mut self.world, - host: &state, + host: Some(&state), entities: &entities, next_entity: &mut self.next_entity, spawn, @@ -550,6 +551,8 @@ impl Game<'_> { } else { 0.0 }, + tick_rate: self.clock.rate(), + tick_frozen: self.clock.frozen(), }; host.hub.tick(&mut ctx) }; @@ -607,13 +610,15 @@ impl Game<'_> { } let mut ctx = TickCtx { world: &mut self.world, - host: state, + host: Some(state), entities, next_entity: &mut self.next_entity, spawn, difficulty: i32::from(self.ui.difficulty), difficulty_locked: false, clock_rate: self.ui.clock.rate, + tick_rate: self.clock.rate(), + tick_frozen: self.clock.frozen(), }; host.hub.place_new_player(conn, &mut ctx); } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index bb64597ef..342f38b45 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -7,6 +7,7 @@ //! block log, the level events and the entity tracker. use super::{Game, Hit, Mining, Screen, lan::LanHost}; use horizon_client::{ + command::vanilla, containers::BlockEntity, entities::Experience, items::ItemStack, @@ -405,6 +406,11 @@ impl Game<'_> { self.guest_command(host, conn, &text); } } + S::Unknown(id, payload) + if id == horizon_protocol::ids::play::serverbound::COMMAND_SUGGESTION => + { + self.guest_suggestions(host, conn, &payload); + } S::ClientCommand(c) if c.action == 0 => self.guest_respawn(host, conn), S::PickItemFromBlock(p) => { let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]); @@ -532,6 +538,46 @@ impl Game<'_> { } } + /// ServerGamePacketListenerImpl.handleCustomCommandSuggestions: the + /// completions of the command typed so far (after an optional slash), for + /// the nodes the tree marks `ask_server`. + fn guest_suggestions(&mut self, host: &mut LanHost, conn: u32, payload: &[u8]) { + let mut r = horizon_protocol::buf::Reader::new(payload); + let (Ok(id), Ok(text)) = (r.varint(), r.string(32500)) else { + return; + }; + let Some(permission) = host.hub.guest(conn).map(|g| g.permission) else { + return; + }; + let skip = usize::from(text.starts_with('/')); + let command = &text[skip..]; + let d = vanilla::dispatcher(); + let level = std::mem::replace(&mut self.ui.registries.permission, permission); + let parse = d.parse(command, &self.ui.registries); + let ((start, end), suggestions) = d.suggestions(&parse, command.len(), &self.ui.registries); + self.ui.registries.permission = level; + let utf16 = |byte: usize| command[..byte.min(command.len())].encode_utf16().count() as i32; + let mut w = horizon_protocol::buf::Writer::new(); + w.varint(id); + w.varint(utf16(start) + skip as i32); + w.varint(utf16(end) - utf16(start)); + w.varint(suggestions.len() as i32); + for s in &suggestions { + w.string(&s.text); + w.bool(s.tooltip.is_some()); + if let Some(tip) = &s.tooltip { + w.nbt(&literal(tip)); + } + } + host.hub.send_to( + conn, + &C::Unknown( + horizon_protocol::ids::play::clientbound::COMMAND_SUGGESTIONS, + w.data, + ), + ); + } + fn guest_respawn(&mut self, host: &mut LanHost, conn: u32) { let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]); let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else { diff --git a/crates/horizon-client/src/lan/command_suggestions.rs b/crates/horizon-client/src/lan/command_suggestions.rs new file mode 100644 index 000000000..1afb299d4 --- /dev/null +++ b/crates/horizon-client/src/lan/command_suggestions.rs @@ -0,0 +1,138 @@ +//! Argument nodes of vanilla's command tree with a custom suggestion +//! provider (path of node names from the root, provider network name). +//! Generated by tools/generate_command_suggestions.py from +//! VanillaCommandSuggestionsExporter; do not edit by hand. + +pub const SUGGESTIONS: &[(&str, &str)] = &[ + ("advancement grant targets only advancement criterion", "minecraft:ask_server"), + ("advancement revoke targets only advancement criterion", "minecraft:ask_server"), + ("attribute target attribute modifier remove id", "minecraft:ask_server"), + ("attribute target attribute modifier value get id", "minecraft:ask_server"), + ("bossbar get id", "minecraft:ask_server"), + ("bossbar remove id", "minecraft:ask_server"), + ("bossbar set id", "minecraft:ask_server"), + ("data get storage target", "minecraft:ask_server"), + ("data merge storage target", "minecraft:ask_server"), + ("data modify block target targetPath append from storage source", "minecraft:ask_server"), + ("data modify block target targetPath append string storage source", "minecraft:ask_server"), + ("data modify block target targetPath insert index from storage source", "minecraft:ask_server"), + ("data modify block target targetPath insert index string storage source", "minecraft:ask_server"), + ("data modify block target targetPath merge from storage source", "minecraft:ask_server"), + ("data modify block target targetPath merge string storage source", "minecraft:ask_server"), + ("data modify block target targetPath prepend from storage source", "minecraft:ask_server"), + ("data modify block target targetPath prepend string storage source", "minecraft:ask_server"), + ("data modify block target targetPath set from storage source", "minecraft:ask_server"), + ("data modify block target targetPath set string storage source", "minecraft:ask_server"), + ("data modify entity target targetPath append from storage source", "minecraft:ask_server"), + ("data modify entity target targetPath append string storage source", "minecraft:ask_server"), + ("data modify entity target targetPath insert index from storage source", "minecraft:ask_server"), + ("data modify entity target targetPath insert index string storage source", "minecraft:ask_server"), + ("data modify entity target targetPath merge from storage source", "minecraft:ask_server"), + ("data modify entity target targetPath merge string storage source", "minecraft:ask_server"), + ("data modify entity target targetPath prepend from storage source", "minecraft:ask_server"), + ("data modify entity target targetPath prepend string storage source", "minecraft:ask_server"), + ("data modify entity target targetPath set from storage source", "minecraft:ask_server"), + ("data modify entity target targetPath set string storage source", "minecraft:ask_server"), + ("data modify storage target", "minecraft:ask_server"), + ("data modify storage target targetPath append from storage source", "minecraft:ask_server"), + ("data modify storage target targetPath append string storage source", "minecraft:ask_server"), + ("data modify storage target targetPath insert index from storage source", "minecraft:ask_server"), + ("data modify storage target targetPath insert index string storage source", "minecraft:ask_server"), + ("data modify storage target targetPath merge from storage source", "minecraft:ask_server"), + ("data modify storage target targetPath merge string storage source", "minecraft:ask_server"), + ("data modify storage target targetPath prepend from storage source", "minecraft:ask_server"), + ("data modify storage target targetPath prepend string storage source", "minecraft:ask_server"), + ("data modify storage target targetPath set from storage source", "minecraft:ask_server"), + ("data modify storage target targetPath set string storage source", "minecraft:ask_server"), + ("data remove storage target", "minecraft:ask_server"), + ("datapack disable name", "minecraft:ask_server"), + ("datapack enable name", "minecraft:ask_server"), + ("datapack enable name after existing", "minecraft:ask_server"), + ("datapack enable name before existing", "minecraft:ask_server"), + ("debug function name", "minecraft:ask_server"), + ("deop targets", "minecraft:ask_server"), + ("execute if data storage source", "minecraft:ask_server"), + ("execute if function name", "minecraft:ask_server"), + ("execute if score target", "minecraft:ask_server"), + ("execute if score target targetObjective < source", "minecraft:ask_server"), + ("execute if score target targetObjective <= source", "minecraft:ask_server"), + ("execute if score target targetObjective = source", "minecraft:ask_server"), + ("execute if score target targetObjective > source", "minecraft:ask_server"), + ("execute if score target targetObjective >= source", "minecraft:ask_server"), + ("execute if stopwatch id", "minecraft:ask_server"), + ("execute store result bossbar id", "minecraft:ask_server"), + ("execute store result score targets", "minecraft:ask_server"), + ("execute store result storage target", "minecraft:ask_server"), + ("execute store success bossbar id", "minecraft:ask_server"), + ("execute store success score targets", "minecraft:ask_server"), + ("execute store success storage target", "minecraft:ask_server"), + ("execute summon entity", "minecraft:summonable_entities"), + ("execute unless data storage source", "minecraft:ask_server"), + ("execute unless function name", "minecraft:ask_server"), + ("execute unless score target", "minecraft:ask_server"), + ("execute unless score target targetObjective < source", "minecraft:ask_server"), + ("execute unless score target targetObjective <= source", "minecraft:ask_server"), + ("execute unless score target targetObjective = source", "minecraft:ask_server"), + ("execute unless score target targetObjective > source", "minecraft:ask_server"), + ("execute unless score target targetObjective >= source", "minecraft:ask_server"), + ("execute unless stopwatch id", "minecraft:ask_server"), + ("function name", "minecraft:ask_server"), + ("function name with storage source", "minecraft:ask_server"), + ("op targets", "minecraft:ask_server"), + ("pardon targets", "minecraft:ask_server"), + ("pardon-ip target", "minecraft:ask_server"), + ("place template template", "minecraft:ask_server"), + ("playsound sound", "minecraft:available_sounds"), + ("posteffect add targets posteffect", "minecraft:post_effects"), + ("posteffect remove targets posteffect", "minecraft:post_effects"), + ("random reset sequence", "minecraft:ask_server"), + ("random roll range sequence", "minecraft:ask_server"), + ("random value range sequence", "minecraft:ask_server"), + ("schedule clear function", "minecraft:ask_server"), + ("schedule function function", "minecraft:ask_server"), + ("scoreboard players add targets", "minecraft:ask_server"), + ("scoreboard players display name targets", "minecraft:ask_server"), + ("scoreboard players display numberformat targets", "minecraft:ask_server"), + ("scoreboard players enable targets", "minecraft:ask_server"), + ("scoreboard players enable targets objective", "minecraft:ask_server"), + ("scoreboard players get target", "minecraft:ask_server"), + ("scoreboard players list target", "minecraft:ask_server"), + ("scoreboard players operation targets", "minecraft:ask_server"), + ("scoreboard players operation targets targetObjective operation source", "minecraft:ask_server"), + ("scoreboard players remove targets", "minecraft:ask_server"), + ("scoreboard players reset targets", "minecraft:ask_server"), + ("scoreboard players set targets", "minecraft:ask_server"), + ("stopsound targets * sound", "minecraft:available_sounds"), + ("stopsound targets ambient sound", "minecraft:available_sounds"), + ("stopsound targets block sound", "minecraft:available_sounds"), + ("stopsound targets hostile sound", "minecraft:available_sounds"), + ("stopsound targets master sound", "minecraft:available_sounds"), + ("stopsound targets music sound", "minecraft:available_sounds"), + ("stopsound targets neutral sound", "minecraft:available_sounds"), + ("stopsound targets player sound", "minecraft:available_sounds"), + ("stopsound targets record sound", "minecraft:available_sounds"), + ("stopsound targets ui sound", "minecraft:available_sounds"), + ("stopsound targets voice sound", "minecraft:available_sounds"), + ("stopsound targets weather sound", "minecraft:available_sounds"), + ("stopwatch query id", "minecraft:ask_server"), + ("stopwatch remove id", "minecraft:ask_server"), + ("stopwatch restart id", "minecraft:ask_server"), + ("summon entity", "minecraft:summonable_entities"), + ("tag targets remove name", "minecraft:ask_server"), + ("team join team members", "minecraft:ask_server"), + ("team leave members", "minecraft:ask_server"), + ("test locate tests", "minecraft:ask_server"), + ("test run tests", "minecraft:ask_server"), + ("test runmultiple tests", "minecraft:ask_server"), + ("test verify tests", "minecraft:ask_server"), + ("tick rate rate", "minecraft:ask_server"), + ("tick sprint time", "minecraft:ask_server"), + ("tick step time", "minecraft:ask_server"), + ("time of clock query timeline", "minecraft:ask_server"), + ("time of clock set timemarker", "minecraft:ask_server"), + ("time query timeline", "minecraft:ask_server"), + ("time set timemarker", "minecraft:ask_server"), + ("trigger objective", "minecraft:ask_server"), + ("whitelist add targets", "minecraft:ask_server"), + ("whitelist remove targets", "minecraft:ask_server"), +]; diff --git a/crates/horizon-client/src/lan/commands.rs b/crates/horizon-client/src/lan/commands.rs new file mode 100644 index 000000000..dd3d36fe9 --- /dev/null +++ b/crates/horizon-client/src/lan/commands.rs @@ -0,0 +1,337 @@ +//! The command tree players receive (Commands.sendCommands and +//! ClientboundCommandsPacket): vanilla's tree from the data generator's +//! commands report, cut down to the nodes the player's permission level may +//! use and the commands of the server kind (dedicated servers have `op`, +//! `ban`, `stop` ...; an integrated server `publish`), numbered breadth first +//! as vanilla does, with the argument parsers' network properties and the +//! custom suggestion providers (`command_suggestions`). +use super::command_suggestions::SUGGESTIONS; +use horizon_protocol::{ + buf::Writer, + packets::play::{CommandNode, Commands}, + registry::Builtin, +}; +use serde_json::Value; +use std::{ + collections::{HashMap, VecDeque}, + path::Path, +}; + +/// Commands.CommandSelection: registered only on dedicated servers. +const DEDICATED_ONLY: &[&str] = &[ + "ban", + "ban-ip", + "banlist", + "deop", + "op", + "pardon", + "pardon-ip", + "perf", + "save-all", + "save-off", + "save-on", + "setidletimeout", + "stop", + "transfer", + "whitelist", +]; +/// Registered only on integrated servers. +const INTEGRATED_ONLY: &[&str] = &["publish", "unpublish"]; +/// Commands that check permissions only on dedicated servers +/// (`checkPermissions` in SeedCommand and VersionCommand). +const OPEN_WHEN_INTEGRATED: &[&str] = &["seed", "version"]; +/// Game rules of experimental features (minecart improvements), which the +/// report lists but a vanilla-features world does not register. +const EXPERIMENTAL_RULES: &[&str] = &["max_minecart_speed", "minecraft:max_minecart_speed"]; + +pub struct CommandTree { + root: Value, +} + +/// A node of the filtered tree. +struct Node { + name: String, + kind: u8, + executable: bool, + restricted: bool, + children: Vec, + redirect: Option>, + parser: Option<(String, Value)>, + suggestions: Option<&'static str>, +} + +/// PermissionLevel names in the report's requirements. +fn required_level(node: &Value) -> u8 { + match node["permissions"]["permission"]["level"].as_str() { + Some("moderators") => 1, + Some("gamemasters") => 2, + Some("admins") => 3, + Some("owners") => 4, + _ => 0, + } +} + +impl CommandTree { + /// commands.json next to registries.json (the data generator's reports). + pub fn load(resources: &Path) -> Option { + let dir = Builtin::find(resources)?.parent()?.to_path_buf(); + let text = std::fs::read_to_string(dir.join("commands.json")).ok()?; + Some(Self { + root: serde_json::from_str(&text).ok()?, + }) + } + + /// The ClientboundCommandsPacket for a player with `level` permissions. + pub fn packet(&self, level: u8, dedicated: bool, builtin: &Builtin) -> Commands { + let mut nodes = vec![Node { + name: String::new(), + kind: 0, + executable: false, + restricted: false, + children: Vec::new(), + redirect: None, + parser: None, + suggestions: None, + }]; + let suggestions: HashMap<&str, &'static str> = SUGGESTIONS.iter().copied().collect(); + let mut paths: HashMap, usize> = HashMap::new(); + paths.insert(Vec::new(), 0); + fill( + &self.root, + 0, + &mut Vec::new(), + level, + dedicated, + &suggestions, + &mut nodes, + &mut paths, + ); + // enumerateNodes: breadth first from the root, each node's children + // (in name order) then its redirect target. + let mut ids = vec![None; nodes.len()]; + let mut order = Vec::new(); + let mut queue = VecDeque::from([0usize]); + while let Some(n) = queue.pop_front() { + if ids[n].is_some() { + continue; + } + ids[n] = Some(order.len() as i32); + order.push(n); + queue.extend(nodes[n].children.iter().copied()); + if let Some(target) = nodes[n].redirect.as_ref().and_then(|p| paths.get(p)) { + queue.push_back(*target); + } + } + let argument_types = builtin.get("minecraft:command_argument_type"); + let out = order + .iter() + .map(|&n| { + let node = &nodes[n]; + CommandNode { + kind: node.kind, + executable: node.executable, + restricted: node.restricted, + children: node.children.iter().filter_map(|c| ids[*c]).collect(), + redirect: node + .redirect + .as_ref() + .and_then(|p| paths.get(p)) + .and_then(|t| ids[*t]), + name: node.name.clone(), + parser: node.parser.as_ref().map(|(parser, props)| { + let id = argument_types.and_then(|t| t.id(parser)).unwrap_or(0); + (id, properties(parser, props)) + }), + suggestions: node.suggestions.map(str::to_owned), + } + }) + .collect(); + Commands { + nodes: out, + root: 0, + } + } +} + +/// Commands.fillUsableCommands over the report: the children the source may use. +#[allow(clippy::too_many_arguments)] +fn fill( + source: &Value, + target: usize, + path: &mut Vec, + level: u8, + dedicated: bool, + suggestions: &HashMap<&str, &'static str>, + nodes: &mut Vec, + paths: &mut HashMap, usize>, +) { + let Some(children) = source["children"].as_object() else { + return; + }; + let mut names: Vec<&String> = children.keys().collect(); + names.sort(); + for name in names { + let child = &children[name]; + let required = if path.is_empty() && !dedicated && OPEN_WHEN_INTEGRATED.contains(&name.as_str()) { + 0 + } else { + required_level(child) + }; + if required > level + || path.len() == 1 && path[0] == "gamerule" && EXPERIMENTAL_RULES.contains(&name.as_str()) + { + continue; + } + if path.is_empty() + && (dedicated && INTEGRATED_ONLY.contains(&name.as_str()) + || !dedicated && DEDICATED_ONLY.contains(&name.as_str())) + { + continue; + } + path.push(name.clone()); + let argument = child["type"] == "argument"; + let index = nodes.len(); + nodes.push(Node { + name: name.clone(), + kind: if argument { 2 } else { 1 }, + executable: child["executable"].as_bool().unwrap_or(false), + restricted: required > 0, + children: Vec::new(), + redirect: redirect(child), + parser: argument.then(|| { + ( + child["parser"].as_str().unwrap_or_default().to_owned(), + child["properties"].clone(), + ) + }), + suggestions: if argument { + suggestions.get(path.join(" ").as_str()).copied() + } else { + None + }, + }); + nodes[target].children.push(index); + paths.insert(path.clone(), index); + fill(child, index, path, level, dedicated, suggestions, nodes, paths); + path.pop(); + } +} + +/// The redirect target's path. The report leaves out redirects to the root +/// (`execute ... run`, `return run`): a node that neither runs nor leads +/// anywhere forks to the root. +fn redirect(node: &Value) -> Option> { + if let Some(path) = node["redirect"].as_array() { + return Some( + path.iter() + .filter_map(|s| s.as_str().map(str::to_owned)) + .collect(), + ); + } + let dead_end = node["children"].as_object().is_none_or(|c| c.is_empty()) + && !node["executable"].as_bool().unwrap_or(false); + dead_end.then(Vec::new) +} + +/// ArgumentTypeInfo.serializeToNetwork for the report's properties. +fn properties(parser: &str, p: &Value) -> Vec { + let mut w = Writer::new(); + let flags = |w: &mut Writer| { + w.u8(u8::from(p.get("min").is_some()) | u8::from(p.get("max").is_some()) << 1); + }; + match parser { + "brigadier:integer" => { + flags(&mut w); + for key in ["min", "max"] { + if let Some(v) = p[key].as_i64() { + w.i32(v as i32); + } + } + } + "brigadier:long" => { + flags(&mut w); + for key in ["min", "max"] { + if let Some(v) = p[key].as_i64() { + w.i64(v); + } + } + } + "brigadier:float" => { + flags(&mut w); + for key in ["min", "max"] { + if let Some(v) = p[key].as_f64() { + w.f32(v as f32); + } + } + } + "brigadier:double" => { + flags(&mut w); + for key in ["min", "max"] { + if let Some(v) = p[key].as_f64() { + w.f64(v); + } + } + } + "brigadier:string" => w.varint(match p["type"].as_str() { + Some("phrase") => 1, + Some("greedy") => 2, + _ => 0, + }), + "minecraft:entity" => { + let single = u8::from(p["amount"] == "single"); + let players = u8::from(p["type"] == "players"); + w.u8(single | players << 1); + } + "minecraft:score_holder" => w.u8(u8::from(p["amount"] == "multiple")), + "minecraft:time" => w.i32(p["min"].as_i64().unwrap_or(0) as i32), + "minecraft:resource" + | "minecraft:resource_key" + | "minecraft:resource_or_tag" + | "minecraft:resource_or_tag_key" + | "minecraft:resource_selector" => w.string(p["registry"].as_str().unwrap_or_default()), + _ => {} + } + w.data +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn integer_bounds_and_entity_flags() { + let p: Value = serde_json::from_str(r#"{"min": 1, "max": 1000}"#).unwrap(); + assert_eq!( + properties("brigadier:integer", &p), + vec![3, 0, 0, 0, 1, 0, 0, 3, 0xE8] + ); + let p: Value = serde_json::from_str(r#"{"amount": "single", "type": "players"}"#).unwrap(); + assert_eq!(properties("minecraft:entity", &p), vec![3]); + let p: Value = serde_json::from_str(r#"{"type": "greedy"}"#).unwrap(); + assert_eq!(properties("brigadier:string", &p), vec![2]); + } + + #[test] + fn levels_filter_and_redirects_resolve() { + let report: Value = serde_json::from_str( + r#"{"type":"root","children":{ + "say":{"type":"literal","children":{"message":{"type":"argument","parser":"minecraft:message","executable":true}}, + "permissions":{"type":"minecraft:require","permission":{"type":"minecraft:command_level","level":"gamemasters"}}}, + "me":{"type":"literal","children":{"action":{"type":"argument","parser":"minecraft:message","executable":true}}}, + "stop":{"type":"literal","executable":true}, + "tell":{"type":"literal","redirect":["me"]}}}"#, + ) + .unwrap(); + let tree = CommandTree { root: report }; + let builtin = Builtin::default(); + let guest = tree.packet(0, false, &builtin); + let names: Vec<_> = guest.nodes.iter().map(|n| n.name.as_str()).collect(); + assert_eq!(names, ["", "me", "tell", "action"]); + // `tell` redirects to `me` (node 1). + assert_eq!(guest.nodes[2].redirect, Some(1)); + let op = tree.packet(2, true, &builtin); + let names: Vec<_> = op.nodes.iter().map(|n| n.name.as_str()).collect(); + assert_eq!(names, ["", "me", "say", "stop", "tell", "action", "message"]); + assert!(op.nodes[2].restricted); + } +} diff --git a/crates/horizon-client/src/lan/data.rs b/crates/horizon-client/src/lan/data.rs index 8101d107c..b6c42cb0c 100644 --- a/crates/horizon-client/src/lan/data.rs +++ b/crates/horizon-client/src/lan/data.rs @@ -64,6 +64,8 @@ pub struct SyncData { registries: Vec<(String, Entries)>, pub tags: UpdateTags, pub features: Vec, + /// Vanilla's command tree (the commands report), when found. + pub commands: Option, } /// Every `*.json` under `dir`, as (path without extension relative to dir, value), sorted. @@ -133,6 +135,7 @@ impl SyncData { registries, tags, features: vec!["minecraft:vanilla".to_owned()], + commands: super::commands::CommandTree::load(resources), }) } diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 88e2806d1..c32e19d07 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -36,6 +36,8 @@ pub struct Guest { pub head_yaw: f32, pub on_ground: bool, pub game_mode: i32, + /// The permission level (0 none, 2 game masters, 4 owners). + pub permission: u8, pub sneaking: bool, pub sprinting: bool, pub fall_flying: bool, @@ -110,6 +112,7 @@ impl Guest { head_yaw: 0.0, on_ground: false, game_mode: SURVIVAL, + permission: 0, sneaking: false, sprinting: false, fall_flying: false, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index e7639cc41..dd8126698 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -17,6 +17,7 @@ use horizon_protocol::{ packets::play::{self, Clientbound as C, Serverbound as S}, text::{literal, translatable}, }; +use horizon_protocol::ids::play::clientbound as ids; use horizon_world::nbt::{JavaString, Tag}; use std::sync::{Arc, atomic::Ordering}; @@ -41,6 +42,8 @@ pub struct HubConfig { pub dimension: String, pub seed: i64, pub max_players: usize, + /// A dedicated server: operators from `ops`, the dedicated-only commands. + pub dedicated: bool, } /// The host player as the other players see them. @@ -64,7 +67,8 @@ pub struct HostState { /// Everything the hub needs from the game for one tick. pub struct TickCtx<'a> { pub world: &'a mut World, - pub host: &'a HostState, + /// The player playing on the host (none on a dedicated server). + pub host: Option<&'a HostState>, pub entities: &'a [EntityState], pub next_entity: &'a mut u32, /// Where new players appear. @@ -73,6 +77,9 @@ pub struct TickCtx<'a> { pub difficulty_locked: bool, /// The overworld clock's speed (0 when the day does not advance). pub clock_rate: f32, + /// TickRateManager: the tick rate and whether the game is frozen. + pub tick_rate: f32, + pub tick_frozen: bool, } /// What the gameplay code has to do for a guest. @@ -94,7 +101,13 @@ pub struct Hub { pub(super) sync: Arc, pub ticks: u64, last_clock: i64, + last_rate: f32, + ticking: (f32, bool), weather: (bool, f32, f32), + /// ClientboundUpdateRecipesPacket, when the game provides it. + pub recipes: Option>, + /// Operators and their permission levels (dedicated servers). + pub ops: std::collections::HashMap, chat_type: i32, dimension_type: i32, clock_ids: Vec, @@ -130,6 +143,10 @@ impl Hub { sync, ticks: 0, last_clock: i64::MIN, + last_rate: 0.0, + ticking: (20.0, false), + recipes: None, + ops: Default::default(), weather: (false, 0.0, 0.0), chat_type, dimension_type, @@ -228,13 +245,13 @@ impl Hub { game_mode: Some(mode), listed: Some(true), latency: Some(latency), - display_name: None, + display_name: Some(None), list_order: Some(0), show_hat: Some(true), } } - /// ClientboundPlayerInfoUpdatePacket.createPlayerInitializing actions. - const INFO_ACTIONS: u8 = 1 | 4 | 8 | 16 | 64 | 128; + /// ClientboundPlayerInfoUpdatePacket.createPlayerInitializing: every action. + const INFO_ACTIONS: u8 = 0xFF; // ---- joining ------------------------------------------------------- @@ -259,6 +276,7 @@ impl Hub { let conn = j.conn; let mut guest = Guest::new(j, entity_id, ctx.spawn, self.config.view_distance); guest.game_mode = self.config.default_game_mode; + guest.permission = self.default_permission(guest.uuid); guest.joined_tick = self.ticks; guest.position = ctx.spawn; guest.previous_position = ctx.spawn; @@ -266,33 +284,41 @@ impl Hub { conn } + /// The permission level a player gets: an integrated server gives every + /// guest the game masters' level when commands are allowed + /// (IntegratedServer.setGuestCommandAccess); a dedicated server its + /// operators' level (`ops`). + fn default_permission(&self, uuid: u128) -> u8 { + if self.config.dedicated { + self.ops.get(&uuid).copied().unwrap_or(0) + } else if self.config.guest_commands { + 2 + } else { + 0 + } + } + + /// The levels of a server, in MinecraftServer.levelKeys order. + fn level_keys() -> Vec { + ["overworld", "the_end", "the_nether"] + .map(|l| format!("minecraft:{l}")) + .to_vec() + } + /// PlayerList.placeNewPlayer for a guest whose saved state is loaded. pub fn place_new_player(&mut self, conn: u32, ctx: &mut TickCtx) { let Some(i) = self.guests.iter().position(|g| g.conn == conn) else { return; }; - let (name, uuid, entity_id, mode, view) = { + let (name, uuid, entity_id, mode) = { let g = &self.guests[i]; - ( - g.name.clone(), - g.uuid, - g.entity_id, - g.game_mode, - g.view_distance, - ) + (g.name.clone(), g.uuid, g.entity_id, g.game_mode) }; - let _ = view; - let levels = vec![ - "minecraft:overworld".to_owned(), - "minecraft:the_nether".to_owned(), - "minecraft:the_end".to_owned(), - ]; - self.guests[i].placed = true; let g = &self.guests[i]; g.send(&C::Login(play::Login { player_id: entity_id, hardcore: self.config.hardcore, - levels, + levels: Self::level_keys(), max_players: self.config.max_players as i32, chunk_radius: self.config.view_distance, simulation_distance: self.config.simulation_distance, @@ -315,13 +341,38 @@ impl Hub { g.send(&C::SetHeldSlot(play::SetHeldSlot { slot: g.selected as i32, })); - self.send_commands(i); - self.system_message(yellow_translation("multiplayer.player.joined", &[&name])); + if let Some(recipes) = &self.recipes { + g.sender.send(recipes.clone()); + } + // PlayerList.sendPlayerPermissionLevel, then the recipe book. + self.send_permission_level(i); + let g = &self.guests[i]; + g.send(&raw( + ids::RECIPE_BOOK_SETTINGS, + vec![0; 8], // four books, each closed and unfiltered + )); + g.send(&raw(ids::RECIPE_BOOK_ADD, vec![0, 1])); // no entries, replace + // The others hear of the newcomer before it joins the list. + self.broadcast_except( + conn, + &C::SystemChat(play::SystemChat { + content: yellow_translation("multiplayer.player.joined", &[&name]), + overlay: false, + }), + ); + self.guests[i].placed = true; self.teleport(i, None); + let g = &self.guests[i]; + g.send(&C::ServerData(play::ServerData { + motd: literal(&self.lan.shared.motd()), + icon: None, + })); // The player list: everyone already here, then the newcomer to all. - let mut entries = - vec![self.player_info(ctx.host.uuid, &ctx.host.name, ctx.host.game_mode, 0)]; - for o in self.guests.iter().filter(|o| o.conn != conn) { + let mut entries = Vec::new(); + if let Some(host) = ctx.host { + entries.push(self.player_info(host.uuid, &host.name, host.game_mode, 0)); + } + for o in self.guests.iter().filter(|o| o.conn != conn && o.placed) { entries.push(self.player_info( o.uuid, &o.name, @@ -329,26 +380,40 @@ impl Hub { o.latency.load(Ordering::Relaxed), )); } - entries.push(self.player_info(uuid, &name, mode, 0)); - let own = play::PlayerInfoUpdate { + self.guests[i].send(&C::PlayerInfoUpdate(play::PlayerInfoUpdate { actions: Self::INFO_ACTIONS, entries, - }; - self.guests[i].send(&C::PlayerInfoUpdate(own)); + })); let newcomer = play::PlayerInfoUpdate { actions: Self::INFO_ACTIONS, entries: vec![self.player_info(uuid, &name, mode, 0)], }; - self.broadcast_except(conn, &C::PlayerInfoUpdate(newcomer)); + self.broadcast(&C::PlayerInfoUpdate(newcomer)); self.send_level_info(i, ctx); + // ServerPlayer.sendPostEffects and initInventoryMenu. + self.guests[i].send(&raw(ids::POST_EFFECTS, vec![0])); self.send_inventory(i); } - /// Send everyone the command tree again (the permissions changed). - pub fn resend_commands(&self) { + /// PlayerList.sendPlayerPermissionLevel: the op level as an entity event + /// (24 + level), then the commands that level may use. + fn send_permission_level(&self, i: usize) { + let g = &self.guests[i]; + g.send(&C::EntityEvent(play::EntityEvent { + id: g.entity_id, + event: 24 + g.permission.min(4) as i8, + })); + self.send_commands(i); + } + + /// The permissions changed: tell everyone their level and commands again. + pub fn resend_commands(&mut self) { for i in 0..self.guests.len() { + if !self.config.dedicated { + self.guests[i].permission = self.default_permission(self.guests[i].uuid); + } if self.guests[i].placed { - self.send_commands(i); + self.send_permission_level(i); } } } @@ -356,53 +421,26 @@ impl Hub { /// Commands.sendCommands: the command tree for this player. fn send_commands(&self, i: usize) { let g = &self.guests[i]; - // A root with every command taking free-form arguments. - let mut nodes = vec![play::CommandNode { - kind: 0, - executable: false, - restricted: false, - children: Vec::new(), - redirect: None, - name: String::new(), - parser: None, - suggestions: None, - }]; - if self.config.guest_commands { - let argument = |name: &str| play::CommandNode { - kind: 2, - executable: true, - restricted: false, - children: Vec::new(), - redirect: None, - name: name.to_owned(), - // brigadier:string with the greedy phrase type. - parser: self - .sync - .builtin - .get("minecraft:command_argument_type") - .and_then(|ids| ids.id("brigadier:string")) - .map(|id| (id, vec![2])), - suggestions: None, - }; - for name in COMMANDS { - nodes.push(play::CommandNode { - kind: 1, - executable: true, + let packet = match &self.sync.commands { + Some(tree) => tree.packet(g.permission, self.config.dedicated, &self.sync.builtin), + None => play::Commands { + nodes: vec![play::CommandNode { + kind: 0, + executable: false, restricted: false, - children: vec![nodes.len() as i32 + 1], + children: Vec::new(), redirect: None, - name: (*name).to_owned(), + name: String::new(), parser: None, suggestions: None, - }); - nodes.push(argument("args")); - let literal_index = nodes.len() as i32 - 2; - nodes[0].children.push(literal_index); - } - } - g.send(&C::Commands(play::Commands { nodes, root: 0 })); + }], + root: 0, + }, + }; + g.send(&C::Commands(packet)); } + /// ServerGamePacketListenerImpl.teleport: move the client and wait for its confirmation. pub fn teleport(&mut self, i: usize, position: Option<[f64; 3]>) { let g = &mut self.guests[i]; @@ -435,7 +473,8 @@ impl Hub { lerp_time: 0, absolute_max_size: 29_999_984, warning_blocks: 5, - warning_time: 15, + // WorldBorder.DEFAULT_WARNING_TIME, in ticks. + warning_time: 300, })); g.send(&self.time_packet(ctx.world, ctx.clock_rate)); g.send(&C::SetDefaultSpawnPosition(play::SetDefaultSpawnPosition { @@ -469,8 +508,14 @@ impl Hub { event: game_event::LEVEL_CHUNKS_LOAD_START, param: 0.0, })); + // TickRateManager.updateJoiningPlayer. + g.send(&ticking_state(ctx.tick_rate, ctx.tick_frozen)); + g.send(&raw(ids::TICKING_STEP, vec![0])); } + /// ServerClockManager.createFullSyncPacket: every clock. Horizon keeps the + /// overworld clock (the day time); the End's clock runs with the game + /// time. Clocks do not advance without the advance_time rule. fn time_packet(&self, world: &World, rate: f32) -> C { let overworld = self .sync @@ -481,11 +526,22 @@ impl Hub { clocks: self .clock_ids .iter() - .map(|&id| play::ClockState { - clock: id, - total_ticks: if id == overworld { world.day_time } else { 0 }, - partial_tick: 0.0, - rate: if id == overworld { rate } else { 0.0 }, + .map(|&id| { + if id == overworld { + play::ClockState { + clock: id, + total_ticks: world.day_time, + partial_tick: 0.0, + rate, + } + } else { + play::ClockState { + clock: id, + total_ticks: world.game_time, + partial_tick: 0.0, + rate: if rate > 0.0 { 1.0 } else { 0.0 }, + } + } }) .collect(), }) @@ -604,9 +660,40 @@ impl Hub { /// Time and weather (ServerLevel.tickTime / advanceWeatherCycle broadcasts). fn sync_world(&mut self, ctx: &TickCtx) { let world = &*ctx.world; - if self.ticks.is_multiple_of(20) || self.last_clock == i64::MIN { - self.broadcast(&self.time_packet(world, ctx.clock_rate)); - self.last_clock = world.day_time; + // MinecraftServer.tickServer: the game time every 20 ticks + // (forceGameTimeSynchronization, no clocks). + if self.ticks.is_multiple_of(20) { + self.broadcast(&C::SetTime(play::SetTime { + game_time: world.game_time, + clocks: Vec::new(), + })); + } + // ServerClockManager.modifyClock: a day that jumped (`time set`, `time + // add`) or a new rate updates the overworld clock. + let (day, rate) = (world.day_time, ctx.clock_rate); + let step = i64::from(rate.ceil() as i32).max(1); + if self.last_clock != i64::MIN + && ((day - self.last_clock).abs() > step || rate != self.last_rate) + { + let overworld = self + .sync + .id("minecraft:world_clock", "minecraft:overworld") + .unwrap_or(0); + self.broadcast(&C::SetTime(play::SetTime { + game_time: world.game_time, + clocks: vec![play::ClockState { + clock: overworld, + total_ticks: day, + partial_tick: 0.0, + rate, + }], + })); + } + self.last_clock = day; + self.last_rate = rate; + if (ctx.tick_rate, ctx.tick_frozen) != self.ticking { + self.ticking = (ctx.tick_rate, ctx.tick_frozen); + self.broadcast(&ticking_state(ctx.tick_rate, ctx.tick_frozen)); } let w = &world.weather; let (raining, rain, thunder) = self.weather; @@ -900,22 +987,23 @@ impl Hub { fn track_entities(&mut self, ctx: &mut TickCtx) { let mut all: Vec = Vec::with_capacity(ctx.entities.len() + self.guests.len() + 1); - let h = ctx.host; - let equipment = { - let e = &h.equipment; - self.equipment_of(&e[0], &e[1], [&e[5], &e[4], &e[3], &e[2]]) - }; - all.push(self.player_state( - h.entity_id, - h.uuid, - h.position, - (h.yaw, h.pitch, h.head_yaw), - h.on_ground, - (h.sneaking, h.sprinting, false, false), - 0x7F, - h.health, - equipment, - )); + if let Some(h) = ctx.host { + let equipment = { + let e = &h.equipment; + self.equipment_of(&e[0], &e[1], [&e[5], &e[4], &e[3], &e[2]]) + }; + all.push(self.player_state( + h.entity_id, + h.uuid, + h.position, + (h.yaw, h.pitch, h.head_yaw), + h.on_ground, + (h.sneaking, h.sprinting, false, false), + 0x7F, + h.health, + equipment, + )); + } let placed: Vec = (0..self.guests.len()) .filter(|&i| self.guests[i].placed) .collect(); @@ -1119,11 +1207,6 @@ impl Hub { events.push(HostEvent::Chat(format!("<{name}> {text}"))); } } - S::Unknown(id, ref payload) => { - // Packets Horizon does not model: ignore the ones that only - // matter to vanilla's chat signing. - let _ = (id, payload); - } other => events.push(HostEvent::Packet(conn, Box::new(other))), } } @@ -1217,43 +1300,6 @@ impl Hub { } } -/// The commands guests may type when the host allows them. -const COMMANDS: &[&str] = &[ - "advancement", - "attribute", - "clear", - "clone", - "damage", - "data", - "difficulty", - "effect", - "enchant", - "experience", - "fill", - "gamemode", - "gamerule", - "give", - "kill", - "me", - "msg", - "particle", - "playsound", - "say", - "scoreboard", - "seed", - "setblock", - "spawnpoint", - "summon", - "tag", - "teleport", - "tell", - "time", - "title", - "tp", - "weather", - "xp", -]; - impl Hub { pub fn item_name(&self, id: i32) -> Option> { self.sync @@ -1289,3 +1335,16 @@ impl Hub { self.send_inventory(i); } } + +/// A packet Horizon sends as raw bytes (no fields worth a type). +fn raw(id: i32, payload: Vec) -> C { + C::Unknown(id, payload) +} + +/// ClientboundTickingStatePacket: the tick rate and whether the game is frozen. +fn ticking_state(rate: f32, frozen: bool) -> C { + let mut w = horizon_protocol::buf::Writer::new(); + w.f32(rate); + w.bool(frozen); + raw(ids::TICKING_STATE, w.data) +} diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index e66406345..cd0214c5e 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -5,16 +5,18 @@ //! ever exchanges decoded packets with these threads through channels, so a //! world that is not open to the network pays nothing. pub mod chunks; +pub mod command_suggestions; +pub mod commands; pub mod conn; pub mod containers; pub mod data; pub mod discovery; pub mod entity; -pub mod tracking; pub mod guest; pub mod hub; pub mod menu; pub mod playerdata; +pub mod tracking; pub use conn::PlayerSender; use horizon_protocol::packets::play; @@ -88,6 +90,9 @@ impl Shared { online.insert(uuid); None } + pub fn motd(&self) -> String { + self.motd.lock().unwrap().clone() + } pub fn release(&self, uuid: u128) { self.online.lock().unwrap().remove(&uuid); } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/OfflineLanHost.java b/mods/horizon/src/test/java/dev/horizonlab/parity/OfflineLanHost.java new file mode 100644 index 000000000..a643805b7 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/OfflineLanHost.java @@ -0,0 +1,42 @@ +package dev.horizonlab.parity; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.server.IntegratedServer; +import net.minecraft.server.MinecraftServer; + +/** + * The vanilla client as the reference LAN host for the multiplayer harness + * (tools/test_lan_vanilla_client.py): it runs net.minecraft.client.main.Main + * unchanged, and once the singleplayer world is up it turns off the + * integrated server's authentication (it always authenticates guests against + * Mojang's session servers, which offline test clients cannot pass) and opens + * the world to LAN on the port in -Dhorizon.lanPort, with commands allowed, + * as the "Open to LAN" screen does. + */ +public final class OfflineLanHost { + public static void main(String[] args) throws Exception { + int port = Integer.getInteger("horizon.lanPort", 0); + Thread watcher = new Thread(() -> { + boolean published = false; + while (!published) { + try { + Thread.sleep(500); + Minecraft mc = Minecraft.getInstance(); + IntegratedServer server = mc == null ? null : mc.getSingleplayerServer(); + if (server == null || mc.player == null || !server.isReady()) continue; + server.setUsesAuthentication(false); + mc.execute(() -> { + boolean ok = server.publishServer(MinecraftServer.MultiplayerScope.LAN, true, port); + System.out.println("[OfflineLanHost] published=" + ok + " port=" + server.getPort()); + }); + published = true; + } catch (Throwable t) { + // The game is still starting. + } + } + }, "horizon-offline-lan"); + watcher.setDaemon(true); + watcher.start(); + net.minecraft.client.main.Main.main(args); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandSuggestionsExporter.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandSuggestionsExporter.java new file mode 100644 index 000000000..34f085642 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandSuggestionsExporter.java @@ -0,0 +1,39 @@ +package dev.horizonlab.parity; + +import com.mojang.brigadier.tree.ArgumentCommandNode; +import com.mojang.brigadier.tree.CommandNode; +import java.io.PrintWriter; +import java.nio.file.Files; +import java.nio.file.Path; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import net.minecraft.commands.synchronization.SuggestionProviders; + +/** + * Lists the argument nodes of vanilla's full command tree (Commands with + * CommandSelection.ALL, the tree the commands report shows) that carry a + * custom suggestion provider, with the provider's network name + * (SuggestionProviders.getName: ask_server unless it is one of the named + * client-side providers). ClientboundCommandsPacket sends that name; the + * report does not include it. One line per node: the path of node names + * from the root, space separated, a tab, the provider id. + */ +public final class VanillaCommandSuggestionsExporter { + public static void main(String[] args) throws Exception { + ParityData.init(); + Commands commands = new Commands(Commands.CommandSelection.ALL, Commands.createValidationContext(ParityData.lookup)); + try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(Path.of(args[0])))) { + walk(commands.getDispatcher().getRoot(), "", out); + } + } + + static void walk(CommandNode node, String path, PrintWriter out) { + for (CommandNode child : node.getChildren()) { + String childPath = path.isEmpty() ? child.getName() : path + " " + child.getName(); + if (child instanceof ArgumentCommandNode arg && arg.getCustomSuggestions() != null) { + out.println(childPath + "\t" + SuggestionProviders.getName(arg.getCustomSuggestions())); + } + walk(child, childPath, out); + } + } +} diff --git a/tools/generate_command_suggestions.py b/tools/generate_command_suggestions.py new file mode 100644 index 000000000..4e85ca37b --- /dev/null +++ b/tools/generate_command_suggestions.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +"""Generate crates/horizon-client/src/lan/command_suggestions.rs: the argument +nodes of vanilla's command tree that have a custom suggestion provider, and +the provider's network name (ClientboundCommandsPacket sends it; the commands +report does not). The list comes from VanillaCommandSuggestionsExporter run +against the pinned client jar: + + javac --release 25 -proc:none -sourcepath mods/horizon/src/test/java -cp CLIENT_CP \\ + -d BUILD mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandSuggestionsExporter.java + java -cp BUILD:CLIENT_CP dev.horizonlab.parity.VanillaCommandSuggestionsExporter suggestions.tsv + generate_command_suggestions.py suggestions.tsv +""" +import argparse +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("tsv", type=Path) + parser.add_argument("--out", type=Path, default=ROOT / "crates/horizon-client/src/lan/command_suggestions.rs") + args = parser.parse_args() + rows = sorted(tuple(line.split("\t")) for line in args.tsv.read_text().splitlines() if line.strip()) + if len(rows) < 50: + raise SystemExit(f"only {len(rows)} nodes") + lines = [ + "//! Argument nodes of vanilla's command tree with a custom suggestion", + "//! provider (path of node names from the root, provider network name).", + "//! Generated by tools/generate_command_suggestions.py from", + "//! VanillaCommandSuggestionsExporter; do not edit by hand.", + "", + "pub const SUGGESTIONS: &[(&str, &str)] = &[", + ] + lines += [f' ("{path}", "{provider}"),' for path, provider in rows] + lines += ["];", ""] + args.out.write_text("\n".join(lines)) + print(f"wrote {len(rows)} nodes to {args.out}") + + +if __name__ == "__main__": + main() diff --git a/tools/vanilla_client.py b/tools/vanilla_client.py index 2196f79bc..88c6aba5b 100644 --- a/tools/vanilla_client.py +++ b/tools/vanilla_client.py @@ -118,6 +118,14 @@ def command(args): "--width", str(args.width), "--height", str(args.height)] if args.join: cmd += ["--quickPlayMultiplayer", args.join] + if args.world: + cmd += ["--quickPlaySingleplayer", args.world] + if args.lan_port is not None: + # The vanilla client as reference LAN host (OfflineLanHost). + cp = cmd.index("-cp") + 1 + cmd[cp] = os.pathsep.join([str(args.classes), cmd[cp]]) + main = cmd.index("net.minecraft.client.main.Main") + cmd[main:main + 1] = [f"-Dhorizon.lanPort={args.lan_port}", "dev.horizonlab.parity.OfflineLanHost"] if args.backend: cmd += ["--graphicsBackend", args.backend] return cmd @@ -127,11 +135,16 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--name", default="Guest") parser.add_argument("--join", help="HOST:PORT to join on start") + parser.add_argument("--world", help="open this saves/ folder in singleplayer on start") parser.add_argument("--game-dir", type=Path, default=ROOT / ".local/vanilla-client") parser.add_argument("--assets", type=Path) parser.add_argument("--heap", default="3G") parser.add_argument("--width", type=int, default=1280) parser.add_argument("--height", type=int, default=800) + parser.add_argument("--lan-port", type=int, + help="open the --world to LAN on this port without authentication (needs --classes)") + parser.add_argument("--classes", type=Path, default=ROOT / ".local/mp/oracle", + help="compiled OfflineLanHost (mods/horizon/src/test/java)") parser.add_argument("--backend", help="graphics backend (opengl or vulkan)") parser.add_argument("--option", action="append", default=[], help="KEY:VALUE for options.txt") parser.add_argument("--print", action="store_true", help="print the command and exit") From fd23a8d6820eadcb78310bd5388d8bb83b1fcabe Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:23:16 +0200 Subject: [PATCH 26/28] Match vanilla atan2 tables, rotation constants, despawn checks and target search Mth.atan2 builds its tables with StrictMath.asin (fdlibm, ported) and HotSpot's cos; the controls multiply by the folded RAD_TO_DEG float constant. Mob.checkDespawn runs before the tick and, in 26.3, persistent mobs only reset their idle time near a player. NearestAttackableTargetGoal always requires a line of sight and ignores mustReach when searching. MeleeAttackGoal starts its canUse clock at game time 0. The harness now records every random draw of the vanilla mobs with its caller, the random state per tick, and starts each scenario at game time 1000. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/mob_ai_probe.rs | 7 +- crates/horizon-client/src/mobs/ai.rs | 53 ++++++------ crates/horizon-client/src/mobs/goals.rs | 46 ++-------- crates/horizon-core/src/geometry/trig.rs | 83 +++++++++++++++++-- crates/horizon-core/src/random.rs | 5 ++ .../horizonlab/parity/VanillaMobAiOracle.java | 41 +++++++++ tools/test_mob_ai_parity.py | 30 ++++++- 7 files changed, 190 insertions(+), 75 deletions(-) diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 952723b9e..2406314d6 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -308,7 +308,7 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob) { d(lk.wanted[1]), d(lk.wanted[2]) ); - let _ = writeln!( + let _ = write!( out, "\tin {},{},{},{}", f(m.ai.xxa), @@ -316,6 +316,7 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob) { f(m.ai.speed), u8::from(m.ai.jumping) ); + let _ = writeln!(out, "\trng {:x}", m.random.state()); } fn main() -> horizon_client::Result<()> { @@ -404,6 +405,7 @@ fn main() -> horizon_client::Result<()> { world.chunks.insert(k, Arc::new(c)); } world.day_time = s.time; + world.game_time = 1000; let mut mobs: Vec = Vec::new(); for (i, spec) in s.mobs.iter().enumerate() { let kind = types @@ -457,6 +459,9 @@ fn main() -> horizon_client::Result<()> { } }); let mut scratch = LegacyRandom::new(0); + for (i, m) in mobs.iter().enumerate() { + print(&mut out, 0, i, m); + } for t in 1..=s.ticks { world.game_time += 1; let snapshot: Vec = mobs.iter().filter(|m| !m.removed).map(seen).collect(); diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 027a55125..be23ad75b 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -268,6 +268,11 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { if m.removed { return false; } + // ServerLevel.tick checks despawning before ticking the entity. + if !check_despawn(m, w) { + m.removed = true; + return false; + } m.previous = m.position; m.previous_yaw = m.yaw; m.previous_body_yaw = m.body_yaw; @@ -304,13 +309,6 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { m.update_walk_animation(); m.anim.end_tick(m.ai.swinging); tick_swing(m); - if !m.alive() { - return true; - } - if !check_despawn(m, w) { - m.removed = true; - return false; - } m.position.y > -128.0 } /// LivingEntity.updateSwingTime (6-tick swing duration). @@ -683,42 +681,39 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { _ => {} } } -/// Mob.checkDespawn (players are the only despawn reference). +/// Mob.checkDespawn, before the tick (players are the only despawn +/// reference). Returns false when the mob is discarded. fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool { - let creature = m.kind.category == "creature"; - // Warden.removeWhenFarAway is false; a jockey's chicken despawns like a monster. - if m.persistent - || m.species() == Species::Warden - || creature && m.kind.flags.animal && !m.extra.jockey - { - m.ai.no_action_time = 0; - return true; - } let Some(p) = &w.player else { return true }; let d = m.distance_sqr(p.position); - // Patrols and raiders (`removeWhenFarAway`, `requiresCustomPersistence`). - if super::raider::keeps_alive(m, d) - || super::zombie_villager::keeps_alive(m) - || super::riders::keeps_alive(m) - // requiresCustomPersistence: a tame nautilus, a sulfur cube holding a - // block or let out of a bucket. + // requiresCustomPersistence: raiders in a raid, a tame nautilus, a sulfur + // cube holding a block or let out of a bucket. + let persistent = m.persistent || super::nautilus::is_nautilus(m.species()) && m.extra.tame || m.species() == Species::SulfurCube - && (super::sulfur_cube::has_body(m) || m.extra.scratch[3] != 0) - { - return true; - } + && (super::sulfur_cube::has_body(m) || m.extra.scratch[3] != 0); + // removeWhenFarAway: animals, wardens, patrols and raiders, zombie + // villagers being cured and ridden mobs stay. + let creature = m.kind.category == "creature"; + let removable = !(m.species() == Species::Warden + || creature && m.kind.flags.animal && !m.extra.jockey + || super::raider::keeps_alive(m, d) + || super::zombie_villager::keeps_alive(m) + || super::riders::keeps_alive(m)); + // MobCategory.getDespawnDistance / getNoDespawnDistance let despawn = if m.kind.category == "water_ambient" { 64.0 } else { 128.0 }; - if d > despawn * despawn { + if !persistent && d > despawn * despawn && removable { return false; } - if m.ai.no_action_time > 600 + if !persistent + && m.ai.no_action_time > 600 && m.random.next_int_bound(800).unwrap_or(1) == 0 && d > 32.0 * 32.0 + && removable { return false; } diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index def62484b..059e58462 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -745,7 +745,7 @@ impl MeleeAttack { path_target: [0.0; 3], recalc: 0, until_attack: 0, - last_check: i64::MIN / 2, + last_check: 0, raise_arm: 0, interval: 20, } @@ -928,8 +928,6 @@ pub struct NearestTarget { pub struct TargetState { unseen: i32, pub unseen_memory: i32, - reach_cache: i32, - reach_time: i32, /// `TargetGoal.getFollowDistance` as a fraction of the follow range. pub follow_scale: f64, } @@ -938,8 +936,6 @@ impl Default for TargetState { Self { unseen: 0, unseen_memory: 0, - reach_cache: 0, - reach_time: 0, follow_scale: 1.0, } } @@ -1008,23 +1004,6 @@ pub fn target_continue(st: &mut TargetState, must_see: bool, m: &mut Mob, cx: &m } true } -/// TargetGoal.canAttack's reach check. -fn can_reach(st: &mut TargetState, m: &mut Mob, cx: &mut Cx, at: Vec3) -> bool { - st.reach_time -= 1; - if st.reach_time <= 0 { - st.reach_cache = 0; - } - if st.reach_cache == 0 { - st.reach_time = reduced(10 + m.random.next_int_bound(5).unwrap_or(0)); - let path = m.create_path_to_entity(cx.w, [at.x, at.y, at.z], 0); - let ok = path.and_then(|p| p.end()).is_some_and(|e| { - let (xx, zz) = (e.x - at.x.floor() as i32, e.z - at.z.floor() as i32); - f64::from(xx * xx + zz * zz) <= 2.25 - }); - st.reach_cache = if ok { 1 } else { 2 }; - } - st.reach_cache == 1 -} impl Goal for NearestTarget { goal_clone!(); fn flags(&self) -> u8 { @@ -1041,21 +1020,17 @@ impl Goal for NearestTarget { } let range = m.attrs.follow_range * self.target_goal.follow_scale; self.found = None; + // NearestAttackableTargetGoal.findTarget: TargetingConditions.forCombat() + // always checks the line of sight; mustSee and mustReach only matter + // to TargetGoal.canContinueToUse and canAttack. match &self.prey { Prey::Player => { - if m.can_target_player(cx.w, range, self.must_see) { - let at = - cx.w.player - .as_ref() - .map(|p| p.position) - .unwrap_or(Vec3::ZERO); - if !self.must_reach || can_reach(&mut self.target_goal, m, cx, at) { - self.found = Some(Who::Player); - } + if m.can_target_player(cx.w, range, true) { + self.found = Some(Who::Player); } } prey => { - let pos = m.position; + let pos = Vec3::new(m.position.x, m.eye_y(), m.position.z); let id = m.id; let candidates: Vec<(u32, Vec3)> = cx.w.nearby(pos, range, move |s| { @@ -1072,10 +1047,7 @@ impl Goal for NearestTarget { if m.distance_sqr(cpos) > range * range { continue; } - if self.must_see && !m.sees(cx.w, Who::Mob(cid)) { - continue; - } - if self.must_reach && !can_reach(&mut self.target_goal, m, cx, cpos) { + if !m.sees(cx.w, Who::Mob(cid)) { continue; } self.found = Some(Who::Mob(cid)); @@ -1090,8 +1062,6 @@ impl Goal for NearestTarget { } fn start(&mut self, m: &mut Mob, _: &mut Cx) { m.ai.target = self.found; - self.target_goal.reach_cache = 0; - self.target_goal.reach_time = 0; self.target_goal.unseen = 0; } fn stop(&mut self, m: &mut Mob, _: &mut Cx) { diff --git a/crates/horizon-core/src/geometry/trig.rs b/crates/horizon-core/src/geometry/trig.rs index 8a8aba77e..36c0b069d 100644 --- a/crates/horizon-core/src/geometry/trig.rs +++ b/crates/horizon-core/src/geometry/trig.rs @@ -29,8 +29,15 @@ pub fn atan2(mut y: f64, mut x: f64) -> f64 { let (asin, cos) = TABLES.get_or_init(|| { (0..257) .map(|i| { - let a = (f64::from(i) / 256.0).asin(); - (a, a.cos()) + let a = fdlibm_asin(f64::from(i) / 256.0); + // HotSpot's x86-64 Math.cos intrinsic rounds entry 61 one ulp + // above the correctly rounded value the platform cos gives. + let c = if i == 61 { + f64::from_bits(0x3fef_140a_0a08_6af1) + } else { + a.cos() + }; + (a, c) }) .unzip() }); @@ -73,10 +80,11 @@ pub fn atan2(mut y: f64, mut x: f64) -> f64 { } theta } -/// `(float)(Mth.atan2(y, x) * 180.0F / (float)Math.PI)`: the angle in degrees -/// as the AI controls compute it. +/// `(float)(Mth.atan2(y, x) * 180.0F / (float)Math.PI)` as the AI controls +/// compute it: the compiled code multiplies by the folded float constant +/// `Mth.RAD_TO_DEG` widened to double. pub fn atan2_degrees(y: f64, x: f64) -> f32 { - (atan2(y, x) * 180.0 / f64::from(std::f32::consts::PI)) as f32 + (atan2(y, x) * f64::from(RAD_TO_DEG)) as f32 } /// `Mth.sin` / `Mth.cos` on a float, as the models call them. @@ -93,9 +101,74 @@ impl Mth for f32 { } } +/// fdlibm `__ieee754_asin`, as `StrictMath.asin` (and so `Math.asin`) computes it. +pub fn fdlibm_asin(x: f64) -> f64 { + const PIO2_HI: f64 = 1.570_796_326_794_896_558_00e+00; + const PIO2_LO: f64 = 6.123_233_995_736_766_035_87e-17; + const PIO4_HI: f64 = 7.853_981_633_974_482_789_99e-01; + const PS0: f64 = 1.666_666_666_666_666_574_15e-01; + const PS1: f64 = -3.255_658_186_224_009_154_05e-01; + const PS2: f64 = 2.012_125_321_348_629_258_81e-01; + const PS3: f64 = -4.005_553_450_067_941_140_27e-02; + const PS4: f64 = 7.915_349_942_898_145_321_76e-04; + const PS5: f64 = 3.479_331_075_960_211_675_70e-05; + const QS1: f64 = -2.403_394_911_734_414_218_78e+00; + const QS2: f64 = 2.020_945_760_233_505_694_71e+00; + const QS3: f64 = -6.882_839_716_054_532_930_30e-01; + const QS4: f64 = 7.703_815_055_590_193_527_91e-02; + let bits = x.to_bits(); + let hx = (bits >> 32) as i32; + let ix = hx & 0x7fff_ffff; + if ix >= 0x3ff0_0000 { + if ((ix - 0x3ff0_0000) as u32 | bits as u32) == 0 { + return x * PIO2_HI + x * PIO2_LO; + } + return (x - x) / (x - x); + } else if ix < 0x3fe0_0000 { + if ix < 0x3e40_0000 && 1.0e300 + x > 1.0 { + return x; + } + let t = x * x; + let p = t * (PS0 + t * (PS1 + t * (PS2 + t * (PS3 + t * (PS4 + t * PS5))))); + let q = 1.0 + t * (QS1 + t * (QS2 + t * (QS3 + t * QS4))); + let w = p / q; + return x + x * w; + } + let w = 1.0 - x.abs(); + let t = w * 0.5; + let p = t * (PS0 + t * (PS1 + t * (PS2 + t * (PS3 + t * (PS4 + t * PS5))))); + let q = 1.0 + t * (QS1 + t * (QS2 + t * (QS3 + t * QS4))); + let s = t.sqrt(); + let t = if ix >= 0x3fef_3333 { + let w = p / q; + PIO2_HI - (2.0 * (s + s * w) - PIO2_LO) + } else { + let w = f64::from_bits(s.to_bits() & 0xffff_ffff_0000_0000); + let c = (t - w * w) / (s + w); + let r = p / q; + let p = 2.0 * s * r - (PIO2_LO - 2.0 * c); + let q = PIO4_HI - 2.0 * w; + PIO4_HI - (p - q) + }; + if hx > 0 { t } else { -t } +} + #[cfg(test)] mod tests { use super::*; + /// Values the 26.3 client computes on x86-64 HotSpot. + #[test] + fn atan2_matches_the_client_tables() { + for (y, x, r) in [ + (0x402f_3b4b_8041_4df1_u64, 0xc018_53ca_369b_9e91_u64, 0x3fff_1334_9f9d_e798_u64), + (0xc025_d316_35f2_9de8, 0xc018_fb4a_7ec4_3ba8, 0xc000_b996_6547_a498), + (0xc026_5d9c_2b5a_472d, 0xc030_954d_c2dc_3d10, 0xc004_62e7_82d4_c97e), + ] { + assert_eq!(atan2(f64::from_bits(y), f64::from_bits(x)).to_bits(), r); + } + assert_eq!(fdlibm_asin(60.0 / 256.0).to_bits(), 0x3fce_481c_0fce_7134); + assert_eq!(fdlibm_asin(61.0 / 256.0).to_bits(), 0x3fce_cbd7_5b6c_d8f0); + } #[test] fn long_narrowing_and_quadrants() { assert_eq!(sin(0.0).to_bits(), 0.0f32.to_bits()); diff --git a/crates/horizon-core/src/random.rs b/crates/horizon-core/src/random.rs index 46397b5c4..9b2b570e4 100644 --- a/crates/horizon-core/src/random.rs +++ b/crates/horizon-core/src/random.rs @@ -78,6 +78,11 @@ impl LegacyRandom { } } + /// The 48-bit generator state (differential tests compare it). + pub fn state(&self) -> u64 { + self.state + } + fn bits(&mut self, count: u32) -> i32 { self.state = self.state.wrapping_mul(Self::MULTIPLIER).wrapping_add(11) & Self::MASK; (self.state >> (48 - count)) as i32 diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java index 4fd1af517..ca1b2f299 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -107,6 +107,32 @@ public final class VanillaMobAiOracle { static PrintWriter out; static final List SOUNDS = new ArrayList<>(); + /** Draws of a traced mob random: the caller frames of each draw (AI_TRACE=scenario:from-to). */ + static final class TracingRandom extends net.minecraft.world.level.levelgen.LegacyRandomSource { + static int tick; + static boolean on; + final List log; + final int who; + TracingRandom(long seed, List log, int who) { super(seed); this.log = log; this.who = who; } + @Override + public int next(int bits) { + int v = super.next(bits); + if (on) { + StringBuilder sb = new StringBuilder(tick + " trace " + who + " " + bits + "=" + Integer.toHexString(v) + ":"); + int n = 0; + for (StackTraceElement e : new Throwable().getStackTrace()) { + String c = e.getClassName(); + if (c.contains("RandomSource") || c.contains("TracingRandom") || c.contains("Mth")) continue; + sb.append(' ').append(c.substring(c.lastIndexOf('.') + 1)).append('.').append(e.getMethodName()).append(':').append(e.getLineNumber()); + if (++n == 7) break; + } + log.add(sb.toString()); + } + return v; + } + } + static final List TRACE = new ArrayList<>(); + static final class MobSpec { String type; double x, y, z; @@ -188,6 +214,12 @@ public final class VanillaMobAiOracle { MinecraftServer.spin(thread -> Server.create(thread, access, packs)); } + static String traceSpec() { String v = System.getenv("AI_TRACE"); return v == null ? "" : v; } + // Every mob random is traced unless AI_TRACE=0. + static boolean tracing(Scenario s) { return !traceSpec().equals("0"); } + static int traceFrom() { return 0; } + static int traceTo() { return Integer.MAX_VALUE; } + static String d(double v) { return Long.toHexString(Double.doubleToRawLongBits(v)); } static String f(float v) { return Integer.toHexString(Float.floatToRawIntBits(v)); } @@ -376,6 +408,8 @@ public final class VanillaMobAiOracle { out.println("== " + s.name); var clock = level.registryAccess().lookupOrThrow(Registries.WORLD_CLOCK).getOrThrow(WorldClocks.OVERWORLD); this.clockManager().setTotalTicks(clock, s.time); + // Every scenario starts at game time 1000. + this.getWorldData().overworldData().setGameTime(1000L); // isRaining/isThundering read the rain and thunder levels only. level.setRainLevel(s.rain ? 1.0F : 0.0F); level.setThunderLevel(s.thunder ? 1.0F : 0.0F); @@ -398,6 +432,7 @@ public final class VanillaMobAiOracle { for (MobSpec spec : s.mobs) { EntityType type = BuiltInRegistries.ENTITY_TYPE.getValue(net.minecraft.resources.Identifier.parse(spec.type)); Mob mob = (Mob) type.create(level, EntitySpawnReason.COMMAND); + if (tracing(s)) field(Entity.class, "random").set(mob, new TracingRandom(0L, TRACE, mobs.size())); mob.setId(id++); mob.snapTo(spec.x, spec.y, spec.z, spec.yaw, 0.0F); mob.setYHeadRot(spec.yaw); @@ -424,6 +459,7 @@ public final class VanillaMobAiOracle { Method tickTime = method(ServerLevel.class, "tickTime"); Object manager = get(level, "entityManager"); Method managerTick = method(manager.getClass(), "tick"); + for (int i = 0; i < mobs.size(); i++) print(0, i, mobs.get(i)); for (int t = 1; t <= s.ticks; t++) { level.environmentAttributes().invalidateTickCache(); level.updateSkyBrightness(); @@ -435,6 +471,8 @@ public final class VanillaMobAiOracle { player.snapTo(s.player[0], s.player[1], s.player[2], 0.0F, 0.0F); player.setDeltaMovement(Vec3.ZERO); } + TracingRandom.tick = t; + TracingRandom.on = tracing(s) && t >= traceFrom() && t <= traceTo(); SOUNDS.clear(); for (Mob mob : mobs) { if (mob.isRemoved()) continue; @@ -445,6 +483,8 @@ public final class VanillaMobAiOracle { managerTick.invoke(manager); for (int i = 0; i < mobs.size(); i++) print(t, i, mobs.get(i)); for (String sound : SOUNDS) out.println(t + " sound " + sound); + for (String line : TRACE) out.println(line); + TRACE.clear(); } for (Mob mob : mobs) mob.discard(); managerTick.invoke(manager); @@ -518,6 +558,7 @@ public final class VanillaMobAiOracle { .append(d((double) get(lc, "wantedY"))).append(',').append(d((double) get(lc, "wantedZ"))); sb.append("\tin ").append(f(m.xxa)).append(',').append(f(m.zza)).append(',').append(f(m.getSpeed())).append(',') .append(field(LivingEntity.class, "jumping").getBoolean(m) ? 1 : 0); + sb.append("\trng ").append(Long.toHexString(((java.util.concurrent.atomic.AtomicLong) field(net.minecraft.world.level.levelgen.LegacyRandomSource.class, "seed").get(m.getRandom())).get())); Brain brain = m.getBrain(); if (!brain.getActiveActivities().isEmpty() && !((Map) get(brain, "sensors")).isEmpty()) { List acts = new ArrayList<>(); diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 33e11edb4..b6b75ec3a 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -116,6 +116,9 @@ def parse(path): if parts[1] == 'sound': cur['sounds'].setdefault(t, []).append(parts[2]) continue + if parts[1] == 'trace': + cur.setdefault('trace', {}).setdefault(t, []).append(parts[2]) + continue mob = int(parts[1]) row = {} if len(parts) > 2: @@ -142,6 +145,22 @@ def decode(value): return ' '.join(out) +MULT, MASK = 0x5DEECE66D, (1 << 48) - 1 + + +def draws(before, after, limit=20000): + """How many LegacyRandomSource steps lead from one state to the next.""" + try: + s, goal = int(before, 16), int(after, 16) + except (TypeError, ValueError): + return '?' + for n in range(limit): + if s == goal: + return n + s = (s * MULT + 11) & MASK + return f'>{limit}' + + def compare(vanilla, rust, fields=None): """Returns (report lines, totals).""" report, totals = [], {'mob_ticks': 0, 'matched': 0, 'scenarios': 0, 'clean': 0} @@ -169,11 +188,18 @@ def compare(vanilla, rust, fields=None): diffs = [] for k in (a or {}): if b is None or a.get(k) != b.get(k): - diffs.append(f'{k}: vanilla {decode(a.get(k, "?"))} | horizon {decode((b or {}).get(k, "?"))}') + show = (lambda x: x) if k == 'rng' else decode + diffs.append(f'{k}: vanilla {show(a.get(k, "?"))} | horizon {show((b or {}).get(k, "?"))}') for k in (b or {}): if a is None or k not in a: diffs.append(f'{k}: vanilla ? | horizon {decode(b[k])}') - report.append(f'{name} mob {mob}: first divergence at tick {t} of {len(ticks)}') + prev_v = v['ticks'].get(t - 1, {}).get(mob, {}).get('rng') + prev_r = r['ticks'].get(t - 1, {}).get(mob, {}).get('rng') + report.append(f'{name} mob {mob}: first divergence at tick {t} of {len(ticks)} ' + f'(random draws this tick: vanilla {draws(prev_v, (a or {}).get("rng"))}, ' + f'horizon {draws(prev_r, (b or {}).get("rng"))})') + for line in [x for x in v.get('trace', {}).get(t, []) if x.split(' ', 1)[0] == str(mob)][:40]: + report.append(' vanilla ' + line) report.extend(' ' + d for d in diffs[:12]) if first is not None: clean = False From 24a58c40d8f7162aff96baf13811de93ac828a03 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 11 Oct 2026 14:08:47 +0200 Subject: [PATCH 27/28] Query the shipped vanilla bytecode through REA tools/rea_vanilla.py runs REA's JADX provider over the pinned client and server JARs: class search, class members, method bodies and callers (including lambdas). REA and the JADX engine are pinned in research-lock.json. Co-Authored-By: Claude Opus 5.5 --- docs/decompilation-status.md | 14 +++++ research-lock.json | 9 +++ tools/rea_vanilla.py | 110 +++++++++++++++++++++++++++++++++++ 3 files changed, 133 insertions(+) create mode 100644 tools/rea_vanilla.py diff --git a/docs/decompilation-status.md b/docs/decompilation-status.md index f7c72d7f7..80d39be68 100644 --- a/docs/decompilation-status.md +++ b/docs/decompilation-status.md @@ -21,3 +21,17 @@ The full outputs and machine-readable reports are local and gitignored: ``` Recheck with `python3 tools/lab.py status`. File coverage and the absence of detected failure markers do not prove every recovered method behaves identically, or that this source can be rebuilt. Original bytecode remains the behavior reference. There has been no gameplay baseline, full Rust port, or measured real-game optimization yet. + +## Querying the shipped bytecode with REA + +`tools/rea_vanilla.py` answers questions about the pinned game JARs with [REA](https://github.com/morluto/rea), which drives a headless JADX over the bytecode itself. Use it next to the Vineflower sources when you need what a text search can't give reliably: every caller of a method, including lambdas and bridge methods; every overload; or a second decompiler's view of a method whose Vineflower output looks wrong. + +```sh +python3 tools/rea_vanilla.py classes DispenserBlock +python3 tools/rea_vanilla.py class net.minecraft.world.level.block.DispenserBlock +python3 tools/rea_vanilla.py method net.minecraft.world.level.block.DispenserBlock dispenseFrom +python3 tools/rea_vanilla.py callers net.minecraft.server.level.ServerLevel tickChunk +python3 tools/rea_vanilla.py --jar server-game classes DedicatedServer +``` + +The REA and JADX engine versions are pinned in `research-lock.json`; the first run downloads the engine into `.local/tools/`. REA only admits JADX targets named `.apk`, so the helper keeps an `.apk`-named copy of each JAR in `.local/rea/`. Each query loads the JAR again, which takes about five seconds. Like the Vineflower output, decompiled method bodies are a reading aid: the bytecode and the oracle harnesses remain the behavior reference. diff --git a/research-lock.json b/research-lock.json index 1afd0035b..8d5fe6eda 100644 --- a/research-lock.json +++ b/research-lock.json @@ -9,5 +9,14 @@ "version": "1.12.0", "url": "https://github.com/Vineflower/vineflower/releases/download/1.12.0/vineflower-1.12.0.jar", "sha256": "1dfcfe974395734fa467ce620661c7623d05ba83670de0529b1fbd63ff548b9d" + }, + "rea": { + "package": "rea-agents", + "version": "6.4.0" + }, + "jadx_headless_mcp": { + "version": "0.7.1", + "url": "https://github.com/1013503897/jadx-headless-mcp/releases/download/v0.7.1/jadx-headless-mcp-0.7.1-all.jar", + "sha256": "6e5eacf500b64292bfb73c49797c1958f6ee44646e43e868039ae7feb573ff75" } } diff --git a/tools/rea_vanilla.py b/tools/rea_vanilla.py new file mode 100644 index 000000000..9a2723716 --- /dev/null +++ b/tools/rea_vanilla.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Query the pinned vanilla bytecode through REA (Reverse Engineer Anything). + +REA drives a headless JADX over the shipped game JAR, so answers come from the +bytecode Mojang ships rather than from the Vineflower sources: callers through +lambdas and bridges, every overload of a method, and members the decompiled +sources fold away. Prints REA's normalized result as JSON. + + python3 tools/rea_vanilla.py classes DispenserBlock + python3 tools/rea_vanilla.py class net.minecraft.world.level.block.DispenserBlock + python3 tools/rea_vanilla.py method net.minecraft.world.level.block.DispenserBlock dispenseFrom + python3 tools/rea_vanilla.py callers net.minecraft.server.level.ServerLevel tickChunk + python3 tools/rea_vanilla.py --jar server-game classes DedicatedServer + +The first run downloads the pinned JADX engine into .local/tools/; REA itself +runs from the global `rea` command when it is the pinned version, otherwise +through npx. Needs Node.js 22.19+ and Java 17+. +""" + +import argparse +import json +import os +import shutil +import subprocess +import sys + +import lab + +COMMANDS = { + "classes": ("search-android-classes", ["query"]), + "class": ("inspect-android-class", ["class_name"]), + "method": ("inspect-android-method", ["class_name", "method_name"]), + "callers": ("trace-android-references", ["class_name", "method_name"]), + "refs": ("trace-android-references", ["class_name"]), +} + + +def engine(lock): + pin = lock["jadx_headless_mcp"] + jar = lab.LOCAL / "tools" / f"jadx-headless-mcp-{pin['version']}-all.jar" + return lab.download(pin["url"], jar, pin["sha256"], "sha256") + + +def target(game_dir, name): + """REA admits JADX targets by their .apk name; JADX reads the class files either way.""" + source = game_dir / "jars" / f"{name}.jar" + if not source.exists(): + raise SystemExit(f"{source} is missing; run python3 tools/prepare_native_client.py --prepare") + copy = lab.LOCAL / "rea" / f"{name}-{lab.digest(source, 'sha256')[:16]}.apk" + if not copy.exists(): + copy.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, copy) + return copy + + +def rea_command(lock): + pin = lock["rea"] + installed = shutil.which("rea") + if installed: + version = subprocess.run([installed, "--version"], capture_output=True, text=True).stdout.strip() + if version == pin["version"]: + return [installed] + return ["npx", "-y", f"{pin['package']}@{pin['version']}"] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--jar", default="client", choices=["client", "server-game"]) + parser.add_argument("--overload-index", type=int) + parser.add_argument("--raw", action="store_true", help="print REA's whole evidence record") + parser.add_argument("command", choices=COMMANDS) + parser.add_argument("arguments", nargs="+") + args = parser.parse_args() + subcommand, names = COMMANDS[args.command] + if len(args.arguments) != len(names): + parser.error(f"{args.command} takes {' '.join(names).upper()}") + lock, game_dir = lab.config() + command = rea_command(lock) + [subcommand, str(target(game_dir, args.jar))] + if args.command in ("callers", "refs"): + command += [args.arguments[0]] + (["--method-name", args.arguments[1]] if args.command == "callers" else []) + else: + command += args.arguments + if args.overload_index is not None: + command += ["--overload-index", str(args.overload_index)] + environment = dict(os.environ, REA_JADX_MCP_JAR=str(engine(lock))) + result = subprocess.run(command + ["--json"], capture_output=True, text=True, env=environment) + try: + record = json.loads(result.stdout) + except json.JSONDecodeError: + sys.stderr.write(result.stdout + result.stderr) + return result.returncode or 1 + if "normalized_result" not in record: + details = record.get("details", {}) + reasons = [issue["message"] for issue in details.get("issues", [])] or [details.get("reason")] + print(record.get("message"), *filter(None, reasons), sep="\n", file=sys.stderr) + return 1 + body = record if args.raw else record["normalized_result"] + if not args.raw: + body.pop("engine", None) + if args.command == "method" and not args.raw and body.get("source", {}).get("text"): + print(f"// {body['class_name']}.{body['method']['reported_signature']}" + f" (overload {body['method']['overload_index']} of {body['overload_count']}, {body['source']['status']})") + print(body["source"]["text"]) + else: + print(json.dumps(body, indent=2)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 6734879ff75eae9f2e6e6df1988e7fece4878b39 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 11 Oct 2026 14:11:51 +0200 Subject: [PATCH 28/28] Pass rustfmt and clippy after merging the parity branches Formats the overnight parity work, fixes the lints it introduced, and updates the LAN bot test and mob AI probe for fields added on the other side of the merges (the bot test also set a field that never existed). Co-Authored-By: Claude Opus 5.5 --- .../examples/item_model_fixture.rs | 3 +- crates/horizon-assets/src/math.rs | 72 +++- crates/horizon-assets/src/palette.rs | 59 +++- .../examples/auto_jump_probe.rs | 10 +- .../horizon-client/examples/camera_probe.rs | 14 +- .../examples/command_parse_fixture.rs | 10 +- .../examples/entity_death_loot_fixture.rs | 36 +- .../examples/frame_limiter_probe.rs | 17 +- .../horizon-client/examples/mob_ai_probe.rs | 9 +- .../examples/spawn_rules_fixture.rs | 3 +- crates/horizon-client/src/auto_jump.rs | 14 +- .../horizon-client/src/block_entity_render.rs | 172 ++++----- crates/horizon-client/src/camera.rs | 29 +- crates/horizon-client/src/command/args.rs | 86 +++-- crates/horizon-client/src/command/block.rs | 9 +- crates/horizon-client/src/command/codec.rs | 10 +- .../horizon-client/src/command/component.rs | 36 +- crates/horizon-client/src/command/item.rs | 68 +++- crates/horizon-client/src/command/mod.rs | 10 +- crates/horizon-client/src/command/packrat.rs | 12 +- crates/horizon-client/src/command/selector.rs | 7 +- crates/horizon-client/src/command/snbt.rs | 72 +++- crates/horizon-client/src/command/tests.rs | 29 +- .../horizon-client/src/command/tree_data.rs | 12 +- .../src/command/tree_execute.rs | 12 +- .../horizon-client/src/command/tree_misc.rs | 6 +- .../horizon-client/src/command/tree_world.rs | 50 ++- crates/horizon-client/src/command/vanilla.rs | 12 +- crates/horizon-client/src/game.rs | 11 +- crates/horizon-client/src/game/creatures.rs | 18 +- crates/horizon-client/src/game/lan.rs | 12 +- crates/horizon-client/src/game/machines.rs | 7 +- crates/horizon-client/src/game/mounts.rs | 4 +- crates/horizon-client/src/game/perspective.rs | 18 +- crates/horizon-client/src/game/recipe_book.rs | 15 +- crates/horizon-client/src/game/tnt.rs | 6 +- .../src/lan/command_suggestions.rs | 330 ++++++++++++++---- crates/horizon-client/src/lan/commands.rs | 31 +- crates/horizon-client/src/lan/entity.rs | 18 +- crates/horizon-client/src/lan/hub.rs | 3 +- crates/horizon-client/src/lan/tracking.rs | 4 +- crates/horizon-client/src/lib.rs | 2 +- crates/horizon-client/src/mobs.rs | 8 +- crates/horizon-client/src/mobs/control.rs | 7 +- crates/horizon-client/src/mobs/drops.rs | 10 +- crates/horizon-client/src/mobs/goals.rs | 5 +- crates/horizon-client/src/mobs/spawn_rules.rs | 62 +++- crates/horizon-client/src/window.rs | 12 +- crates/horizon-client/tests/lan_bot.rs | 6 +- crates/horizon-core/src/geometry/trig.rs | 19 +- .../examples/block_update_fixture.rs | 76 ++-- crates/horizon-world/src/level/data.rs | 5 +- crates/horizon-world/src/level/hooks.rs | 3 +- crates/horizon-world/src/level/mod.rs | 6 +- crates/horizon-world/src/level/portal.rs | 32 +- crates/horizon-world/src/level/shapes.rs | 9 +- crates/horizon-world/src/level/shelf.rs | 60 +++- crates/horizon-world/src/level/update.rs | 7 +- crates/horizon-world/src/loot.rs | 37 +- 59 files changed, 1254 insertions(+), 468 deletions(-) diff --git a/crates/horizon-assets/examples/item_model_fixture.rs b/crates/horizon-assets/examples/item_model_fixture.rs index c14ee3866..615492fe6 100644 --- a/crates/horizon-assets/examples/item_model_fixture.rs +++ b/crates/horizon-assets/examples/item_model_fixture.rs @@ -240,7 +240,8 @@ fn main() -> Result<(), Box> { let sprites = Sprites { root: root.clone(), permutations: PalettedPermutations::from_atlas( - &fs::read_to_string(root.join("assets/minecraft/atlases/items.json")).unwrap_or_default(), + &fs::read_to_string(root.join("assets/minecraft/atlases/items.json")) + .unwrap_or_default(), ), cache: RefCell::default(), }; diff --git a/crates/horizon-assets/src/math.rs b/crates/horizon-assets/src/math.rs index 74595c4d2..2f344d042 100644 --- a/crates/horizon-assets/src/math.rs +++ b/crates/horizon-assets/src/math.rs @@ -59,7 +59,10 @@ impl Mat4 { if m[0][3] == 0.0 && m[1][3] == 0.0 { if m[2][3] == 0.0 && m[3][3] == 1.0 { properties |= AFFINE; - if m[0] == [1.0, 0.0, 0.0, 0.0] && m[1] == [0.0, 1.0, 0.0, 0.0] && m[2] == [0.0, 0.0, 1.0, 0.0] { + if m[0] == [1.0, 0.0, 0.0, 0.0] + && m[1] == [0.0, 1.0, 0.0, 0.0] + && m[2] == [0.0, 0.0, 1.0, 0.0] + { properties |= TRANSLATION | ORTHONORMAL; if m[3][0] == 0.0 && m[3][1] == 0.0 && m[3][2] == 0.0 { properties |= IDENTITY; @@ -111,12 +114,20 @@ impl Mat4 { // mulAffine for c in 0..3 { for row in 0..3 { - out[c][row] = fma(m[0][row], r[c][0], fma(m[1][row], r[c][1], m[2][row] * r[c][2])); + out[c][row] = fma( + m[0][row], + r[c][0], + fma(m[1][row], r[c][1], m[2][row] * r[c][2]), + ); } out[c][3] = m[c][3]; } for row in 0..3 { - out[3][row] = fma(m[0][row], r[3][0], fma(m[1][row], r[3][1], fma(m[2][row], r[3][2], m[3][row]))); + out[3][row] = fma( + m[0][row], + r[3][0], + fma(m[1][row], r[3][1], fma(m[2][row], r[3][2], m[3][row])), + ); } out[3][3] = m[3][3]; return Self(out, AFFINE | self.1 & right.1 & ORTHONORMAL); @@ -124,7 +135,12 @@ impl Mat4 { if self.has(PERSPECTIVE) && right.has(AFFINE) { // mulPerspectiveAffine for c in 0..4 { - out[c] = [m[0][0] * r[c][0], m[1][1] * r[c][1], m[2][2] * r[c][2], m[2][3] * r[c][2]]; + out[c] = [ + m[0][0] * r[c][0], + m[1][1] * r[c][1], + m[2][2] * r[c][2], + m[2][3] * r[c][2], + ]; } out[3][2] = m[2][2] * r[3][2] + m[3][2]; out[3][3] = m[2][3] * r[3][2]; @@ -134,13 +150,24 @@ impl Mat4 { // mulAffineR for c in 0..3 { for row in 0..4 { - out[c][row] = fma(m[0][row], r[c][0], fma(m[1][row], r[c][1], m[2][row] * r[c][2])); + out[c][row] = fma( + m[0][row], + r[c][0], + fma(m[1][row], r[c][1], m[2][row] * r[c][2]), + ); } } for row in 0..4 { - out[3][row] = fma(m[0][row], r[3][0], fma(m[1][row], r[3][1], fma(m[2][row], r[3][2], m[3][row]))); + out[3][row] = fma( + m[0][row], + r[3][0], + fma(m[1][row], r[3][1], fma(m[2][row], r[3][2], m[3][row])), + ); } - return Self(out, self.1 & !(PERSPECTIVE | IDENTITY | TRANSLATION | ORTHONORMAL)); + return Self( + out, + self.1 & !(PERSPECTIVE | IDENTITY | TRANSLATION | ORTHONORMAL), + ); } // mul0 for c in 0..4 { @@ -148,7 +175,11 @@ impl Mat4 { out[c][row] = fma( m[0][row], r[c][0], - fma(m[1][row], r[c][1], fma(m[2][row], r[c][2], m[3][row] * r[c][3])), + fma( + m[1][row], + r[c][1], + fma(m[2][row], r[c][2], m[3][row] * r[c][3]), + ), ); } } @@ -162,7 +193,15 @@ impl Mat4 { // translateGeneric let mut out = *self; for row in 0..4 { - out.0[3][row] = fma(self.0[0][row], t[0], fma(self.0[1][row], t[1], fma(self.0[2][row], t[2], self.0[3][row]))); + out.0[3][row] = fma( + self.0[0][row], + t[0], + fma( + self.0[1][row], + t[1], + fma(self.0[2][row], t[2], self.0[3][row]), + ), + ); } out.1 = self.1 & !(PERSPECTIVE | IDENTITY); out @@ -186,7 +225,8 @@ impl Mat4 { out.0[c][row] = self.0[c][row] * s[c]; } } - out.1 = self.1 & !(PERSPECTIVE | IDENTITY | TRANSLATION | if one { 0 } else { ORTHONORMAL }); + out.1 = + self.1 & !(PERSPECTIVE | IDENTITY | TRANSLATION | if one { 0 } else { ORTHONORMAL }); out } /// `Matrix4f.rotate(Quaternionfc)`. @@ -228,7 +268,11 @@ impl Mat4 { // rotateGeneric for c in 0..3 { for row in 0..4 { - out.0[c][row] = fma(m[0][row], r[c][0], fma(m[1][row], r[c][1], m[2][row] * r[c][2])); + out.0[c][row] = fma( + m[0][row], + r[c][0], + fma(m[1][row], r[c][1], m[2][row] * r[c][2]), + ); } } } @@ -281,7 +325,11 @@ pub fn quaternion_xyz(x: f32, y: f32, z: f32) -> [f32; 4] { /// [0, 2Ï€) and the axis is used as given. pub fn quaternion_from_axis_angle(angle: f32, axis: [f32; 3]) -> [f32; 4] { let tau = (std::f64::consts::PI * 2.0) as f32; - let angle = if angle < 0.0 { tau + angle % tau } else { angle } % tau; + let angle = if angle < 0.0 { + tau + angle % tau + } else { + angle + } % tau; let sin = joml_sin(angle * 0.5); let cos = cos_from_sin(sin, angle * 0.5); [axis[0] * sin, axis[1] * sin, axis[2] * sin, cos] diff --git a/crates/horizon-assets/src/palette.rs b/crates/horizon-assets/src/palette.rs index 788d1b17d..9f825d05d 100644 --- a/crates/horizon-assets/src/palette.rs +++ b/crates/horizon-assets/src/palette.rs @@ -25,7 +25,11 @@ pub struct Permutation<'a> { } fn qualified(id: &str) -> String { - if id.contains(':') { id.to_owned() } else { format!("minecraft:{id}") } + if id.contains(':') { + id.to_owned() + } else { + format!("minecraft:{id}") + } } impl PalettedPermutations { @@ -34,13 +38,29 @@ impl PalettedPermutations { let Ok(json) = serde_json::from_str::(atlas) else { return Vec::new(); }; - let sources = json.get("sources").and_then(Value::as_array).cloned().unwrap_or_default(); + let sources = json + .get("sources") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); sources .iter() - .filter(|s| s.get("type").and_then(Value::as_str).map(qualified).as_deref() == Some("minecraft:paletted_permutations")) + .filter(|s| { + s.get("type") + .and_then(Value::as_str) + .map(qualified) + .as_deref() + == Some("minecraft:paletted_permutations") + }) .filter_map(|s| { Some(Self { - textures: s.get("textures")?.as_array()?.iter().filter_map(Value::as_str).map(qualified).collect(), + textures: s + .get("textures")? + .as_array()? + .iter() + .filter_map(Value::as_str) + .map(qualified) + .collect(), palette_key: qualified(s.get("palette_key")?.as_str()?), permutations: s .get("permutations")? @@ -48,7 +68,11 @@ impl PalettedPermutations { .iter() .filter_map(|(k, v)| Some((k.clone(), qualified(v.as_str()?)))) .collect(), - separator: s.get("separator").and_then(Value::as_str).unwrap_or("_").to_owned(), + separator: s + .get("separator") + .and_then(Value::as_str) + .unwrap_or("_") + .to_owned(), }) }) .collect() @@ -57,8 +81,14 @@ impl PalettedPermutations { pub fn find(&self, sprite: &str) -> Option> { let sprite = qualified(sprite); self.textures.iter().find_map(|base| { - let suffix = sprite.strip_prefix(base.as_str())?.strip_prefix(self.separator.as_str())?; - Some(Permutation { base, palette_key: &self.palette_key, palette: self.permutations.get(suffix)? }) + let suffix = sprite + .strip_prefix(base.as_str())? + .strip_prefix(self.separator.as_str())?; + Some(Permutation { + base, + palette_key: &self.palette_key, + palette: self.permutations.get(suffix)?, + }) }) } } @@ -95,9 +125,18 @@ mod tests { let atlas = r#"{"sources":[{"type":"minecraft:paletted_permutations","palette_key":"minecraft:trim_base", "permutations":{"quartz":"minecraft:trim/quartz"},"textures":["minecraft:trims/items/boots_trim"]}]}"#; let sources = PalettedPermutations::from_atlas(atlas); - let p = sources[0].find("minecraft:trims/items/boots_trim_quartz").unwrap(); - assert_eq!((p.base, p.palette), ("minecraft:trims/items/boots_trim", "minecraft:trim/quartz")); - assert!(sources[0].find("minecraft:trims/items/boots_trim_gold").is_none()); + let p = sources[0] + .find("minecraft:trims/items/boots_trim_quartz") + .unwrap(); + assert_eq!( + (p.base, p.palette), + ("minecraft:trims/items/boots_trim", "minecraft:trim/quartz") + ); + assert!( + sources[0] + .find("minecraft:trims/items/boots_trim_gold") + .is_none() + ); let mut pixels = [0xFF11_2233, 0x8011_2233, 0x0011_2233, 0xFF44_5566]; apply_palette(&mut pixels, &[0xFF11_2233], &[0xFFAA_BBCC]).unwrap(); assert_eq!(pixels, [0xFFAA_BBCC, 0x80AA_BBCC, 0x0011_2233, 0xFF44_5566]); diff --git a/crates/horizon-client/examples/auto_jump_probe.rs b/crates/horizon-client/examples/auto_jump_probe.rs index f0f474c04..3dea957a2 100644 --- a/crates/horizon-client/examples/auto_jump_probe.rs +++ b/crates/horizon-client/examples/auto_jump_probe.rs @@ -64,7 +64,10 @@ fn main() -> Result<()> { .properties .insert(name.clone(), value.as_str().unwrap().into()); } - state = assets.registry.id(&definition).ok_or("missing fixture state")?; + state = assets + .registry + .id(&definition) + .ok_or("missing fixture state")?; } restore.push((x, y, z, scene.block(x, y, z))); scene.set(x, y, z, state)?; @@ -76,7 +79,10 @@ fn main() -> Result<()> { player.shift_key_down = p["shift"].as_bool().unwrap(); player.yaw = fl(&p["yr"]); player.pitch = fl(&p["xr"]); - let key = player.attributes.key("minecraft:movement_speed").ok_or("speed")?; + let key = player + .attributes + .key("minecraft:movement_speed") + .ok_or("speed")?; let handle = player .attributes .get_instance(Some(key)) diff --git a/crates/horizon-client/examples/camera_probe.rs b/crates/horizon-client/examples/camera_probe.rs index 889c1020a..e88e18926 100644 --- a/crates/horizon-client/examples/camera_probe.rs +++ b/crates/horizon-client/examples/camera_probe.rs @@ -86,7 +86,11 @@ impl RayWorld for Cells { ) -> std::result::Result { Ok(self.shapes[s].clone()) } - fn interaction_shape(&mut self, _: usize, _: BlockPos) -> std::result::Result { + fn interaction_shape( + &mut self, + _: usize, + _: BlockPos, + ) -> std::result::Result { Ok(VoxelShape::empty()) } fn fluid_is_source(&mut self, _: ()) -> std::result::Result { @@ -120,7 +124,9 @@ fn cells(c: &Value) -> Result { ShapeOp::OR, )?; } - world.index.insert(BlockPos::new(at[0], at[1], at[2]), world.shapes.len()); + world + .index + .insert(BlockPos::new(at[0], at[1], at[2]), world.shapes.len()); world.shapes.push(shape); } Ok(world) @@ -147,9 +153,7 @@ fn entity(s: &Value) -> (CameraEntity, Option) { dead: s["dead"].as_i64().map(|t| t as i32), }); let mount = if player { - s["mount"] - .as_array() - .map(|a| (db(&a[0]) as f32, db(&a[1]))) + s["mount"].as_array().map(|a| (db(&a[0]) as f32, db(&a[1]))) } else { None }; diff --git a/crates/horizon-client/examples/command_parse_fixture.rs b/crates/horizon-client/examples/command_parse_fixture.rs index f962b0e3b..1b6905bef 100644 --- a/crates/horizon-client/examples/command_parse_fixture.rs +++ b/crates/horizon-client/examples/command_parse_fixture.rs @@ -54,7 +54,9 @@ fn parser_id(ty: &ArgType) -> String { ArgType::ResOrTagKey(_) => "minecraft:resource_or_tag_key".into(), ArgType::StrEnum(values, _) => match values.first().copied() { Some("world_surface") => "minecraft:heightmap".into(), - Some("none") if values.len() == 3 && values[1] == "left_right" => "minecraft:template_mirror".into(), + Some("none") if values.len() == 3 && values[1] == "left_right" => { + "minecraft:template_mirror".into() + } Some("none") if values.len() == 3 => "minecraft:swing_animation".into(), _ => "minecraft:template_rotation".into(), }, @@ -194,10 +196,12 @@ fn main() -> horizon_client::Result<()> { reg.persistent_components = strings(&r["persistent_components"]); reg.learnable_recipes = strings(&r["learnable_recipes"]); for (clock, markers) in r["clock_time_markers"].as_object().into_iter().flatten() { - reg.clock_time_markers.insert(clock.clone(), strings(markers)); + reg.clock_time_markers + .insert(clock.clone(), strings(markers)); } for (id, criteria) in r["advancement_criteria"].as_object().into_iter().flatten() { - reg.advancement_criteria.insert(id.clone(), strings(criteria)); + reg.advancement_criteria + .insert(id.clone(), strings(criteria)); } reg.datapacks_enabled = strings(&r["datapacks_selected"]); let enabled = reg.datapacks_enabled.clone(); diff --git a/crates/horizon-client/examples/entity_death_loot_fixture.rs b/crates/horizon-client/examples/entity_death_loot_fixture.rs index 0e6dede38..1c9d06440 100644 --- a/crates/horizon-client/examples/entity_death_loot_fixture.rs +++ b/crates/horizon-client/examples/entity_death_loot_fixture.rs @@ -4,9 +4,7 @@ //! //! usage: entity_death_loot_fixture RESOURCES INPUT OUTPUT use horizon_client::{ - mobs::{ - Mob, MobTypes, Species, cube, drops, gear, raider, render::DYE_NAMES, sulfur_cube, - }, + mobs::{Mob, MobTypes, Species, cube, drops, gear, raider, render::DYE_NAMES, sulfur_cube}, random_sequences::RandomSequences, }; use horizon_core::{geometry::Vec3, random::LegacyRandom}; @@ -78,7 +76,8 @@ fn main() -> horizon_client::Result<()> { None => name = token, } } - let get = |k: &str, d: &'static str| -> String { c.get(k).copied().unwrap_or(d).to_owned() }; + let get = + |k: &str, d: &'static str| -> String { c.get(k).copied().unwrap_or(d).to_owned() }; let _ = writeln!(out, "== {name}"); let Some(kind) = types.types.get(c["type"]) else { let _ = writeln!(out, "error unsupported {}", c["type"]); @@ -213,11 +212,12 @@ fn main() -> horizon_client::Result<()> { kind: kind.to_owned(), ..LootEntity::default() }; - let damage = |kind: &str, source: Option, direct: Option| LootDamage { - kind: kind.to_owned(), - source, - direct, - }; + let damage = + |kind: &str, source: Option, direct: Option| LootDamage { + kind: kind.to_owned(), + source, + direct, + }; let source = match get("source", "attack").as_str() { "attack" => match &killer { None => damage("minecraft:generic", None, None), @@ -226,9 +226,17 @@ fn main() -> horizon_client::Result<()> { } Some(k) => damage("minecraft:mob_attack", Some(k.clone()), Some(k.clone())), }, - "arrow" => damage("minecraft:arrow", killer.clone(), Some(projectile("minecraft:arrow"))), + "arrow" => damage( + "minecraft:arrow", + killer.clone(), + Some(projectile("minecraft:arrow")), + ), "fireball" => match &killer { - Some(k) => damage("minecraft:fireball", Some(k.clone()), Some(projectile("minecraft:fireball"))), + Some(k) => damage( + "minecraft:fireball", + Some(k.clone()), + Some(projectile("minecraft:fireball")), + ), None => damage( "minecraft:unattributed_fireball", Some(projectile("minecraft:fireball")), @@ -236,7 +244,11 @@ fn main() -> horizon_client::Result<()> { ), }, "explosion" => match &killer { - Some(k) => damage("minecraft:player_explosion", Some(k.clone()), Some(k.clone())), + Some(k) => damage( + "minecraft:player_explosion", + Some(k.clone()), + Some(k.clone()), + ), None => damage("minecraft:explosion", None, None), }, "lightning" => damage("minecraft:lightning_bolt", None, None), diff --git a/crates/horizon-client/examples/frame_limiter_probe.rs b/crates/horizon-client/examples/frame_limiter_probe.rs index a877d05f9..7a5d4e437 100644 --- a/crates/horizon-client/examples/frame_limiter_probe.rs +++ b/crates/horizon-client/examples/frame_limiter_probe.rs @@ -62,15 +62,26 @@ fn main() -> Result<()> { now: i("now"), call: i("call"), spin: i("spin"), - overshoot: c["overshoot"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect(), + overshoot: c["overshoot"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_i64().unwrap()) + .collect(), next_overshoot: 0, - interrupts: c["interrupts"].as_array().unwrap().iter().map(|v| v.as_bool().unwrap()).collect(), + interrupts: c["interrupts"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_bool().unwrap()) + .collect(), next_interrupt: 0, parks: Vec::new(), spins: 0, queries: 0, }; - let mut limiter = FramerateLimiter::with_state(i("last"), i("average"), i("last_limit") as i32); + let mut limiter = + FramerateLimiter::with_state(i("last"), i("average"), i("last_limit") as i32); for frame in c["frames"].as_array().unwrap() { clock.now = clock.now.wrapping_add(frame[0].as_i64().unwrap()); clock.parks.clear(); diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 2406314d6..ab6cce246 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -483,6 +483,8 @@ fn main() -> horizon_client::Result<()> { biomes: &biomes, mob_griefing: true, difficulty: LocalDifficulty::new(2, world.day_time, 0, 0.0), + end: false, + world_seed: 0, }; let mut events = Vec::new(); for m in &mut mobs { @@ -498,7 +500,12 @@ fn main() -> horizon_client::Result<()> { } for e in &events { if let MobEvent::Sound(name, _, volume, pitch) = e { - let _ = writeln!(out, "{t} sound minecraft:{name} {} {}", f(*volume), f(*pitch)); + let _ = writeln!( + out, + "{t} sound minecraft:{name} {} {}", + f(*volume), + f(*pitch) + ); } else if let MobEvent::SoundId(name, _, volume, pitch) = e { let _ = writeln!(out, "{t} sound {name} {} {}", f(*volume), f(*pitch)); } diff --git a/crates/horizon-client/examples/spawn_rules_fixture.rs b/crates/horizon-client/examples/spawn_rules_fixture.rs index 8e4fff1c3..dc491be00 100644 --- a/crates/horizon-client/examples/spawn_rules_fixture.rs +++ b/crates/horizon-client/examples/spawn_rules_fixture.rs @@ -164,7 +164,8 @@ fn main() -> horizon_client::Result<()> { None => name = token, } } - let get = |k: &str, d: &'static str| -> String { c.get(k).copied().unwrap_or(d).to_owned() }; + let get = + |k: &str, d: &'static str| -> String { c.get(k).copied().unwrap_or(d).to_owned() }; let Some(kind) = types.types.get(c["type"]) else { let _ = writeln!(out, "{name} error unsupported {}", c["type"]); continue; diff --git a/crates/horizon-client/src/auto_jump.rs b/crates/horizon-client/src/auto_jump.rs index 123c84ce6..bd7bdcbad 100644 --- a/crates/horizon-client/src/auto_jump.rs +++ b/crates/horizon-client/src/auto_jump.rs @@ -148,7 +148,8 @@ pub fn update_auto_jump( let right_end = seg_end.add_vector(right_offset); let mut obstacle = NO_OBSTACLE; for b in world.collision_boxes(test_box)? { - if intersects_segment(b, left_begin, left_end) || intersects_segment(b, right_begin, right_end) + if intersects_segment(b, left_begin, left_end) + || intersects_segment(b, right_begin, right_end) { obstacle = b.max_position().y as f32; let obstacle_pos = BlockPos::containing(b.center()); @@ -175,7 +176,10 @@ pub fn update_auto_jump( } if obstacle != NO_OBSTACLE { let y_delta = (f64::from(obstacle) - p.position.y) as f32; - if !(y_delta <= 0.5) && !(y_delta > jump_height) { + // Negated as in LocalPlayer.updateAutoJump, so a NaN delta still jumps. + #[allow(clippy::neg_cmp_op_on_partial_ord)] + let jumps = !(y_delta <= 0.5) && !(y_delta > jump_height); + if jumps { return Ok(true); } } @@ -197,7 +201,11 @@ mod tests { } fn collision_boxes(&mut self, bounds: Aabb) -> Result, ()> { let b = Aabb::new(Vec3::new(1.0, 0.0, -5.0), Vec3::new(2.0, 1.0, 5.0)); - Ok(if b.intersects(bounds) { vec![b] } else { Vec::new() }) + Ok(if b.intersects(bounds) { + vec![b] + } else { + Vec::new() + }) } } #[test] diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 4e2a7704b..f3638865b 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -1434,6 +1434,92 @@ impl BlockEntityRenderer { } } +/// `BeaconRenderer.submit`: for each beam section (ARGB colour, height) the +/// rotating solid beam and its translucent glow, the last section 2048 +/// blocks tall. `origin` is the beacon block's corner relative to the camera, +/// `time` the animation time (game time mod 40 plus partial tick) and `scale` +/// the radius scale. The sprite's v range rides in the light bytes (the +/// entity shader wraps v for layer 6). +pub fn beacon_beam( + origin: Vec3, + sections: &[(u32, i32)], + time: f32, + scale: f32, + s: Rect, + out: &mut Vec, +) { + let q = |v: f32| (v * 65535.0).round().clamp(0.0, 65535.0) as u32; + let wrap = q(s.v0) | q(s.v1 - s.v0) << 16; + let o = origin + Vec3::new(0.5, 0.0, 0.5); + let mut start = 0i32; + for (i, &(color, height)) in sections.iter().enumerate() { + let height = if i == sections.len() - 1 { + 2048 + } else { + height + }; + let end = start + height; + let scroll = if height < 0 { time } else { -time }; + let v_off = frac(scroll * 0.2 - (scroll * 0.1).floor()); + let abgr = + |a: u32| a << 24 | (color & 255) << 16 | (color >> 8 & 255) << 8 | (color >> 16 & 255); + // Solid beam: radius 0.2 * scale, rotated with time. + let r = 0.2 * scale; + let rot = glam::Mat3::from_rotation_y((time * 2.25 - 45.0).to_radians()); + let corners = [ + rot * Vec3::new(0.0, 0.0, r), + rot * Vec3::new(r, 0.0, 0.0), + rot * Vec3::new(-r, 0.0, 0.0), + rot * Vec3::new(0.0, 0.0, -r), + ]; + let v2 = -1.0 + v_off; + let v1 = height as f32 * (0.5 / r) + v2; + beam_part(out, o, start, end, corners, [v1, v2], abgr(255), s, wrap); + // Glow: radius 0.25 * scale, translucent. + let g = 0.25 * scale; + let corners = [ + Vec3::new(-g, 0.0, -g), + Vec3::new(g, 0.0, -g), + Vec3::new(-g, 0.0, g), + Vec3::new(g, 0.0, g), + ]; + let v1 = height as f32 + v2; + beam_part(out, o, start, end, corners, [v1, v2], abgr(32), s, wrap); + start = end; + } +} +/// `BeaconRenderer.renderPart`: four quads between the corners (wn, en, ws, es). +#[allow(clippy::too_many_arguments)] +fn beam_part( + out: &mut Vec, + o: Vec3, + start: i32, + end: i32, + [wn, en, ws, es]: [Vec3; 4], + [v1, v2]: [f32; 2], + color: u32, + s: Rect, + wrap: u32, +) { + for (a, b) in [(wn, en), (es, ws), (en, es), (ws, wn)] { + let at = |c: Vec3, y: i32| o + c + Vec3::new(0.0, y as f32, 0.0); + for (p, uv) in [ + (at(a, end), [s.u1, v1]), + (at(a, start), [s.u1, v2]), + (at(b, start), [s.u0, v2]), + (at(b, end), [s.u0, v1]), + ] { + out.push(Vertex { + pos: p.to_array(), + uv, + layer: 6, + color, + light: wrap, + }); + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -1560,89 +1646,3 @@ mod tests { assert_eq!(out[2].uv, [0.5, 0.5]); } } - -/// `BeaconRenderer.submit`: for each beam section (ARGB colour, height) the -/// rotating solid beam and its translucent glow, the last section 2048 -/// blocks tall. `origin` is the beacon block's corner relative to the camera, -/// `time` the animation time (game time mod 40 plus partial tick) and `scale` -/// the radius scale. The sprite's v range rides in the light bytes (the -/// entity shader wraps v for layer 6). -pub fn beacon_beam( - origin: Vec3, - sections: &[(u32, i32)], - time: f32, - scale: f32, - s: Rect, - out: &mut Vec, -) { - let q = |v: f32| (v * 65535.0).round().clamp(0.0, 65535.0) as u32; - let wrap = q(s.v0) | q(s.v1 - s.v0) << 16; - let o = origin + Vec3::new(0.5, 0.0, 0.5); - let mut start = 0i32; - for (i, &(color, height)) in sections.iter().enumerate() { - let height = if i == sections.len() - 1 { - 2048 - } else { - height - }; - let end = start + height; - let scroll = if height < 0 { time } else { -time }; - let v_off = frac(scroll * 0.2 - (scroll * 0.1).floor()); - let abgr = - |a: u32| a << 24 | (color & 255) << 16 | (color >> 8 & 255) << 8 | (color >> 16 & 255); - // Solid beam: radius 0.2 * scale, rotated with time. - let r = 0.2 * scale; - let rot = glam::Mat3::from_rotation_y((time * 2.25 - 45.0).to_radians()); - let corners = [ - rot * Vec3::new(0.0, 0.0, r), - rot * Vec3::new(r, 0.0, 0.0), - rot * Vec3::new(-r, 0.0, 0.0), - rot * Vec3::new(0.0, 0.0, -r), - ]; - let v2 = -1.0 + v_off; - let v1 = height as f32 * (0.5 / r) + v2; - beam_part(out, o, start, end, corners, [v1, v2], abgr(255), s, wrap); - // Glow: radius 0.25 * scale, translucent. - let g = 0.25 * scale; - let corners = [ - Vec3::new(-g, 0.0, -g), - Vec3::new(g, 0.0, -g), - Vec3::new(-g, 0.0, g), - Vec3::new(g, 0.0, g), - ]; - let v1 = height as f32 + v2; - beam_part(out, o, start, end, corners, [v1, v2], abgr(32), s, wrap); - start = end; - } -} -/// `BeaconRenderer.renderPart`: four quads between the corners (wn, en, ws, es). -#[allow(clippy::too_many_arguments)] -fn beam_part( - out: &mut Vec, - o: Vec3, - start: i32, - end: i32, - [wn, en, ws, es]: [Vec3; 4], - [v1, v2]: [f32; 2], - color: u32, - s: Rect, - wrap: u32, -) { - for (a, b) in [(wn, en), (es, ws), (en, es), (ws, wn)] { - let at = |c: Vec3, y: i32| o + c + Vec3::new(0.0, y as f32, 0.0); - for (p, uv) in [ - (at(a, end), [s.u1, v1]), - (at(a, start), [s.u1, v2]), - (at(b, start), [s.u0, v2]), - (at(b, end), [s.u0, v1]), - ] { - out.push(Vertex { - pos: p.to_array(), - uv, - layer: 6, - color, - light: wrap, - }); - } - } -} diff --git a/crates/horizon-client/src/camera.rs b/crates/horizon-client/src/camera.rs index 329ae3e86..561a22b95 100644 --- a/crates/horizon-client/src/camera.rs +++ b/crates/horizon-client/src/camera.rs @@ -57,7 +57,11 @@ pub fn wrap_degrees(angle: f32) -> f32 { } /// `Mth.clamp(float, float, float)`. pub fn clamp(value: f32, min: f32, max: f32) -> f32 { - if value < min { min } else { java_min(value, max) } + if value < min { + min + } else { + java_min(value, max) + } } /// JOML's float trigonometry (`org.joml.Math` without fast math). @@ -130,12 +134,9 @@ pub mod joml { let yw = self.y * self.w; let k = 1.0 / (xx + yy + zz + ww); [ - (xx - yy - zz + ww) * k * x - + (2.0 * (xy - zw) * k * y + 2.0 * (xz + yw) * k * z), - 2.0 * (xy + zw) * k * x - + ((yy - xx - zz + ww) * k * y + 2.0 * (yz - xw) * k * z), - 2.0 * (xz - yw) * k * x - + (2.0 * (yz + xw) * k * y + (zz - xx - yy + ww) * k * z), + (xx - yy - zz + ww) * k * x + (2.0 * (xy - zw) * k * y + 2.0 * (xz + yw) * k * z), + 2.0 * (xy + zw) * k * x + ((yy - xx - zz + ww) * k * y + 2.0 * (yz - xw) * k * z), + 2.0 * (xz - yw) * k * x + (2.0 * (yz + xw) * k * y + (zz - xx - yy + ww) * k * z), ] } } @@ -568,8 +569,7 @@ impl Camera { if panoramic { return 90.0; } - let fov = - fov_option as f32 * lerp(partial, self.old_fov_modifier, self.fov_modifier); + let fov = fov_option as f32 * lerp(partial, self.old_fov_modifier, self.fov_modifier); modify_fov_based_on_death_or_fluid(partial, fov, effect_scale, dead, fluid) } /// `Camera.calculateHudFov`. @@ -704,7 +704,11 @@ pub fn bob_view(state: &BobState, pose: &mut Mat4) { 0.0, ); rotate_degrees(pose, 2, trig::sin(f64::from(walk * PI)) * bob * 3.0); - rotate_degrees(pose, 0, (trig::cos(f64::from(walk * PI - 0.2)) * bob).abs() * 5.0); + rotate_degrees( + pose, + 0, + (trig::cos(f64::from(walk * PI - 0.2)) * bob).abs() * 5.0, + ); } /// The bob matrix `GameRenderer.renderLevel` multiplies into the projection /// (and `renderItemInHand` into the hand's pose). @@ -767,7 +771,10 @@ mod tests { movement_speed: 0.13, using: None, }; - assert_eq!(field_of_view_modifier(&p, true, 1.0), (0.13f32 / 0.1 + 1.0) / 2.0); + assert_eq!( + field_of_view_modifier(&p, true, 1.0), + (0.13f32 / 0.1 + 1.0) / 2.0 + ); assert_eq!(field_of_view_modifier(&p, true, 0.0), 1.0); p.using = Some((UseItem::Spyglass, 3)); assert_eq!(field_of_view_modifier(&p, true, 1.0), 0.1); diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-client/src/command/args.rs index 1f24bfbf6..43770802f 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-client/src/command/args.rs @@ -540,9 +540,9 @@ pub fn parse_identifier(raw: &str) -> Option { && ns .chars() .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-')); - let path_ok = path - .chars() - .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/')); + let path_ok = path.chars().all(|c| { + c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/') + }); (ns_ok && path_ok).then(|| format!("{ns}:{path}")) } pub fn normalize(id: &str) -> String { @@ -690,7 +690,11 @@ pub fn read_double_bounds(reader: &mut Reader) -> CmdResult { } /// MinMaxBounds.FloatDegrees.fromReader (no swap check). pub fn read_float_bounds(reader: &mut Reader) -> CmdResult<(Option, Option)> { - read_bounds(reader, |s| java_parse_double(s).map(|v| v as f32), "parsing.float.invalid") + read_bounds( + reader, + |s| java_parse_double(s).map(|v| v as f32), + "parsing.float.invalid", + ) } /// Integer.parseInt over number characters. pub fn java_parse_int(s: &str) -> Option { @@ -886,7 +890,12 @@ fn java_split(s: &str) -> Vec<&str> { } /// SharedSuggestionProvider.suggestCoordinates / suggest2DCoordinates: the /// candidates `ty` parses completely. -fn suggest_coordinates(builder: &mut SuggestionsBuilder, reg: &Registries, ty: &ArgType, relevant: bool) { +fn suggest_coordinates( + builder: &mut SuggestionsBuilder, + reg: &Registries, + ty: &ArgType, + relevant: bool, +) { let remaining = builder.remaining().to_owned(); let three = matches!(ty, ArgType::BlockPos | ArgType::Vec3 { .. }); let coords: [String; 3] = if remaining.starts_with('^') { @@ -903,7 +912,11 @@ fn suggest_coordinates(builder: &mut SuggestionsBuilder, reg: &Registries, ty: & let mut result: Vec = Vec::new(); let [x, y, z] = &coords; if remaining.is_empty() { - let full = if three { format!("{x} {y} {z}") } else { format!("{x} {z}") }; + let full = if three { + format!("{x} {y} {z}") + } else { + format!("{x} {z}") + }; if valid(&full) { result.push(x.clone()); if three { @@ -965,7 +978,11 @@ fn parse_nbt_path(reader: &mut Reader) -> CmdResult<()> { // StringReader.peek past the end (StringIndexOutOfBoundsException). let len = reader.string.encode_utf16().count(); let message = format!("Index {len} out of bounds for length {len}"); - return Err(CommandError::tr_at("command.exception", &[&message], reader)); + return Err(CommandError::tr_at( + "command.exception", + &[&message], + reader, + )); } match reader.peek() { '{' => { @@ -988,7 +1005,10 @@ fn parse_nbt_path(reader: &mut Reader) -> CmdResult<()> { _ => { let s = reader.cursor; while reader.can_read() - && !matches!(reader.peek(), ' ' | '"' | '\'' | '[' | ']' | '.' | '{' | '}') + && !matches!( + reader.peek(), + ' ' | '"' | '\'' | '[' | ']' | '.' | '{' | '}' + ) { reader.skip(); } @@ -1049,10 +1069,9 @@ fn particle_options(id: &str, t: &horizon_world::nbt::Tag) -> Result<(), String> { // withAlternative(BlockState.CODEC, the block id codec). let first = match state { - horizon_world::nbt::Tag::Compound(_) => super::codec::either( - "Not a string".into(), - no_key("id", state), - ), + horizon_world::nbt::Tag::Compound(_) => { + super::codec::either("Not a string".into(), no_key("id", state)) + } _ => not_map(state), }; let _ = snbt; @@ -1121,7 +1140,10 @@ impl ArgType { reader.cursor = start; return Err(CommandError::tr_at( "argument.double.low", - &[&crate::snbt::java_double(*min), &crate::snbt::java_double(v)], + &[ + &crate::snbt::java_double(*min), + &crate::snbt::java_double(v), + ], reader, )); } @@ -1129,7 +1151,10 @@ impl ArgType { reader.cursor = start; return Err(CommandError::tr_at( "argument.double.big", - &[&crate::snbt::java_double(*max), &crate::snbt::java_double(v)], + &[ + &crate::snbt::java_double(*max), + &crate::snbt::java_double(v), + ], reader, )); } @@ -1146,10 +1171,7 @@ impl ArgType { // MessageArgument.Message.parseText. let len = reader.remaining().encode_utf16().count(); if len > 256 { - return Err(CommandError::tr( - "argument.message.too_long", - &[&len, &256], - )); + return Err(CommandError::tr("argument.message.too_long", &[&len, &256])); } let s = reader.remaining().to_owned(); if reg.permission >= 2 { @@ -1329,7 +1351,11 @@ impl ArgType { ArgType::HexColor => { let text = reader.read_unquoted_string(); if !matches!(text.len(), 3 | 6) { - return Err(CommandError::tr_at("argument.hexcolor.invalid", &[&text], reader)); + return Err(CommandError::tr_at( + "argument.hexcolor.invalid", + &[&text], + reader, + )); } // Integer.parseInt(s, begin, end, 16) per channel: a bad digit // escapes Brigadier as a dispatcher parse exception. @@ -1341,7 +1367,11 @@ impl ArgType { if let Some(i) = digits.find(|ch: char| !ch.is_ascii_hexdigit()) { let index = i + usize::from(signed); let message = format!("Error at index {index} in: \"{c}\""); - return Err(CommandError::tr_at("command.exception", &[&message], reader)); + return Err(CommandError::tr_at( + "command.exception", + &[&message], + reader, + )); } } let v = i64::from_str_radix(text, 16).unwrap_or(0); @@ -1361,7 +1391,10 @@ impl ArgType { .take_while(|c| c.is_ascii_hexdigit() || *c == '-') .map(char::len_utf8) .sum(); - match (run > 0).then(|| super::selector::java_uuid(&rest[..run])).flatten() { + match (run > 0) + .then(|| super::selector::java_uuid(&rest[..run])) + .flatten() + { Some(_) => { let text = rest[..run].to_owned(); reader.cursor += run; @@ -1391,7 +1424,11 @@ impl ArgType { let v = reader.read_float()?; let unit = reader.read_unquoted_string(); let Some(m) = time_unit(unit) else { - return Err(CommandError::tr_at("argument.time.invalid_unit", &[], reader)); + return Err(CommandError::tr_at( + "argument.time.invalid_unit", + &[], + reader, + )); }; // Math.round(float): floor(x + 0.5). let ticks = (v * m as f32 + 0.5).floor() as i32; @@ -1425,7 +1462,10 @@ impl ArgType { // ParserBasedArgument.withCodec: SNBT, then the codec (errors at the start). let tag = super::snbt::parse_tag_argument(reader)?; let (decoded, key) = if matches!(self, ArgType::Style) { - (super::component::decode_style(&tag), "argument.style.invalid") + ( + super::component::decode_style(&tag), + "argument.style.invalid", + ) } else { (super::component::decode(&tag), "argument.component.invalid") }; diff --git a/crates/horizon-client/src/command/block.rs b/crates/horizon-client/src/command/block.rs index 0656a7898..db38a6fbd 100644 --- a/crates/horizon-client/src/command/block.rs +++ b/crates/horizon-client/src/command/block.rs @@ -379,7 +379,8 @@ impl<'r, 'a> BlockParser<'r, 'a> { } let prefix = b.remaining_lower(); for (name, _) in definition { - if !self.properties.iter().any(|(n, _)| n == name) && name.starts_with(&prefix) { + if !self.properties.iter().any(|(n, _)| n == name) && name.starts_with(&prefix) + { b.suggest(format!("{name}=")); } } @@ -439,11 +440,7 @@ impl<'r, 'a> BlockParser<'r, 'a> { } /// BlockStateParser.parseForBlock / parseForTesting (the reader is rewound on errors). -pub fn parse( - reader: &mut Reader, - reg: &Registries, - for_testing: bool, -) -> CmdResult { +pub fn parse(reader: &mut Reader, reg: &Registries, for_testing: bool) -> CmdResult { let cursor = reader.cursor; let r = BlockParser::new(reader, reg, for_testing, true).parse(); if r.is_err() { diff --git a/crates/horizon-client/src/command/codec.rs b/crates/horizon-client/src/command/codec.rs index f0febe13a..783d26e30 100644 --- a/crates/horizon-client/src/command/codec.rs +++ b/crates/horizon-client/src/command/codec.rs @@ -86,10 +86,7 @@ fn provider_fields(id: &str, map: &Compound, t: &Tag) -> Result<(), String> { } } /// A holder list codec: a single element, a `#tag`, or a list. -fn element_or_list( - t: &Tag, - element: &dyn Fn(&Tag) -> Result<(), String>, -) -> Result<(), String> { +fn element_or_list(t: &Tag, element: &dyn Fn(&Tag) -> Result<(), String>) -> Result<(), String> { let first = match element(t) { Ok(()) => return Ok(()), Err(e) => e, @@ -179,7 +176,6 @@ pub fn resource_or_id(reader: &mut Reader, reg: &Registries, registry: &str) -> } reader.cursor = start; let tag = super::snbt::parse_tag_argument(reader)?; - decode(registry, &tag, reg).map_err(|m| { - CommandError::tr_at("argument.resource_or_id.failed_to_parse", &[&m], reader) - }) + decode(registry, &tag, reg) + .map_err(|m| CommandError::tr_at("argument.resource_or_id.failed_to_parse", &[&m], reader)) } diff --git a/crates/horizon-client/src/command/component.rs b/crates/horizon-client/src/command/component.rs index 114a90ccf..9bc0668d5 100644 --- a/crates/horizon-client/src/command/component.rs +++ b/crates/horizon-client/src/command/component.rs @@ -47,7 +47,11 @@ fn is_string(t: &Tag) -> bool { matches!(t, Tag::String(_)) } fn string(t: &Tag) -> R { - if is_string(t) { Ok(()) } else { err("Not a string") } + if is_string(t) { + Ok(()) + } else { + err("Not a string") + } } fn string_of(t: &Tag) -> Option { match t { @@ -131,9 +135,9 @@ pub fn identifier(t: &Tag) -> Result<(), String> { "Not a valid resource location: {s} Non [a-z0-9_.-] character in namespace of location: {ns}:{path}" )); } - let path_ok = path - .chars() - .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/')); + let path_ok = path.chars().all(|c| { + c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/') + }); if !path_ok { return Err(format!( "Not a valid resource location: {s} Non [a-z0-9/._-] character in path of location: {ns}:{path}" @@ -208,7 +212,13 @@ fn style_fields(map: &Compound) -> R { if let Some(c) = get(map, "color") { color(c)?; } - for key in ["bold", "italic", "underlined", "strikethrough", "obfuscated"] { + for key in [ + "bold", + "italic", + "underlined", + "strikethrough", + "obfuscated", + ] { if let Some(v) = get(map, key) && bool_value(v).is_err() { @@ -262,12 +272,13 @@ fn content(kind: &str, map: &Compound) -> bool { _ => false, }, "selector" => { - get(map, "selector").is_some_and(selector_string) && optional_component(map, "separator") + get(map, "selector").is_some_and(selector_string) + && optional_component(map, "separator") } "nbt" => { - let path_ok = get(map, "nbt").and_then(string_of).is_some_and(|p| { - crate::nbt_path::NbtPath::parse(&p).is_ok() - }); + let path_ok = get(map, "nbt") + .and_then(string_of) + .is_some_and(|p| crate::nbt_path::NbtPath::parse(&p).is_ok()); let source = if let Some(e) = get(map, "entity") { selector_string(e) } else if let Some(b) = get(map, "block") { @@ -336,10 +347,9 @@ fn full(t: &Tag) -> R { style_fields(map) } fn component(t: &Tag) -> R { - either( - either(string(t), || non_empty_list(t, &component)), - || full(t), - ) + either(either(string(t), || non_empty_list(t, &component)), || { + full(t) + }) } /// ComponentSerialization.CODEC.parse: the error message on failure. pub fn decode(t: &Tag) -> Result<(), String> { diff --git a/crates/horizon-client/src/command/item.rs b/crates/horizon-client/src/command/item.rs index 909b918fa..e0ed4a516 100644 --- a/crates/horizon-client/src/command/item.rs +++ b/crates/horizon-client/src/command/item.rs @@ -1,7 +1,9 @@ //! ItemParser (item stacks with components, `stone[damage=5]`) and //! ItemPredicateArgument (ComponentPredicateParser's packrat grammar: //! `#logs[count~1..|!damage]`), with vanilla's errors and suggestions. -use super::args::{ItemInput, Registries, is_id_char, parse_identifier, read_identifier, suggest_resources}; +use super::args::{ + ItemInput, Registries, is_id_char, parse_identifier, read_identifier, suggest_resources, +}; use super::codec::{either, is_number, not_map, snbt}; use super::packrat::{Grammar, Reason, State, Sugg, Term, Value, alt, ch, opt, seq}; use super::{CmdResult, CommandError, Reader, SuggestionsBuilder}; @@ -159,7 +161,10 @@ impl ItemState<'_, '_> { self.sugg = ISugg::Component; let ty = self.component_type()?; if visited.contains(&ty) { - return Err(CommandError::tr("arguments.item.component.repeated", &[&ty])); + return Err(CommandError::tr( + "arguments.item.component.repeated", + &[&ty], + )); } visited.push(ty); self.sugg = ISugg::Nothing; @@ -167,7 +172,10 @@ impl ItemState<'_, '_> { } else { let ty = self.component_type()?; if visited.contains(&ty) { - return Err(CommandError::tr("arguments.item.component.repeated", &[&ty])); + return Err(CommandError::tr( + "arguments.item.component.repeated", + &[&ty], + )); } visited.push(ty.clone()); self.sugg = ISugg::Assignment; @@ -401,10 +409,12 @@ fn predicate_grammar() -> Grammar { "type", alt(vec![element, seq(vec![ch('#'), Term::Cut, tag]), any]), |s| { - Some(IV::Type(match s.scope.get_any(&["element_type", "tag_type"]) { - Some(IV::Elem(t)) => Some(t), - _ => None, - })) + Some(IV::Type( + match s.scope.get_any(&["element_type", "tag_type"]) { + Some(IV::Elem(t)) => Some(t), + _ => None, + }, + )) }, ); g.put_term("any_type", ch('*'), |_| Some(IV::Unit)); @@ -415,7 +425,11 @@ fn predicate_grammar() -> Grammar { if r.ids("minecraft:item").iter().any(|i| i == id) { Ok(IV::Elem(TypeRes::Item(id.to_owned()))) } else { - Err(CommandError::tr_at("argument.item.id.invalid", &[&id], reader)) + Err(CommandError::tr_at( + "argument.item.id.invalid", + &[&id], + reader, + )) } }) }); @@ -426,7 +440,11 @@ fn predicate_grammar() -> Grammar { if r.tags("minecraft:item").iter().any(|i| i == id) { Ok(IV::Elem(TypeRes::Tag(id.to_owned()))) } else { - Err(CommandError::tr_at("arguments.item.tag.unknown", &[&id], reader)) + Err(CommandError::tr_at( + "arguments.item.tag.unknown", + &[&id], + reader, + )) } }) }); @@ -509,29 +527,49 @@ fn predicate_grammar() -> Grammar { if id == "minecraft:count" { return Ok(IV::Comp(id.to_owned())); } - let known = r.ids("minecraft:data_component_type").iter().any(|c| c == id); + let known = r + .ids("minecraft:data_component_type") + .iter() + .any(|c| c == id); if known && r.persistent_components.iter().any(|c| c == id) { Ok(IV::Comp(id.to_owned())) } else { - Err(CommandError::tr_at("arguments.item.component.unknown", &[&id], reader)) + Err(CommandError::tr_at( + "arguments.item.component.unknown", + &[&id], + reader, + )) } }) }); g.put_custom("predicate_type", move |s| { let r = reg(s); let mut list = vec!["minecraft:count".to_owned()]; - list.extend(r.ids("minecraft:data_component_predicate_type").iter().cloned()); + list.extend( + r.ids("minecraft:data_component_predicate_type") + .iter() + .cloned(), + ); lookup(s, id, Rc::new(list), &|id, reader| { if id == "minecraft:count" - || r.ids("minecraft:data_component_predicate_type").iter().any(|c| c == id) + || r.ids("minecraft:data_component_predicate_type") + .iter() + .any(|c| c == id) { return Ok(IV::Pred(id.to_owned())); } - if r.ids("minecraft:data_component_type").iter().any(|c| c == id) { + if r.ids("minecraft:data_component_type") + .iter() + .any(|c| c == id) + { // A component existence predicate (decodes Unit). return Ok(IV::Pred(format!("exists:{id}"))); } - Err(CommandError::tr_at("arguments.item.predicate.unknown", &[&id], reader)) + Err(CommandError::tr_at( + "arguments.item.predicate.unknown", + &[&id], + reader, + )) }) }); g.put_custom("tag", |s| super::snbt::rule_in(s, IV::Tag)); diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-client/src/command/mod.rs index f0c89fb01..e6931852a 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-client/src/command/mod.rs @@ -616,7 +616,8 @@ pub fn merge_suggestions(input: &str, list: Vec) -> (Range, Vec = Vec::with_capacity(out.len()); for s in out { - let pos = sorted.partition_point(|x| compare_suggestions(x, &s) != std::cmp::Ordering::Greater); + let pos = + sorted.partition_point(|x| compare_suggestions(x, &s) != std::cmp::Ordering::Greater); sorted.insert(pos, s); } ((start, end), sorted) @@ -644,7 +645,8 @@ impl Suggests { for id in ®.summonable { if args::resource_matches(&contents, id) { let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id)); - let name = crate::lang::get(&format!("entity.{ns}.{}", path.replace('/', "."))); + let name = + crate::lang::get(&format!("entity.{ns}.{}", path.replace('/', "."))); builder.suggest_tooltip(id.clone(), name); } } @@ -673,7 +675,9 @@ impl Suggests { .trigger_scores .iter() .filter(|(_, scores)| { - targets.iter().any(|t| scores.get(t).is_none_or(|locked| *locked)) + targets + .iter() + .any(|t| scores.get(t).is_none_or(|locked| *locked)) }) .map(|(o, _)| o.as_str()) .collect(); diff --git a/crates/horizon-client/src/command/packrat.rs b/crates/horizon-client/src/command/packrat.rs index 996f84291..42f42d9f4 100644 --- a/crates/horizon-client/src/command/packrat.rs +++ b/crates/horizon-client/src/command/packrat.rs @@ -94,13 +94,11 @@ impl Scope { let current = self.top_marker; let n = self.top_entry - self.top_marker; self.setup_new_frame(); - let mut source = current + 1; let mut target = self.top_entry; - for _ in 0..n { + for source in current + 1..current + 1 + n { target += 1; let key = self.stack[source].0; self.set(target, key, None); - source += 1; } self.top_entry = target; } @@ -139,11 +137,13 @@ impl Scope { } } pub fn get(&self, atom: Atom) -> Option { - self.value_index(&[atom]).and_then(|i| self.stack[i].1.clone()) + self.value_index(&[atom]) + .and_then(|i| self.stack[i].1.clone()) } /// Scope.getAny: the newest of several atoms. pub fn get_any(&self, atoms: &[Atom]) -> Option { - self.value_index(atoms).and_then(|i| self.stack[i].1.clone()) + self.value_index(atoms) + .and_then(|i| self.stack[i].1.clone()) } /// Whether the atom has an entry (even a null one). pub fn has(&self, atom: Atom) -> bool { @@ -385,7 +385,7 @@ impl<'g, V: Value> State<'g, V> { r } fn first_error(&self) -> CommandError { - for (_, reason) in &self.errors { + if let Some((_, reason)) = self.errors.first() { return match reason { Reason::Delayed(key, args) => { let args: Vec<&dyn std::fmt::Display> = diff --git a/crates/horizon-client/src/command/selector.rs b/crates/horizon-client/src/command/selector.rs index 6b65de823..eb4e637a4 100644 --- a/crates/horizon-client/src/command/selector.rs +++ b/crates/horizon-client/src/command/selector.rs @@ -143,7 +143,12 @@ pub fn java_uuid(name: &str) -> Option { Some((u128::from(msb) << 64) | u128::from(lsb)) } -fn rollback(reader: &mut Reader, start: usize, key: &str, args: &[&dyn std::fmt::Display]) -> CommandError { +fn rollback( + reader: &mut Reader, + start: usize, + key: &str, + args: &[&dyn std::fmt::Display], +) -> CommandError { reader.cursor = start; CommandError::tr_at(key, args, reader) } diff --git a/crates/horizon-client/src/command/snbt.rs b/crates/horizon-client/src/command/snbt.rs index 042f6daa1..05fe6d9bc 100644 --- a/crates/horizon-client/src/command/snbt.rs +++ b/crates/horizon-client/src/command/snbt.rs @@ -153,7 +153,9 @@ fn parse_small(s: &str, radix: u32, lo: i32, hi: i32) -> Result { } fn parse_unsigned_int(s: &str, radix: u32) -> Result { if s.starts_with('-') { - return Err(format!("Illegal leading minus sign on unsigned string {s}.")); + return Err(format!( + "Illegal leading minus sign on unsigned string {s}." + )); } let len = s.chars().count(); if len <= 5 || (radix == 10 && len <= 9) { @@ -168,7 +170,9 @@ fn parse_unsigned_int(s: &str, radix: u32) -> Result { } fn parse_unsigned_long(s: &str, radix: u32) -> Result { if s.starts_with('-') { - return Err(format!("Illegal leading minus sign on unsigned string {s}.")); + return Err(format!( + "Illegal leading minus sign on unsigned string {s}." + )); } let digits = s.strip_prefix('+').unwrap_or(s); match u64::from_str_radix(digits, radix) { @@ -338,7 +342,11 @@ pub fn grammar() -> Grammar { |s| s.scope.get("integer_suffix"), ); g.put_custom("binary_numeral", |s| { - number_run(s, |c| matches!(c, '0' | '1' | '_'), "snbt.parser.expected_binary_numeral") + number_run( + s, + |c| matches!(c, '0' | '1' | '_'), + "snbt.parser.expected_binary_numeral", + ) }); g.put_custom("decimal_numeral", |s| { number_run( @@ -394,7 +402,10 @@ pub fn grammar() -> Grammar { } else if let Some(h) = get_str(s, "hex_numeral") { (Base::Hex, h) } else { - (Base::Binary, get_str(s, "binary_numeral").unwrap_or_default()) + ( + Base::Binary, + get_str(s, "binary_numeral").unwrap_or_default(), + ) }; Some(SV::Int(IntLit { minus, @@ -408,8 +419,14 @@ pub fn grammar() -> Grammar { g.put_term( "float_type_suffix", alt(vec![ - seq(vec![chs('f', 'F'), Term::Marker("float_type_suffix", SV::Type(TypeSuffix::Float))]), - seq(vec![chs('d', 'D'), Term::Marker("float_type_suffix", SV::Type(TypeSuffix::Double))]), + seq(vec![ + chs('f', 'F'), + Term::Marker("float_type_suffix", SV::Type(TypeSuffix::Float)), + ]), + seq(vec![ + chs('d', 'D'), + Term::Marker("float_type_suffix", SV::Type(TypeSuffix::Double)), + ]), ]), |s| s.scope.get("float_type_suffix"), ); @@ -420,7 +437,10 @@ pub fn grammar() -> Grammar { seq(vec![chs('e', 'E'), opt(sign), decimal]), |s| { let minus = matches!(s.scope.get("sign"), Some(SV::Sign(true))); - Some(SV::Exp(minus, get_str(s, "decimal_numeral").unwrap_or_default())) + Some(SV::Exp( + minus, + get_str(s, "decimal_numeral").unwrap_or_default(), + )) }, ); let sign = g.named("sign"); @@ -470,7 +490,11 @@ pub fn grammar() -> Grammar { float_tag(&text, ty, s).map(SV::Tag) }, ); - for (name, n) in [("string_hex_2", 2), ("string_hex_4", 4), ("string_hex_8", 8)] { + for (name, n) in [ + ("string_hex_2", 2), + ("string_hex_4", 4), + ("string_hex_8", 8), + ] { g.put_custom(name, move |s| { greedy( s, @@ -521,7 +545,9 @@ pub fn grammar() -> Grammar { if let Some(SV::Str(plain)) = s.scope.get_any(&["string_escape_sequence"]) { return Some(SV::Str(plain)); } - if let Some(SV::Str(h)) = s.scope.get_any(&["string_hex_2", "string_hex_4", "string_hex_8"]) + if let Some(SV::Str(h)) = + s.scope + .get_any(&["string_hex_2", "string_hex_4", "string_hex_8"]) { let cp = u32::from_str_radix(&h, 16).unwrap_or(u32::MAX); if cp > 0x10ffff { @@ -531,7 +557,9 @@ pub fn grammar() -> Grammar { )); return None; } - return Some(SV::Str(char::from_u32(cp).unwrap_or('\u{fffd}').to_string())); + return Some(SV::Str( + char::from_u32(cp).unwrap_or('\u{fffd}').to_string(), + )); } // Character.codePointOf: Unicode names are not tabulated here. s.store_at_mark(delayed("snbt.parser.invalid_character_name")); @@ -663,7 +691,8 @@ pub fn grammar() -> Grammar { let qs = g.named("quoted_string_literal"); let uq = g.named("unquoted_string"); g.put_term("map_key", alt(vec![qs, uq]), |s| { - s.scope.get_any(&["quoted_string_literal", "unquoted_string"]) + s.scope + .get_any(&["quoted_string_literal", "unquoted_string"]) }); let key = g.named("map_key"); let lit = g.named("literal"); @@ -712,9 +741,18 @@ pub fn grammar() -> Grammar { g.put_term( "array_prefix", alt(vec![ - seq(vec![ch('B'), Term::Marker("array_prefix", SV::Prefix(ArrayPrefix::Byte))]), - seq(vec![ch('L'), Term::Marker("array_prefix", SV::Prefix(ArrayPrefix::Long))]), - seq(vec![ch('I'), Term::Marker("array_prefix", SV::Prefix(ArrayPrefix::Int))]), + seq(vec![ + ch('B'), + Term::Marker("array_prefix", SV::Prefix(ArrayPrefix::Byte)), + ]), + seq(vec![ + ch('L'), + Term::Marker("array_prefix", SV::Prefix(ArrayPrefix::Long)), + ]), + seq(vec![ + ch('I'), + Term::Marker("array_prefix", SV::Prefix(ArrayPrefix::Int)), + ]), ]), |s| s.scope.get("array_prefix"), ); @@ -890,7 +928,11 @@ thread_local! { pub fn parse_tag_argument(reader: &mut Reader) -> CmdResult { GRAMMAR.with(|g| match g.parse_for_commands(reader)? { SV::Tag(t) => Ok(t), - _ => Err(CommandError::tr_at("argument.nbt.expected.compound", &[], reader)), + _ => Err(CommandError::tr_at( + "argument.nbt.expected.compound", + &[], + reader, + )), }) } /// TagParser.parseCompoundAsArgument. diff --git a/crates/horizon-client/src/command/tests.rs b/crates/horizon-client/src/command/tests.rs index ed4fe4123..ea29da523 100644 --- a/crates/horizon-client/src/command/tests.rs +++ b/crates/horizon-client/src/command/tests.rs @@ -37,9 +37,18 @@ fn reg() -> Registries { }, ); }; - registry("minecraft:worldgen/biome", &["minecraft:desert", "minecraft:plains"]); - registry("minecraft:damage_type", &["minecraft:fall", "minecraft:magic"]); - registry("minecraft:attribute", &["minecraft:max_health", "minecraft:scale"]); + registry( + "minecraft:worldgen/biome", + &["minecraft:desert", "minecraft:plains"], + ); + registry( + "minecraft:damage_type", + &["minecraft:fall", "minecraft:magic"], + ); + registry( + "minecraft:attribute", + &["minecraft:max_health", "minecraft:scale"], + ); registry("minecraft:item_modifier", &["a:b"]); registry("minecraft:predicate", &["a:b"]); registry( @@ -54,7 +63,14 @@ fn reg() -> Registries { "minecraft:entity_type", &["minecraft:pig", "minecraft:player", "minecraft:zombie"], ); - registry("minecraft:item", &["minecraft:diamond", "minecraft:diamond_sword", "minecraft:stone"]); + registry( + "minecraft:item", + &[ + "minecraft:diamond", + "minecraft:diamond_sword", + "minecraft:stone", + ], + ); r } fn run(input: &str) -> CmdResult<(String, Vec)> { @@ -436,7 +452,10 @@ fn world_command_trees() { "particle minecraft:dust{color:[1.0,0.0,0.0],scale:2.0} ~ ~ ~ 0.1 0.1 0.1 0 10 force @a", "particle", ), - ("particle minecraft:block{block_state:\"minecraft:stone\"} ~ ~ ~", "particle"), + ( + "particle minecraft:block{block_state:\"minecraft:stone\"} ~ ~ ~", + "particle", + ), ("attribute @s minecraft:max_health get 2", "attribute.get"), ( "attribute @s minecraft:max_health base set 40", diff --git a/crates/horizon-client/src/command/tree_data.rs b/crates/horizon-client/src/command/tree_data.rs index 003c5c045..34ce17bea 100644 --- a/crates/horizon-client/src/command/tree_data.rs +++ b/crates/horizon-client/src/command/tree_data.rs @@ -52,7 +52,11 @@ pub fn register(d: &mut Dispatcher, root: usize) { d.requires(compute, GAMEMASTERS); context_sources(d, compute, &mut |d, node| { let f = d.literal(node, "float"); - let p = d.argument(f, "provider", ArgType::ResourceOrId("minecraft:context_float_provider")); + let p = d.argument( + f, + "provider", + ArgType::ResourceOrId("minecraft:context_float_provider"), + ); d.executes(p, "compute"); let scale = d.argument( p, @@ -64,7 +68,11 @@ pub fn register(d: &mut Dispatcher, root: usize) { ); d.executes(scale, "compute"); let i = d.literal(node, "integer"); - let p = d.argument(i, "provider", ArgType::ResourceOrId("minecraft:context_int_provider")); + let p = d.argument( + i, + "provider", + ArgType::ResourceOrId("minecraft:context_int_provider"), + ); d.executes(p, "compute"); }); diff --git a/crates/horizon-client/src/command/tree_execute.rs b/crates/horizon-client/src/command/tree_execute.rs index 1fd4e444b..53085410a 100644 --- a/crates/horizon-client/src/command/tree_execute.rs +++ b/crates/horizon-client/src/command/tree_execute.rs @@ -48,7 +48,11 @@ pub fn register(d: &mut Dispatcher, root: usize) { let t = d.argument(as_, "targets", ENTITIES); d.redirect(t, ex); let over = d.literal(positioned, "over"); - let hm = d.argument(over, "heightmap", ArgType::StrEnum(HEIGHTMAPS, "argument.enum.invalid")); + let hm = d.argument( + over, + "heightmap", + ArgType::StrEnum(HEIGHTMAPS, "argument.enum.invalid"), + ); d.redirect(hm, ex); let rotated = d.literal(ex, "rotated"); let rot = d.argument(rotated, "rot", ArgType::Rotation); @@ -179,7 +183,11 @@ fn conditionals(d: &mut Dispatcher, m: usize, ex: usize) { conditional(d, targets, ex); let predicate = d.literal(m, "predicate"); - let p = d.argument(predicate, "predicate", ArgType::ResourceOrId("minecraft:predicate")); + let p = d.argument( + predicate, + "predicate", + ArgType::ResourceOrId("minecraft:predicate"), + ); conditional(d, p, ex); let stopwatch = d.literal(m, "stopwatch"); diff --git a/crates/horizon-client/src/command/tree_misc.rs b/crates/horizon-client/src/command/tree_misc.rs index 221b1fe5d..a66fd5f37 100644 --- a/crates/horizon-client/src/command/tree_misc.rs +++ b/crates/horizon-client/src/command/tree_misc.rs @@ -169,7 +169,11 @@ fn item(d: &mut Dispatcher, root: usize) { d.argument(p, "targetPos", ArgType::BlockPos) }; let slot = d.argument(target, "slot", ArgType::SlotSource); - let modifier = d.argument(slot, "modifier", ArgType::ResourceOrId("minecraft:item_modifier")); + let modifier = d.argument( + slot, + "modifier", + ArgType::ResourceOrId("minecraft:item_modifier"), + ); d.executes(modifier, "item.modify"); } for mode in ["replace", "fill", "override"] { diff --git a/crates/horizon-client/src/command/tree_world.rs b/crates/horizon-client/src/command/tree_world.rs index 892275102..0bd2edd3b 100644 --- a/crates/horizon-client/src/command/tree_world.rs +++ b/crates/horizon-client/src/command/tree_world.rs @@ -56,19 +56,31 @@ pub fn register(d: &mut Dispatcher, root: usize) { let place = d.literal(root, "place"); d.requires(place, GAMEMASTERS); let feature = d.literal(place, "feature"); - let f = d.argument(feature, "feature", ArgType::ResourceOrId("minecraft:worldgen/feature")); + let f = d.argument( + feature, + "feature", + ArgType::ResourceOrId("minecraft:worldgen/feature"), + ); d.executes(f, "place.feature"); let pos = d.argument(f, "pos", ArgType::BlockPos); d.executes(pos, "place.feature"); let jigsaw = d.literal(place, "jigsaw"); - let pool = d.argument(jigsaw, "pool", ArgType::ResKey("minecraft:worldgen/template_pool")); + let pool = d.argument( + jigsaw, + "pool", + ArgType::ResKey("minecraft:worldgen/template_pool"), + ); let target = d.argument(pool, "target", ArgType::Id("none")); let depth = d.argument(target, "max_depth", ArgType::Integer { min: 1, max: 20 }); d.executes(depth, "place.jigsaw"); let position = d.argument(depth, "position", ArgType::BlockPos); d.executes(position, "place.jigsaw"); let structure = d.literal(place, "structure"); - let st = d.argument(structure, "structure", ArgType::ResKey("minecraft:worldgen/structure")); + let st = d.argument( + structure, + "structure", + ArgType::ResKey("minecraft:worldgen/structure"), + ); d.executes(st, "place.structure"); let pos = d.argument(st, "pos", ArgType::BlockPos); d.executes(pos, "place.structure"); @@ -89,7 +101,10 @@ pub fn register(d: &mut Dispatcher, root: usize) { let mirror = d.argument( rotation, "mirror", - ArgType::StrEnum(&["none", "left_right", "front_back"], "argument.enum.invalid"), + ArgType::StrEnum( + &["none", "left_right", "front_back"], + "argument.enum.invalid", + ), ); d.executes(mirror, "place"); let integrity = d.argument(mirror, "integrity", ArgType::Float { min: 0.0, max: 1.0 }); @@ -160,7 +175,14 @@ fn rotate_swing(d: &mut Dispatcher, root: usize) { for hand in ["mainhand", "offhand"] { let h = d.literal(targets, hand); d.executes(h, "swing"); - let animation = d.argument(h, "animation", ArgType::StrEnum(&["none", "whack", "stab"], "argument.swing_animation.invalid")); + let animation = d.argument( + h, + "animation", + ArgType::StrEnum( + &["none", "whack", "stab"], + "argument.swing_animation.invalid", + ), + ); d.executes(animation, "swing"); let duration = d.argument(animation, "duration", ArgType::Time { min: 1 }); d.executes(duration, "swing"); @@ -285,7 +307,11 @@ fn fillbiome(d: &mut Dispatcher, root: usize) { let biome = d.argument(to, "biome", ArgType::Res("minecraft:worldgen/biome")); d.executes(biome, "fillbiome"); let replace = d.literal(biome, "replace"); - let filter = d.argument(replace, "filter", ArgType::ResOrTag("minecraft:worldgen/biome")); + let filter = d.argument( + replace, + "filter", + ArgType::ResOrTag("minecraft:worldgen/biome"), + ); d.executes(filter, "fillbiome"); } @@ -357,7 +383,11 @@ fn loot(d: &mut Dispatcher, root: usize) { // Sources. for t in targets { let fish = d.literal(t, "fish"); - let table = d.argument(fish, "loot_table", ArgType::ResourceOrId("minecraft:loot_table")); + let table = d.argument( + fish, + "loot_table", + ArgType::ResourceOrId("minecraft:loot_table"), + ); let pos = d.argument(table, "pos", ArgType::BlockPos); d.executes(pos, "loot.fish"); for hand in ["mainhand", "offhand"] { @@ -367,7 +397,11 @@ fn loot(d: &mut Dispatcher, root: usize) { let tool = d.argument(pos, "tool", ArgType::Item); d.executes(tool, "loot.fish"); let l = d.literal(t, "loot"); - let lt = d.argument(l, "loot_table", ArgType::ResourceOrId("minecraft:loot_table")); + let lt = d.argument( + l, + "loot_table", + ArgType::ResourceOrId("minecraft:loot_table"), + ); d.executes(lt, "loot.loot"); let kill = d.literal(t, "kill"); let target = d.argument(kill, "target", ENTITY); diff --git a/crates/horizon-client/src/command/vanilla.rs b/crates/horizon-client/src/command/vanilla.rs index 2c982e470..495f36966 100644 --- a/crates/horizon-client/src/command/vanilla.rs +++ b/crates/horizon-client/src/command/vanilla.rs @@ -322,13 +322,21 @@ pub fn build_with(dev: bool) -> Dispatcher { let locate = d.literal(root, "locate"); d.requires(locate, GAMEMASTERS); let s = d.literal(locate, "structure"); - let a = d.argument(s, "structure", ArgType::ResOrTagKey("minecraft:worldgen/structure")); + let a = d.argument( + s, + "structure", + ArgType::ResOrTagKey("minecraft:worldgen/structure"), + ); d.executes(a, "locate.structure"); let b = d.literal(locate, "biome"); let a = d.argument(b, "biome", ArgType::ResOrTag("minecraft:worldgen/biome")); d.executes(a, "locate.biome"); let p = d.literal(locate, "poi"); - let a = d.argument(p, "poi", ArgType::ResOrTag("minecraft:point_of_interest_type")); + let a = d.argument( + p, + "poi", + ArgType::ResOrTag("minecraft:point_of_interest_type"), + ); d.executes(a, "locate.poi"); if dev { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index aa7bb7cd5..e83908171 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1304,7 +1304,10 @@ impl Game<'_> { .sections .iter() .enumerate() - .filter(|(_, s)| s.blocks.maybe_has(|id| facts.get(BlockStateId(id)).random_ticks)) + .filter(|(_, s)| { + s.blocks + .maybe_has(|id| facts.get(BlockStateId(id)).random_ticks) + }) .map(|(i, _)| MIN_Y + i as i32 * 16) .collect(); ticking.push((x, z, sections)); @@ -1692,7 +1695,8 @@ impl Game<'_> { // FallingBlockEntity.tick: off the ground, it gives up after 600 // ticks (100 outside the world) and drops itself as an item. let y = next.y.floor() as i32; - let outside = y <= horizon_client::chunk::MIN_Y || y >= horizon_client::chunk::MIN_Y + 384; + let outside = + y <= horizon_client::chunk::MIN_Y || y >= horizon_client::chunk::MIN_Y + 384; if !solid && (f.age > 100 && outside || f.age > 600) { if f.drop_item && entity_drops { dropped.push((f.state, next)); @@ -7204,7 +7208,8 @@ impl Game<'_> { } } MouseButton::Right => { - self.toggles.button(3, pressed, false, self.settings.toggle_use); + self.toggles + .button(3, pressed, false, self.settings.toggle_use); self.right = self.toggles.is_down(3); if pressed { self.use_item()?; diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index de1bbedb7..50d0d1aab 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -812,7 +812,8 @@ impl Game<'_> { fn drop_death_loot(&mut self, m: &mut Mob, by_player: bool, consumed: bool, pos: [f64; 3]) { use horizon_client::mobs::{DamageKind, Who, drops}; use horizon_world::loot::{LootDamage, LootEntity}; - let Some(loot) = horizon_client::structure_blocks::loot_data(&self.options.resources) else { + let Some(loot) = horizon_client::structure_blocks::loot_data(&self.options.resources) + else { return; }; let player = || { @@ -2732,7 +2733,10 @@ impl Game<'_> { pub(super) fn portal_spawn(&mut self, pos: [i32; 3]) { // ChunkMap.anyPlayerCloseEnoughForSpawning: a non-spectator within 128 // blocks of the chunk centre. - let centre = [f64::from((pos[0] >> 4) * 16 + 8), f64::from((pos[2] >> 4) * 16 + 8)]; + let centre = [ + f64::from((pos[0] >> 4) * 16 + 8), + f64::from((pos[2] >> 4) * 16 + 8), + ]; let spectator = self.spectator(); let Some(close) = self.player.as_ref().filter(|_| !spectator).map(|p| { let (dx, dz) = (p.position.x - centre[0], p.position.z - centre[1]); @@ -2744,7 +2748,9 @@ impl Game<'_> { return; } let mut y = pos[1]; - while &*self.res.facts.get(self.world.block(pos[0], y, pos[2])).name == "minecraft:nether_portal" { + while &*self.res.facts.get(self.world.block(pos[0], y, pos[2])).name + == "minecraft:nether_portal" + { y -= 1; } // isValidSpawn: a sturdy top face (portal frames emit no light). @@ -2752,7 +2758,11 @@ impl Game<'_> { if below.sturdy_full & (1 << 1) == 0 { return; } - let at = [f64::from(pos[0]) + 0.5, f64::from(y + 1), f64::from(pos[2]) + 0.5]; + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(y + 1), + f64::from(pos[2]) + 0.5, + ]; let _ = self.spawn_mob("minecraft:zombified_piglin", at, false); } } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 8fb31db45..ca54a3a91 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -186,7 +186,11 @@ fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> { if e.chested { meta.push((19, serializer::BOOLEAN, Value::Bool(true))); } - meta.push((20, serializer::INT, Value::Int(i32::from(e.variant2.max(1))))); + meta.push(( + 20, + serializer::INT, + Value::Int(i32::from(e.variant2.max(1))), + )); if e.variant != 0 { meta.push((21, serializer::INT, Value::Int(i32::from(e.variant)))); } @@ -205,7 +209,11 @@ fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> { ) { let index = if kind == "minecraft:villager" { 19 } else { 20 }; let level = i32::from(e.variant3.max(1)); - meta.push((index, serializer::VILLAGER_DATA, Value::Ids(vec![t, p, level]))); + meta.push(( + index, + serializer::VILLAGER_DATA, + Value::Ids(vec![t, p, level]), + )); } } // AbstractCubeMob.ID_SIZE. diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index ef66e1d96..e6c73a13b 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -605,7 +605,12 @@ impl Game<'_> { let Some(slot) = slot else { self.dispenser_event(1001, key, 0); if !dropper { - self.post_block_game_event("minecraft:block_activate", [pos.x, pos.y, pos.z], None, Some(state)); + self.post_block_game_event( + "minecraft:block_activate", + [pos.x, pos.y, pos.z], + None, + Some(state), + ); } return Ok(()); }; diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index 9fb26ec83..9f6ce609b 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -462,8 +462,8 @@ impl Game<'_> { }; let m = &self.mobs[i]; let atlas = &self.res.atlas; - 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); + let hearts = horizon_client::hud_layout::vehicle_max_hearts(m.attrs.max_health); + let draws = horizon_client::hud_layout::vehicle_health(w, h, hearts, m.health); horizon_client::hud_layout::paint(batch, atlas, &draws); if m.extra.saddled { let x = (w / 2 - 91) as f32; diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index 2f1e36602..cd387342f 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -3,16 +3,16 @@ //! `getMaxZoom`), and the local player drawn as a model: in third person //! and in the inventory (`InventoryScreen.extractEntityInInventoryFollowsMouse`). use super::{Game, Screen}; -use horizon_client::{ - hud::HudBatch, - mobs::{Anim, Brain, Mob, MobType}, - pose::Pose, -}; use horizon_client::{ blocks::BlockFacts, camera::{CameraEntity, LivingCamera}, collisions::SceneCollisions, }; +use horizon_client::{ + hud::HudBatch, + mobs::{Anim, Brain, Mob, MobType}, + pose::Pose, +}; use horizon_core::{ geometry::{Aabb, ShapeOp, Vec3, VoxelShape}, position::BlockPos, @@ -272,10 +272,14 @@ impl Game<'_> { 4096, ) .ok()?; - (!hit.miss).then(|| [hit.hit.location.x, hit.hit.location.y, hit.hit.location.z]) + (!hit.miss).then_some([hit.hit.location.x, hit.hit.location.y, hit.hit.location.z]) }); self.view = view; - Some((glam::DVec3::from_array(view.position), view.y_rot, view.x_rot)) + Some(( + glam::DVec3::from_array(view.position), + view.y_rot, + view.x_rot, + )) } /// Keep the player's model in step with the player (`LivingEntity.tick` /// body turning, `WalkAnimationState`, the swing and the pose). diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 95470203d..1a1095bd4 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -490,7 +490,8 @@ impl Game<'_> { if !open { self.recipe_ui.overlay = None; } - self.audio.play("minecraft:ui.button.click", None, 0.25, 1.0); + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); return true; } if !self.book_open(book_type) || self.spectator() { @@ -518,12 +519,14 @@ impl Game<'_> { if self.recipe_ui.page + 1 < pages && inside(cursor, xo + 93.0, yo + 137.0, 12.0, 17.0) { self.recipe_ui.page += 1; - self.audio.play("minecraft:ui.button.click", None, 0.25, 1.0); + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); return true; } if self.recipe_ui.page > 0 && inside(cursor, xo + 38.0, yo + 137.0, 12.0, 17.0) { self.recipe_ui.page -= 1; - self.audio.play("minecraft:ui.button.click", None, 0.25, 1.0); + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); return true; } } @@ -570,7 +573,8 @@ impl Game<'_> { let filtering = !self.book_filtering(book_type); self.level.recipe_book.filtering[book_type.index()] = filtering; self.recipe_ui.page = 0; - self.audio.play("minecraft:ui.button.click", None, 0.25, 1.0); + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); return true; } // Tabs. @@ -581,7 +585,8 @@ impl Game<'_> { self.recipe_ui.tab = Some(tab); self.recipe_ui.page = 0; } - self.audio.play("minecraft:ui.button.click", None, 0.25, 1.0); + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); return true; } } diff --git a/crates/horizon-client/src/game/tnt.rs b/crates/horizon-client/src/game/tnt.rs index d8435da21..71b88cc9b 100644 --- a/crates/horizon-client/src/game/tnt.rs +++ b/crates/horizon-client/src/game/tnt.rs @@ -48,7 +48,11 @@ impl Game<'_> { } else { self.audio.play( "minecraft:entity.tnt.primed", - Some([f64::from(pos.x) + 0.5, f64::from(pos.y), f64::from(pos.z) + 0.5]), + Some([ + f64::from(pos.x) + 0.5, + f64::from(pos.y), + f64::from(pos.z) + 0.5, + ]), 1.0, 1.0, ); diff --git a/crates/horizon-client/src/lan/command_suggestions.rs b/crates/horizon-client/src/lan/command_suggestions.rs index 1afb299d4..e55e6ef92 100644 --- a/crates/horizon-client/src/lan/command_suggestions.rs +++ b/crates/horizon-client/src/lan/command_suggestions.rs @@ -4,77 +4,224 @@ //! VanillaCommandSuggestionsExporter; do not edit by hand. pub const SUGGESTIONS: &[(&str, &str)] = &[ - ("advancement grant targets only advancement criterion", "minecraft:ask_server"), - ("advancement revoke targets only advancement criterion", "minecraft:ask_server"), - ("attribute target attribute modifier remove id", "minecraft:ask_server"), - ("attribute target attribute modifier value get id", "minecraft:ask_server"), + ( + "advancement grant targets only advancement criterion", + "minecraft:ask_server", + ), + ( + "advancement revoke targets only advancement criterion", + "minecraft:ask_server", + ), + ( + "attribute target attribute modifier remove id", + "minecraft:ask_server", + ), + ( + "attribute target attribute modifier value get id", + "minecraft:ask_server", + ), ("bossbar get id", "minecraft:ask_server"), ("bossbar remove id", "minecraft:ask_server"), ("bossbar set id", "minecraft:ask_server"), ("data get storage target", "minecraft:ask_server"), ("data merge storage target", "minecraft:ask_server"), - ("data modify block target targetPath append from storage source", "minecraft:ask_server"), - ("data modify block target targetPath append string storage source", "minecraft:ask_server"), - ("data modify block target targetPath insert index from storage source", "minecraft:ask_server"), - ("data modify block target targetPath insert index string storage source", "minecraft:ask_server"), - ("data modify block target targetPath merge from storage source", "minecraft:ask_server"), - ("data modify block target targetPath merge string storage source", "minecraft:ask_server"), - ("data modify block target targetPath prepend from storage source", "minecraft:ask_server"), - ("data modify block target targetPath prepend string storage source", "minecraft:ask_server"), - ("data modify block target targetPath set from storage source", "minecraft:ask_server"), - ("data modify block target targetPath set string storage source", "minecraft:ask_server"), - ("data modify entity target targetPath append from storage source", "minecraft:ask_server"), - ("data modify entity target targetPath append string storage source", "minecraft:ask_server"), - ("data modify entity target targetPath insert index from storage source", "minecraft:ask_server"), - ("data modify entity target targetPath insert index string storage source", "minecraft:ask_server"), - ("data modify entity target targetPath merge from storage source", "minecraft:ask_server"), - ("data modify entity target targetPath merge string storage source", "minecraft:ask_server"), - ("data modify entity target targetPath prepend from storage source", "minecraft:ask_server"), - ("data modify entity target targetPath prepend string storage source", "minecraft:ask_server"), - ("data modify entity target targetPath set from storage source", "minecraft:ask_server"), - ("data modify entity target targetPath set string storage source", "minecraft:ask_server"), + ( + "data modify block target targetPath append from storage source", + "minecraft:ask_server", + ), + ( + "data modify block target targetPath append string storage source", + "minecraft:ask_server", + ), + ( + "data modify block target targetPath insert index from storage source", + "minecraft:ask_server", + ), + ( + "data modify block target targetPath insert index string storage source", + "minecraft:ask_server", + ), + ( + "data modify block target targetPath merge from storage source", + "minecraft:ask_server", + ), + ( + "data modify block target targetPath merge string storage source", + "minecraft:ask_server", + ), + ( + "data modify block target targetPath prepend from storage source", + "minecraft:ask_server", + ), + ( + "data modify block target targetPath prepend string storage source", + "minecraft:ask_server", + ), + ( + "data modify block target targetPath set from storage source", + "minecraft:ask_server", + ), + ( + "data modify block target targetPath set string storage source", + "minecraft:ask_server", + ), + ( + "data modify entity target targetPath append from storage source", + "minecraft:ask_server", + ), + ( + "data modify entity target targetPath append string storage source", + "minecraft:ask_server", + ), + ( + "data modify entity target targetPath insert index from storage source", + "minecraft:ask_server", + ), + ( + "data modify entity target targetPath insert index string storage source", + "minecraft:ask_server", + ), + ( + "data modify entity target targetPath merge from storage source", + "minecraft:ask_server", + ), + ( + "data modify entity target targetPath merge string storage source", + "minecraft:ask_server", + ), + ( + "data modify entity target targetPath prepend from storage source", + "minecraft:ask_server", + ), + ( + "data modify entity target targetPath prepend string storage source", + "minecraft:ask_server", + ), + ( + "data modify entity target targetPath set from storage source", + "minecraft:ask_server", + ), + ( + "data modify entity target targetPath set string storage source", + "minecraft:ask_server", + ), ("data modify storage target", "minecraft:ask_server"), - ("data modify storage target targetPath append from storage source", "minecraft:ask_server"), - ("data modify storage target targetPath append string storage source", "minecraft:ask_server"), - ("data modify storage target targetPath insert index from storage source", "minecraft:ask_server"), - ("data modify storage target targetPath insert index string storage source", "minecraft:ask_server"), - ("data modify storage target targetPath merge from storage source", "minecraft:ask_server"), - ("data modify storage target targetPath merge string storage source", "minecraft:ask_server"), - ("data modify storage target targetPath prepend from storage source", "minecraft:ask_server"), - ("data modify storage target targetPath prepend string storage source", "minecraft:ask_server"), - ("data modify storage target targetPath set from storage source", "minecraft:ask_server"), - ("data modify storage target targetPath set string storage source", "minecraft:ask_server"), + ( + "data modify storage target targetPath append from storage source", + "minecraft:ask_server", + ), + ( + "data modify storage target targetPath append string storage source", + "minecraft:ask_server", + ), + ( + "data modify storage target targetPath insert index from storage source", + "minecraft:ask_server", + ), + ( + "data modify storage target targetPath insert index string storage source", + "minecraft:ask_server", + ), + ( + "data modify storage target targetPath merge from storage source", + "minecraft:ask_server", + ), + ( + "data modify storage target targetPath merge string storage source", + "minecraft:ask_server", + ), + ( + "data modify storage target targetPath prepend from storage source", + "minecraft:ask_server", + ), + ( + "data modify storage target targetPath prepend string storage source", + "minecraft:ask_server", + ), + ( + "data modify storage target targetPath set from storage source", + "minecraft:ask_server", + ), + ( + "data modify storage target targetPath set string storage source", + "minecraft:ask_server", + ), ("data remove storage target", "minecraft:ask_server"), ("datapack disable name", "minecraft:ask_server"), ("datapack enable name", "minecraft:ask_server"), - ("datapack enable name after existing", "minecraft:ask_server"), - ("datapack enable name before existing", "minecraft:ask_server"), + ( + "datapack enable name after existing", + "minecraft:ask_server", + ), + ( + "datapack enable name before existing", + "minecraft:ask_server", + ), ("debug function name", "minecraft:ask_server"), ("deop targets", "minecraft:ask_server"), ("execute if data storage source", "minecraft:ask_server"), ("execute if function name", "minecraft:ask_server"), ("execute if score target", "minecraft:ask_server"), - ("execute if score target targetObjective < source", "minecraft:ask_server"), - ("execute if score target targetObjective <= source", "minecraft:ask_server"), - ("execute if score target targetObjective = source", "minecraft:ask_server"), - ("execute if score target targetObjective > source", "minecraft:ask_server"), - ("execute if score target targetObjective >= source", "minecraft:ask_server"), + ( + "execute if score target targetObjective < source", + "minecraft:ask_server", + ), + ( + "execute if score target targetObjective <= source", + "minecraft:ask_server", + ), + ( + "execute if score target targetObjective = source", + "minecraft:ask_server", + ), + ( + "execute if score target targetObjective > source", + "minecraft:ask_server", + ), + ( + "execute if score target targetObjective >= source", + "minecraft:ask_server", + ), ("execute if stopwatch id", "minecraft:ask_server"), ("execute store result bossbar id", "minecraft:ask_server"), ("execute store result score targets", "minecraft:ask_server"), - ("execute store result storage target", "minecraft:ask_server"), + ( + "execute store result storage target", + "minecraft:ask_server", + ), ("execute store success bossbar id", "minecraft:ask_server"), - ("execute store success score targets", "minecraft:ask_server"), - ("execute store success storage target", "minecraft:ask_server"), + ( + "execute store success score targets", + "minecraft:ask_server", + ), + ( + "execute store success storage target", + "minecraft:ask_server", + ), ("execute summon entity", "minecraft:summonable_entities"), ("execute unless data storage source", "minecraft:ask_server"), ("execute unless function name", "minecraft:ask_server"), ("execute unless score target", "minecraft:ask_server"), - ("execute unless score target targetObjective < source", "minecraft:ask_server"), - ("execute unless score target targetObjective <= source", "minecraft:ask_server"), - ("execute unless score target targetObjective = source", "minecraft:ask_server"), - ("execute unless score target targetObjective > source", "minecraft:ask_server"), - ("execute unless score target targetObjective >= source", "minecraft:ask_server"), + ( + "execute unless score target targetObjective < source", + "minecraft:ask_server", + ), + ( + "execute unless score target targetObjective <= source", + "minecraft:ask_server", + ), + ( + "execute unless score target targetObjective = source", + "minecraft:ask_server", + ), + ( + "execute unless score target targetObjective > source", + "minecraft:ask_server", + ), + ( + "execute unless score target targetObjective >= source", + "minecraft:ask_server", + ), ("execute unless stopwatch id", "minecraft:ask_server"), ("function name", "minecraft:ask_server"), ("function name with storage source", "minecraft:ask_server"), @@ -83,37 +230,88 @@ pub const SUGGESTIONS: &[(&str, &str)] = &[ ("pardon-ip target", "minecraft:ask_server"), ("place template template", "minecraft:ask_server"), ("playsound sound", "minecraft:available_sounds"), - ("posteffect add targets posteffect", "minecraft:post_effects"), - ("posteffect remove targets posteffect", "minecraft:post_effects"), + ( + "posteffect add targets posteffect", + "minecraft:post_effects", + ), + ( + "posteffect remove targets posteffect", + "minecraft:post_effects", + ), ("random reset sequence", "minecraft:ask_server"), ("random roll range sequence", "minecraft:ask_server"), ("random value range sequence", "minecraft:ask_server"), ("schedule clear function", "minecraft:ask_server"), ("schedule function function", "minecraft:ask_server"), ("scoreboard players add targets", "minecraft:ask_server"), - ("scoreboard players display name targets", "minecraft:ask_server"), - ("scoreboard players display numberformat targets", "minecraft:ask_server"), + ( + "scoreboard players display name targets", + "minecraft:ask_server", + ), + ( + "scoreboard players display numberformat targets", + "minecraft:ask_server", + ), ("scoreboard players enable targets", "minecraft:ask_server"), - ("scoreboard players enable targets objective", "minecraft:ask_server"), + ( + "scoreboard players enable targets objective", + "minecraft:ask_server", + ), ("scoreboard players get target", "minecraft:ask_server"), ("scoreboard players list target", "minecraft:ask_server"), - ("scoreboard players operation targets", "minecraft:ask_server"), - ("scoreboard players operation targets targetObjective operation source", "minecraft:ask_server"), + ( + "scoreboard players operation targets", + "minecraft:ask_server", + ), + ( + "scoreboard players operation targets targetObjective operation source", + "minecraft:ask_server", + ), ("scoreboard players remove targets", "minecraft:ask_server"), ("scoreboard players reset targets", "minecraft:ask_server"), ("scoreboard players set targets", "minecraft:ask_server"), ("stopsound targets * sound", "minecraft:available_sounds"), - ("stopsound targets ambient sound", "minecraft:available_sounds"), - ("stopsound targets block sound", "minecraft:available_sounds"), - ("stopsound targets hostile sound", "minecraft:available_sounds"), - ("stopsound targets master sound", "minecraft:available_sounds"), - ("stopsound targets music sound", "minecraft:available_sounds"), - ("stopsound targets neutral sound", "minecraft:available_sounds"), - ("stopsound targets player sound", "minecraft:available_sounds"), - ("stopsound targets record sound", "minecraft:available_sounds"), + ( + "stopsound targets ambient sound", + "minecraft:available_sounds", + ), + ( + "stopsound targets block sound", + "minecraft:available_sounds", + ), + ( + "stopsound targets hostile sound", + "minecraft:available_sounds", + ), + ( + "stopsound targets master sound", + "minecraft:available_sounds", + ), + ( + "stopsound targets music sound", + "minecraft:available_sounds", + ), + ( + "stopsound targets neutral sound", + "minecraft:available_sounds", + ), + ( + "stopsound targets player sound", + "minecraft:available_sounds", + ), + ( + "stopsound targets record sound", + "minecraft:available_sounds", + ), ("stopsound targets ui sound", "minecraft:available_sounds"), - ("stopsound targets voice sound", "minecraft:available_sounds"), - ("stopsound targets weather sound", "minecraft:available_sounds"), + ( + "stopsound targets voice sound", + "minecraft:available_sounds", + ), + ( + "stopsound targets weather sound", + "minecraft:available_sounds", + ), ("stopwatch query id", "minecraft:ask_server"), ("stopwatch remove id", "minecraft:ask_server"), ("stopwatch restart id", "minecraft:ask_server"), diff --git a/crates/horizon-client/src/lan/commands.rs b/crates/horizon-client/src/lan/commands.rs index dd3d36fe9..26def5d7e 100644 --- a/crates/horizon-client/src/lan/commands.rs +++ b/crates/horizon-client/src/lan/commands.rs @@ -172,13 +172,16 @@ fn fill( names.sort(); for name in names { let child = &children[name]; - let required = if path.is_empty() && !dedicated && OPEN_WHEN_INTEGRATED.contains(&name.as_str()) { - 0 - } else { - required_level(child) - }; + let required = + if path.is_empty() && !dedicated && OPEN_WHEN_INTEGRATED.contains(&name.as_str()) { + 0 + } else { + required_level(child) + }; if required > level - || path.len() == 1 && path[0] == "gamerule" && EXPERIMENTAL_RULES.contains(&name.as_str()) + || path.len() == 1 + && path[0] == "gamerule" + && EXPERIMENTAL_RULES.contains(&name.as_str()) { continue; } @@ -212,7 +215,16 @@ fn fill( }); nodes[target].children.push(index); paths.insert(path.clone(), index); - fill(child, index, path, level, dedicated, suggestions, nodes, paths); + fill( + child, + index, + path, + level, + dedicated, + suggestions, + nodes, + paths, + ); path.pop(); } } @@ -331,7 +343,10 @@ mod tests { assert_eq!(guest.nodes[2].redirect, Some(1)); let op = tree.packet(2, true, &builtin); let names: Vec<_> = op.nodes.iter().map(|n| n.name.as_str()).collect(); - assert_eq!(names, ["", "me", "say", "stop", "tell", "action", "message"]); + assert_eq!( + names, + ["", "me", "say", "stop", "tell", "action", "message"] + ); assert!(op.nodes[2].restricted); } } diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index 179a75a82..3b926b372 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -188,17 +188,21 @@ impl Tracker { }) } } else if rotate { - Some(play::Clientbound::MoveEntityRot(MoveEntityRot(MoveEntity { - id: e.id, - delta: None, - rotation: Some((rotation.1, rotation.0)), - on_ground: e.on_ground, - }))) + Some(play::Clientbound::MoveEntityRot(MoveEntityRot( + MoveEntity { + id: e.id, + delta: None, + rotation: Some((rotation.1, rotation.0)), + on_ground: e.on_ground, + }, + ))) } else { None }; if s.track_deltas { - let diff: f64 = (0..3).map(|k| (e.velocity[k] - s.velocity[k]).powi(2)).sum(); + let diff: f64 = (0..3) + .map(|k| (e.velocity[k] - s.velocity[k]).powi(2)) + .sum(); let still = e.velocity.iter().all(|v| *v == 0.0); if diff > 1.0e-7 || diff > 0.0 && still { s.velocity = e.velocity; diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index dd8126698..ed9771043 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -12,12 +12,12 @@ use super::{ guest::{Guest, stack_to_network}, }; use crate::{items::ItemStack, world::World}; +use horizon_protocol::ids::play::clientbound as ids; use horizon_protocol::{ entity_data::{Value, serializer}, packets::play::{self, Clientbound as C, Serverbound as S}, text::{literal, translatable}, }; -use horizon_protocol::ids::play::clientbound as ids; use horizon_world::nbt::{JavaString, Tag}; use std::sync::{Arc, atomic::Ordering}; @@ -440,7 +440,6 @@ impl Hub { g.send(&C::Commands(packet)); } - /// ServerGamePacketListenerImpl.teleport: move the client and wait for its confirmation. pub fn teleport(&mut self, i: usize, position: Option<[f64; 3]>) { let g = &mut self.guests[i]; diff --git a/crates/horizon-client/src/lan/tracking.rs b/crates/horizon-client/src/lan/tracking.rs index d0853507f..61b471de6 100644 --- a/crates/horizon-client/src/lan/tracking.rs +++ b/crates/horizon-client/src/lan/tracking.rs @@ -172,5 +172,7 @@ pub const TRACKING: &[(&str, u8, u32, bool)] = &[ pub fn settings(kind: &str) -> (u8, u32, bool) { TRACKING .binary_search_by(|row| row.0.cmp(kind)) - .map_or((5, 3, true), |i| (TRACKING[i].1, TRACKING[i].2, TRACKING[i].3)) + .map_or((5, 3, true), |i| { + (TRACKING[i].1, TRACKING[i].2, TRACKING[i].3) + }) } diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index ce36a21de..53685eeb2 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -16,8 +16,8 @@ pub mod block_entity_render; pub mod block_transform; pub mod blocks; pub mod bossbar; -pub mod camera; pub mod brewing; +pub mod camera; pub mod cauldron; pub mod chat; pub mod chunk; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 8379fc8c2..1f139a11a 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -46,8 +46,8 @@ pub mod render; pub mod riders; pub mod shulker; pub mod sniffer; -pub mod spawning; pub mod spawn_rules; +pub mod spawning; pub mod species; pub mod sulfur_cube; pub mod tame; @@ -1097,9 +1097,9 @@ impl Mob { // dealDefaultKnockback, unless the damage type is tagged no_knockback; // a source without a position knocks in a random direction. if knock && !source.no_knockback() { - let (dx, dz) = source - .from - .map_or((0.0, 0.0), |f| (f[0] - self.position.x, f[2] - self.position.z)); + let (dx, dz) = source.from.map_or((0.0, 0.0), |f| { + (f[0] - self.position.x, f[2] - self.position.z) + }); self.knockback(0.4, dx, dz); } ai::after_hurt(self, &source); diff --git a/crates/horizon-client/src/mobs/control.rs b/crates/horizon-client/src/mobs/control.rs index 4e2dd124f..361b1b13a 100644 --- a/crates/horizon-client/src/mobs/control.rs +++ b/crates/horizon-client/src/mobs/control.rs @@ -363,10 +363,9 @@ impl Mob { at[2] - self.position.z, ); let sd = (xd * xd + zd * zd).sqrt(); - let x = - (yd.abs() > EPSILON || sd.abs() > EPSILON).then(|| -trig::atan2_degrees(yd, sd)); - let y = (zd.abs() > EPSILON || xd.abs() > EPSILON) - .then(|| trig::atan2_degrees(zd, xd) - 90.0); + let x = (yd.abs() > EPSILON || sd.abs() > EPSILON).then(|| -trig::atan2_degrees(yd, sd)); + let y = + (zd.abs() > EPSILON || xd.abs() > EPSILON).then(|| trig::atan2_degrees(zd, xd) - 90.0); (x, y) } /// JumpControl.tick. diff --git a/crates/horizon-client/src/mobs/drops.rs b/crates/horizon-client/src/mobs/drops.rs index 42010afd9..102a5a5b6 100644 --- a/crates/horizon-client/src/mobs/drops.rs +++ b/crates/horizon-client/src/mobs/drops.rs @@ -399,7 +399,10 @@ pub fn die(m: &mut Mob, d: &Death, sequences: &mut RandomSequences) -> (Vec i32 { let mut result = reward; for slot in SLOTS { // EquipmentSlot.canIncreaseExperience: all but the saddle. - if slot != "saddle" && slot_item(m, slot).is_some() && drop_chance(m, slot) <= 1.0 { + if slot != "saddle" + && slot_item(m, slot).is_some() + && drop_chance(m, slot) <= 1.0 + { result += 1 + m.random.next_int_bound(3).unwrap_or(0); } } diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 059e58462..c5439479b 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -199,9 +199,8 @@ impl Mob { let center = horizon_core::geometry::trig::atan2(zd, xd) - f64::from(std::f32::consts::FRAC_PI_2); let yrad = center + f64::from(2.0 * self.random.next_float() - 1.0) * max_rad; - let dist = - (min + self.random.next_double().sqrt() * (max - min)) - * f64::from(std::f32::consts::SQRT_2); + let dist = (min + self.random.next_double().sqrt() * (max - min)) + * f64::from(std::f32::consts::SQRT_2); let xt = -dist * yrad.sin(); let zt = dist * yrad.cos(); if xt.abs() > max || zt.abs() > max { diff --git a/crates/horizon-client/src/mobs/spawn_rules.rs b/crates/horizon-client/src/mobs/spawn_rules.rs index f64918bd4..40806b04e 100644 --- a/crates/horizon-client/src/mobs/spawn_rules.rs +++ b/crates/horizon-client/src/mobs/spawn_rules.rs @@ -252,14 +252,21 @@ pub fn is_spawn_position_ok(s: Species, l: &L, x: i32, y: i32, z: && is_valid_empty_spawn(s, l, x, y + 1, z) } data::Placement::InWater => { - fluid(l, x, y, z) == Fluid::Water && flags(l, x, y + 1, z) & data::REDSTONE_CONDUCTOR == 0 + fluid(l, x, y, z) == Fluid::Water + && flags(l, x, y + 1, z) & data::REDSTONE_CONDUCTOR == 0 } data::Placement::InLava => fluid(l, x, y, z) == Fluid::Lava, data::Placement::NoRestrictions => true, } } /// `Monster.isDarkEnoughToSpawn`. -pub fn is_dark_enough(l: &L, random: &mut impl RandomSource, x: i32, y: i32, z: i32) -> bool { +pub fn is_dark_enough( + l: &L, + random: &mut impl RandomSource, + x: i32, + y: i32, + z: i32, +) -> bool { if l.sky_light(x, y, z) > random.next_int_bound(32).unwrap_or(0) { return false; } @@ -290,7 +297,8 @@ fn monster_rules( y: i32, z: i32, ) -> bool { - (reason.ignores_light() || is_dark_enough(l, random, x, y, z)) && mob_rules(s, l, reason, x, y, z) + (reason.ignores_light() || is_dark_enough(l, random, x, y, z)) + && mob_rules(s, l, reason, x, y, z) } /// `Animal.checkAnimalSpawnRules` with the given spawnable-on tag. fn animal_rules(l: &L, reason: Reason, on: &str, x: i32, y: i32, z: i32) -> bool { @@ -336,14 +344,17 @@ pub fn check_spawn_rules( if frequent { random.next_int_bound(15).unwrap_or(1) == 0 && can_spawn } else { - random.next_int_bound(40).unwrap_or(1) == 0 && y < l.sea_level() - 5 && can_spawn + random.next_int_bound(40).unwrap_or(1) == 0 + && y < l.sea_level() - 5 + && can_spawn } } else { true } } S::Guardian | S::ElderGuardian => { - (random.next_int_bound(20).unwrap_or(1) == 0 || !can_see_sky_from_below_water(l, x, y, z)) + (random.next_int_bound(20).unwrap_or(1) == 0 + || !can_see_sky_from_below_water(l, x, y, z)) && !l.peaceful() && (reason.is_spawner() || fluid(l, x, y, z) == Fluid::Water) && fluid(l, x, y - 1, z) == Fluid::Water @@ -351,10 +362,16 @@ pub fn check_spawn_rules( S::TropicalFish => { fluid(l, x, y - 1, z) == Fluid::Water && name(l, x, y + 1, z) == "minecraft:water" - && (l.biome_tag("minecraft:allows_tropical_fish_spawns_at_any_height", x, y, z) - || surface_water(l, x, y, z)) + && (l.biome_tag( + "minecraft:allows_tropical_fish_spawns_at_any_height", + x, + y, + z, + ) || surface_water(l, x, y, z)) + } + S::Armadillo => { + tag(l, "minecraft:armadillo_spawnable_on", x, y - 1, z) && bright(l, x, y, z) } - S::Armadillo => tag(l, "minecraft:armadillo_spawnable_on", x, y - 1, z) && bright(l, x, y, z), S::Bat => { if y >= l.world_surface(x, z) || random.next_boolean() { return false; @@ -387,9 +404,18 @@ pub fn check_spawn_rules( return false; } reason.is_spawner() - || !l.player_near(f64::from(x) + 0.5, f64::from(y) + 0.5, f64::from(z) + 0.5, 5.0) + || !l.player_near( + f64::from(x) + 0.5, + f64::from(y) + 0.5, + f64::from(z) + 0.5, + 5.0, + ) } - S::IronGolem | S::SnowGolem | S::Villager | S::Phantom | S::Shulker + S::IronGolem + | S::SnowGolem + | S::Villager + | S::Phantom + | S::Shulker | S::WanderingTrader => mob_rules(s, l, reason, x, y, z), S::Frog => tag(l, "minecraft:frogs_spawnable_on", x, y - 1, z) && bright(l, x, y, z), S::Ghast => { @@ -405,7 +431,9 @@ pub fn check_spawn_rules( S::Goat => tag(l, "minecraft:goats_spawnable_on", x, y - 1, z) && bright(l, x, y, z), S::MagmaCube => !l.peaceful(), S::SulfurCube => true, - S::Mooshroom => tag(l, "minecraft:mooshrooms_spawnable_on", x, y - 1, z) && bright(l, x, y, z), + S::Mooshroom => { + tag(l, "minecraft:mooshrooms_spawnable_on", x, y - 1, z) && bright(l, x, y, z) + } S::Nautilus => { let sea = l.sea_level(); y >= sea - 25 @@ -420,7 +448,13 @@ pub fn check_spawn_rules( S::PolarBear => { if l.biome_tag("minecraft:polar_bears_spawn_on_alternate_blocks", x, y, z) { bright(l, x, y, z) - && tag(l, "minecraft:polar_bears_spawnable_on_alternate", x, y - 1, z) + && tag( + l, + "minecraft:polar_bears_spawnable_on_alternate", + x, + y - 1, + z, + ) } else { animal_rules(l, reason, "minecraft:animals_spawnable_on", x, y, z) } @@ -582,7 +616,9 @@ impl SpawnLevel for super::MobWorld<'_> { } fn player_near(&self, x: f64, y: f64, z: f64, distance: f64) -> bool { self.player.as_ref().is_some_and(|p| { - let d = (p.position.x - x).powi(2) + (p.position.y - y).powi(2) + (p.position.z - z).powi(2); + let d = (p.position.x - x).powi(2) + + (p.position.y - y).powi(2) + + (p.position.z - z).powi(2); p.alive && !p.creative && !p.spectator && d < distance * distance }) } diff --git a/crates/horizon-client/src/window.rs b/crates/horizon-client/src/window.rs index bfcb973dd..d621a02c3 100644 --- a/crates/horizon-client/src/window.rs +++ b/crates/horizon-client/src/window.rs @@ -176,7 +176,11 @@ impl LimiterClock for SystemClock { /// `Minecraft.runTick`'s frame-limiter step: only limits below 260 /// (the "unlimited" setting) pace frames. -pub fn end_frame(limiter: &mut FramerateLimiter, framerate_limit: i32, clock: &mut impl LimiterClock) { +pub fn end_frame( + limiter: &mut FramerateLimiter, + framerate_limit: i32, + clock: &mut impl LimiterClock, +) { if framerate_limit < 260 { limiter.limit_display_fps(framerate_limit, clock); } @@ -188,7 +192,11 @@ impl FramerateLimiter { } /// The limiter's static state: `lastFrameTime`, `averageOvershootNs` /// and `lastFramerateLimit`. - pub fn with_state(last_frame_time: i64, average_overshoot_ns: i64, last_framerate_limit: i32) -> Self { + pub fn with_state( + last_frame_time: i64, + average_overshoot_ns: i64, + last_framerate_limit: i32, + ) -> Self { Self { last_frame_time, average_overshoot_ns, diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index c8ee6e6c2..d82bf4858 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -184,13 +184,15 @@ impl Server { }; let mut ctx = TickCtx { world: &mut self.world, - host: &host, + host: Some(&host), entities, next_entity: &mut self.next_entity, spawn: [8.5, f64::from(MIN_Y + 5), 8.5], difficulty: 2, difficulty_locked: false, clock_rate: 1.0, + tick_rate: 20.0, + tick_frozen: false, }; let events = self.hub.tick(&mut ctx); for event in events { @@ -238,6 +240,7 @@ fn server(resources: &Path) -> Server { hardcore: false, view_distance: 3, simulation_distance: 3, + dedicated: false, dimension: "minecraft:overworld".into(), seed: 1234, max_players: 8, @@ -419,7 +422,6 @@ fn guests_see_each_other_and_the_world_entities() { data: 0, meta: Vec::new(), equipment: Vec::new(), - send_velocity: false, }; let first = thread::spawn(move || { let mut bot = connect(port, "Alex", false)?; diff --git a/crates/horizon-core/src/geometry/trig.rs b/crates/horizon-core/src/geometry/trig.rs index 36c0b069d..d2c3a0746 100644 --- a/crates/horizon-core/src/geometry/trig.rs +++ b/crates/horizon-core/src/geometry/trig.rs @@ -102,6 +102,7 @@ impl Mth for f32 { } /// fdlibm `__ieee754_asin`, as `StrictMath.asin` (and so `Math.asin`) computes it. +#[allow(clippy::excessive_precision, clippy::approx_constant, clippy::eq_op)] // fdlibm's constants and NaN, verbatim. pub fn fdlibm_asin(x: f64) -> f64 { const PIO2_HI: f64 = 1.570_796_326_794_896_558_00e+00; const PIO2_LO: f64 = 6.123_233_995_736_766_035_87e-17; @@ -160,9 +161,21 @@ mod tests { #[test] fn atan2_matches_the_client_tables() { for (y, x, r) in [ - (0x402f_3b4b_8041_4df1_u64, 0xc018_53ca_369b_9e91_u64, 0x3fff_1334_9f9d_e798_u64), - (0xc025_d316_35f2_9de8, 0xc018_fb4a_7ec4_3ba8, 0xc000_b996_6547_a498), - (0xc026_5d9c_2b5a_472d, 0xc030_954d_c2dc_3d10, 0xc004_62e7_82d4_c97e), + ( + 0x402f_3b4b_8041_4df1_u64, + 0xc018_53ca_369b_9e91_u64, + 0x3fff_1334_9f9d_e798_u64, + ), + ( + 0xc025_d316_35f2_9de8, + 0xc018_fb4a_7ec4_3ba8, + 0xc000_b996_6547_a498, + ), + ( + 0xc026_5d9c_2b5a_472d, + 0xc030_954d_c2dc_3d10, + 0xc004_62e7_82d4_c97e, + ), ] { assert_eq!(atan2(f64::from_bits(y), f64::from_bits(x)).to_bits(), r); } diff --git a/crates/horizon-world/examples/block_update_fixture.rs b/crates/horizon-world/examples/block_update_fixture.rs index 0e5e28f91..9590c90bb 100644 --- a/crates/horizon-world/examples/block_update_fixture.rs +++ b/crates/horizon-world/examples/block_update_fixture.rs @@ -53,8 +53,17 @@ impl LevelAccess for Cells { } /// Fresh block entities hold nothing, but a lectern whose state has a book /// reads page progress 1 of an empty book: signal 14. - fn block_entity_analog_signal(&self, _pos: BlockPos, state: BlockStateId, _direction: Direction) -> i32 { - if self.lecterns_with_books.contains(&state) { 14 } else { 0 } + fn block_entity_analog_signal( + &self, + _pos: BlockPos, + state: BlockStateId, + _direction: Direction, + ) -> i32 { + if self.lecterns_with_books.contains(&state) { + 14 + } else { + 0 + } } /// A chest's fresh block entity: nobody has it open. fn recheck_container_openers(&mut self, _pos: BlockPos) -> Option<(i32, i32)> { @@ -62,7 +71,10 @@ impl LevelAccess for Cells { } /// A fresh command block entity: unpowered and not automatic. fn set_command_block_powered(&mut self, pos: BlockPos, powered: bool) -> Option<(bool, bool)> { - Some((self.command_blocks.insert(pos, powered).unwrap_or(false), false)) + Some(( + self.command_blocks.insert(pos, powered).unwrap_or(false), + false, + )) } fn random(&mut self) -> &mut LegacyRandom { &mut self.random @@ -137,16 +149,18 @@ fn main() -> Result<(), Box> { let registry = load_registry(resources)?; let behaviours = Behaviours::load(®istry, resources)?; let air = registry.default_state("minecraft:air").unwrap(); - let lecterns_with_books: std::rc::Rc> = std::rc::Rc::new( - (0..registry.len() as u32) - .map(BlockStateId) - .filter(|&id| { - registry.state(id).is_some_and(|s| { - s.name == "minecraft:lectern" && s.properties.get("has_book").is_some_and(|v| v == "true") + let lecterns_with_books: std::rc::Rc> = + std::rc::Rc::new( + (0..registry.len() as u32) + .map(BlockStateId) + .filter(|&id| { + registry.state(id).is_some_and(|s| { + s.name == "minecraft:lectern" + && s.properties.get("has_book").is_some_and(|v| v == "true") + }) }) - }) - .collect(), - ); + .collect(), + ); let mut out = std::io::BufWriter::new(std::fs::File::create(output)?); for (index, line) in std::io::BufReader::new(std::fs::File::open(cases)?) .lines() @@ -320,28 +334,36 @@ fn main() -> Result<(), Box> { // Dispensing from the fixture's empty block entities, as the // client does: the fail event, plus `block_activate` for a // dispenser; a crafter without a recipe only fails. - LevelEvent::BlockEvent { kind: "dispense", pos, state } => { - match behaviours.table.name(*state) { - "minecraft:crafter" => { - let _ = writeln!(result, "L 1050 {} 0", p(*pos)); - } - "minecraft:dispenser" => { - let _ = writeln!(result, "L 1001 {} 0", p(*pos)); - let _ = writeln!(result, "G {} minecraft:block_activate", p(*pos)); - } - _ => { - let _ = writeln!(result, "L 1001 {} 0", p(*pos)); - } + LevelEvent::BlockEvent { + kind: "dispense", + pos, + state, + } => match behaviours.table.name(*state) { + "minecraft:crafter" => { + let _ = writeln!(result, "L 1050 {} 0", p(*pos)); } - } + "minecraft:dispenser" => { + let _ = writeln!(result, "L 1001 {} 0", p(*pos)); + let _ = writeln!(result, "G {} minecraft:block_activate", p(*pos)); + } + _ => { + let _ = writeln!(result, "L 1001 {} 0", p(*pos)); + } + }, // DriedGhastBlock.spawnGhastling, as the client does it. - LevelEvent::BlockEvent { kind: "spawn_ghastling", .. } => { + LevelEvent::BlockEvent { + kind: "spawn_ghastling", + .. + } => { let _ = writeln!(result, "E minecraft:happy_ghast"); let _ = writeln!(result, "S entity minecraft:entity.ghastling.spawn"); } // A fresh shrieker has warning level 0 and so never responds, // and no player is near enough for a portal to spawn a piglin. - LevelEvent::BlockEvent { kind: "shrieker_respond" | "portal_spawn", .. } => {} + LevelEvent::BlockEvent { + kind: "shrieker_respond" | "portal_spawn", + .. + } => {} LevelEvent::BlockEvent { kind, .. } => { let _ = writeln!(result, "X {kind}"); } diff --git a/crates/horizon-world/src/level/data.rs b/crates/horizon-world/src/level/data.rs index a3736fb20..3c62a39a4 100644 --- a/crates/horizon-world/src/level/data.rs +++ b/crates/horizon-world/src/level/data.rs @@ -995,7 +995,10 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result 1, Some("WEATHERED") => 2, Some("OXIDIZED") => 3, diff --git a/crates/horizon-world/src/level/hooks.rs b/crates/horizon-world/src/level/hooks.rs index d91198035..677b12a4b 100644 --- a/crates/horizon-world/src/level/hooks.rs +++ b/crates/horizon-world/src/level/hooks.rs @@ -34,7 +34,8 @@ impl Sim<'_, L> { Class::Command => { // CommandBlock.setPoweredAndUpdate let signal = self.has_neighbor_signal(pos); - if let Some((was_powered, automatic)) = self.level.set_command_block_powered(pos, signal) + if let Some((was_powered, automatic)) = + self.level.set_command_block_powered(pos, signal) && signal && !was_powered && !automatic diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 4f240ae6b..166483709 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -351,7 +351,11 @@ pub trait LevelAccess { /// `CommandBlockEntity.setPowered` for the command block entity at `pos`: /// stores `powered` and returns the previous flag and `isAutomatic`, or /// None when there is no command block entity. - fn set_command_block_powered(&mut self, _pos: BlockPos, _powered: bool) -> Option<(bool, bool)> { + fn set_command_block_powered( + &mut self, + _pos: BlockPos, + _powered: bool, + ) -> Option<(bool, bool)> { None } /// Weak/strong signal of a block-entity-driven source (trapped chest diff --git a/crates/horizon-world/src/level/portal.rs b/crates/horizon-world/src/level/portal.rs index 81a6a0562..047f474d9 100644 --- a/crates/horizon-world/src/level/portal.rs +++ b/crates/horizon-world/src/level/portal.rs @@ -21,7 +21,10 @@ pub struct PortalShape { impl PortalShape { pub const fn is_valid(&self) -> bool { - self.width >= MIN_WIDTH && self.width <= MAX_WIDTH && self.height >= MIN_HEIGHT && self.height <= MAX_HEIGHT + self.width >= MIN_WIDTH + && self.width <= MAX_WIDTH + && self.height >= MIN_HEIGHT + && self.height <= MAX_HEIGHT } pub const fn is_complete(&self) -> bool { self.is_valid() && self.portal_blocks == self.width * self.height @@ -36,13 +39,15 @@ fn step(pos: BlockPos, dir: Direction, n: i32) -> BlockPos { impl Sim<'_, L> { fn portal_frame(&self, state: BlockStateId) -> bool { let b = self.b; - b.tag("minecraft:nether_portal_frame").is_some_and(|tag| b.in_set(state, tag)) + b.tag("minecraft:nether_portal_frame") + .is_some_and(|tag| b.in_set(state, tag)) } /// `PortalShape.isEmpty`: air, fire or a portal block. fn portal_empty(&self, state: BlockStateId) -> bool { let b = self.b; b.is_air(state) - || b.tag("minecraft:fire").is_some_and(|tag| b.in_set(state, tag)) + || b.tag("minecraft:fire") + .is_some_and(|tag| b.in_set(state, tag)) || b.is_block(state, b.named.nether_portal) } fn portal_distance_until_edge_above_frame(&self, pos: BlockPos, dir: Direction) -> i32 { @@ -60,8 +65,19 @@ impl Sim<'_, L> { } /// `PortalShape.findAnyShape`. pub fn find_portal_shape(&self, pos: BlockPos, x_axis: bool) -> PortalShape { - let right = if x_axis { Direction::West } else { Direction::South }; - let mut shape = PortalShape { x_axis, right, bottom_left: pos, width: 0, height: 0, portal_blocks: 0 }; + let right = if x_axis { + Direction::West + } else { + Direction::South + }; + let mut shape = PortalShape { + x_axis, + right, + bottom_left: pos, + width: 0, + height: 0, + portal_blocks: 0, + }; // calculateBottomLeft let min_y = self.level.min_y().max(pos.y - MAX_HEIGHT); let mut start = pos; @@ -103,7 +119,11 @@ impl Sim<'_, L> { } let top = step(shape.bottom_left, Direction::Up, height); let has_top = (0..width).all(|i| self.portal_frame(self.state(step(top, right, i)))); - shape.height = if (MIN_HEIGHT..=MAX_HEIGHT).contains(&height) && has_top { height } else { 0 }; + shape.height = if (MIN_HEIGHT..=MAX_HEIGHT).contains(&height) && has_top { + height + } else { + 0 + }; shape } } diff --git a/crates/horizon-world/src/level/shapes.rs b/crates/horizon-world/src/level/shapes.rs index 242be2713..154e4b582 100644 --- a/crates/horizon-world/src/level/shapes.rs +++ b/crates/horizon-world/src/level/shapes.rs @@ -11,7 +11,11 @@ use super::{ update::{above, below, rel}, }; use crate::{fluid::FluidKind, registry::BlockStateId}; -use horizon_core::{geometry::{Axis, Direction}, position::BlockPos, random::RandomSource}; +use horizon_core::{ + geometry::{Axis, Direction}, + position::BlockPos, + random::RandomSource, +}; impl Sim<'_, L> { /// `BlockState.updateShape(level, ticks, pos, direction, neighbourPos, neighbourState, random)`. @@ -794,7 +798,8 @@ impl Sim<'_, L> { Class::NetherPortal => { let x_axis = table.text(state, p.axis) == "x"; let update_axis = axis_of(dir); - let wrong_axis = update_axis != if x_axis { Axis::X } else { Axis::Z } && update_axis != Axis::Y; + let wrong_axis = + update_axis != if x_axis { Axis::X } else { Axis::Z } && update_axis != Axis::Y; if !wrong_axis && !b.is_block(nstate, block) && !self.find_portal_shape(pos, x_axis).is_complete() diff --git a/crates/horizon-world/src/level/shelf.rs b/crates/horizon-world/src/level/shelf.rs index 44a011190..f060fa530 100644 --- a/crates/horizon-world/src/level/shelf.rs +++ b/crates/horizon-world/src/level/shelf.rs @@ -84,12 +84,22 @@ impl Sim<'_, L> { /// `ShelfBlock.isConnectable`. fn shelf_connectable(&self, state: BlockStateId) -> bool { let b = self.b; - b.tag("minecraft:wooden_shelves").is_some_and(|tag| b.in_set(state, tag)) + b.tag("minecraft:wooden_shelves") + .is_some_and(|tag| b.in_set(state, tag)) && b.table.has(state, b.props.powered) && b.table.bool(state, b.props.powered) } - fn chain_neighbor(&mut self, n: &mut Neighbors, left: bool, steps: i32) -> (BlockPos, Option) { - let dir = if left { clockwise(n.facing) } else { counter_clockwise(n.facing) }; + fn chain_neighbor( + &mut self, + n: &mut Neighbors, + left: bool, + steps: i32, + ) -> (BlockPos, Option) { + let dir = if left { + clockwise(n.facing) + } else { + counter_clockwise(n.facing) + }; let mut pos = n.center; for _ in 0..steps { pos = rel(pos, dir); @@ -105,7 +115,10 @@ impl Sim<'_, L> { fn shelf_set_part(&mut self, pos: BlockPos, part: Part) { let state = self.state(pos); if self.shelf_part(state) != part { - let next = self.b.table.set_text(state, self.b.props.side_chain, part.name()); + let next = self + .b + .table + .set_text(state, self.b.props.side_chain, part.name()); self.set_block_and_update(pos, next); } } @@ -115,7 +128,11 @@ impl Sim<'_, L> { if !self.shelf_connectable(state) { return 0; } - let mut n = Neighbors { facing: self.b.facing(state), center: pos, cache: HashMap::new() }; + let mut n = Neighbors { + facing: self.b.facing(state), + center: pos, + cache: HashMap::new(), + }; let mut size = 1; for (left, end) in [(true, Part::Left), (false, Part::Right)] { for steps in 1..MAX_CHAIN_LENGTH as i32 { @@ -132,7 +149,11 @@ impl Sim<'_, L> { } /// `SideChainPartBlock.updateNeighborsAfterPoweringDown`. pub(crate) fn shelf_after_powering_down(&mut self, pos: BlockPos, state: BlockStateId) { - let mut n = Neighbors { facing: self.b.facing(state), center: pos, cache: HashMap::new() }; + let mut n = Neighbors { + facing: self.b.facing(state), + center: pos, + cache: HashMap::new(), + }; if let (at, Some(part)) = self.chain_neighbor(&mut n, true, 1) { self.shelf_set_part(at, part.disconnected_from_the_right()); } @@ -150,11 +171,23 @@ impl Sim<'_, L> { if updated_by_neighbor { return; } - let mut n = Neighbors { facing: self.b.facing(state), center: pos, cache: HashMap::new() }; + let mut n = Neighbors { + facing: self.b.facing(state), + center: pos, + cache: HashMap::new(), + }; let (left_pos, left) = self.chain_neighbor(&mut n, true, 1); let (right_pos, right) = self.chain_neighbor(&mut n, false, 1); - let on_left = if left.is_some() { self.shelf_chain_size(left_pos) } else { 0 }; - let on_right = if right.is_some() { self.shelf_chain_size(right_pos) } else { 0 }; + let on_left = if left.is_some() { + self.shelf_chain_size(left_pos) + } else { + 0 + }; + let on_right = if right.is_some() { + self.shelf_chain_size(right_pos) + } else { + 0 + }; let mut own = Part::Unconnected; let mut length = 1; if on_left > 0 && length + on_left <= MAX_CHAIN_LENGTH { @@ -189,13 +222,18 @@ impl Sim<'_, L> { } let mut next = b.table.set_bool(state, b.props.powered, signal); if !signal { - next = b.table.set_text(next, b.props.side_chain, Part::Unconnected.name()); + next = b + .table + .set_text(next, b.props.side_chain, Part::Unconnected.name()); } self.set_block_and_update(pos, next); let (sound, event) = if signal { ("minecraft:block.shelf.activate", "minecraft:block_activate") } else { - ("minecraft:block.shelf.deactivate", "minecraft:block_deactivate") + ( + "minecraft:block.shelf.deactivate", + "minecraft:block_deactivate", + ) }; self.sound(pos, &sound.into(), 1.0, 1.0); self.game_event_state(pos, event, next); diff --git a/crates/horizon-world/src/level/update.rs b/crates/horizon-world/src/level/update.rs index 1fd90c33e..15117c890 100644 --- a/crates/horizon-world/src/level/update.rs +++ b/crates/horizon-world/src/level/update.rs @@ -188,7 +188,12 @@ impl Sim<'_, L> { pub fn prime_tnt(&mut self, pos: BlockPos) { let rot = self.random().next_double() * f64::from(std::f32::consts::TAU); self.emit(LevelEvent::PrimeTnt { pos, rot }); - self.sound(pos, &std::sync::Arc::from("minecraft:entity.tnt.primed"), 1.0, 1.0); + self.sound( + pos, + &std::sync::Arc::from("minecraft:entity.tnt.primed"), + 1.0, + 1.0, + ); self.game_event(pos, "minecraft:prime_fuse"); } pub fn level_event(&mut self, id: i32, pos: BlockPos, data: i32) { diff --git a/crates/horizon-world/src/loot.rs b/crates/horizon-world/src/loot.rs index b863e9659..fccfa4c77 100644 --- a/crates/horizon-world/src/loot.rs +++ b/crates/horizon-world/src/loot.rs @@ -683,7 +683,8 @@ impl Context<'_, R> { { continue; } - if !effect["requirements"].is_null() && !self.condition(&effect["requirements"]) { + if !effect["requirements"].is_null() && !self.condition(&effect["requirements"]) + { continue; } let value = level_value(&effect["effect"]["value"], *level); @@ -731,21 +732,22 @@ impl Context<'_, R> { .is_some_and(|stack| self.item_matches(item, stack)) }) } - "minecraft:components" => v.as_object().into_iter().flatten().all(|(c, want)| { - match c.as_str() { - "minecraft:sheep/color" => e - .sheep - .as_ref() - .is_some_and(|(color, _)| want.as_str() == Some(color)), - "minecraft:frog/variant" => { - e.frog_variant.is_some() && want.as_str() == e.frog_variant.as_deref() - } - _ => false, + "minecraft:components" => v.as_object().into_iter().flatten().all(|(c, want)| match c + .as_str() + { + "minecraft:sheep/color" => e + .sheep + .as_ref() + .is_some_and(|(color, _)| want.as_str() == Some(color)), + "minecraft:frog/variant" => { + e.frog_variant.is_some() && want.as_str() == e.frog_variant.as_deref() } + _ => false, }), - "minecraft:type_specific/sheep" => e.sheep.as_ref().is_some_and(|(_, sheared)| { - v["sheared"].as_bool().is_none_or(|w| w == *sheared) - }), + "minecraft:type_specific/sheep" => e + .sheep + .as_ref() + .is_some_and(|(_, sheared)| v["sheared"].as_bool().is_none_or(|w| w == *sheared)), "minecraft:type_specific/cube_mob" => { e.cube_size.is_some_and(|size| int_bounds(&v["size"], size)) } @@ -1237,7 +1239,7 @@ impl Context<'_, R> { + e["quality"].as_i64().unwrap_or(0) as f32 * luck; w.floor().max(0.0) as i32 }; - let total: i32 = valid.iter().map(|e| weight(e)).sum(); + let total: i32 = valid.iter().map(&weight).sum(); if total == 0 || valid.is_empty() { return; } @@ -1289,7 +1291,10 @@ impl Context<'_, R> { let items = self.data.holder_set("item", &entry["items"]); for item in items { if entry["weight"].as_i64().unwrap_or(1) > 0 { - out.push(Choice { entry, item: Some(item) }); + out.push(Choice { + entry, + item: Some(item), + }); } } true