From df14adbfbab7603dbf2d1cdf44784e20a352ae9e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 00:28:32 +0200 Subject: [PATCH] Format the workspace with rustfmt Co-Authored-By: Claude Opus 5.5 --- .../examples/enchanting_fixture.rs | 24 +- crates/horizon-client/src/ambience.rs | 77 +- crates/horizon-client/src/assets.rs | 8 +- crates/horizon-client/src/audio.rs | 116 +- crates/horizon-client/src/biome.rs | 15 +- .../horizon-client/src/block_entity_render.rs | 83 +- crates/horizon-client/src/blocks.rs | 12 +- crates/horizon-client/src/brewing.rs | 282 +- crates/horizon-client/src/chat.rs | 272 +- crates/horizon-client/src/chunk.rs | 4 +- crates/horizon-client/src/command/args.rs | 507 ++- crates/horizon-client/src/command/mod.rs | 298 +- crates/horizon-client/src/command/tests.rs | 118 +- crates/horizon-client/src/command/vanilla.rs | 43 +- crates/horizon-client/src/containers.rs | 97 +- crates/horizon-client/src/crafting.rs | 69 +- crates/horizon-client/src/creative.rs | 26 +- crates/horizon-client/src/effects.rs | 119 +- crates/horizon-client/src/enchant.rs | 546 ++- crates/horizon-client/src/entities.rs | 108 +- crates/horizon-client/src/entity_nbt.rs | 148 +- crates/horizon-client/src/environment.rs | 94 +- crates/horizon-client/src/font.rs | 137 +- crates/horizon-client/src/game.rs | 3166 ++++++++++++++--- crates/horizon-client/src/game/chat.rs | 241 +- crates/horizon-client/src/game/commands.rs | 758 +++- .../src/game/commands/effects.rs | 143 +- crates/horizon-client/src/game/control.rs | 21 +- .../src/game/enchant_effects.rs | 220 +- crates/horizon-client/src/game/end.rs | 3 +- crates/horizon-client/src/game/explosion.rs | 17 +- crates/horizon-client/src/game/music.rs | 49 +- crates/horizon-client/src/game/options.rs | 49 +- crates/horizon-client/src/game/packs.rs | 67 +- crates/horizon-client/src/game/persist.rs | 106 +- crates/horizon-client/src/game/potions.rs | 216 +- crates/horizon-client/src/game/remote.rs | 847 ++++- .../horizon-client/src/game/render_control.rs | 7 +- crates/horizon-client/src/game/screens.rs | 134 +- crates/horizon-client/src/game/sign_edit.rs | 100 +- .../src/game/station_control.rs | 49 +- crates/horizon-client/src/game/stations.rs | 965 ++++- crates/horizon-client/src/game/trading.rs | 262 +- crates/horizon-client/src/gamerules.rs | 73 +- crates/horizon-client/src/gfx.rs | 316 +- crates/horizon-client/src/health.rs | 4 +- crates/horizon-client/src/hud.rs | 131 +- crates/horizon-client/src/item_data.rs | 100 +- crates/horizon-client/src/items.rs | 301 +- crates/horizon-client/src/keybinds.rs | 56 +- crates/horizon-client/src/lang.rs | 47 +- crates/horizon-client/src/lib.rs | 12 +- crates/horizon-client/src/light.rs | 176 +- crates/horizon-client/src/merchant.rs | 306 +- crates/horizon-client/src/mesher.rs | 56 +- crates/horizon-client/src/mobs.rs | 278 +- crates/horizon-client/src/mobs/ai.rs | 25 +- crates/horizon-client/src/mobs/anim.rs | 4 +- crates/horizon-client/src/mobs/aquatic.rs | 170 +- crates/horizon-client/src/mobs/goals.rs | 45 +- crates/horizon-client/src/mobs/render.rs | 163 +- crates/horizon-client/src/mobs/spawning.rs | 4 +- crates/horizon-client/src/models/cube.rs | 6 +- crates/horizon-client/src/motion.rs | 20 +- crates/horizon-client/src/multiplayer.rs | 421 ++- crates/horizon-client/src/music.rs | 65 +- crates/horizon-client/src/net.rs | 186 +- crates/horizon-client/src/options_ui.rs | 761 +++- crates/horizon-client/src/packs.rs | 167 +- crates/horizon-client/src/save.rs | 730 +++- crates/horizon-client/src/settings.rs | 181 +- crates/horizon-client/src/shadows.rs | 44 +- crates/horizon-client/src/signs.rs | 47 +- crates/horizon-client/src/stations.rs | 408 ++- crates/horizon-client/src/streaming.rs | 109 +- crates/horizon-client/src/text.rs | 86 +- crates/horizon-client/src/title.rs | 355 +- crates/horizon-client/src/ui.rs | 469 ++- crates/horizon-client/src/vanillagen.rs | 49 +- crates/horizon-client/src/world.rs | 35 +- crates/horizon-client/src/zip.rs | 55 +- .../horizon-world/examples/chunkgen_bench.rs | 6 +- .../examples/tree_feature_fixture.rs | 8 +- crates/horizon-world/src/level/growth.rs | 6 +- crates/horizon-world/src/level/tick.rs | 6 +- .../src/worldgen/generator_decoration.rs | 4 +- .../horizon-world/src/worldgen/structure.rs | 4 +- .../src/worldgen/structure/mansion.rs | 143 +- .../src/worldgen/structure/monument.rs | 96 +- .../src/worldgen/structure/ruined_portal.rs | 29 +- .../src/worldgen/structure/start.rs | 15 +- .../src/worldgen/structure/temple.rs | 207 +- 92 files changed, 14589 insertions(+), 3019 deletions(-) diff --git a/crates/horizon-client/examples/enchanting_fixture.rs b/crates/horizon-client/examples/enchanting_fixture.rs index cd82cad48..736b9189e 100644 --- a/crates/horizon-client/examples/enchanting_fixture.rs +++ b/crates/horizon-client/examples/enchanting_fixture.rs @@ -3,12 +3,19 @@ //! prints costs, clues and applied enchantments in the oracle's format. //! //! usage: enchanting_fixture RESOURCES INPUT OUTPUT -use horizon_client::{enchant::Enchantments, items::{ItemStack, Items}, stations}; +use horizon_client::{ + enchant::Enchantments, + items::{ItemStack, Items}, + stations, +}; use std::{fmt::Write as _, fs, path::Path}; fn main() -> horizon_client::Result<()> { let args: Vec = std::env::args().collect(); - let root = Path::new(args.get(1).ok_or("usage: enchanting_fixture RESOURCES INPUT OUTPUT")?); + let root = Path::new( + args.get(1) + .ok_or("usage: enchanting_fixture RESOURCES INPUT OUTPUT")?, + ); let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; let items = Items::tags_only(root)?; let e = Enchantments::load(root); @@ -20,10 +27,19 @@ fn main() -> horizon_client::Result<()> { let offers = stations::enchant_offers(&e, &items, seed, bookcases, Some(&stack)); for i in 0..3 { let cost = offers.costs[i]; - let clue = offers.clues[i].as_ref().map_or("-".to_owned(), |(id, l)| format!("{id}:{l}")); + let clue = offers.clues[i] + .as_ref() + .map_or("-".to_owned(), |(id, l)| format!("{id}:{l}")); let applied = if cost > 0 { let list = stations::enchantment_list(&e, &items, seed, i, cost, item); - if list.is_empty() { "-".to_owned() } else { list.iter().map(|(id, l)| format!("{id}:{l}")).collect::>().join(",") } + if list.is_empty() { + "-".to_owned() + } else { + list.iter() + .map(|(id, l)| format!("{id}:{l}")) + .collect::>() + .join(",") + } } else { "-".to_owned() }; diff --git a/crates/horizon-client/src/ambience.rs b/crates/horizon-client/src/ambience.rs index a033606dc..e5b3fafa4 100644 --- a/crates/horizon-client/src/ambience.rs +++ b/crates/horizon-client/src/ambience.rs @@ -25,7 +25,8 @@ pub struct AmbientSounds { impl AmbientSounds { fn parse(v: &Value) -> Self { let mood = &v["mood"]; - let addition = |a: &Value| Some((a["sound"].as_str()?.to_owned(), a["tick_chance"].as_f64()?)); + let addition = + |a: &Value| Some((a["sound"].as_str()?.to_owned(), a["tick_chance"].as_f64()?)); Self { r#loop: v["loop"].as_str().map(str::to_owned), mood: mood["sound"].as_str().map(|sound| Mood { @@ -51,7 +52,9 @@ pub struct AmbientTables { impl AmbientTables { pub fn load(root: &Path) -> Self { let read = |dir: &str| -> HashMap { - let Ok(entries) = fs::read_dir(root.join("data/minecraft").join(dir)) else { return HashMap::new() }; + let Ok(entries) = fs::read_dir(root.join("data/minecraft").join(dir)) else { + return HashMap::new(); + }; entries .flatten() .filter_map(|e| { @@ -63,11 +66,18 @@ impl AmbientTables { }) .collect() }; - Self { dimensions: read("dimension_type"), biomes: read("worldgen/biome") } + Self { + dimensions: read("dimension_type"), + biomes: read("worldgen/biome"), + } } /// `EnvironmentAttributes.AMBIENT_SOUNDS` at a position. pub fn get(&self, dimension: &str, biome: &str) -> AmbientSounds { - self.biomes.get(biome).or_else(|| self.dimensions.get(dimension)).cloned().unwrap_or_default() + self.biomes + .get(biome) + .or_else(|| self.dimensions.get(dimension)) + .cloned() + .unwrap_or_default() } } /// The sound engine side of the handlers. @@ -147,7 +157,9 @@ pub struct Ambience { } 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); + let seed = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos() as i64); Self::new(seed) } } @@ -191,7 +203,9 @@ impl Ambience { 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)); + 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); @@ -233,7 +247,15 @@ impl Ambience { 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.push(( + event.clone(), + LoopSound { + id, + fade: 0, + direction: 0, + stopped: false, + }, + )); } if let Some((_, l)) = self.loops.iter_mut().find(|(e, _)| e == event) { l.fade_in(); @@ -350,8 +372,18 @@ mod tests { self.at.push(event.to_owned()); } } - fn ctx<'a>(sounds: &'a AmbientSounds, underwater: bool, light: &'a dyn Fn([i32; 3]) -> (u8, u8)) -> AmbientContext<'a> { - AmbientContext { sounds, position: [0.5, 10.0, 0.5], eye_y: 11.62, underwater, light } + fn ctx<'a>( + sounds: &'a AmbientSounds, + underwater: bool, + light: &'a dyn Fn([i32; 3]) -> (u8, u8), + ) -> AmbientContext<'a> { + AmbientContext { + sounds, + position: [0.5, 10.0, 0.5], + eye_y: 11.62, + underwater, + light, + } } #[test] @@ -359,22 +391,34 @@ mod tests { let mut a = Ambience::new(1); let mut out = Fake::default(); let dark = |_: [i32; 3]| (15u8, 0u8); - let crimson = AmbientSounds { r#loop: Some("crimson".into()), ..Default::default() }; + let crimson = AmbientSounds { + r#loop: Some("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()), ..Default::default() }; + let warped = AmbientSounds { + r#loop: Some("warped".into()), + ..Default::default() + }; for _ in 0..20 { a.tick(&ctx(&warped, false, &dark), &mut out); } 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)]); + assert_eq!( + volumes, + [("crimson".to_owned(), 0.5), ("warped".to_owned(), 0.5)] + ); for _ in 0..30 { a.tick(&ctx(&warped, false, &dark), &mut out); } - assert_eq!(out.live.values().map(|v| v.0.as_str()).collect::>(), ["warped"]); + assert_eq!( + out.live.values().map(|v| v.0.as_str()).collect::>(), + ["warped"] + ); } #[test] @@ -383,7 +427,12 @@ mod tests { let mut out = Fake::default(); let cave = |_: [i32; 3]| (0u8, 0u8); let sounds = AmbientSounds { - mood: Some(Mood { sound: "minecraft:ambient.cave".into(), tick_delay: 6000, block_search_extent: 8, offset: 2.0 }), + mood: Some(Mood { + sound: "minecraft:ambient.cave".into(), + tick_delay: 6000, + block_search_extent: 8, + offset: 2.0, + }), ..Default::default() }; // Block light 0: +1/6000 per tick (float), so the sound plays around tick 6000. diff --git a/crates/horizon-client/src/assets.rs b/crates/horizon-client/src/assets.rs index 8e22f7736..fd6e196ee 100644 --- a/crates/horizon-client/src/assets.rs +++ b/crates/horizon-client/src/assets.rs @@ -192,7 +192,13 @@ impl Assets { let models = crate::models::prepare(root, registry, &mut sprites)?; // Fluids are drawn by the fluid renderer, not block models; breaking // progress uses the destroy-stage overlays. - for name in ["water_still", "water_flow", "water_overlay", "lava_still", "lava_flow"] { + for name in [ + "water_still", + "water_flow", + "water_overlay", + "lava_still", + "lava_flow", + ] { sprites.insert(root, &format!("minecraft:block/{name}"))?; } for stage in 0..10 { diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index 77408d411..929c5c0e2 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -73,7 +73,12 @@ fn decode(path: &Path) -> Option<(Vec, u32)> { let mut hint = Hint::new(); hint.with_extension("ogg"); let probed = symphonia::default::get_probe() - .format(&hint, stream, &FormatOptions::default(), &MetadataOptions::default()) + .format( + &hint, + stream, + &FormatOptions::default(), + &MetadataOptions::default(), + ) .ok()?; let mut format = probed.format; let track = format.default_track()?; @@ -87,7 +92,9 @@ fn decode(path: &Path) -> Option<(Vec, u32)> { if packet.track_id() != id { continue; } - let Ok(buffer) = decoder.decode(&packet) else { continue }; + let Ok(buffer) = decoder.decode(&packet) else { + continue; + }; let spec = *buffer.spec(); let channels = spec.channels.count().max(1); let mut samples = SampleBuffer::::new(buffer.capacity() as u64, spec); @@ -131,7 +138,10 @@ impl Audio { events.insert(format!("minecraft:{name}"), variants); } } - let mixer = Arc::new(Mutex::new(Mixer { music_gain: 1.0, ..Mixer::default() })); + 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) => { @@ -156,7 +166,9 @@ impl Audio { } fn open(mixer: Arc>) -> Result<(cpal::Stream, u32)> { let host = cpal::default_host(); - let device = host.default_output_device().ok_or("no audio output device")?; + let device = host + .default_output_device() + .ok_or("no audio output device")?; let config = device.default_output_config()?; let rate = config.sample_rate().0; let channels = config.channels() as usize; @@ -211,9 +223,17 @@ impl Audio { 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 + .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; } }, @@ -245,7 +265,11 @@ impl Audio { } })?; if chosen.is_event && depth < 4 { - let name = if chosen.name.contains(':') { chosen.name.clone() } else { format!("minecraft:{}", chosen.name) }; + 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; @@ -258,17 +282,32 @@ impl Audio { if self._stream.is_none() { return; } - let Some(variant) = self.resolve(event, 0) else { return }; + let Some(variant) = self.resolve(event, 0) else { + 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)) + 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 }; - let volume = (volume * variant.volume).clamp(0.0, 1.0) * self.master * crate::settings::event_volume(event); + let Some((samples, rate)) = entry.clone() else { + return; + }; + let volume = (volume * variant.volume).clamp(0.0, 1.0) + * self.master + * crate::settings::event_volume(event); 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 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); @@ -277,7 +316,8 @@ impl Audio { } 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 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); @@ -304,9 +344,15 @@ impl Audio { if self._stream.is_none() { return false; } - let Some(variant) = self.resolve(event, 0) else { return false }; - 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 Some(variant) = self.resolve(event, 0) else { + return false; + }; + 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()); @@ -325,14 +371,19 @@ impl Audio { } done.store(true, std::sync::atomic::Ordering::Release); }); - self.music = Some(MusicTrack { event: event.to_owned(), ready }); + 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); + track + .ready + .store(true, std::sync::atomic::Ordering::Release); } if let Ok(mut m) = self.mixer.lock() { m.music = None; @@ -340,7 +391,9 @@ impl Audio { } /// `SoundManager.isActive`: decoding or still sounding. pub fn music_active(&mut self) -> bool { - let Some(track) = &self.music else { return false }; + let Some(track) = &self.music else { + return false; + }; if !track.ready.load(std::sync::atomic::Ordering::Acquire) { return true; } @@ -370,16 +423,27 @@ impl Audio { 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))) + .or_insert_with(|| { + decode(&root.join(format!("assets/minecraft/sounds/{file}.ogg"))) + .map(|(s, r)| (Arc::new(s), r)) + }) .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)); + 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 }, + voice: Voice { + samples, + position: 0.0, + step, + left: gain, + right: gain, + }, looping, volume: volume.clamp(0.0, 1.0), }); @@ -400,6 +464,8 @@ impl Audio { } /// 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)) + self.mixer + .lock() + .is_ok_and(|m| m.tracked.iter().any(|t| t.id == id)) } } diff --git a/crates/horizon-client/src/biome.rs b/crates/horizon-client/src/biome.rs index bc4a0344e..5fd6f3e4b 100644 --- a/crates/horizon-client/src/biome.rs +++ b/crates/horizon-client/src/biome.rs @@ -80,10 +80,10 @@ impl Biomes { let dimension: Value = serde_json::from_slice(&fs::read( root.join("data/minecraft/dimension_type/overworld.json"), )?)?; - let default_fog = color(&dimension["attributes"]["minecraft:visual/fog_color"]) - .unwrap_or(0xC0D8FF); - let default_sky = color(&dimension["attributes"]["minecraft:visual/sky_color"]) - .unwrap_or(0x78A7FF); + let default_fog = + color(&dimension["attributes"]["minecraft:visual/fog_color"]).unwrap_or(0xC0D8FF); + let default_sky = + color(&dimension["attributes"]["minecraft:visual/sky_color"]).unwrap_or(0x78A7FF); let mut list = Vec::new(); let mut names: Vec<_> = fs::read_dir(root.join("data/minecraft/worldgen/biome"))? .filter_map(|e| e.ok()) @@ -94,7 +94,9 @@ impl Biomes { for path in names { let name = format!( "minecraft:{}", - path.file_stem().and_then(|s| s.to_str()).ok_or("bad biome")? + path.file_stem() + .and_then(|s| s.to_str()) + .ok_or("bad biome")? ); let v: Value = serde_json::from_slice(&fs::read(&path)?)?; let effects = &v["effects"]; @@ -136,7 +138,8 @@ impl Biomes { } list.push(BiomeInfo { spawns, - creature_probability: v["creature_spawn_probability"].as_f64().unwrap_or(0.1) as f32, + creature_probability: v["creature_spawn_probability"].as_f64().unwrap_or(0.1) + as f32, temperature, downfall, precipitation: v["has_precipitation"].as_bool().unwrap_or(true), diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 70670e167..c45a98547 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -335,9 +335,16 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Kind { let angle = if wall { y_rot(facing()) } else { - prop("rotation").and_then(|r| r.parse::().ok()).unwrap_or(0.0) * 22.5 + prop("rotation") + .and_then(|r| r.parse::().ok()) + .unwrap_or(0.0) + * 22.5 + }; + return Kind::Sign { + hanging, + wall, + angle, }; - return Kind::Sign { hanging, wall, angle }; } let unwaxed = name.strip_prefix("waxed_").unwrap_or(name); match unwaxed { @@ -598,7 +605,15 @@ fn frac(x: f32) -> f32 { /// `AbstractSignRenderer.submitSignText`: four centred lines, glowing text /// full-bright with an 8x outline in the dark colour. -fn sign_text(scene: &Scene, data: &crate::signs::SignData, text: &crate::signs::SignText, m: Mat4, packed: u8, near: bool, out: &mut Vec) { +fn sign_text( + scene: &Scene, + data: &crate::signs::SignData, + text: &crate::signs::SignText, + m: Mat4, + packed: u8, + near: bool, + out: &mut Vec, +) { let line_height = data.line_height(); let midpoint = (4.0 * line_height / 2.0).floor(); let dark = text.dark_color(); @@ -608,7 +623,11 @@ fn sign_text(scene: &Scene, data: &crate::signs::SignData, text: &crate::signs:: } else { (dark, None, vertex_light(packed)) }; - let width = |s: &str| s.chars().map(|c| (scene.glyph)(c).map_or(6.0, |g| g.1)).sum::(); + 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(); @@ -629,18 +648,39 @@ fn sign_text(scene: &Scene, data: &crate::signs::SignData, text: &crate::signs:: 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 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); + 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 }); + out.push(Vertex { + pos: m.transform_point3(Vec3::new(cx, cy, 0.0)).to_array(), + uv, + layer: 0, + color: c, + 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)] { + 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); } } @@ -805,8 +845,14 @@ impl BlockEntityRenderer { let none = |_: &str, _: &mut [f32; 9]| {}; match kind { Kind::None => {} - Kind::Sign { hanging, wall, angle } => { - let Some(data) = (scene.sign)(pos) else { return }; + Kind::Sign { + hanging, + wall, + angle, + } => { + let Some(data) = (scene.sign)(pos) else { + return; + }; let s = Vec3::new(1.0, -1.0, 1.0); for (front, text) in [(true, &data.front), (false, &data.back)] { if text.is_empty() { @@ -821,19 +867,28 @@ impl BlockEntityRenderer { if !front { m *= Mat4::from_rotation_y(PI); } - m *= Mat4::from_translation(Vec3::new(0.0, -0.32, 0.073)) * Mat4::from_scale(s * 0.014_062_5); + m *= Mat4::from_translation(Vec3::new(0.0, -0.32, 0.073)) + * Mat4::from_scale(s * 0.014_062_5); } else { // StandingSignRenderer.textTransformation. - m *= Mat4::from_translation(Vec3::splat(0.5)) * Mat4::from_rotation_y((-angle).to_radians()); + m *= Mat4::from_translation(Vec3::splat(0.5)) + * Mat4::from_rotation_y((-angle).to_radians()); if *wall { m *= Mat4::from_translation(Vec3::new(0.0, -0.3125, -0.4375)); } if !front { m *= Mat4::from_rotation_y(PI); } - m *= Mat4::from_translation(Vec3::new(0.0, 1.0 / 3.0, 0.046_666_667)) * Mat4::from_scale(s * 0.010_416_667); + m *= Mat4::from_translation(Vec3::new(0.0, 1.0 / 3.0, 0.046_666_667)) + * Mat4::from_scale(s * 0.010_416_667); } - let near = DVec3::new(f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, f64::from(pos[2]) + 0.5).distance_squared(scene.camera) < 256.0; + let near = DVec3::new( + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ) + .distance_squared(scene.camera) + < 256.0; sign_text(scene, data, text, m, packed, near, out); } } diff --git a/crates/horizon-client/src/blocks.rs b/crates/horizon-client/src/blocks.rs index fe7547e65..85a774f88 100644 --- a/crates/horizon-client/src/blocks.rs +++ b/crates/horizon-client/src/blocks.rs @@ -72,8 +72,9 @@ pub struct BlockFacts { } impl BlockFacts { pub fn load(root: &Path, registry: &BlockRegistry) -> Result { - let raw: Value = - serde_json::from_reader(BufReader::new(File::open(root.join("gameplay-facts.json"))?))?; + let raw: Value = serde_json::from_reader(BufReader::new(File::open( + root.join("gameplay-facts.json"), + )?))?; let entries = raw["states"] .as_array() .ok_or("missing gameplay state facts")?; @@ -143,8 +144,11 @@ impl BlockFacts { (kind, 8 - level, false) } } - "minecraft:bubble_column" | "minecraft:kelp" | "minecraft:kelp_plant" - | "minecraft:seagrass" | "minecraft:tall_seagrass" => (Fluid::Water, 8, false), + "minecraft:bubble_column" + | "minecraft:kelp" + | "minecraft:kelp_plant" + | "minecraft:seagrass" + | "minecraft:tall_seagrass" => (Fluid::Water, 8, false), _ if prop("waterlogged") == Some("true") => (Fluid::Water, 8, false), _ => (Fluid::None, 0, false), }; diff --git a/crates/horizon-client/src/brewing.rs b/crates/horizon-client/src/brewing.rs index 13bdb826b..f29bfc08b 100644 --- a/crates/horizon-client/src/brewing.rs +++ b/crates/horizon-client/src/brewing.rs @@ -24,7 +24,12 @@ pub struct EffectDef { pub instant: bool, } const fn fx(id: &'static str, color: u32, category: Category) -> EffectDef { - EffectDef { id, color, category, instant: false } + EffectDef { + id, + color, + category, + instant: false, + } } use Category::{Beneficial as B, Harmful as H, Neutral as N}; /// `MobEffects` in registration order. @@ -34,8 +39,18 @@ pub const EFFECTS: &[EffectDef] = &[ fx("haste", 14270531, B), fx("mining_fatigue", 4866583, H), fx("strength", 16762624, B), - EffectDef { id: "instant_health", color: 16262179, category: B, instant: true }, - EffectDef { id: "instant_damage", color: 11101546, category: H, instant: true }, + EffectDef { + id: "instant_health", + color: 16262179, + category: B, + instant: true, + }, + EffectDef { + id: "instant_damage", + color: 11101546, + category: H, + instant: true, + }, fx("jump_boost", 16646020, B), fx("nausea", 5578058, H), fx("regeneration", 13458603, B), @@ -51,7 +66,12 @@ pub const EFFECTS: &[EffectDef] = &[ fx("wither", 7561558, H), fx("health_boost", 16284963, B), fx("absorption", 2445989, B), - EffectDef { id: "saturation", color: 16262179, category: B, instant: true }, + EffectDef { + id: "saturation", + color: 16262179, + category: B, + instant: true, + }, fx("glowing", 9740385, N), fx("levitation", 13565951, H), fx("luck", 5882118, B), @@ -82,7 +102,11 @@ pub struct PotionDef { pub name: &'static str, pub effects: &'static [(&'static str, i32, i32)], } -const fn p(id: &'static str, name: &'static str, effects: &'static [(&'static str, i32, i32)]) -> PotionDef { +const fn p( + id: &'static str, + name: &'static str, + effects: &'static [(&'static str, i32, i32)], +) -> PotionDef { PotionDef { id, name, effects } } /// `Potions` in registration order. @@ -92,25 +116,61 @@ pub const POTIONS: &[PotionDef] = &[ p("thick", "thick", &[]), p("awkward", "awkward", &[]), p("night_vision", "night_vision", &[("night_vision", 3600, 0)]), - p("long_night_vision", "night_vision", &[("night_vision", 9600, 0)]), + p( + "long_night_vision", + "night_vision", + &[("night_vision", 9600, 0)], + ), p("invisibility", "invisibility", &[("invisibility", 3600, 0)]), - p("long_invisibility", "invisibility", &[("invisibility", 9600, 0)]), + p( + "long_invisibility", + "invisibility", + &[("invisibility", 9600, 0)], + ), p("leaping", "leaping", &[("jump_boost", 3600, 0)]), p("long_leaping", "leaping", &[("jump_boost", 9600, 0)]), p("strong_leaping", "leaping", &[("jump_boost", 1800, 1)]), - p("fire_resistance", "fire_resistance", &[("fire_resistance", 3600, 0)]), - p("long_fire_resistance", "fire_resistance", &[("fire_resistance", 9600, 0)]), + p( + "fire_resistance", + "fire_resistance", + &[("fire_resistance", 3600, 0)], + ), + p( + "long_fire_resistance", + "fire_resistance", + &[("fire_resistance", 9600, 0)], + ), p("swiftness", "swiftness", &[("speed", 3600, 0)]), p("long_swiftness", "swiftness", &[("speed", 9600, 0)]), p("strong_swiftness", "swiftness", &[("speed", 1800, 1)]), p("slowness", "slowness", &[("slowness", 1800, 0)]), p("long_slowness", "slowness", &[("slowness", 4800, 0)]), p("strong_slowness", "slowness", &[("slowness", 400, 3)]), - p("turtle_master", "turtle_master", &[("slowness", 400, 3), ("resistance", 400, 2)]), - p("long_turtle_master", "turtle_master", &[("slowness", 800, 3), ("resistance", 800, 2)]), - p("strong_turtle_master", "turtle_master", &[("slowness", 400, 5), ("resistance", 400, 3)]), - p("water_breathing", "water_breathing", &[("water_breathing", 3600, 0)]), - p("long_water_breathing", "water_breathing", &[("water_breathing", 9600, 0)]), + p( + "turtle_master", + "turtle_master", + &[("slowness", 400, 3), ("resistance", 400, 2)], + ), + p( + "long_turtle_master", + "turtle_master", + &[("slowness", 800, 3), ("resistance", 800, 2)], + ), + p( + "strong_turtle_master", + "turtle_master", + &[("slowness", 400, 5), ("resistance", 400, 3)], + ), + p( + "water_breathing", + "water_breathing", + &[("water_breathing", 3600, 0)], + ), + p( + "long_water_breathing", + "water_breathing", + &[("water_breathing", 9600, 0)], + ), p("healing", "healing", &[("instant_health", 1, 0)]), p("strong_healing", "healing", &[("instant_health", 1, 1)]), p("harming", "harming", &[("instant_damage", 1, 0)]), @@ -119,8 +179,16 @@ pub const POTIONS: &[PotionDef] = &[ p("long_poison", "poison", &[("poison", 1800, 0)]), p("strong_poison", "poison", &[("poison", 432, 1)]), p("regeneration", "regeneration", &[("regeneration", 900, 0)]), - p("long_regeneration", "regeneration", &[("regeneration", 1800, 0)]), - p("strong_regeneration", "regeneration", &[("regeneration", 450, 1)]), + p( + "long_regeneration", + "regeneration", + &[("regeneration", 1800, 0)], + ), + p( + "strong_regeneration", + "regeneration", + &[("regeneration", 450, 1)], + ), p("strength", "strength", &[("strength", 3600, 0)]), p("long_strength", "strength", &[("strength", 9600, 0)]), p("strong_strength", "strength", &[("strength", 1800, 1)]), @@ -128,7 +196,11 @@ pub const POTIONS: &[PotionDef] = &[ p("long_weakness", "weakness", &[("weakness", 4800, 0)]), p("luck", "luck", &[("luck", 6000, 0)]), p("slow_falling", "slow_falling", &[("slow_falling", 1800, 0)]), - p("long_slow_falling", "slow_falling", &[("slow_falling", 4800, 0)]), + p( + "long_slow_falling", + "slow_falling", + &[("slow_falling", 4800, 0)], + ), p("wind_charged", "wind_charged", &[("wind_charged", 3600, 0)]), p("weaving", "weaving", &[("weaving", 3600, 0)]), p("oozing", "oozing", &[("oozing", 3600, 0)]), @@ -142,7 +214,9 @@ pub fn potion(id: &str) -> Option<&'static PotionDef> { pub const BASE_POTION_COLOR: u32 = 0x385DC6; /// `PotionContents.getColor`: amplifier-weighted mix of visible effect colours. pub fn potion_color(id: Option<&str>) -> u32 { - let Some(def) = id.and_then(potion) else { return BASE_POTION_COLOR }; + let Some(def) = id.and_then(potion) else { + return BASE_POTION_COLOR; + }; let (mut r, mut g, mut b, mut total) = (0u32, 0u32, 0u32, 0u32); for (e, _, amp) in def.effects { let Some(e) = effect(e) else { continue }; @@ -152,7 +226,11 @@ pub fn potion_color(id: Option<&str>) -> u32 { b += w * (e.color & 255); total += w; } - match (r.checked_div(total), g.checked_div(total), b.checked_div(total)) { + match ( + r.checked_div(total), + g.checked_div(total), + b.checked_div(total), + ) { (Some(r), Some(g), Some(b)) => (r << 16) | (g << 8) | b, _ => BASE_POTION_COLOR, } @@ -161,7 +239,11 @@ pub fn potion_color(id: Option<&str>) -> u32 { pub fn format_duration(ticks: i32) -> String { let secs = ticks / 20; let (h, m, s) = (secs / 3600, secs / 60 % 60, secs % 60); - if h > 0 { format!("{h}:{m:02}:{s:02}") } else { format!("{m}:{s:02}") } + if h > 0 { + format!("{h}:{m:02}:{s:02}") + } else { + format!("{m}:{s:02}") + } } /// `item.minecraft.potion.effect.` style translation key for a potion item. pub fn potion_name_key(item: &str, potion: Option<&str>) -> String { @@ -170,18 +252,31 @@ pub fn potion_name_key(item: &str, potion: Option<&str>) -> String { format!("item.minecraft.{prefix}.effect.{suffix}") } /// Roman amplifier suffix (`potion.potency.N`) and duration lines of a potion. -pub fn tooltip(potion: Option<&str>, scale: f32, translate: &dyn Fn(&str) -> Option) -> Vec<(String, Category)> { - let Some(def) = potion.and_then(self::potion) else { return vec![] }; +pub fn tooltip( + potion: Option<&str>, + scale: f32, + translate: &dyn Fn(&str) -> Option, +) -> Vec<(String, Category)> { + let Some(def) = potion.and_then(self::potion) else { + return vec![]; + }; if def.effects.is_empty() { - return vec![(translate("effect.none").unwrap_or_else(|| "No Effects".into()), Category::Neutral)]; + return vec![( + translate("effect.none").unwrap_or_else(|| "No Effects".into()), + Category::Neutral, + )]; } def.effects .iter() .map(|(e, duration, amp)| { - let mut line = translate(&format!("effect.minecraft.{e}")).unwrap_or_else(|| (*e).to_owned()); + let mut line = + translate(&format!("effect.minecraft.{e}")).unwrap_or_else(|| (*e).to_owned()); if *amp > 0 { line.push(' '); - line.push_str(&translate(&format!("potion.potency.{amp}")).unwrap_or_else(|| crate::enchant::level_name(*amp as u32 + 1))); + line.push_str( + &translate(&format!("potion.potency.{amp}")) + .unwrap_or_else(|| crate::enchant::level_name(*amp as u32 + 1)), + ); } let instant = effect(e).is_some_and(|d| d.instant); let scaled = (*duration as f32 * scale) as i32; @@ -210,18 +305,32 @@ impl PotionIngredient { }; match &v["item"] { Value::String(s) => add(s, &mut set), - Value::Array(a) => a.iter().filter_map(Value::as_str).for_each(|s| add(s, &mut set)), + Value::Array(a) => a + .iter() + .filter_map(Value::as_str) + .for_each(|s| add(s, &mut set)), _ => {} } let potions = match &v["potion_contents"]["potions"] { Value::String(s) => Some([s.clone()].into_iter().collect()), - Value::Array(a) => Some(a.iter().filter_map(|x| x.as_str().map(str::to_owned)).collect()), + Value::Array(a) => Some( + a.iter() + .filter_map(|x| x.as_str().map(str::to_owned)) + .collect(), + ), _ => None, }; - Self { items: set, potions } + Self { + items: set, + potions, + } } pub fn test(&self, stack: &ItemStack) -> bool { - self.items.contains(&*stack.item) && self.potions.as_ref().is_none_or(|p| stack.potion().is_some_and(|x| p.contains(x))) + self.items.contains(&*stack.item) + && self + .potions + .as_ref() + .is_none_or(|p| stack.potion().is_some_and(|x| p.contains(x))) } } #[derive(Clone, Debug)] @@ -240,32 +349,60 @@ pub struct Brewing { } impl Brewing { pub fn load(root: &Path, items: &Items) -> Self { - let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/recipe/brewing")).into_iter().flatten().flatten().map(|e| e.path()).collect(); + let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/recipe/brewing")) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path()) + .collect(); files.sort(); let mut recipes = Vec::new(); for p in files { let Ok(bytes) = fs::read(&p) else { continue }; - let Ok(v) = serde_json::from_slice::(&bytes) else { continue }; + let Ok(v) = serde_json::from_slice::(&bytes) else { + continue; + }; if v["type"] != "minecraft:brewing" { continue; } - let mut output = ItemStack::new(v["output"]["id"].as_str().unwrap_or("minecraft:potion"), v["output"]["count"].as_u64().unwrap_or(1) as u32); - if let Some(potion) = v["output"]["components"]["minecraft:potion_contents"]["potion"].as_str() { + let mut output = ItemStack::new( + v["output"]["id"].as_str().unwrap_or("minecraft:potion"), + v["output"]["count"].as_u64().unwrap_or(1) as u32, + ); + if let Some(potion) = + v["output"]["components"]["minecraft:potion_contents"]["potion"].as_str() + { output = output.with_potion(potion); } recipes.push(BrewingRecipe { - id: format!("minecraft:brewing/{}", p.file_stem().and_then(|s| s.to_str()).unwrap_or("")), + id: format!( + "minecraft:brewing/{}", + p.file_stem().and_then(|s| s.to_str()).unwrap_or("") + ), input: PotionIngredient::parse(&v["input"], items), reagent: PotionIngredient::parse(&v["reagent"], items), output, }); } - let reagents = recipes.iter().flat_map(|r| r.reagent.items.iter().cloned()).collect(); - let inputs = recipes.iter().flat_map(|r| r.input.items.iter().cloned()).chain(std::iter::once("minecraft:glass_bottle".to_owned())).collect(); - Self { recipes, reagents, inputs } + let reagents = recipes + .iter() + .flat_map(|r| r.reagent.items.iter().cloned()) + .collect(); + let inputs = recipes + .iter() + .flat_map(|r| r.input.items.iter().cloned()) + .chain(std::iter::once("minecraft:glass_bottle".to_owned())) + .collect(); + Self { + recipes, + reagents, + inputs, + } } pub fn find(&self, input: &ItemStack, reagent: &ItemStack) -> Option<&BrewingRecipe> { - self.recipes.iter().find(|r| r.input.test(input) && r.reagent.test(reagent)) + self.recipes + .iter() + .find(|r| r.input.test(input) && r.reagent.test(reagent)) } pub fn is_reagent(&self, stack: &ItemStack) -> bool { self.reagents.contains(&*stack.item) @@ -299,14 +436,24 @@ pub struct BrewTick { } impl BrewingStand { pub fn new() -> Self { - Self { total_brew_time: 400, total_fuel: 20, speed: 1.0, ..Default::default() } + Self { + total_brew_time: 400, + total_fuel: 20, + speed: 1.0, + ..Default::default() + } } fn brewable(&self, brewing: &Brewing) -> bool { - let Some(ingredient) = &self.items[3] else { return false }; + let Some(ingredient) = &self.items[3] else { + return false; + }; if !brewing.is_reagent(ingredient) { return false; } - self.items[..3].iter().flatten().any(|b| brewing.find(b, ingredient).is_some()) + self.items[..3] + .iter() + .flatten() + .any(|b| brewing.find(b, ingredient).is_some()) } /// `BrewingStandBlockEntity.serverTick`. pub fn tick(&mut self, brewing: &Brewing, items: &Items, providers: &Providers) -> BrewTick { @@ -342,7 +489,11 @@ impl BrewingStand { self.total_brew_time = self.brew_time; self.ingredient = self.items[3].as_ref().map(|s| s.item.clone()); } - let bottles = [self.items[0].is_some(), self.items[1].is_some(), self.items[2].is_some()]; + let bottles = [ + self.items[0].is_some(), + self.items[1].is_some(), + self.items[2].is_some(), + ]; if self.last_bottles != Some(bottles) { self.last_bottles = Some(bottles); out.bottles = Some(bottles); @@ -350,7 +501,9 @@ impl BrewingStand { out } fn brew(&mut self, brewing: &Brewing, items: &Items, out: &mut BrewTick) { - let Some(ingredient) = self.items[3].clone() else { return }; + let Some(ingredient) = self.items[3].clone() else { + return; + }; for slot in 0..3 { if let Some(input) = &self.items[slot] && let Some(r) = brewing.find(input, &ingredient) @@ -358,7 +511,9 @@ impl BrewingStand { self.items[slot] = Some(r.output.clone()); } } - let remainder = items.get(&ingredient.item).and_then(|i| i.remainder.clone()); + let remainder = items + .get(&ingredient.item) + .and_then(|i| i.remainder.clone()); if let Some(i) = self.items[3].as_mut() { i.count -= 1; if i.count == 0 { @@ -387,8 +542,14 @@ mod tests { // Turtle master mixes slowness x4 and resistance x3. let (s, r) = (9154528u32, 9520880u32); let mix = |sh: u32| ((s >> sh & 255) * 4 + (r >> sh & 255) * 3) / 7; - assert_eq!(potion_color(Some("minecraft:turtle_master")), mix(16) << 16 | mix(8) << 8 | mix(0)); - assert_eq!(potion_name_key("minecraft:splash_potion", Some("minecraft:long_swiftness")), "item.minecraft.splash_potion.effect.swiftness"); + assert_eq!( + potion_color(Some("minecraft:turtle_master")), + mix(16) << 16 | mix(8) << 8 | mix(0) + ); + assert_eq!( + potion_name_key("minecraft:splash_potion", Some("minecraft:long_swiftness")), + "item.minecraft.splash_potion.effect.swiftness" + ); assert_eq!(format_duration(9600), "8:00"); assert_eq!(format_duration(450), "0:22"); let t = tooltip(Some("minecraft:strong_poison"), 1.0, &|_| None); @@ -403,16 +564,27 @@ mod tests { let items = Items::for_tests(item_tags); let recipe = BrewingRecipe { id: "awkward".into(), - input: PotionIngredient { items: ["minecraft:potion".to_owned()].into_iter().collect(), potions: Some(["minecraft:water".to_owned()].into_iter().collect()) }, - reagent: PotionIngredient { items: ["minecraft:nether_wart".to_owned()].into_iter().collect(), potions: None }, + input: PotionIngredient { + items: ["minecraft:potion".to_owned()].into_iter().collect(), + potions: Some(["minecraft:water".to_owned()].into_iter().collect()), + }, + reagent: PotionIngredient { + items: ["minecraft:nether_wart".to_owned()].into_iter().collect(), + potions: None, + }, output: ItemStack::new("minecraft:potion", 1).with_potion("minecraft:awkward"), }; - let brewing = Brewing { reagents: ["minecraft:nether_wart".to_owned()].into_iter().collect(), inputs: HashSet::new(), recipes: vec![recipe] }; + let brewing = Brewing { + reagents: ["minecraft:nether_wart".to_owned()].into_iter().collect(), + inputs: HashSet::new(), + recipes: vec![recipe], + }; let providers = Providers::empty(); let mut stand = BrewingStand::new(); stand.fuel = 1; stand.items[0] = Some(ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water")); - stand.items[2] = Some(ItemStack::new("minecraft:potion", 1).with_potion("minecraft:awkward")); + stand.items[2] = + Some(ItemStack::new("minecraft:potion", 1).with_potion("minecraft:awkward")); stand.items[3] = Some(ItemStack::new("minecraft:nether_wart", 2)); let first = stand.tick(&brewing, &items, &providers); assert_eq!(first.bottles, Some([true, false, true])); @@ -424,9 +596,15 @@ mod tests { } } assert_eq!(brewed_at, 400); - assert_eq!(stand.items[0].as_ref().unwrap().potion(), Some("minecraft:awkward")); + assert_eq!( + stand.items[0].as_ref().unwrap().potion(), + Some("minecraft:awkward") + ); // The awkward potion had no recipe and stays. - assert_eq!(stand.items[2].as_ref().unwrap().potion(), Some("minecraft:awkward")); + assert_eq!( + stand.items[2].as_ref().unwrap().potion(), + Some("minecraft:awkward") + ); assert_eq!(stand.items[3].as_ref().unwrap().count, 1); // No fuel left: nothing more brews. stand.tick(&brewing, &items, &providers); diff --git a/crates/horizon-client/src/chat.rs b/crates/horizon-client/src/chat.rs index 33459b29f..1c5abe777 100644 --- a/crates/horizon-client/src/chat.rs +++ b/crates/horizon-client/src/chat.rs @@ -24,7 +24,15 @@ pub struct ChatOptions { } impl Default for ChatOptions { fn default() -> Self { - Self { opacity: 1.0, background_opacity: 0.5, scale: 1.0, width: 1.0, height_focused: 1.0, height_unfocused: 70.0 / 160.0, line_spacing: 0.0 } + Self { + opacity: 1.0, + background_opacity: 0.5, + scale: 1.0, + width: 1.0, + height_focused: 1.0, + height_unfocused: 70.0 / 160.0, + line_spacing: 0.0, + } } } impl ChatOptions { @@ -33,7 +41,13 @@ impl ChatOptions { (self.width * 280.0 + 40.0).floor() } pub fn height_px(&self, focused: bool) -> f32 { - ((if focused { self.height_focused } else { self.height_unfocused }) * 160.0 + 20.0).floor() + ((if focused { + self.height_focused + } else { + self.height_unfocused + }) * 160.0 + + 20.0) + .floor() } pub fn line_height(&self) -> f32 { (9.0 * (self.line_spacing + 1.0)).floor() @@ -72,11 +86,22 @@ impl Chat { (self.options.width_px() / self.options.scale.max(0.01)).floor() } /// ChatComponent.addMessage: wrap, prepend and trim to 100 lines. - pub fn add(&mut self, atlas: &HudAtlas, content: Text, indicator: Option, ticks: u64, focused: bool) { + pub fn add( + &mut self, + atlas: &HudAtlas, + content: Text, + indicator: Option, + ticks: u64, + focused: bool, + ) { if self.log { println!("[CHAT] {}", content.plain()); } - let message = Message { added: ticks, content, indicator }; + let message = Message { + added: ticks, + content, + indicator, + }; self.add_lines(atlas, &message, focused); self.messages.insert(0, message); self.messages.truncate(100); @@ -88,7 +113,14 @@ impl Chat { self.new_since_scroll = true; self.scroll_by(1, focused); } - self.lines.insert(0, Line { added: message.added, content: line, indicator: message.indicator }); + self.lines.insert( + 0, + Line { + added: message.added, + content: line, + indicator: message.indicator, + }, + ); } self.lines.truncate(100); } @@ -120,7 +152,10 @@ impl Chat { self.new_since_scroll = false; } pub fn scroll_by(&mut self, dir: i32, focused: bool) { - let max = self.lines.len().saturating_sub(self.lines_per_page(focused)) as i32; + let max = self + .lines + .len() + .saturating_sub(self.lines_per_page(focused)) as i32; let pos = (self.scroll as i32 + dir).min(max); if pos <= 0 { self.scroll = 0; @@ -149,7 +184,8 @@ impl Chat { if focused { return 1.0; } - let t = ((1.0 - (ticks.saturating_sub(line.added)) as f64 / 200.0) * 10.0).clamp(0.0, 1.0); + let t = + ((1.0 - (ticks.saturating_sub(line.added)) as f64 / 200.0) * 10.0).clamp(0.0, 1.0); (t * t) as f32 }; let visible = self.lines.len().saturating_sub(self.scroll).min(per_page); @@ -165,7 +201,14 @@ impl Chat { count += 1; let bottom = chat_bottom - i as f32 * entry_height; let top = bottom - entry_height; - batch.fill(atlas, 0.0, s(top), s(max_width + 8.0), s(entry_height), rgba(0, 0, 0, (alpha * o.background_opacity * 255.0) as u8)); + batch.fill( + atlas, + 0.0, + s(top), + s(max_width + 8.0), + s(entry_height), + rgba(0, 0, 0, (alpha * o.background_opacity * 255.0) as u8), + ); } for i in (0..visible).rev() { let line = &self.lines[i + self.scroll]; @@ -178,10 +221,24 @@ impl Chat { let text_top = bottom - bottom_to_text; let a = (alpha * text_opacity * 255.0) as u8; if let Some(c) = line.indicator { - batch.fill(atlas, 0.0, s(top), s(2.0), s(entry_height), rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, a)); + batch.fill( + atlas, + 0.0, + s(top), + s(2.0), + s(entry_height), + rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, a), + ); } if a > 3 { - batch.text_styled(atlas, &line.content, s(4.0), s(text_top), rgba(255, 255, 255, a), true); + batch.text_styled( + atlas, + &line.content, + s(4.0), + s(text_top), + rgba(255, 255, 255, a), + true, + ); } } // Scroll bar while focused and scrolled content exists. @@ -193,16 +250,38 @@ impl Chat { let y = self.scroll as f32 * chat_height / total - chat_bottom; let height = chat_height * chat_height / virtual_height; let alpha = if y > 0.0 { 170 } else { 96 }; - let c = if self.new_since_scroll { 0xCC3333 } else { 0x3333AA }; + let c = if self.new_since_scroll { + 0xCC3333 + } else { + 0x3333AA + }; let x = max_width + 4.0 + 4.0; - batch.fill(atlas, s(x), s(-y - height), s(2.0), s(height), rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, alpha)); - batch.fill(atlas, s(x + 1.0), s(-y - height), s(1.0), s(height), rgba(0xCC, 0xCC, 0xCC, alpha)); + batch.fill( + atlas, + s(x), + s(-y - height), + s(2.0), + s(height), + rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, alpha), + ); + batch.fill( + atlas, + s(x + 1.0), + s(-y - height), + s(1.0), + s(height), + rgba(0xCC, 0xCC, 0xCC, alpha), + ); } } } /// Plain text of the newest messages (for tests and the control socket). pub fn recent_lines(&self, n: usize) -> Vec { - self.messages.iter().take(n).map(|m| m.content.plain()).collect() + self.messages + .iter() + .take(n) + .map(|m| m.content.plain()) + .collect() } } @@ -292,7 +371,10 @@ impl ChatScreen { self.usage.clear(); self.pending.clear(); let cursor_chars = self.input.cursor; - let cursor = command.char_indices().nth(cursor_chars).map_or(command.len(), |(i, _)| i); + let cursor = command + .char_indices() + .nth(cursor_chars) + .map_or(command.len(), |(i, _)| i); if !command.starts_with('/') { return; } @@ -317,8 +399,19 @@ impl ChatScreen { } } if literals > 0 { - let reader = crate::command::Reader { string: &parse.input, cursor: parse.cursor }; - self.usage.push(crate::command::CommandError::tr_at("command.unknown.argument", &[], &reader).with_context().with_color(text::RED)); + let reader = crate::command::Reader { + string: &parse.input, + cursor: parse.cursor, + }; + self.usage.push( + crate::command::CommandError::tr_at( + "command.unknown.argument", + &[], + &reader, + ) + .with_context() + .with_color(text::RED), + ); } } else if parse.can_read() { trailing = true; @@ -329,7 +422,9 @@ impl ChatScreen { let mut lines: Vec = d .smart_usage(node, reg.permission) .into_iter() - .filter(|(n, _)| !matches!(d.nodes[*n].kind, crate::command::NodeKind::Literal(_))) + .filter(|(n, _)| { + !matches!(d.nodes[*n].kind, crate::command::NodeKind::Literal(_)) + }) .map(|(_, u)| Text::colored(u, text::GRAY)) .collect(); if lines.is_empty() @@ -340,12 +435,20 @@ impl ChatScreen { } self.usage = lines; } - let usage_width = self.usage.iter().map(|u| atlas.font.width_text(u)).fold(0.0, f32::max); + let usage_width = self + .usage + .iter() + .map(|u| atlas.font.width_text(u)) + .fold(0.0, f32::max); let start_chars = char_len(&command[..start.min(command.len())]); self.usage_x = if self.usage.is_empty() { 0.0 } else { - self.input.screen_x(atlas, start_chars).clamp(0.0, (self.input.screen_x(atlas, 0) + self.input.inner_width() - usage_width).max(0.0)) + self.input.screen_x(atlas, start_chars).clamp( + 0.0, + (self.input.screen_x(atlas, 0) + self.input.inner_width() - usage_width) + .max(0.0), + ) }; self.suggestions = None; if self.allow_suggestions && self.auto_suggestions { @@ -359,18 +462,39 @@ impl ChatScreen { return; } let value = self.input.value.clone(); - let width = self.pending.iter().map(|s| atlas.font.width(&s.text)).fold(0.0, f32::max); + let width = self + .pending + .iter() + .map(|s| atlas.font.width(&s.text)) + .fold(0.0, f32::max); let start_chars = char_len(&value[..self.pending_start.min(value.len())]); - let x = self.input.screen_x(atlas, start_chars).clamp(0.0, (self.input.screen_x(atlas, 0) + self.input.inner_width() - width).max(0.0)); + let x = self.input.screen_x(atlas, start_chars).clamp( + 0.0, + (self.input.screen_x(atlas, 0) + self.input.inner_width() - width).max(0.0), + ); // Sort: suggestions starting with the last word first. - let cursor = value.char_indices().nth(self.input.cursor).map_or(value.len(), |(i, _)| i); + let cursor = value + .char_indices() + .nth(self.input.cursor) + .map_or(value.len(), |(i, _)| i); let partial = &value[..cursor]; let last_word = partial.rfind(char::is_whitespace).map_or(0, |i| i + 1); let word = partial[last_word..].to_lowercase(); let (mut first, partial_matches): (Vec, Vec) = - self.pending.iter().cloned().partition(|s| s.text.starts_with(&word) || s.text.starts_with(&format!("minecraft:{word}"))); + self.pending.iter().cloned().partition(|s| { + s.text.starts_with(&word) || s.text.starts_with(&format!("minecraft:{word}")) + }); first.extend(partial_matches); - let mut list = SuggestionList { x: x - 1.0, width: width + 1.0, list: first, offset: 0, current: 0, original: value, tab_cycles: false, last_mouse: (-1.0, -1.0) }; + let mut list = SuggestionList { + x: x - 1.0, + width: width + 1.0, + list: first, + offset: 0, + current: 0, + original: value, + tab_cycles: false, + last_mouse: (-1.0, -1.0), + }; self.select(&mut list, 0); self.suggestions = Some(list); } @@ -378,7 +502,10 @@ impl ChatScreen { let n = list.list.len() as isize; list.current = index.rem_euclid(n.max(1)) as usize; let applied = list.list[list.current].apply(&list.original); - self.input.suggestion = applied.strip_prefix(self.input.value.as_str()).filter(|s| !s.is_empty()).map(str::to_owned); + self.input.suggestion = applied + .strip_prefix(self.input.value.as_str()) + .filter(|s| !s.is_empty()) + .map(str::to_owned); } fn cycle(&mut self, list: &mut SuggestionList, dir: isize) { self.select(list, list.current as isize + dir); @@ -395,7 +522,8 @@ impl ChatScreen { self.keep_suggestions = true; let applied = s.apply(&list.original); self.input.set_value(&applied); - let end = char_len(&list.original[..s.range.0.min(list.original.len())]) + char_len(&s.text); + let end = + char_len(&list.original[..s.range.0.min(list.original.len())]) + char_len(&s.text); self.input.set_cursor(end, false); self.dirty = true; self.select(list, list.current as isize); @@ -403,7 +531,14 @@ impl ChatScreen { list.tab_cycles = true; } /// Suggestion-list keys (CommandSuggestions.keyPressed). Returns true if handled. - pub fn suggestion_key(&mut self, atlas: &HudAtlas, d: &Dispatcher, reg: &Registries, key: winit::keyboard::KeyCode, shift: bool) -> bool { + pub fn suggestion_key( + &mut self, + atlas: &HudAtlas, + d: &Dispatcher, + reg: &Registries, + key: winit::keyboard::KeyCode, + shift: bool, + ) -> bool { use winit::keyboard::KeyCode as K; self.update(atlas, d, reg); if let Some(mut list) = self.suggestions.take() { @@ -470,7 +605,9 @@ impl ChatScreen { } /// Mouse wheel over the suggestion list. pub fn scroll_suggestions(&mut self, cursor: (f32, f32), height: f32, amount: f32) -> bool { - let Some(list) = &mut self.suggestions else { return false }; + let Some(list) = &mut self.suggestions else { + return false; + }; let n = list.list.len().min(10); let top = height - 12.0 - 3.0 - n as f32 * 12.0; if crate::ui::hovered(cursor, list.x, top, list.width, n as f32 * 12.0) { @@ -482,7 +619,9 @@ impl ChatScreen { } /// Click on a suggestion row. pub fn click(&mut self, cursor: (f32, f32), height: f32) -> bool { - let Some(mut list) = self.suggestions.take() else { return false }; + let Some(mut list) = self.suggestions.take() else { + return false; + }; let n = list.list.len().min(10); let top = height - 12.0 - 3.0 - n as f32 * 12.0; if crate::ui::hovered(cursor, list.x, top, list.width, n as f32 * 12.0) { @@ -501,7 +640,13 @@ impl ChatScreen { fn formatted(&self) -> Option { let parse = self.parse.as_ref()?; let value = &self.input.value; - let styles = [text::AQUA, text::YELLOW, text::GREEN, text::LIGHT_PURPLE, text::GOLD]; + let styles = [ + text::AQUA, + text::YELLOW, + text::GREEN, + text::LIGHT_PURPLE, + text::GOLD, + ]; let mut colors = vec![text::GRAY; value.len()]; let ctx = parse.context.last_child(); for (i, arg) in ctx.args.iter().enumerate() { @@ -522,10 +667,25 @@ impl ChatScreen { Some(out) } /// ChatScreen.extractRenderState minus the chat lines. - pub fn draw(&mut self, batch: &mut HudBatch, atlas: &HudAtlas, d: &Dispatcher, reg: &Registries, cursor: (f32, f32), background_opacity: f32) { + pub fn draw( + &mut self, + batch: &mut HudBatch, + atlas: &HudAtlas, + d: &Dispatcher, + reg: &Registries, + cursor: (f32, f32), + background_opacity: f32, + ) { self.update(atlas, d, reg); let (w, h) = (batch.width, batch.height); - batch.fill(atlas, 2.0, h - 14.0, w - 4.0, 12.0, rgba(0, 0, 0, (background_opacity * 255.0) as u8)); + batch.fill( + atlas, + 2.0, + h - 14.0, + w - 4.0, + 12.0, + rgba(0, 0, 0, (background_opacity * 255.0) as u8), + ); let formatted = self.formatted(); self.input.draw(batch, atlas, formatted.as_ref()); let fill = fill_color(); @@ -538,13 +698,27 @@ impl ChatScreen { list.last_mouse = cursor; if has_prev || has_next { batch.fill(atlas, list.x, top - 1.0, list.width, 1.0, fill); - batch.fill(atlas, list.x, top + limit as f32 * 12.0, list.width, 1.0, fill); + batch.fill( + atlas, + list.x, + top + limit as f32 * 12.0, + list.width, + 1.0, + fill, + ); for x in (0..list.width as i32).step_by(2) { if has_prev { batch.fill(atlas, list.x + x as f32, top - 1.0, 1.0, 1.0, u32::MAX); } if has_next { - batch.fill(atlas, list.x + x as f32, top + limit as f32 * 12.0, 1.0, 1.0, u32::MAX); + batch.fill( + atlas, + list.x + x as f32, + top + limit as f32 * 12.0, + 1.0, + 1.0, + u32::MAX, + ); } } } @@ -552,7 +726,11 @@ impl ChatScreen { for i in 0..limit { let y = top + 12.0 * i as f32; batch.fill(atlas, list.x, y, list.width, 12.0, fill); - if cursor.0 > list.x && cursor.0 < list.x + list.width && cursor.1 > y && cursor.1 < y + 12.0 { + if cursor.0 > list.x + && cursor.0 < list.x + list.width + && cursor.1 > y + && cursor.1 < y + 12.0 + { hovered_row = Some(i + list.offset); } } @@ -561,8 +739,19 @@ impl ChatScreen { } for i in 0..limit { let s = &list.list[i + list.offset]; - let color = if i + list.offset == list.current { rgba(255, 255, 0, 255) } else { rgba(0xAA, 0xAA, 0xAA, 255) }; - batch.text(atlas, &s.text, list.x + 1.0, top + 2.0 + 12.0 * i as f32, color, true); + let color = if i + list.offset == list.current { + rgba(255, 255, 0, 255) + } else { + rgba(0xAA, 0xAA, 0xAA, 255) + }; + batch.text( + atlas, + &s.text, + list.x + 1.0, + top + 2.0 + 12.0 * i as f32, + color, + true, + ); } if hovered_row.is_some() && let Some(tip) = &list.list[list.current].tooltip @@ -581,7 +770,12 @@ impl ChatScreen { } /// ChatScreen.normalizeChatMessage. pub fn normalized(&self) -> String { - let collapsed = self.input.value.split_whitespace().collect::>().join(" "); + let collapsed = self + .input + .value + .split_whitespace() + .collect::>() + .join(" "); collapsed.chars().take(256).collect() } pub fn suggestions_visible(&self) -> bool { diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs index 7f436033a..c9dee3e73 100644 --- a/crates/horizon-client/src/chunk.rs +++ b/crates/horizon-client/src/chunk.rs @@ -111,7 +111,9 @@ impl Chunk { Self { x, z, - sections: (0..SECTIONS).map(|_| Arc::new(Section::default())).collect(), + sections: (0..SECTIONS) + .map(|_| Arc::new(Section::default())) + .collect(), biomes: Arc::new(vec![0; 16 * (HEIGHT as usize / 4)]), heights: Arc::new([MIN_Y as i16; 256]), lit: false, diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-client/src/command/args.rs index 3500f6fd6..98c7810ab 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-client/src/command/args.rs @@ -70,15 +70,29 @@ impl Resource { #[derive(Clone, Debug)] pub enum ArgType { Bool, - Integer { min: i32, max: i32 }, - Float { min: f32, max: f32 }, - Double { min: f64, max: f64 }, + Integer { + min: i32, + max: i32, + }, + Float { + min: f32, + max: f32, + }, + Double { + min: f64, + max: f64, + }, Word, Str, Greedy, - Entity { single: bool, players: bool }, + Entity { + single: bool, + players: bool, + }, BlockPos, - Vec3 { center: bool }, + Vec3 { + center: bool, + }, Rotation, Angle, Item, @@ -88,7 +102,9 @@ pub enum ArgType { Resource(Resource), /// A plain identifier; suggestions come from the named list. Id(&'static str), - Time { min: i32 }, + Time { + min: i32, + }, GameMode, Message, Dimension, @@ -107,7 +123,11 @@ pub struct Coord { } impl Coord { pub fn get(self, base: f64) -> f64 { - if self.relative { base + self.value } else { self.value } + if self.relative { + base + self.value + } else { + self.value + } } } #[derive(Clone, Debug, PartialEq)] @@ -130,10 +150,22 @@ impl Coordinates { let sin_p = (-pitch * d).sin(); let cos_p2 = ((-pitch + 90.0) * d).cos(); let sin_p2 = ((-pitch + 90.0) * d).sin(); - let f = [f64::from(cos_y * cos_p), f64::from(sin_p), f64::from(sin_y * cos_p)]; - let u = [f64::from(cos_y * cos_p2), f64::from(sin_p2), f64::from(sin_y * cos_p2)]; + let f = [ + f64::from(cos_y * cos_p), + f64::from(sin_p), + f64::from(sin_y * cos_p), + ]; + let u = [ + f64::from(cos_y * cos_p2), + f64::from(sin_p2), + f64::from(sin_y * cos_p2), + ]; // left = -(forward x up) - let l = [-(f[1] * u[2] - f[2] * u[1]), -(f[2] * u[0] - f[0] * u[2]), -(f[0] * u[1] - f[1] * u[0])]; + let l = [ + -(f[1] * u[2] - f[2] * u[1]), + -(f[2] * u[0] - f[0] * u[2]), + -(f[0] * u[1] - f[1] * u[0]), + ]; [ pos[0] + f[0] * forwards + u[0] * up + l[0] * left, pos[1] + f[1] * forwards + u[1] * up + l[1] * left, @@ -144,12 +176,19 @@ impl Coordinates { } pub fn block(&self, pos: [f64; 3], rot: [f32; 2]) -> [i32; 3] { let p = self.position(pos, rot); - [p[0].floor() as i32, p[1].floor() as i32, p[2].floor() as i32] + [ + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32, + ] } /// RotationArgument: (yaw, pitch) from the source rotation. pub fn rotation(&self, rot: [f32; 2]) -> [f32; 2] { match self { - Coordinates::World(c) => [c[0].get(f64::from(rot[0])) as f32, c[1].get(f64::from(rot[1])) as f32], + Coordinates::World(c) => [ + c[0].get(f64::from(rot[0])) as f32, + c[1].get(f64::from(rot[1])) as f32, + ], Coordinates::Local(_) => rot, } } @@ -215,7 +254,12 @@ pub enum GameMode { Spectator, } impl GameMode { - pub const ALL: [GameMode; 4] = [GameMode::Survival, GameMode::Creative, GameMode::Adventure, GameMode::Spectator]; + pub const ALL: [GameMode; 4] = [ + GameMode::Survival, + GameMode::Creative, + GameMode::Adventure, + GameMode::Spectator, + ]; pub fn name(self) -> &'static str { match self { GameMode::Survival => "survival", @@ -257,7 +301,10 @@ pub fn read_id(reader: &mut Reader) -> CmdResult { reader.skip(); } let raw = &reader.string[start..reader.cursor]; - let valid = !raw.is_empty() && raw.matches(':').count() <= 1 && !raw.ends_with(':') && !raw.split(':').next().unwrap_or("").contains('/'); + let valid = !raw.is_empty() + && raw.matches(':').count() <= 1 + && !raw.ends_with(':') + && !raw.split(':').next().unwrap_or("").contains('/'); if !valid { reader.cursor = start; return Err(CommandError::tr_at("argument.id.invalid", &[], reader)); @@ -286,15 +333,23 @@ pub fn matches_sub_str(input: &str, candidate: &str) -> bool { } } /// SharedSuggestionProvider.suggestResource. -pub fn suggest_resources<'a>(builder: &mut SuggestionsBuilder, ids: impl IntoIterator, prefix: &str) { +pub fn suggest_resources<'a>( + builder: &mut SuggestionsBuilder, + ids: impl IntoIterator, + prefix: &str, +) { let remaining = builder.remaining_lower(); - let remaining = remaining.strip_prefix(prefix).unwrap_or(&remaining).to_owned(); + let remaining = remaining + .strip_prefix(prefix) + .unwrap_or(&remaining) + .to_owned(); for id in ids { let matched = if remaining.contains(':') { matches_sub_str(&remaining, id) } else { let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id)); - matches_sub_str(&remaining, ns) || (ns == "minecraft" && matches_sub_str(&remaining, path)) + matches_sub_str(&remaining, ns) + || (ns == "minecraft" && matches_sub_str(&remaining, path)) }; if matched { builder.suggest(format!("{prefix}{id}")); @@ -303,7 +358,10 @@ pub fn suggest_resources<'a>(builder: &mut SuggestionsBuilder, ids: impl IntoIte } fn range_double(reader: &mut Reader) -> CmdResult { let (a, b) = read_range(reader)?; - let parse = |s: &str, reader: &Reader| s.parse::().map_err(|_| CommandError::tr_at("parsing.double.invalid", &[&s], reader)); + let parse = |s: &str, reader: &Reader| { + s.parse::() + .map_err(|_| CommandError::tr_at("parsing.double.invalid", &[&s], reader)) + }; let lo = a.map(|s| parse(&s, reader)).transpose()?; let hi = b.map(|s| parse(&s, reader)).transpose()?; if let (Some(l), Some(h)) = (lo, hi) @@ -319,7 +377,8 @@ fn range_int(reader: &mut Reader) -> CmdResult { if s.contains('.') { return Err(CommandError::tr_at("argument.range.ints", &[], reader)); } - s.parse::().map_err(|_| CommandError::tr_at("parsing.int.invalid", &[&s], reader)) + s.parse::() + .map_err(|_| CommandError::tr_at("parsing.int.invalid", &[&s], reader)) }; let lo = a.map(|s| parse(&s, reader)).transpose()?; let hi = b.map(|s| parse(&s, reader)).transpose()?; @@ -337,7 +396,11 @@ fn read_range(reader: &mut Reader) -> CmdResult<(Option, Option) } let number = |reader: &mut Reader| { let start = reader.cursor; - while reader.can_read() && (reader.peek().is_ascii_digit() || reader.peek() == '-' || (reader.peek() == '.' && reader.peek_at(1) != '.')) { + while reader.can_read() + && (reader.peek().is_ascii_digit() + || reader.peek() == '-' + || (reader.peek() == '.' && reader.peek_at(1) != '.')) + { reader.skip(); } let s = &reader.string[start..reader.cursor]; @@ -368,7 +431,11 @@ fn parse_coord_int(reader: &mut Reader) -> CmdResult { reader.skip(); } let value = if reader.can_read() && reader.peek() != ' ' { - if relative { reader.read_double()? } else { f64::from(reader.read_int()?) } + if relative { + reader.read_double()? + } else { + f64::from(reader.read_int()?) + } } else { 0.0 }; @@ -379,17 +446,28 @@ fn parse_coord_double(reader: &mut Reader, center: bool) -> CmdResult { return Err(CommandError::tr_at("argument.pos.mixed", &[], reader)); } if !reader.can_read() { - return Err(CommandError::tr_at("argument.pos.missing.double", &[], reader)); + return Err(CommandError::tr_at( + "argument.pos.missing.double", + &[], + reader, + )); } let relative = reader.peek() == '~'; if relative { reader.skip(); } let start = reader.cursor; - let mut value = if reader.can_read() && reader.peek() != ' ' { reader.read_double()? } else { 0.0 }; + let mut value = if reader.can_read() && reader.peek() != ' ' { + reader.read_double()? + } else { + 0.0 + }; let number = &reader.string[start..reader.cursor]; if relative && number.is_empty() { - return Ok(Coord { relative, value: 0.0 }); + return Ok(Coord { + relative, + value: 0.0, + }); } if !number.contains('.') && !relative && center { value += 0.5; @@ -403,7 +481,11 @@ fn parse_local(reader: &mut Reader) -> CmdResult { if i > 0 { if !reader.can_read() || reader.peek() != ' ' { reader.cursor = start; - return Err(CommandError::tr_at("argument.pos3d.incomplete", &[], reader)); + return Err(CommandError::tr_at( + "argument.pos3d.incomplete", + &[], + reader, + )); } reader.skip(); } @@ -412,22 +494,37 @@ fn parse_local(reader: &mut Reader) -> CmdResult { return Err(CommandError::tr_at("argument.pos.mixed", &[], reader)); } reader.skip(); - *slot = if reader.can_read() && reader.peek() != ' ' { reader.read_double()? } else { 0.0 }; + *slot = if reader.can_read() && reader.peek() != ' ' { + reader.read_double()? + } else { + 0.0 + }; } Ok(Coordinates::Local(v)) } fn parse_world(reader: &mut Reader, block: bool, center: bool) -> CmdResult { let start = reader.cursor; - let mut c = [Coord { relative: false, value: 0.0 }; 3]; + let mut c = [Coord { + relative: false, + value: 0.0, + }; 3]; for (i, slot) in c.iter_mut().enumerate() { if i > 0 { if !reader.can_read() || reader.peek() != ' ' { reader.cursor = start; - return Err(CommandError::tr_at("argument.pos3d.incomplete", &[], reader)); + return Err(CommandError::tr_at( + "argument.pos3d.incomplete", + &[], + reader, + )); } reader.skip(); } - *slot = if block { parse_coord_int(reader)? } else { parse_coord_double(reader, center && i != 1)? }; + *slot = if block { + parse_coord_int(reader)? + } else { + parse_coord_double(reader, center && i != 1)? + }; } Ok(Coordinates::World(c)) } @@ -470,7 +567,22 @@ const SELECTORS: [(&str, &str); 6] = [ ("@s", "argument.entity.selector.self"), ]; const OPTIONS: [&str; 16] = [ - "name", "distance", "level", "x", "y", "z", "dx", "dy", "dz", "x_rotation", "y_rotation", "limit", "sort", "gamemode", "tag", "type", + "name", + "distance", + "level", + "x", + "y", + "z", + "dx", + "dy", + "dz", + "x_rotation", + "y_rotation", + "limit", + "sort", + "gamemode", + "tag", + "type", ]; fn parse_selector(reader: &mut Reader, reg: &Registries) -> CmdResult { let start = reader.cursor; @@ -481,14 +593,27 @@ fn parse_selector(reader: &mut Reader, reg: &Registries) -> CmdResult reader.cursor = start; return Err(CommandError::tr_at("argument.entity.invalid", &[], reader)); } - return Ok(Selector { player_name: Some(name), kind: '\0', limit: 1, include_entities: false, ..Selector::default() }); + return Ok(Selector { + player_name: Some(name), + kind: '\0', + limit: 1, + include_entities: false, + ..Selector::default() + }); } reader.skip(); if !reader.can_read() { - return Err(CommandError::tr_at("argument.entity.selector.missing", &[], reader)); + return Err(CommandError::tr_at( + "argument.entity.selector.missing", + &[], + reader, + )); } let kind = reader.read(); - let mut s = Selector { kind, ..Selector::default() }; + let mut s = Selector { + kind, + ..Selector::default() + }; match kind { 'p' => { s.limit = 1; @@ -519,7 +644,11 @@ fn parse_selector(reader: &mut Reader, reg: &Registries) -> CmdResult } other => { reader.cursor = start; - return Err(CommandError::tr_at("argument.entity.selector.unknown", &[&format!("@{other}")], reader)); + return Err(CommandError::tr_at( + "argument.entity.selector.unknown", + &[&format!("@{other}")], + reader, + )); } } if reader.can_read() && reader.peek() == '[' { @@ -531,12 +660,20 @@ fn parse_selector(reader: &mut Reader, reg: &Registries) -> CmdResult let option = reader.read_string()?; if !OPTIONS.contains(&option.as_str()) { reader.cursor = option_start; - return Err(CommandError::tr_at("argument.entity.options.unknown", &[&option], reader)); + return Err(CommandError::tr_at( + "argument.entity.options.unknown", + &[&option], + reader, + )); } reader.skip_whitespace(); if !reader.can_read() || reader.peek() != '=' { reader.cursor = option_start; - return Err(CommandError::tr_at("argument.entity.options.valueless", &[&option], reader)); + return Err(CommandError::tr_at( + "argument.entity.options.valueless", + &[&option], + reader, + )); } reader.skip(); reader.skip_whitespace(); @@ -560,18 +697,30 @@ fn parse_selector(reader: &mut Reader, reg: &Registries) -> CmdResult let r = range_double(reader)?; if r.0.is_some_and(|v| v < 0.0) || r.1.is_some_and(|v| v < 0.0) { reader.cursor = option_start; - return Err(CommandError::tr_at("argument.entity.options.distance.negative", &[], reader)); + return Err(CommandError::tr_at( + "argument.entity.options.distance.negative", + &[], + reader, + )); } s.distance = Some(r); if s.kind != 's' { - s.sort = if s.sort == Sort::Arbitrary { Sort::Arbitrary } else { s.sort }; + s.sort = if s.sort == Sort::Arbitrary { + Sort::Arbitrary + } else { + s.sort + }; } } "level" => { let r = range_int(reader)?; if r.0.is_some_and(|v| v < 0) || r.1.is_some_and(|v| v < 0) { reader.cursor = option_start; - return Err(CommandError::tr_at("argument.entity.options.level.negative", &[], reader)); + return Err(CommandError::tr_at( + "argument.entity.options.level.negative", + &[], + reader, + )); } s.level = Some(r); s.include_entities = false; @@ -591,7 +740,11 @@ fn parse_selector(reader: &mut Reader, reg: &Registries) -> CmdResult let n = reader.read_int()?; if n < 1 { reader.cursor = at; - return Err(CommandError::tr_at("argument.entity.options.limit.toosmall", &[], reader)); + return Err(CommandError::tr_at( + "argument.entity.options.limit.toosmall", + &[], + reader, + )); } s.limit = n as usize; } @@ -605,7 +758,11 @@ fn parse_selector(reader: &mut Reader, reg: &Registries) -> CmdResult "arbitrary" => Sort::Arbitrary, _ => { reader.cursor = at; - return Err(CommandError::tr_at("argument.entity.options.sort.irreversible", &[&v], reader)); + return Err(CommandError::tr_at( + "argument.entity.options.sort.irreversible", + &[&v], + reader, + )); } }; } @@ -615,7 +772,11 @@ fn parse_selector(reader: &mut Reader, reg: &Registries) -> CmdResult let v = reader.read_unquoted_string().to_owned(); if GameMode::from_name(&v).is_none() { reader.cursor = at; - return Err(CommandError::tr_at("argument.entity.options.mode.invalid", &[&v], reader)); + return Err(CommandError::tr_at( + "argument.entity.options.mode.invalid", + &[&v], + reader, + )); } s.gamemodes.push((v, neg)); s.include_entities = false; @@ -635,7 +796,11 @@ fn parse_selector(reader: &mut Reader, reg: &Registries) -> CmdResult let id = read_id(reader)?; if !tag && !reg.entity_types.is_empty() && !reg.entity_types.contains(&id) { reader.cursor = at; - return Err(CommandError::tr_at("argument.entity.options.type.invalid", &[&id], reader)); + return Err(CommandError::tr_at( + "argument.entity.options.type.invalid", + &[&id], + reader, + )); } let id = if tag { format!("#{id}") } else { id }; if s.kind == 'p' || s.kind == 'a' || s.kind == 'r' { @@ -654,11 +819,19 @@ fn parse_selector(reader: &mut Reader, reg: &Registries) -> CmdResult continue; } if !reader.can_read() || reader.peek() != ']' { - return Err(CommandError::tr_at("argument.entity.options.unterminated", &[], reader)); + return Err(CommandError::tr_at( + "argument.entity.options.unterminated", + &[], + reader, + )); } } if !reader.can_read() { - return Err(CommandError::tr_at("argument.entity.options.unterminated", &[], reader)); + return Err(CommandError::tr_at( + "argument.entity.options.unterminated", + &[], + reader, + )); } reader.skip(); } @@ -682,7 +855,8 @@ fn suggest_selector(builder: &mut SuggestionsBuilder, reg: &Registries) { let complete = match name { "type" => { let v = value.trim_start_matches('#'); - !v.is_empty() && (reg.entity_types.contains(&normalize(v)) || value.starts_with('#')) + !v.is_empty() + && (reg.entity_types.contains(&normalize(v)) || value.starts_with('#')) } "sort" => ["nearest", "furthest", "random", "arbitrary"].contains(&value), "gamemode" => GameMode::from_name(value).is_some(), @@ -716,7 +890,10 @@ fn suggest_selector(builder: &mut SuggestionsBuilder, reg: &Registries) { let lower = part.trim_start().to_lowercase(); for o in OPTIONS { if o.starts_with(&lower) { - b.suggest_tooltip(format!("{o}="), crate::lang::get(&format!("argument.entity.options.{o}.description"))); + b.suggest_tooltip( + format!("{o}="), + crate::lang::get(&format!("argument.entity.options.{o}.description")), + ); } } if part.is_empty() { @@ -745,16 +922,28 @@ fn parse_block(reader: &mut Reader, reg: &Registries, tags: bool) -> CmdResult CmdResult CmdResult CmdResult CmdResult { @@ -832,13 +1057,19 @@ fn read_braced(reader: &mut Reader, open: char, close: char) -> CmdResult {} } } - Err(CommandError::tr_at("argument.nbt.expected.compound", &[], reader)) + Err(CommandError::tr_at( + "argument.nbt.expected.compound", + &[], + reader, + )) } fn suggest_block(builder: &mut SuggestionsBuilder, reg: &Registries, tags: bool) { let remaining = builder.remaining().to_owned(); if let Some(open) = remaining.find('[') { let id = normalize(&remaining[..open]); - let Some(props) = reg.blocks.get(&id) else { return }; + let Some(props) = reg.blocks.get(&id) else { + return; + }; let inside = &remaining[open + 1..]; if inside.contains(']') { return; @@ -846,7 +1077,10 @@ fn suggest_block(builder: &mut SuggestionsBuilder, reg: &Registries, tags: bool) let part_start = inside.rfind(',').map_or(0, |i| i + 1); let part = &inside[part_start..]; let base = builder.start + open + 1 + part_start; - let used: Vec<&str> = inside.split(',').filter_map(|p| p.split_once('=').map(|(n, _)| n.trim())).collect(); + let used: Vec<&str> = inside + .split(',') + .filter_map(|p| p.split_once('=').map(|(n, _)| n.trim())) + .collect(); match part.split_once('=') { Some((name, value)) => { let mut b = builder.offset(base + name.len() + 1); @@ -895,24 +1129,50 @@ fn parse_item(reader: &mut Reader, reg: &Registries, predicate: bool) -> CmdResu let start = reader.cursor; if predicate && reader.can_read() && reader.peek() == '*' { reader.skip(); - return Ok(ItemInput { id: "*".into(), tag: false, any: true, components: None }); + return Ok(ItemInput { + id: "*".into(), + tag: false, + any: true, + components: None, + }); } let tag = reader.can_read() && reader.peek() == '#'; if tag && !predicate { - return Err(CommandError::tr_at("argument.item.tag.disallowed", &[], reader)); + return Err(CommandError::tr_at( + "argument.item.tag.disallowed", + &[], + reader, + )); } if tag { reader.skip(); } let id = read_id(reader)?; - let known = if tag { reg.item_tags.is_empty() || reg.item_tags.contains(&id) } else { reg.items.is_empty() || reg.items.contains(&id) }; + let known = if tag { + reg.item_tags.is_empty() || reg.item_tags.contains(&id) + } else { + reg.items.is_empty() || reg.items.contains(&id) + }; if !known { reader.cursor = start; - let key = if tag { "arguments.item.tag.unknown" } else { "argument.item.id.invalid" }; + let key = if tag { + "arguments.item.tag.unknown" + } else { + "argument.item.id.invalid" + }; return Err(CommandError::tr_at(key, &[&id], reader)); } - let components = if reader.can_read() && reader.peek() == '[' { Some(read_braced(reader, '[', ']')?) } else { None }; - Ok(ItemInput { id, tag, any: false, components }) + let components = if reader.can_read() && reader.peek() == '[' { + Some(read_braced(reader, '[', ']')?) + } else { + None + }; + Ok(ItemInput { + id, + tag, + any: false, + components, + }) } /// TimeArgument units. fn time_unit(unit: &str) -> Option { @@ -933,11 +1193,19 @@ impl ArgType { let v = reader.read_int()?; if v < *min { reader.cursor = start; - return Err(CommandError::tr_at("argument.integer.low", &[min, &v], reader)); + return Err(CommandError::tr_at( + "argument.integer.low", + &[min, &v], + reader, + )); } if v > *max { reader.cursor = start; - return Err(CommandError::tr_at("argument.integer.big", &[max, &v], reader)); + return Err(CommandError::tr_at( + "argument.integer.big", + &[max, &v], + reader, + )); } Arg::Int(v) } @@ -945,11 +1213,19 @@ impl ArgType { let v = reader.read_float()?; if v < *min { reader.cursor = start; - return Err(CommandError::tr_at("argument.float.low", &[min, &v], reader)); + return Err(CommandError::tr_at( + "argument.float.low", + &[min, &v], + reader, + )); } if v > *max { reader.cursor = start; - return Err(CommandError::tr_at("argument.float.big", &[max, &v], reader)); + return Err(CommandError::tr_at( + "argument.float.big", + &[max, &v], + reader, + )); } Arg::Float(v) } @@ -957,11 +1233,19 @@ impl ArgType { let v = reader.read_double()?; if v < *min { reader.cursor = start; - return Err(CommandError::tr_at("argument.double.low", &[min, &v], reader)); + return Err(CommandError::tr_at( + "argument.double.low", + &[min, &v], + reader, + )); } if v > *max { reader.cursor = start; - return Err(CommandError::tr_at("argument.double.big", &[max, &v], reader)); + return Err(CommandError::tr_at( + "argument.double.big", + &[max, &v], + reader, + )); } Arg::Double(v) } @@ -976,7 +1260,11 @@ impl ArgType { let s = parse_selector(reader, reg)?; if s.limit > 1 && *single { reader.cursor = start; - let key = if *players { "argument.player.toomany" } else { "argument.entity.toomany" }; + let key = if *players { + "argument.player.toomany" + } else { + "argument.entity.toomany" + }; return Err(CommandError::tr_at(key, &[], reader)); } if s.include_entities && *players && !s.is_self() { @@ -1001,26 +1289,49 @@ impl ArgType { } ArgType::Rotation => { if !reader.can_read() { - return Err(CommandError::tr_at("argument.rotation.incomplete", &[], reader)); + return Err(CommandError::tr_at( + "argument.rotation.incomplete", + &[], + reader, + )); } let yaw = parse_coord_double(reader, false)?; if !reader.can_read() || reader.peek() != ' ' { reader.cursor = start; - return Err(CommandError::tr_at("argument.rotation.incomplete", &[], reader)); + return Err(CommandError::tr_at( + "argument.rotation.incomplete", + &[], + reader, + )); } reader.skip(); let pitch = parse_coord_double(reader, false)?; - Arg::Coords(Coordinates::World([yaw, pitch, Coord { relative: true, value: 0.0 }])) + Arg::Coords(Coordinates::World([ + yaw, + pitch, + Coord { + relative: true, + value: 0.0, + }, + ])) } ArgType::Angle => { if !reader.can_read() { - return Err(CommandError::tr_at("argument.angle.incomplete", &[], reader)); + return Err(CommandError::tr_at( + "argument.angle.incomplete", + &[], + reader, + )); } let relative = reader.peek() == '~'; if relative { reader.skip(); } - let value = if reader.can_read() && reader.peek() != ' ' { f64::from(reader.read_float()?) } else { 0.0 }; + let value = if reader.can_read() && reader.peek() != ' ' { + f64::from(reader.read_float()?) + } else { + 0.0 + }; if value.is_nan() || value.is_infinite() { return Err(CommandError::tr_at("argument.angle.invalid", &[], reader)); } @@ -1035,7 +1346,10 @@ impl ArgType { let values = kind.values(reg); if !values.is_empty() && !values.contains(&id) { reader.cursor = start; - return Err(CommandError::new(crate::text::Text::tr("argument.resource.not_found", &[&id, &kind.registry()]))); + return Err(CommandError::new(crate::text::Text::tr( + "argument.resource.not_found", + &[&id, &kind.registry()], + ))); } Arg::Resource(id) } @@ -1055,7 +1369,10 @@ impl ArgType { }; let ticks = (v * m as f32).round() as i32; if ticks < *min { - return Err(CommandError::tr("argument.time.tick_count_too_low", &[min, &ticks])); + return Err(CommandError::tr( + "argument.time.tick_count_too_low", + &[min, &ticks], + )); } Arg::Int(ticks) } @@ -1065,13 +1382,21 @@ impl ArgType { Some(m) => Arg::GameMode(m), None => { reader.cursor = start; - return Err(CommandError::tr_at("argument.gamemode.invalid", &[&name], reader)); + return Err(CommandError::tr_at( + "argument.gamemode.invalid", + &[&name], + reader, + )); } } } ArgType::Nbt => { if !reader.can_read() || reader.peek() != '{' { - return Err(CommandError::tr_at("argument.nbt.expected.compound", &[], reader)); + return Err(CommandError::tr_at( + "argument.nbt.expected.compound", + &[], + reader, + )); } Arg::Str(read_braced(reader, '{', '}')?) } @@ -1082,13 +1407,23 @@ impl ArgType { "feet" => Arg::Anchor(false), _ => { reader.cursor = start; - return Err(CommandError::tr_at("argument.anchor.invalid", &[&name], reader)); + return Err(CommandError::tr_at( + "argument.anchor.invalid", + &[&name], + reader, + )); } } } }) } - pub fn suggest(&self, builder: &mut SuggestionsBuilder, reg: &Registries, context: &Context, _name: &str) { + pub fn suggest( + &self, + builder: &mut SuggestionsBuilder, + reg: &Registries, + context: &Context, + _name: &str, + ) { let _ = context; match self { ArgType::Bool => builder.suggest_matching(["true", "false"]), diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-client/src/command/mod.rs index f186f02cf..86eabdb54 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-client/src/command/mod.rs @@ -21,13 +21,23 @@ pub struct CommandError { } impl CommandError { pub fn new(message: Text) -> Self { - Self { message, input: None, cursor: 0, literal_incorrect: false } + Self { + message, + input: None, + cursor: 0, + literal_incorrect: false, + } } pub fn tr(key: &str, args: &[&dyn std::fmt::Display]) -> Self { Self::new(Text::tr(key, args)) } pub fn at(message: Text, reader: &Reader) -> Self { - Self { message, input: Some(reader.string.to_owned()), cursor: reader.cursor, literal_incorrect: false } + Self { + message, + input: Some(reader.string.to_owned()), + cursor: reader.cursor, + literal_incorrect: false, + } } pub fn tr_at(key: &str, args: &[&dyn std::fmt::Display], reader: &Reader) -> Self { Self::at(Text::tr(key, args), reader) @@ -49,7 +59,14 @@ impl CommandError { /// The message as shown by command suggestions ("... at position N: ..."). pub fn with_context(&self) -> Text { match self.context() { - Some(context) => Text::translate("command.context.parse_error", &[self.message.clone(), Text::literal(self.cursor.to_string()), Text::literal(context)]), + Some(context) => Text::translate( + "command.context.parse_error", + &[ + self.message.clone(), + Text::literal(self.cursor.to_string()), + Text::literal(context), + ], + ), None => self.message.clone(), } } @@ -76,7 +93,10 @@ impl<'a> Reader<'a> { self.string[self.cursor..].chars().next().unwrap_or('\0') } pub fn peek_at(&self, offset: usize) -> char { - self.string[self.cursor..].chars().nth(offset).unwrap_or('\0') + self.string[self.cursor..] + .chars() + .nth(offset) + .unwrap_or('\0') } pub fn skip(&mut self) { self.cursor += self.peek().len_utf8(); @@ -111,14 +131,22 @@ impl<'a> Reader<'a> { let start = self.cursor; let text = self.read_number_text(); if text.is_empty() { - return Err(CommandError::tr_at(&format!("parsing.{kind}.expected"), &[], self)); + return Err(CommandError::tr_at( + &format!("parsing.{kind}.expected"), + &[], + self, + )); } // Java's parsers reject a trailing '.'-less exponent etc. the same way. match text.parse::() { Ok(v) if !(kind == "int" || kind == "long") || !text.contains('.') => Ok(v), _ => { self.cursor = start; - Err(CommandError::tr_at(&format!("parsing.{kind}.invalid"), &[&text], self)) + Err(CommandError::tr_at( + &format!("parsing.{kind}.invalid"), + &[&text], + self, + )) } } } @@ -170,7 +198,11 @@ impl<'a> Reader<'a> { } let next = self.peek(); if next != '"' && next != '\'' { - return Err(CommandError::tr_at("parsing.quote.expected.start", &[], self)); + return Err(CommandError::tr_at( + "parsing.quote.expected.start", + &[], + self, + )); } self.skip(); self.read_string_until(next) @@ -264,7 +296,15 @@ pub struct Context { } impl Context { fn new(root: usize, start: usize) -> Self { - Self { root, nodes: Vec::new(), args: Vec::new(), command: None, range: (start, start), child: None, literals: Vec::new() } + Self { + root, + nodes: Vec::new(), + args: Vec::new(), + command: None, + range: (start, start), + child: None, + literals: Vec::new(), + } } /// Whether the literal `word` was parsed (in this context). pub fn has(&self, word: &str) -> bool { @@ -282,7 +322,11 @@ impl Context { c } pub fn get(&self, name: &str) -> Option<&Arg> { - self.args.iter().rev().find(|a| a.name == name).map(|a| &a.value) + self.args + .iter() + .rev() + .find(|a| a.name == name) + .map(|a| &a.value) } /// CommandContextBuilder.findSuggestionContext: the node whose children /// complete the text at `cursor`, and where that text starts. @@ -325,7 +369,10 @@ impl ParseResults { if self.errors.len() == 1 { return Some(self.errors[0].1.clone()); } - let reader = Reader { string: &self.input, cursor: self.cursor }; + let reader = Reader { + string: &self.input, + cursor: self.cursor, + }; Some(if self.context.range.0 == self.context.range.1 { CommandError::tr_at("command.unknown.command", &[], &reader) } else { @@ -340,7 +387,14 @@ impl ParseResults { let last = self.context.last_child(); match last.command { Some(id) => Ok((last, id)), - None => Err(CommandError::tr_at("command.unknown.command", &[], &Reader { string: &self.input, cursor: self.cursor })), + None => Err(CommandError::tr_at( + "command.unknown.command", + &[], + &Reader { + string: &self.input, + cursor: self.cursor, + }, + )), } } } @@ -366,7 +420,11 @@ pub struct SuggestionsBuilder<'a> { } impl<'a> SuggestionsBuilder<'a> { pub fn new(input: &'a str, start: usize) -> Self { - Self { input, start: start.min(input.len()), out: Vec::new() } + Self { + input, + start: start.min(input.len()), + out: Vec::new(), + } } pub fn remaining(&self) -> &'a str { &self.input[self.start..] @@ -377,13 +435,21 @@ impl<'a> SuggestionsBuilder<'a> { pub fn suggest(&mut self, text: impl Into) { let text = text.into(); if text != self.remaining() { - self.out.push(Suggestion { range: (self.start, self.input.len()), text, tooltip: None }); + self.out.push(Suggestion { + range: (self.start, self.input.len()), + text, + tooltip: None, + }); } } pub fn suggest_tooltip(&mut self, text: impl Into, tooltip: impl Into) { let text = text.into(); if text != self.remaining() { - self.out.push(Suggestion { range: (self.start, self.input.len()), text, tooltip: Some(tooltip.into()) }); + self.out.push(Suggestion { + range: (self.start, self.input.len()), + text, + tooltip: Some(tooltip.into()), + }); } } pub fn offset(&self, start: usize) -> SuggestionsBuilder<'a> { @@ -409,8 +475,17 @@ pub fn merge_suggestions(input: &str, list: Vec) -> (Range, Vec = Vec::new(); for s in list { // Suggestion.expand: pad the text with the input around it. - let text = format!("{}{}{}", &input[start..s.range.0], s.text, &input[s.range.1..end]); - let expanded = Suggestion { range: (start, end), text, tooltip: s.tooltip }; + let text = format!( + "{}{}{}", + &input[start..s.range.0], + s.text, + &input[s.range.1..end] + ); + let expanded = Suggestion { + range: (start, end), + text, + tooltip: s.tooltip, + }; if !out.iter().any(|o| o.text == expanded.text) { out.push(expanded); } @@ -431,7 +506,15 @@ impl Default for Dispatcher { } impl Dispatcher { pub fn new() -> Self { - Self { nodes: vec![Node { kind: NodeKind::Root, children: Vec::new(), command: None, redirect: None, permission: 0 }] } + Self { + nodes: vec![Node { + kind: NodeKind::Root, + children: Vec::new(), + command: None, + redirect: None, + permission: 0, + }], + } } fn add(&mut self, parent: usize, kind: NodeKind) -> usize { let name = match &kind { @@ -440,11 +523,21 @@ impl Dispatcher { NodeKind::Root => String::new(), }; // CommandNode.addChild merges same-named children. - if let Some(&existing) = self.nodes[parent].children.iter().find(|&&c| self.nodes[c].name() == name) { + if let Some(&existing) = self.nodes[parent] + .children + .iter() + .find(|&&c| self.nodes[c].name() == name) + { return existing; } let permission = self.nodes[parent].permission; - self.nodes.push(Node { kind, children: Vec::new(), command: None, redirect: None, permission }); + self.nodes.push(Node { + kind, + children: Vec::new(), + command: None, + redirect: None, + permission, + }); let id = self.nodes.len() - 1; self.nodes[parent].children.push(id); id @@ -453,7 +546,13 @@ impl Dispatcher { self.add(parent, NodeKind::Literal(name.to_owned())) } pub fn argument(&mut self, parent: usize, name: &str, ty: ArgType) -> usize { - self.add(parent, NodeKind::Argument { name: name.to_owned(), ty }) + self.add( + parent, + NodeKind::Argument { + name: name.to_owned(), + ty, + }, + ) } pub fn executes(&mut self, node: usize, command: &'static str) -> usize { self.nodes[node].command = Some(command); @@ -469,12 +568,24 @@ impl Dispatcher { } /// A root literal by name. pub fn find(&self, name: &str) -> Option { - self.nodes[0].children.iter().copied().find(|&c| self.nodes[c].name() == name) + self.nodes[0] + .children + .iter() + .copied() + .find(|&c| self.nodes[c].name() == name) } fn relevant(&self, node: usize, reader: &Reader) -> Vec { let children = &self.nodes[node].children; - let literals: Vec = children.iter().copied().filter(|&c| matches!(self.nodes[c].kind, NodeKind::Literal(_))).collect(); - let arguments: Vec = children.iter().copied().filter(|&c| matches!(self.nodes[c].kind, NodeKind::Argument { .. })).collect(); + let literals: Vec = children + .iter() + .copied() + .filter(|&c| matches!(self.nodes[c].kind, NodeKind::Literal(_))) + .collect(); + let arguments: Vec = children + .iter() + .copied() + .filter(|&c| matches!(self.nodes[c].kind, NodeKind::Argument { .. })) + .collect(); if literals.is_empty() { return arguments; } @@ -485,7 +596,13 @@ impl Dispatcher { None => arguments, } } - fn parse_node(&self, node: usize, reader: &mut Reader, context: &mut Context, reg: &Registries) -> CmdResult<()> { + fn parse_node( + &self, + node: usize, + reader: &mut Reader, + context: &mut Context, + reg: &Registries, + ) -> CmdResult<()> { let start = reader.cursor; match &self.nodes[node].kind { NodeKind::Root => Ok(()), @@ -507,29 +624,50 @@ impl Dispatcher { NodeKind::Argument { name, ty } => { let value = ty.parse(reader, reg)?; let range = (start, reader.cursor); - context.args.push(ParsedArg { name: name.clone(), value, range }); + context.args.push(ParsedArg { + name: name.clone(), + value, + range, + }); context.with_node(node, range); Ok(()) } } } - fn parse_nodes(&self, node: usize, input: &str, cursor: usize, so_far: &Context, reg: &Registries, level: u8) -> ParseResults { + fn parse_nodes( + &self, + node: usize, + input: &str, + cursor: usize, + so_far: &Context, + reg: &Registries, + level: u8, + ) -> ParseResults { let mut errors = Vec::new(); let mut potentials: Vec = Vec::new(); - let original = Reader { string: input, cursor }; + let original = Reader { + string: input, + cursor, + }; for child in self.relevant(node, &original) { if self.nodes[child].permission > level { continue; } let mut context = so_far.clone(); let mut reader = original.clone(); - let parsed = self.parse_node(child, &mut reader, &mut context, reg).and_then(|()| { - if reader.can_read() && reader.peek() != ' ' { - Err(CommandError::tr_at("command.expected.separator", &[], &reader)) - } else { - Ok(()) - } - }); + let parsed = self + .parse_node(child, &mut reader, &mut context, reg) + .and_then(|()| { + if reader.can_read() && reader.peek() != ' ' { + Err(CommandError::tr_at( + "command.expected.separator", + &[], + &reader, + )) + } else { + Ok(()) + } + }); if let Err(e) = parsed { errors.push((child, e)); continue; @@ -540,13 +678,31 @@ impl Dispatcher { reader.skip(); if let Some(target) = redirect { let child_context = Context::new(target, reader.cursor); - let parse = self.parse_nodes(target, input, reader.cursor, &child_context, reg, level); + let parse = + self.parse_nodes(target, input, reader.cursor, &child_context, reg, level); context.child = Some(Box::new(parse.context)); - return ParseResults { context, input: input.to_owned(), cursor: parse.cursor, errors: parse.errors }; + return ParseResults { + context, + input: input.to_owned(), + cursor: parse.cursor, + errors: parse.errors, + }; } - potentials.push(self.parse_nodes(child, input, reader.cursor, &context, reg, level)); + potentials.push(self.parse_nodes( + child, + input, + reader.cursor, + &context, + reg, + level, + )); } else { - potentials.push(ParseResults { context, input: input.to_owned(), cursor: reader.cursor, errors: Vec::new() }); + potentials.push(ParseResults { + context, + input: input.to_owned(), + cursor: reader.cursor, + errors: Vec::new(), + }); } } if !potentials.is_empty() { @@ -554,7 +710,12 @@ impl Dispatcher { potentials.sort_by_key(|p| (p.can_read(), !p.errors.is_empty())); return potentials.swap_remove(0); } - ParseResults { context: so_far.clone(), input: input.to_owned(), cursor, errors } + ParseResults { + context: so_far.clone(), + input: input.to_owned(), + cursor, + errors, + } } /// CommandDispatcher.parse from the start of `input` (no leading slash). pub fn parse(&self, input: &str, reg: &Registries) -> ParseResults { @@ -566,7 +727,12 @@ impl Dispatcher { self.parse_nodes(0, input, start, &context, reg, reg.permission) } /// CommandDispatcher.getCompletionSuggestions at `cursor`. - pub fn suggestions(&self, parse: &ParseResults, cursor: usize, reg: &Registries) -> (Range, Vec) { + pub fn suggestions( + &self, + parse: &ParseResults, + cursor: usize, + reg: &Registries, + ) -> (Range, Vec) { let (parent, start, context) = parse.context.suggestion_context(cursor); let start = start.min(cursor); let truncated = &parse.input[..cursor.min(parse.input.len())]; @@ -594,17 +760,36 @@ impl Dispatcher { if n.permission > level { return None; } - let this = if optional { format!("[{}]", n.usage_text()) } else { n.usage_text() }; + let this = if optional { + format!("[{}]", n.usage_text()) + } else { + n.usage_text() + }; let child_optional = n.command.is_some(); - let (open, close) = if child_optional { ("[", "]") } else { ("(", ")") }; + let (open, close) = if child_optional { + ("[", "]") + } else { + ("(", ")") + }; if !deep { if let Some(r) = n.redirect { - let target = if r == 0 { "...".to_owned() } else { format!("-> {}", self.nodes[r].usage_text()) }; + let target = if r == 0 { + "...".to_owned() + } else { + format!("-> {}", self.nodes[r].usage_text()) + }; return Some(format!("{this} {target}")); } - let children: Vec = n.children.iter().copied().filter(|&c| self.nodes[c].permission <= level).collect(); + let children: Vec = n + .children + .iter() + .copied() + .filter(|&c| self.nodes[c].permission <= level) + .collect(); if children.len() == 1 { - if let Some(usage) = self.smart_usage_of(children[0], child_optional, child_optional, level) { + if let Some(usage) = + self.smart_usage_of(children[0], child_optional, child_optional, level) + { return Some(format!("{this} {usage}")); } } else if children.len() > 1 { @@ -618,10 +803,20 @@ impl Dispatcher { } if child_usage.len() == 1 { let usage = &child_usage[0]; - return Some(format!("{this} {}", if child_optional { format!("[{usage}]") } else { usage.clone() })); + return Some(format!( + "{this} {}", + if child_optional { + format!("[{usage}]") + } else { + usage.clone() + } + )); } if child_usage.len() > 1 { - let alternatives: Vec = children.iter().map(|&c| self.nodes[c].usage_text()).collect(); + let alternatives: Vec = children + .iter() + .map(|&c| self.nodes[c].usage_text()) + .collect(); return Some(format!("{this} {open}{}{close}", alternatives.join("|"))); } } @@ -631,7 +826,14 @@ impl Dispatcher { /// CommandDispatcher.getSmartUsage: one line per child of `node`. pub fn smart_usage(&self, node: usize, level: u8) -> Vec<(usize, String)> { let optional = self.nodes[node].command.is_some(); - self.nodes[node].children.iter().filter_map(|&c| self.smart_usage_of(c, optional, false, level).map(|u| (c, u))).collect() + self.nodes[node] + .children + .iter() + .filter_map(|&c| { + self.smart_usage_of(c, optional, false, level) + .map(|u| (c, u)) + }) + .collect() } } diff --git a/crates/horizon-client/src/command/tests.rs b/crates/horizon-client/src/command/tests.rs index f2645a4b2..7d1a4cda1 100644 --- a/crates/horizon-client/src/command/tests.rs +++ b/crates/horizon-client/src/command/tests.rs @@ -1,15 +1,29 @@ use super::{args::*, vanilla, *}; fn reg() -> Registries { - let mut r = Registries { permission: 4, ..Registries::default() }; - r.items = vec!["minecraft:diamond".into(), "minecraft:diamond_sword".into(), "minecraft:stone".into()]; + let mut r = Registries { + permission: 4, + ..Registries::default() + }; + r.items = vec![ + "minecraft:diamond".into(), + "minecraft:diamond_sword".into(), + "minecraft:stone".into(), + ]; r.blocks.insert("minecraft:stone".into(), vec![]); r.blocks.insert( "minecraft:oak_stairs".into(), - vec![("facing".into(), vec!["north".into(), "south".into()]), ("half".into(), vec!["top".into(), "bottom".into()])], + vec![ + ("facing".into(), vec!["north".into(), "south".into()]), + ("half".into(), vec!["top".into(), "bottom".into()]), + ], ); r.summonable = vec!["minecraft:pig".into(), "minecraft:zombie".into()]; - r.entity_types = vec!["minecraft:pig".into(), "minecraft:player".into(), "minecraft:zombie".into()]; + r.entity_types = vec![ + "minecraft:pig".into(), + "minecraft:player".into(), + "minecraft:zombie".into(), + ]; r.players = vec!["Player".into()]; r.dimensions = vec!["minecraft:overworld".into()]; r.time_markers = vec!["minecraft:day".into(), "minecraft:noon".into()]; @@ -19,13 +33,20 @@ fn run(input: &str) -> CmdResult<(String, Vec)> { let reg = reg(); let parse = vanilla::dispatcher().parse(input, ®); let (ctx, id) = parse.executable()?; - Ok((id.to_owned(), ctx.args.iter().map(|a| a.name.clone()).collect())) + Ok(( + id.to_owned(), + ctx.args.iter().map(|a| a.name.clone()).collect(), + )) } fn suggestions(input: &str) -> Vec { let reg = reg(); let d = vanilla::dispatcher(); let parse = d.parse(input, ®); - d.suggestions(&parse, input.len(), ®).1.into_iter().map(|s| s.text).collect() + d.suggestions(&parse, input.len(), ®) + .1 + .into_iter() + .map(|s| s.text) + .collect() } #[test] @@ -47,12 +68,21 @@ fn reader_matches_brigadier() { #[test] fn parses_vanilla_commands() { assert_eq!(run("gamemode creative").unwrap().0, "gamemode"); - assert_eq!(run("gamemode creative @s").unwrap().1, ["gamemode", "target"]); - assert_eq!(run("give @s minecraft:diamond 64").unwrap().1, ["targets", "item", "count"]); + assert_eq!( + run("gamemode creative @s").unwrap().1, + ["gamemode", "target"] + ); + assert_eq!( + run("give @s minecraft:diamond 64").unwrap().1, + ["targets", "item", "count"] + ); assert_eq!(run("tp 1 2 3").unwrap().0, "teleport.location"); assert_eq!(run("tp Player").unwrap().0, "teleport.destination"); assert_eq!(run("tp @s ~ ~10 ~").unwrap().0, "teleport.targets.location"); - assert_eq!(run("teleport @e[type=pig,limit=2] ^ ^ ^5 90 0").unwrap().0, "teleport.targets.location"); + assert_eq!( + run("teleport @e[type=pig,limit=2] ^ ^ ^5 90 0").unwrap().0, + "teleport.targets.location" + ); assert_eq!(run("time set 1000").unwrap().0, "time.set"); assert_eq!(run("time set 1d").unwrap().0, "time.set"); assert_eq!(run("time set day").unwrap().0, "time.set.marker"); @@ -60,16 +90,31 @@ fn parses_vanilla_commands() { assert_eq!(run("weather rain 10s").unwrap().0, "weather"); assert_eq!(run("xp add @s 5 levels").unwrap().0, "experience"); assert_eq!(run("gamerule keep_inventory true").unwrap().0, "gamerule"); - assert_eq!(run("gamerule minecraft:random_tick_speed 10").unwrap().0, "gamerule"); + assert_eq!( + run("gamerule minecraft:random_tick_speed 10").unwrap().0, + "gamerule" + ); assert_eq!(run("fill ~ ~ ~ ~1 ~1 ~1 stone hollow").unwrap().0, "fill"); - assert_eq!(run("fill 0 0 0 1 1 1 minecraft:oak_stairs[facing=north] replace stone").unwrap().0, "fill"); - assert_eq!(run("clone 0 0 0 1 1 1 5 5 5 masked move").unwrap().0, "clone"); - assert_eq!(run("setblock ~ ~1 ~ oak_stairs[half=top] keep").unwrap().0, "setblock"); + assert_eq!( + run("fill 0 0 0 1 1 1 minecraft:oak_stairs[facing=north] replace stone") + .unwrap() + .0, + "fill" + ); + assert_eq!( + run("clone 0 0 0 1 1 1 5 5 5 masked move").unwrap().0, + "clone" + ); + assert_eq!( + run("setblock ~ ~1 ~ oak_stairs[half=top] keep").unwrap().0, + "setblock" + ); assert_eq!(run("summon zombie ~ ~ ~ {NoAI:1b}").unwrap().0, "summon"); assert_eq!(run("difficulty hard").unwrap().0, "difficulty"); assert_eq!(run("say hello @p").unwrap().0, "say"); let reg = reg(); - let parse = vanilla::dispatcher().parse("clone 0 0 0 1 1 1 5 5 5 strict filtered stone force", ®); + let parse = + vanilla::dispatcher().parse("clone 0 0 0 1 1 1 5 5 5 strict filtered stone force", ®); let (ctx, _) = parse.executable().unwrap(); assert!(ctx.has("strict") && ctx.has("filtered") && ctx.has("force") && !ctx.has("move")); } @@ -99,9 +144,15 @@ fn suggestions_like_vanilla() { let root = suggestions(""); assert!(root.contains(&"gamemode".to_owned()) && root.contains(&"tp".to_owned())); assert_eq!(suggestions("game"), ["gamemode", "gamerule"]); - assert_eq!(suggestions("gamemode "), ["adventure", "creative", "spectator", "survival"]); + assert_eq!( + suggestions("gamemode "), + ["adventure", "creative", "spectator", "survival"] + ); assert_eq!(suggestions("gamemode c"), ["creative"]); - assert_eq!(suggestions("give @s dia"), ["minecraft:diamond", "minecraft:diamond_sword"]); + assert_eq!( + suggestions("give @s dia"), + ["minecraft:diamond", "minecraft:diamond_sword"] + ); // Underscore-separated parts match too (SharedSuggestionProvider.matchesSubStr). assert_eq!(suggestions("give @s sword"), ["minecraft:diamond_sword"]); assert_eq!(suggestions("kill @"), ["@a", "@e", "@n", "@p", "@r", "@s"]); @@ -111,20 +162,34 @@ fn suggestions_like_vanilla() { assert_eq!(suggestions("kill @e[type=pig"), [",", "]"]); assert_eq!(suggestions("setblock 0 0 0 oak_stairs[fa"), ["facing="]); assert_eq!(suggestions("setblock 0 0 0 oak_stairs[facing=n"), ["north"]); - assert_eq!(suggestions("tp "), ["@a", "@e", "@n", "@p", "@r", "@s", "Player", "~", "~ ~", "~ ~ ~"]); + assert_eq!( + suggestions("tp "), + [ + "@a", "@e", "@n", "@p", "@r", "@s", "Player", "~", "~ ~", "~ ~ ~" + ] + ); assert_eq!(suggestions("time set 5"), ["d", "s", "t"]); assert!(suggestions("time set ").contains(&"minecraft:day".to_owned())); } #[test] fn smart_usage_matches_brigadier() { let d = vanilla::dispatcher(); - let usage = |name: &str| d.smart_usage(0, 4).into_iter().find(|(n, _)| d.nodes[*n].name() == name).unwrap().1; + let usage = |name: &str| { + d.smart_usage(0, 4) + .into_iter() + .find(|(n, _)| d.nodes[*n].name() == name) + .unwrap() + .1 + }; assert_eq!(usage("gamemode"), "gamemode []"); assert_eq!(usage("give"), "give []"); assert_eq!(usage("kill"), "kill []"); assert_eq!(usage("weather"), "weather (clear|rain|thunder)"); assert_eq!(usage("tp"), "tp -> teleport"); - assert_eq!(usage("difficulty"), "difficulty [peaceful|easy|normal|hard]"); + assert_eq!( + usage("difficulty"), + "difficulty [peaceful|easy|normal|hard]" + ); } #[test] fn local_coordinates_follow_view() { @@ -134,6 +199,19 @@ fn local_coordinates_follow_view() { // ^1 (left) while facing south is +X. let p = Coordinates::Local([1.0, 0.0, 0.0]).position([0.0, 64.0, 0.0], [0.0, 0.0]); assert!((p[0] - 1.0).abs() < 1e-6, "{p:?}"); - let w = Coordinates::World([Coord { relative: true, value: 1.0 }, Coord { relative: false, value: 5.0 }, Coord { relative: true, value: 0.0 }]); + let w = Coordinates::World([ + Coord { + relative: true, + value: 1.0, + }, + Coord { + relative: false, + value: 5.0, + }, + Coord { + relative: true, + value: 0.0, + }, + ]); assert_eq!(w.position([10.0, 64.0, 3.0], [0.0, 0.0]), [11.0, 5.0, 3.0]); } diff --git a/crates/horizon-client/src/command/vanilla.rs b/crates/horizon-client/src/command/vanilla.rs index 1bb3bff0e..059537a64 100644 --- a/crates/horizon-client/src/command/vanilla.rs +++ b/crates/horizon-client/src/command/vanilla.rs @@ -11,10 +11,22 @@ use crate::gamerules::{RULES, Value}; pub const ALL: u8 = 0; pub const GAMEMASTERS: u8 = 2; -const PLAYERS: ArgType = ArgType::Entity { single: false, players: true }; -const PLAYER: ArgType = ArgType::Entity { single: true, players: true }; -const ENTITIES: ArgType = ArgType::Entity { single: false, players: false }; -const ENTITY: ArgType = ArgType::Entity { single: true, players: false }; +const PLAYERS: ArgType = ArgType::Entity { + single: false, + players: true, +}; +const PLAYER: ArgType = ArgType::Entity { + single: true, + players: true, +}; +const ENTITIES: ArgType = ArgType::Entity { + single: false, + players: false, +}; +const ENTITY: ArgType = ArgType::Entity { + single: true, + players: false, +}; pub const DIFFICULTIES: [&str; 4] = ["peaceful", "easy", "normal", "hard"]; @@ -117,7 +129,14 @@ pub fn build() -> Dispatcher { let t = d.argument(give, "targets", ENTITIES); let e = d.argument(t, "effect", ArgType::Resource(Resource::Effect)); d.executes(e, "effect.give"); - let seconds = d.argument(e, "seconds", ArgType::Integer { min: 1, max: 1_000_000 }); + let seconds = d.argument( + e, + "seconds", + ArgType::Integer { + min: 1, + max: 1_000_000, + }, + ); let infinite = d.literal(e, "infinite"); for duration in [seconds, infinite] { d.executes(duration, "effect.give"); @@ -211,7 +230,10 @@ pub fn build() -> Dispatcher { d.executes(r, "gamerule"); let ty = match rule.default { Value::Bool(_) => ArgType::Bool, - Value::Int(_) => ArgType::Integer { min: rule.min, max: rule.max }, + Value::Int(_) => ArgType::Integer { + min: rule.min, + max: rule.max, + }, }; let v = d.argument(r, "value", ty); d.executes(v, "gamerule"); @@ -310,7 +332,14 @@ fn clock_nodes(d: &mut Dispatcher, node: usize) { let resume = d.literal(node, "resume"); d.executes(resume, "time.resume"); let rate = d.literal(node, "rate"); - let r = d.argument(rate, "rate", ArgType::Float { min: 1.0e-5, max: 1000.0 }); + let r = d.argument( + rate, + "rate", + ArgType::Float { + min: 1.0e-5, + max: 1000.0, + }, + ); d.executes(r, "time.rate"); let query = d.literal(node, "query"); let time = d.literal(query, "time"); diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 1e72a167c..7b8eb7a27 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -56,7 +56,10 @@ pub enum BlockEntity { impl BlockEntity { pub fn for_block(name: &str) -> Option { if let Some(hanging) = crate::signs::sign_kind(name) { - return Some(Self::Sign(crate::signs::SignData { hanging, ..Default::default() })); + return Some(Self::Sign(crate::signs::SignData { + hanging, + ..Default::default() + })); } if let Some(kind) = FurnaceKind::from_block(name) { return Some(Self::Furnace(Furnace { @@ -142,10 +145,16 @@ pub struct Providers { floats: HashMap, } fn load_dir(dir: &Path, prefix: &str, out: &mut HashMap) { - let Ok(entries) = fs::read_dir(dir) else { return }; + let Ok(entries) = fs::read_dir(dir) else { + return; + }; for e in entries.flatten() { let p = e.path(); - let name = p.file_stem().and_then(|s| s.to_str()).unwrap_or("").to_owned(); + let name = p + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("") + .to_owned(); if p.is_dir() { load_dir(&p, &format!("{prefix}{name}/"), out); } else if let Ok(bytes) = fs::read(&p) @@ -159,8 +168,16 @@ impl Providers { pub fn load(root: &Path) -> Self { let mut ints = HashMap::new(); let mut floats = HashMap::new(); - load_dir(&root.join("data/minecraft/context_int_provider"), "", &mut ints); - load_dir(&root.join("data/minecraft/context_float_provider"), "", &mut floats); + load_dir( + &root.join("data/minecraft/context_int_provider"), + "", + &mut ints, + ); + load_dir( + &root.join("data/minecraft/context_float_provider"), + "", + &mut floats, + ); Self { ints, floats } } fn eval(&self, v: &Value, fast: bool, table: &HashMap, depth: u32) -> f64 { @@ -169,13 +186,20 @@ impl Providers { } match v { Value::Number(n) => n.as_f64().unwrap_or(0.0), - Value::String(name) => table.get(name).map_or(0.0, |v| self.eval(v, fast, table, depth + 1)), + Value::String(name) => table + .get(name) + .map_or(0.0, |v| self.eval(v, fast, table, depth + 1)), Value::Object(o) => { - let f = |k: &str| self.eval(o.get(k).unwrap_or(&Value::Null), fast, table, depth + 1); + let f = + |k: &str| self.eval(o.get(k).unwrap_or(&Value::Null), fast, table, depth + 1); match o.get("type").and_then(Value::as_str).unwrap_or("") { "minecraft:div" => { let r = f("right"); - if r == 0.0 { 0.0 } else { (f("left") / r).trunc() } + if r == 0.0 { + 0.0 + } else { + (f("left") / r).trunc() + } } "minecraft:mul" => f("left") * f("right"), "minecraft:add" | "minecraft:sum" => f("left") + f("right"), @@ -183,8 +207,13 @@ impl Providers { "minecraft:constant" => f("value"), "minecraft:conditional" => { // The only condition in the pinned data: block/fast_cooking. - let condition = o.get("condition").and_then(Value::as_str) == Some("minecraft:block/fast_cooking"); - if condition && fast { f("on_true") } else { f("on_false") } + let condition = o.get("condition").and_then(Value::as_str) + == Some("minecraft:block/fast_cooking"); + if condition && fast { + f("on_true") + } else { + f("on_false") + } } _ => 0.0, } @@ -198,11 +227,18 @@ impl Providers { } /// A plain `context_float_provider` value or reference; `default` when absent. pub fn float_value(&self, v: &Value, default: f32) -> f32 { - if v.is_null() { default } else { self.eval(v, false, &self.floats, 0) as f32 } + if v.is_null() { + default + } else { + self.eval(v, false, &self.floats, 0) as f32 + } } #[cfg(test)] pub fn empty() -> Self { - Self { ints: HashMap::new(), floats: HashMap::new() } + Self { + ints: HashMap::new(), + floats: HashMap::new(), + } } pub fn burn_time(&self, items: &Items, stack: &ItemStack, fast: bool) -> i32 { items @@ -214,18 +250,27 @@ impl Providers { items .get(&stack.item) .and_then(|i| i.fuel.as_ref()) - .map_or(1.0, |(_, speed)| self.eval(speed, fast, &self.floats, 0) as f32) + .map_or(1.0, |(_, speed)| { + self.eval(speed, fast, &self.floats, 0) as f32 + }) } } fn remainder(item: &str) -> Option<&'static str> { match item { - "minecraft:lava_bucket" | "minecraft:water_bucket" | "minecraft:milk_bucket" => Some("minecraft:bucket"), + "minecraft:lava_bucket" | "minecraft:water_bucket" | "minecraft:milk_bucket" => { + Some("minecraft:bucket") + } _ => None, } } impl Furnace { /// One server tick. Returns `Some(lit)` when the LIT block state must change. - pub fn tick(&mut self, recipes: &Recipes, items: &Items, providers: &Providers) -> Option { + pub fn tick( + &mut self, + recipes: &Recipes, + items: &Items, + providers: &Providers, + ) -> Option { let was_lit = self.lit_remaining > 0; let mut lit = false; if self.lit_remaining > 0 { @@ -244,27 +289,39 @@ impl Furnace { let max = items.get(&recipe.result.item).map_or(64, |i| i.max_stack); let can_burn = match &self.items[2] { None => true, - Some(out) => out.item == recipe.result.item && out.count + recipe.result.count <= max, + Some(out) => { + out.item == recipe.result.item && out.count + recipe.result.count <= max + } }; if can_burn { if !lit { let fuel = self.items[1].clone(); - let time = fuel.as_ref().map_or(0, |f| providers.burn_time(items, f, fast)); - let speed = fuel.as_ref().map_or(1.0, |f| providers.speed(items, f, fast)); + let time = fuel + .as_ref() + .map_or(0, |f| providers.burn_time(items, f, fast)); + let speed = fuel + .as_ref() + .map_or(1.0, |f| providers.speed(items, f, fast)); self.lit_remaining = time; self.lit_total = time; self.speed = speed; if self.cooking_total > 0 && self.cooking_timer < self.cooking_total { let ratio = self.cooking_timer as f32 / self.cooking_total as f32; self.cooking_total = total_time(recipe.time, self.speed); - self.cooking_timer = (ratio * self.cooking_total as f32).ceil() as i32; + self.cooking_timer = + (ratio * self.cooking_total as f32).ceil() as i32; } if time > 0 { if let Some(f) = self.items[1].as_mut() { let item = f.item.clone(); f.count -= 1; if f.count == 0 { - self.items[1] = remainder(&item).map(|r| ItemStack { item: Arc::from(r), count: 1, damage: 0, extra: None }); + self.items[1] = remainder(&item).map(|r| ItemStack { + item: Arc::from(r), + count: 1, + damage: 0, + extra: None, + }); } } lit = true; diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index ba8ddb74e..ecf8f9bd6 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -2,7 +2,10 @@ //! (placed anywhere in the grid, optionally mirrored as in //! `ShapedRecipePattern.matches`), shapeless ingredient sets, and furnace-type //! cooking lookups. -use crate::{Result, items::{ItemStack, Items}}; +use crate::{ + Result, + items::{ItemStack, Items}, +}; use serde_json::Value; use std::{collections::HashSet, fs, path::Path, sync::Arc}; @@ -82,7 +85,11 @@ impl Recipes { .collect(); files.sort(); for path in files { - let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("").to_owned(); + let name = path + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("") + .to_owned(); let v: Value = serde_json::from_slice(&fs::read(&path)?)?; match v["type"].as_str().unwrap_or("") { "minecraft:crafting_shaped" => { @@ -110,7 +117,15 @@ impl Recipes { } } if let (true, Some(result)) = (ok, result(&v["result"])) { - crafting.push((name, Recipe::Shaped { width, height, cells, result })); + crafting.push(( + name, + Recipe::Shaped { + width, + height, + cells, + result, + }, + )); } } "minecraft:crafting_shapeless" => { @@ -121,11 +136,23 @@ impl Recipes { .map(|i| Ingredient::parse(i, items)) .collect(); if let (Some(ingredients), Some(result)) = (ingredients, result(&v["result"])) { - crafting.push((name, Recipe::Shapeless { ingredients, result })); + crafting.push(( + name, + Recipe::Shapeless { + ingredients, + result, + }, + )); } } - kind @ ("minecraft:smelting" | "minecraft:blasting" | "minecraft:smoking" | "minecraft:campfire_cooking") => { - if let (Some(ingredient), Some(result)) = (Ingredient::parse(&v["ingredient"], items), result(&v["result"])) { + kind @ ("minecraft:smelting" + | "minecraft:blasting" + | "minecraft:smoking" + | "minecraft:campfire_cooking") => { + if let (Some(ingredient), Some(result)) = ( + Ingredient::parse(&v["ingredient"], items), + result(&v["result"]), + ) { cooking.push(Cooking { kind: kind.to_owned(), ingredient, @@ -150,13 +177,24 @@ impl Recipes { if occupied.is_empty() { return None; } - let (x0, x1) = (occupied.iter().map(|p| p.0).min()?, occupied.iter().map(|p| p.0).max()?); - let (y0, y1) = (occupied.iter().map(|p| p.1).min()?, occupied.iter().map(|p| p.1).max()?); + let (x0, x1) = ( + occupied.iter().map(|p| p.0).min()?, + occupied.iter().map(|p| p.0).max()?, + ); + let (y0, y1) = ( + occupied.iter().map(|p| p.1).min()?, + occupied.iter().map(|p| p.1).max()?, + ); let (w, h) = (x1 - x0 + 1, y1 - y0 + 1); let cell = |x: usize, y: usize| grid[(y0 + y) * size + x0 + x].as_ref(); for (_, recipe) in &self.crafting { match recipe { - Recipe::Shaped { width, height, cells, result } => { + Recipe::Shaped { + width, + height, + cells, + result, + } => { if *width != w || *height != h { continue; } @@ -176,7 +214,10 @@ impl Recipes { return Some(result.clone()); } } - Recipe::Shapeless { ingredients, result } => { + Recipe::Shapeless { + ingredients, + result, + } => { let stacks: Vec<&ItemStack> = grid.iter().flatten().collect(); if stacks.len() != ingredients.len() { continue; @@ -184,7 +225,9 @@ impl Recipes { // Greedy bipartite matching is sufficient for vanilla's ingredient sets. let mut used = vec![false; stacks.len()]; let ok = ingredients.iter().all(|ingredient| { - if let Some(i) = (0..stacks.len()).find(|&i| !used[i] && ingredient.test(stacks[i])) { + if let Some(i) = + (0..stacks.len()).find(|&i| !used[i] && ingredient.test(stacks[i])) + { used[i] = true; true } else { @@ -200,6 +243,8 @@ impl Recipes { None } pub fn cook(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> { - self.cooking.iter().find(|c| c.kind == kind && c.ingredient.test(input)) + self.cooking + .iter() + .find(|c| c.kind == kind && c.ingredient.test(input)) } } diff --git a/crates/horizon-client/src/creative.rs b/crates/horizon-client/src/creative.rs index 331ca794f..6be74498c 100644 --- a/crates/horizon-client/src/creative.rs +++ b/crates/horizon-client/src/creative.rs @@ -56,7 +56,12 @@ impl Creative { let mut tabs = Vec::new(); let mut all_items: Vec = Vec::new(); for t in raw.as_array().into_iter().flatten() { - let items: Vec = t["items"].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(str::to_owned)).collect(); + let items: Vec = t["items"] + .as_array() + .into_iter() + .flatten() + .filter_map(|v| v.as_str().map(str::to_owned)) + .collect(); for i in &items { if !all_items.contains(i) { all_items.push(i.clone()); @@ -77,7 +82,13 @@ impl Creative { inventory: kind == "INVENTORY", }); } - Ok(Self { tabs, selected: 0, scroll: 0.0, search: String::new(), all_items }) + Ok(Self { + tabs, + selected: 0, + scroll: 0.0, + search: String::new(), + all_items, + }) } pub fn tab(&self) -> &Tab { &self.tabs[self.selected.min(self.tabs.len() - 1)] @@ -87,7 +98,16 @@ impl Creative { let tab = self.tab(); if tab.search { let query = self.search.to_lowercase(); - return self.all_items.iter().filter(|i| query.is_empty() || names.item(i).to_lowercase().contains(&query) || i.contains(&query)).cloned().collect(); + return self + .all_items + .iter() + .filter(|i| { + query.is_empty() + || names.item(i).to_lowercase().contains(&query) + || i.contains(&query) + }) + .cloned() + .collect(); } tab.items.clone() } diff --git a/crates/horizon-client/src/effects.rs b/crates/horizon-client/src/effects.rs index 25a899c52..bfa582781 100644 --- a/crates/horizon-client/src/effects.rs +++ b/crates/horizon-client/src/effects.rs @@ -17,7 +17,14 @@ pub struct EffectInstance { } impl EffectInstance { pub fn new(id: &'static str, duration: i32, amplifier: i32) -> Self { - Self { id, duration, amplifier: amplifier.clamp(0, 255), ambient: false, visible: true, hidden: None } + Self { + id, + duration, + amplifier: amplifier.clamp(0, 255), + ambient: false, + visible: true, + hidden: None, + } } fn infinite(&self) -> bool { self.duration == -1 @@ -45,7 +52,10 @@ impl EffectInstance { } else if let Some(h) = self.hidden.as_mut() { h.update(take); } else { - self.hidden = Some(Box::new(EffectInstance { hidden: None, ..take.clone() })); + self.hidden = Some(Box::new(EffectInstance { + hidden: None, + ..take.clone() + })); } } if !take.ambient && self.ambient || changed { @@ -102,15 +112,23 @@ fn periodic(id: &str, tick: i32, amp: i32) -> Option { "hunger" => Some(EffectAction::Exhaust(0.005 * (amp + 1) as f32)), "saturation" if tick >= 1 => Some(EffectAction::Eat(amp + 1, 1.0)), "instant_health" if tick >= 1 => Some(EffectAction::Heal((4 << amp.min(30)) as f32)), - "instant_damage" if tick >= 1 => Some(EffectAction::Hurt("minecraft:magic", (6 << amp.min(30)) as f32)), + "instant_damage" if tick >= 1 => Some(EffectAction::Hurt( + "minecraft:magic", + (6 << amp.min(30)) as f32, + )), _ => None, } } /// `InstantenousMobEffect.applyInstantenousEffect` (potions apply these directly). pub fn instant(id: &str, amp: i32, scale: f64) -> Option { match id { - "instant_health" => Some(EffectAction::Heal((scale * f64::from(4 << amp.min(30))) as i32 as f32)), - "instant_damage" => Some(EffectAction::Hurt("minecraft:magic", (scale * f64::from(6 << amp.min(30))) as i32 as f32)), + "instant_health" => Some(EffectAction::Heal( + (scale * f64::from(4 << amp.min(30))) as i32 as f32, + )), + "instant_damage" => Some(EffectAction::Hurt( + "minecraft:magic", + (scale * f64::from(6 << amp.min(30))) as i32 as f32, + )), "saturation" => Some(EffectAction::Eat(amp + 1, 1.0)), _ => None, } @@ -160,7 +178,10 @@ impl PlayerEffects { actions } /// Effects applied by drinking a potion (`PotionContents.applyToLivingEntity`). - pub fn potion_effects(potion: Option<&str>, scale: f32) -> (Vec, Vec) { + pub fn potion_effects( + potion: Option<&str>, + scale: f32, + ) -> (Vec, Vec) { let mut lasting = Vec::new(); let mut now = Vec::new(); if let Some(def) = potion.and_then(brewing::potion) { @@ -185,7 +206,8 @@ impl PlayerEffects { levitation: self.amplifier("levitation"), resistance: self.amplifier("resistance"), fire_resistance: self.get("fire_resistance").is_some(), - water_breathing: self.get("water_breathing").is_some() || self.get("conduit_power").is_some(), + water_breathing: self.get("water_breathing").is_some() + || self.get("conduit_power").is_some(), protection: Vec::new(), } } @@ -195,16 +217,61 @@ impl PlayerEffects { for e in &self.list { let level = f64::from(e.amplifier + 1); let m = match e.id { - "speed" => Some(("minecraft:movement_speed", "minecraft:effect.speed", 0.2, "add_multiplied_total")), - "slowness" => Some(("minecraft:movement_speed", "minecraft:effect.slowness", -0.15, "add_multiplied_total")), - "haste" => Some(("minecraft:attack_speed", "minecraft:effect.haste", 0.1, "add_multiplied_total")), - "mining_fatigue" => Some(("minecraft:attack_speed", "minecraft:effect.mining_fatigue", -0.1, "add_multiplied_total")), - "strength" => Some(("minecraft:attack_damage", "minecraft:effect.strength", 3.0, "add_value")), - "weakness" => Some(("minecraft:attack_damage", "minecraft:effect.weakness", -4.0, "add_value")), - "jump_boost" => Some(("minecraft:safe_fall_distance", "minecraft:effect.jump_boost", 1.0, "add_value")), - "health_boost" => Some(("minecraft:max_health", "minecraft:effect.health_boost", 4.0, "add_value")), + "speed" => Some(( + "minecraft:movement_speed", + "minecraft:effect.speed", + 0.2, + "add_multiplied_total", + )), + "slowness" => Some(( + "minecraft:movement_speed", + "minecraft:effect.slowness", + -0.15, + "add_multiplied_total", + )), + "haste" => Some(( + "minecraft:attack_speed", + "minecraft:effect.haste", + 0.1, + "add_multiplied_total", + )), + "mining_fatigue" => Some(( + "minecraft:attack_speed", + "minecraft:effect.mining_fatigue", + -0.1, + "add_multiplied_total", + )), + "strength" => Some(( + "minecraft:attack_damage", + "minecraft:effect.strength", + 3.0, + "add_value", + )), + "weakness" => Some(( + "minecraft:attack_damage", + "minecraft:effect.weakness", + -4.0, + "add_value", + )), + "jump_boost" => Some(( + "minecraft:safe_fall_distance", + "minecraft:effect.jump_boost", + 1.0, + "add_value", + )), + "health_boost" => Some(( + "minecraft:max_health", + "minecraft:effect.health_boost", + 4.0, + "add_value", + )), "luck" => Some(("minecraft:luck", "minecraft:effect.luck", 1.0, "add_value")), - "unluck" => Some(("minecraft:luck", "minecraft:effect.unluck", -1.0, "add_value")), + "unluck" => Some(( + "minecraft:luck", + "minecraft:effect.unluck", + -1.0, + "add_value", + )), _ => None, }; if let Some((a, id, amount, op)) = m { @@ -245,7 +312,10 @@ pub struct StatusFlags { } impl StatusFlags { pub fn protection(&self, damage_type: &str) -> f32 { - self.protection.iter().find(|(t, _)| *t == damage_type).map_or(0.0, |(_, p)| *p) + self.protection + .iter() + .find(|(t, _)| *t == damage_type) + .map_or(0.0, |(_, p)| *p) } } @@ -261,7 +331,10 @@ mod tests { fx.add(EffectInstance::new("speed", 1800, 1)); let e = fx.get("speed").unwrap(); assert_eq!((e.amplifier, e.duration), (1, 1800)); - assert_eq!(e.hidden.as_ref().map(|h| (h.amplifier, h.duration)), Some((0, 9600))); + assert_eq!( + e.hidden.as_ref().map(|h| (h.amplifier, h.duration)), + Some((0, 9600)) + ); for _ in 0..1800 { fx.tick(); } @@ -275,13 +348,19 @@ mod tests { fn regeneration_and_poison_intervals() { let mut fx = PlayerEffects::default(); fx.add(EffectInstance::new("regeneration", 900, 0)); - let heals = (0..900).flat_map(|_| fx.tick()).filter(|a| *a == EffectAction::Heal(1.0)).count(); + let heals = (0..900) + .flat_map(|_| fx.tick()) + .filter(|a| *a == EffectAction::Heal(1.0)) + .count(); // Duration 900..1 divisible by 50: 18 heals. assert_eq!(heals, 18); assert!(fx.get("regeneration").is_none()); let mut fx = PlayerEffects::default(); fx.add(EffectInstance::new("poison", 432, 1)); - let hurts = (0..432).flat_map(|_| fx.tick()).filter(|a| matches!(a, EffectAction::Hurt(..))).count(); + let hurts = (0..432) + .flat_map(|_| fx.tick()) + .filter(|a| matches!(a, EffectAction::Hurt(..))) + .count(); // Interval 25 >> 1 = 12: 432/12 = 36 hits. assert_eq!(hurts, 36); } diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs index e10a5ab4d..42d237c50 100644 --- a/crates/horizon-client/src/enchant.rs +++ b/crates/horizon-client/src/enchant.rs @@ -21,7 +21,10 @@ pub struct Cost { } impl Cost { fn parse(v: &Value) -> Self { - Self { base: v["base"].as_i64().unwrap_or(1) as i32, per_level: v["per_level_above_first"].as_i64().unwrap_or(0) as i32 } + Self { + base: v["base"].as_i64().unwrap_or(1) as i32, + per_level: v["per_level_above_first"].as_i64().unwrap_or(0) as i32, + } } pub fn calculate(self, level: u32) -> i32 { self.base + self.per_level * (level as i32 - 1) @@ -71,13 +74,18 @@ pub struct Enchantments { fn string_list(v: &Value) -> Vec { match v { Value::String(s) => vec![s.clone()], - Value::Array(a) => a.iter().filter_map(|e| e.as_str().map(str::to_owned)).collect(), + Value::Array(a) => a + .iter() + .filter_map(|e| e.as_str().map(str::to_owned)) + .collect(), _ => vec![], } } fn read_tag_dir(dir: &Path) -> HashMap> { fn walk(dir: &Path, base: &Path, out: &mut HashMap>) { - let Ok(entries) = fs::read_dir(dir) else { return }; + let Ok(entries) = fs::read_dir(dir) else { + return; + }; for e in entries.flatten() { let p = e.path(); if p.is_dir() { @@ -87,8 +95,16 @@ fn read_tag_dir(dir: &Path) -> HashMap> { && let Ok(bytes) = fs::read(&p) && let Ok(v) = serde_json::from_slice::(&bytes) { - let name = format!("minecraft:{}", rel.with_extension("").to_string_lossy().replace('\\', "/")); - let values = v["values"].as_array().into_iter().flatten().filter_map(|e| e.as_str().or_else(|| e["id"].as_str()).map(str::to_owned)).collect(); + let name = format!( + "minecraft:{}", + rel.with_extension("").to_string_lossy().replace('\\', "/") + ); + let values = v["values"] + .as_array() + .into_iter() + .flatten() + .filter_map(|e| e.as_str().or_else(|| e["id"].as_str()).map(str::to_owned)) + .collect(); out.insert(name, values); } } @@ -98,7 +114,12 @@ fn read_tag_dir(dir: &Path) -> HashMap> { out } /// Expand a tag keeping first-seen order (`TagLoader` builds a linked set). -fn expand_ordered(name: &str, raw: &HashMap>, out: &mut Vec, depth: u32) { +fn expand_ordered( + name: &str, + raw: &HashMap>, + out: &mut Vec, + depth: u32, +) { if depth > 16 { return; } @@ -113,7 +134,9 @@ fn expand_ordered(name: &str, raw: &HashMap>, out: &mut Vec< /// Roman numerals as in `enchantment.level.N` (falls back to the number). pub fn level_name(level: u32) -> String { const NAMES: [&str; 10] = ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"]; - NAMES.get(level.wrapping_sub(1) as usize).map_or_else(|| level.to_string(), |s| (*s).to_owned()) + NAMES + .get(level.wrapping_sub(1) as usize) + .map_or_else(|| level.to_string(), |s| (*s).to_owned()) } impl Enchantments { @@ -125,7 +148,10 @@ impl Enchantments { .map(|k| { let mut v = Vec::new(); expand_ordered(k, &raw_tags, &mut v, 0); - (k.clone(), v.into_iter().map(|s| Arc::from(s.as_str())).collect()) + ( + k.clone(), + v.into_iter().map(|s| Arc::from(s.as_str())).collect(), + ) }) .collect(); let unordered = |raw: HashMap>| -> HashMap> { @@ -144,7 +170,8 @@ impl Enchantments { if let Ok(entries) = fs::read_dir(data.join("enchantment")) { for e in entries.flatten() { let p = e.path(); - if let (Some(stem), Ok(bytes)) = (p.file_stem().and_then(|s| s.to_str()), fs::read(&p)) + if let (Some(stem), Ok(bytes)) = + (p.file_stem().and_then(|s| s.to_str()), fs::read(&p)) && let Ok(v) = serde_json::from_slice(&bytes) { files.insert(format!("minecraft:{stem}"), v); @@ -156,18 +183,38 @@ impl Enchantments { .and_then(|b| serde_json::from_slice::>(&b).ok()) .unwrap_or_default() .into_iter() - .filter(|(k, _)| k.starts_with("enchantment.") || k.starts_with("effect.") || k.starts_with("item.minecraft.potion") || k.starts_with("item.minecraft.splash_potion") || k.starts_with("item.minecraft.lingering_potion") || k.starts_with("item.minecraft.tipped_arrow") || k.starts_with("trim_") || k.starts_with("potion.") || k.starts_with("container.") || k.starts_with("merchant.") || k.starts_with("entity.minecraft.villager")) + .filter(|(k, _)| { + k.starts_with("enchantment.") + || k.starts_with("effect.") + || k.starts_with("item.minecraft.potion") + || k.starts_with("item.minecraft.splash_potion") + || k.starts_with("item.minecraft.lingering_potion") + || k.starts_with("item.minecraft.tipped_arrow") + || k.starts_with("trim_") + || k.starts_with("potion.") + || k.starts_with("container.") + || k.starts_with("merchant.") + || k.starts_with("entity.minecraft.villager") + }) .collect(); let mut list = Vec::new(); for (id, v) in &files { let exclusive = match &v["exclusive_set"] { - Value::String(s) if s.starts_with('#') => tags.get(&s[1..]).cloned().unwrap_or_default(), - other => string_list(other).into_iter().map(|s| Arc::from(s.as_str())).collect(), + Value::String(s) if s.starts_with('#') => { + tags.get(&s[1..]).cloned().unwrap_or_default() + } + other => string_list(other) + .into_iter() + .map(|s| Arc::from(s.as_str())) + .collect(), }; let key = v["description"]["translate"].as_str().unwrap_or(""); list.push(Enchantment { id: Arc::from(id.as_str()), - description: lang.get(key).cloned().unwrap_or_else(|| id.trim_start_matches("minecraft:").replace('_', " ")), + description: lang + .get(key) + .cloned() + .unwrap_or_else(|| id.trim_start_matches("minecraft:").replace('_', " ")), max_level: v["max_level"].as_u64().unwrap_or(1) as u32, weight: v["weight"].as_u64().unwrap_or(1) as u32, anvil_cost: v["anvil_cost"].as_u64().unwrap_or(0) as u32, @@ -180,7 +227,11 @@ impl Enchantments { effects: v["effects"].clone(), }); } - let index = list.iter().enumerate().map(|(i, e)| (e.id.clone(), i)).collect(); + let index = list + .iter() + .enumerate() + .map(|(i, e)| (e.id.clone(), i)) + .collect(); let mut props = HashMap::new(); if let Ok(bytes) = fs::read(root.join("items.json")) && let Ok(raw) = serde_json::from_slice::>(&bytes) @@ -189,23 +240,41 @@ impl Enchantments { props.insert( Arc::from(id.as_str()), ItemProps { - enchantable: c["minecraft:enchantable"]["value"].as_u64().unwrap_or(0) as u32, + enchantable: c["minecraft:enchantable"]["value"].as_u64().unwrap_or(0) + as u32, repairable: string_list(&c["minecraft:repairable"]["items"]), - glint: c["minecraft:enchantment_glint_override"].as_bool().unwrap_or(false), - rarity: c["minecraft:rarity"].as_str().unwrap_or("common").to_owned(), - trim_material: c["minecraft:provides_trim_material"].as_str().map(str::to_owned), + glint: c["minecraft:enchantment_glint_override"] + .as_bool() + .unwrap_or(false), + rarity: c["minecraft:rarity"] + .as_str() + .unwrap_or("common") + .to_owned(), + trim_material: c["minecraft:provides_trim_material"] + .as_str() + .map(str::to_owned), brewing_fuel: c.get("minecraft:brewing_fuel").is_some(), }, ); } } - Self { list, index, tags, entity_tags, damage_tags, props, lang } + Self { + list, + index, + tags, + entity_tags, + damage_tags, + props, + lang, + } } pub fn get(&self, id: &str) -> Option<&Enchantment> { self.index.get(id).map(|&i| &self.list[i]) } pub fn tag(&self, name: &str) -> &[Arc] { - self.tags.get(name.trim_start_matches('#')).map_or(&[], Vec::as_slice) + self.tags + .get(name.trim_start_matches('#')) + .map_or(&[], Vec::as_slice) } pub fn in_tag(&self, name: &str, id: &str) -> bool { self.tag(name).iter().any(|e| &**e == id) @@ -231,11 +300,15 @@ impl Enchantments { } /// `Enchantment.canEnchant` / `isSupportedItem`. pub fn can_enchant(&self, items: &Items, id: &str, item: &str) -> bool { - self.get(id).is_some_and(|e| Self::item_in(items, &e.supported, item)) + self.get(id) + .is_some_and(|e| Self::item_in(items, &e.supported, item)) } /// `Enchantment.isPrimaryItem`. pub fn is_primary(&self, items: &Items, e: &Enchantment, item: &str) -> bool { - Self::item_in(items, &e.supported, item) && e.primary.as_ref().is_none_or(|p| Self::item_in(items, p, item)) + Self::item_in(items, &e.supported, item) + && e.primary + .as_ref() + .is_none_or(|p| Self::item_in(items, p, item)) } /// `Enchantment.areCompatible`. pub fn compatible(&self, a: &str, b: &str) -> bool { @@ -247,11 +320,17 @@ impl Enchantments { } /// `Enchantment.getFullname` as plain text and whether it is a curse (red). pub fn full_name(&self, id: &str, level: u32) -> (String, bool) { - let Some(e) = self.get(id) else { return (format!("{id} {}", level_name(level)), false) }; + let Some(e) = self.get(id) else { + return (format!("{id} {}", level_name(level)), false); + }; let mut name = e.description.clone(); if level != 1 || e.max_level != 1 { name.push(' '); - name.push_str(self.lang.get(&format!("enchantment.level.{level}")).map_or(&level_name(level), |s| s)); + name.push_str( + self.lang + .get(&format!("enchantment.level.{level}")) + .map_or(&level_name(level), |s| s), + ); } (name, self.is_curse(id)) } @@ -279,7 +358,13 @@ impl Enchantments { // ---- Enchanting table (EnchantmentHelper) ---- /// `EnchantmentHelper.getEnchantmentCost`. - pub fn enchantment_cost(&self, random: &mut R, slot: usize, bookcases: i32, item: &str) -> i32 { + pub fn enchantment_cost( + &self, + random: &mut R, + slot: usize, + bookcases: i32, + item: &str, + ) -> i32 { if self.enchantable(item) == 0 { return 0; } @@ -292,7 +377,13 @@ impl Enchantments { } } /// `EnchantmentHelper.getAvailableEnchantmentResults`. - pub fn available_results(&self, items: &Items, value: i32, item: &str, pool: &[Arc]) -> Vec<(Arc, u32)> { + pub fn available_results( + &self, + items: &Items, + value: i32, + item: &str, + pool: &[Arc], + ) -> Vec<(Arc, u32)> { let book = item == "minecraft:book"; let mut out = Vec::new(); for id in pool { @@ -309,8 +400,15 @@ impl Enchantments { } out } - fn weighted(&self, random: &mut R, list: &[(Arc, u32)]) -> Option<(Arc, u32)> { - let total: i32 = list.iter().map(|(id, _)| self.get(id).map_or(0, |e| e.weight as i32)).sum(); + fn weighted( + &self, + random: &mut R, + list: &[(Arc, u32)], + ) -> Option<(Arc, u32)> { + let total: i32 = list + .iter() + .map(|(id, _)| self.get(id).map_or(0, |e| e.weight as i32)) + .sum(); if total <= 0 { return None; } @@ -324,7 +422,14 @@ impl Enchantments { None } /// `EnchantmentHelper.selectEnchantment`. - pub fn select(&self, items: &Items, random: &mut R, item: &str, cost: i32, pool: &[Arc]) -> Vec<(Arc, u32)> { + pub fn select( + &self, + items: &Items, + random: &mut R, + item: &str, + cost: i32, + pool: &[Arc], + ) -> Vec<(Arc, u32)> { let mut results = Vec::new(); let value = self.enchantable(item) as i32; if value == 0 { @@ -358,7 +463,14 @@ impl Enchantments { // ---- Effect components ---- /// Run `component` value effects of every enchantment on `stack` over `value`. - pub fn modify_value(&self, stack: Option<&ItemStack>, component: &str, ctx: &EffectContext<'_>, random: &mut LegacyRandom, value: f32) -> f32 { + pub fn modify_value( + &self, + stack: Option<&ItemStack>, + component: &str, + ctx: &EffectContext<'_>, + random: &mut LegacyRandom, + value: f32, + ) -> f32 { let Some(stack) = stack else { return value }; let mut value = value; for (id, level) in stack.enchantments() { @@ -366,7 +478,15 @@ impl Enchantments { } value } - pub fn modify_value_with(&self, id: &str, level: u32, component: &str, ctx: &EffectContext<'_>, random: &mut LegacyRandom, mut value: f32) -> f32 { + pub fn modify_value_with( + &self, + id: &str, + level: u32, + component: &str, + ctx: &EffectContext<'_>, + random: &mut LegacyRandom, + mut value: f32, + ) -> f32 { let Some(e) = self.get(id) else { return value }; for effect in e.effects[component].as_array().into_iter().flatten() { if let Some(req) = effect.get("requirements") @@ -380,18 +500,34 @@ impl Enchantments { } /// Whether `stack` has any enchantment providing `component`. pub fn has_component(&self, stack: &ItemStack, component: &str) -> bool { - stack.enchantments().iter().any(|(id, _)| self.get(id).is_some_and(|e| e.effects.get(component).is_some())) + stack.enchantments().iter().any(|(id, _)| { + self.get(id) + .is_some_and(|e| e.effects.get(component).is_some()) + }) } /// The highest level among enchantments on `stack` that have `component`. pub fn component_level(&self, stack: &ItemStack, component: &str) -> u32 { - stack.enchantments().iter().filter(|(id, _)| self.get(id).is_some_and(|e| e.effects.get(component).is_some())).map(|(_, l)| *l).max().unwrap_or(0) + stack + .enchantments() + .iter() + .filter(|(id, _)| { + self.get(id) + .is_some_and(|e| e.effects.get(component).is_some()) + }) + .map(|(_, l)| *l) + .max() + .unwrap_or(0) } /// `minecraft:attributes` contributions of `stack`: (attribute, id, amount, operation). pub fn attributes(&self, stack: &ItemStack) -> Vec<(String, String, f64, String)> { let mut out = Vec::new(); for (id, level) in stack.enchantments() { let Some(e) = self.get(id) else { continue }; - for a in e.effects["minecraft:attributes"].as_array().into_iter().flatten() { + for a in e.effects["minecraft:attributes"] + .as_array() + .into_iter() + .flatten() + { out.push(( a["attribute"].as_str().unwrap_or("").to_owned(), format!("{}.{}", a["id"].as_str().unwrap_or(""), level), @@ -404,34 +540,61 @@ impl Enchantments { } /// Sum of `add_value` amounts of one attribute from enchantments on `stack`. pub fn attribute_add(&self, stack: Option<&ItemStack>, attribute: &str) -> f64 { - stack.map_or(0.0, |s| self.attributes(s).iter().filter(|a| a.0 == attribute && a.3 == "add_value").map(|a| a.2).sum()) + stack.map_or(0.0, |s| { + self.attributes(s) + .iter() + .filter(|a| a.0 == attribute && a.3 == "add_value") + .map(|a| a.2) + .sum() + }) } fn entity_matches(&self, spec: &Value, entity: Option<&str>) -> bool { let Some(entity) = entity else { return false }; match spec.as_str() { Some(s) => match s.strip_prefix('#') { - Some(tag) => self.entity_tags.get(tag).is_some_and(|t| t.contains(entity)), + Some(tag) => self + .entity_tags + .get(tag) + .is_some_and(|t| t.contains(entity)), None => s == entity, }, None => string_list(spec).iter().any(|s| s == entity), } } /// The loot-condition subset enchantment `requirements` use. - pub fn condition(&self, c: &Value, level: u32, ctx: &EffectContext<'_>, random: &mut LegacyRandom) -> bool { + pub fn condition( + &self, + c: &Value, + level: u32, + ctx: &EffectContext<'_>, + random: &mut LegacyRandom, + ) -> bool { match c["type"].as_str().or(c["condition"].as_str()).unwrap_or("") { "minecraft:inverted" => !self.condition(&c["term"], level, ctx, random), - "minecraft:all_of" => c["terms"].as_array().into_iter().flatten().all(|t| self.condition(t, level, ctx, random)), - "minecraft:any_of" => c["terms"].as_array().into_iter().flatten().any(|t| self.condition(t, level, ctx, random)), + "minecraft:all_of" => c["terms"] + .as_array() + .into_iter() + .flatten() + .all(|t| self.condition(t, level, ctx, random)), + "minecraft:any_of" => c["terms"] + .as_array() + .into_iter() + .flatten() + .any(|t| self.condition(t, level, ctx, random)), "minecraft:match_tool" => { let Some(tool) = ctx.tool else { return false }; let items = &c["predicate"]["items"]; if items.is_null() { return true; } - string_list(items).iter().any(|s| match s.strip_prefix('#') { - Some(tag) => ctx.items.is_some_and(|i| i.item_tags.get(tag).is_some_and(|t| t.contains(tool))), - None => s == tool, - }) + string_list(items) + .iter() + .any(|s| match s.strip_prefix('#') { + Some(tag) => ctx.items.is_some_and(|i| { + i.item_tags.get(tag).is_some_and(|t| t.contains(tool)) + }), + None => s == tool, + }) } "minecraft:damage_source_properties" => { let p = &c["predicate"]; @@ -442,7 +605,9 @@ impl Enchantments { } p["tags"].as_array().into_iter().flatten().all(|t| { let tag = t["id"].as_str().unwrap_or("").trim_start_matches('#'); - let has = ctx.damage_type.is_some_and(|d| self.damage_tags.get(tag).is_some_and(|s| s.contains(d))); + let has = ctx + .damage_type + .is_some_and(|d| self.damage_tags.get(tag).is_some_and(|s| s.contains(d))); has == t["expected"].as_bool().unwrap_or(true) }) } @@ -454,13 +619,24 @@ impl Enchantments { _ => None, }; let spec = &c["predicate"]["minecraft:entity_type"]; - let spec = if spec.is_null() { &c["predicate"]["type"] } else { spec }; + let spec = if spec.is_null() { + &c["predicate"]["type"] + } else { + spec + }; spec.is_null() && entity.is_some() || self.entity_matches(spec, entity) } "minecraft:random_chance" => { let chance = match &c["chance"] { - Value::Object(o) if o.get("type").and_then(Value::as_str) == Some("minecraft:enchantment_level") => level_value(&c["chance"]["amount"], level), - v => v.as_f64().map_or_else(|| level_value(v, level), |f| f as f32), + Value::Object(o) + if o.get("type").and_then(Value::as_str) + == Some("minecraft:enchantment_level") => + { + level_value(&c["chance"]["amount"], level) + } + v => v + .as_f64() + .map_or_else(|| level_value(v, level), |f| f as f32), }; random.next_float() < chance } @@ -498,9 +674,15 @@ pub fn level_value(v: &Value, level: u32) -> f32 { "minecraft:clamped" => level_value(&o["value"], level).clamp(f("min"), f("max")), "minecraft:fraction" => { let d = level_value(&o["denominator"], level); - if d == 0.0 { 0.0 } else { level_value(&o["numerator"], level) / d } + if d == 0.0 { + 0.0 + } else { + level_value(&o["numerator"], level) / d + } + } + "minecraft:exponent" => { + level_value(&o["base"], level).powf(level_value(&o["power"], level)) } - "minecraft:exponent" => level_value(&o["base"], level).powf(level_value(&o["power"], level)), "minecraft:lookup" => { let values = o.get("values").and_then(Value::as_array); match values.and_then(|a| a.get(level as usize - 1)) { @@ -515,7 +697,12 @@ pub fn level_value(v: &Value, level: u32) -> f32 { } } /// `EnchantmentValueEffect.process`. -pub fn apply_value_effect(effect: &Value, level: u32, random: &mut LegacyRandom, value: f32) -> f32 { +pub fn apply_value_effect( + effect: &Value, + level: u32, + random: &mut LegacyRandom, + value: f32, +) -> f32 { match effect["type"].as_str().unwrap_or("") { "minecraft:add" => value + level_value(&effect["value"], level), "minecraft:multiply" => value * level_value(&effect["factor"], level), @@ -540,7 +727,11 @@ pub fn apply_value_effect(effect: &Value, level: u32, random: &mut LegacyRandom, }; n - removed as f32 } - "minecraft:all_of" => effect["effects"].as_array().into_iter().flatten().fold(value, |v, e| apply_value_effect(e, level, random, v)), + "minecraft:all_of" => effect["effects"] + .as_array() + .into_iter() + .flatten() + .fold(value, |v, e| apply_value_effect(e, level, random, v)), _ => value, } } @@ -553,11 +744,26 @@ pub(crate) mod tests { /// A small registry built from literal JSON matching the vanilla files. pub fn sample() -> Enchantments { let defs = [ - ("minecraft:sharpness", json!({"anvil_cost":1,"exclusive_set":"#minecraft:exclusive_set/damage","max_cost":{"base":21,"per_level_above_first":11},"max_level":5,"min_cost":{"base":1,"per_level_above_first":11},"primary_items":"#minecraft:enchantable/melee_weapon","supported_items":"#minecraft:enchantable/sharp_weapon","weight":10,"slots":["mainhand"],"effects":{"minecraft:damage":[{"effect":{"type":"minecraft:add","value":{"type":"minecraft:linear","base":1.0,"per_level_above_first":0.5}}}]}})), - ("minecraft:smite", json!({"anvil_cost":2,"exclusive_set":"#minecraft:exclusive_set/damage","max_cost":{"base":25,"per_level_above_first":8},"max_level":5,"min_cost":{"base":5,"per_level_above_first":8},"primary_items":"#minecraft:enchantable/melee_weapon","supported_items":"#minecraft:enchantable/weapon","weight":5,"effects":{"minecraft:damage":[{"effect":{"type":"minecraft:add","value":{"type":"minecraft:linear","base":2.5,"per_level_above_first":2.5}},"requirements":{"type":"minecraft:entity_properties","entity":"this","predicate":{"minecraft:entity_type":"#minecraft:sensitive_to_smite"}}}]}})), - ("minecraft:unbreaking", json!({"anvil_cost":2,"max_cost":{"base":55,"per_level_above_first":8},"max_level":3,"min_cost":{"base":5,"per_level_above_first":8},"supported_items":"#minecraft:enchantable/durability","weight":5,"effects":{"minecraft:item_damage":[{"effect":{"type":"minecraft:remove_binomial","chance":{"type":"minecraft:fraction","denominator":{"type":"minecraft:linear","base":2.0,"per_level_above_first":1.0},"numerator":{"type":"minecraft:linear","base":1.0,"per_level_above_first":1.0}}}}]}})), - ("minecraft:mending", json!({"anvil_cost":4,"max_cost":{"base":75,"per_level_above_first":25},"max_level":1,"min_cost":{"base":25,"per_level_above_first":25},"supported_items":"#minecraft:enchantable/durability","weight":2})), - ("minecraft:feather_falling", json!({"anvil_cost":2,"max_cost":{"base":11,"per_level_above_first":6},"max_level":4,"min_cost":{"base":5,"per_level_above_first":6},"supported_items":"#minecraft:enchantable/foot_armor","weight":5,"effects":{"minecraft:damage_protection":[{"effect":{"type":"minecraft:add","value":{"type":"minecraft:linear","base":3.0,"per_level_above_first":3.0}},"requirements":{"type":"minecraft:damage_source_properties","predicate":{"tags":[{"expected":true,"id":"#minecraft:is_fall"},{"expected":false,"id":"#minecraft:bypasses_invulnerability"}]}}}]}})), + ( + "minecraft:sharpness", + json!({"anvil_cost":1,"exclusive_set":"#minecraft:exclusive_set/damage","max_cost":{"base":21,"per_level_above_first":11},"max_level":5,"min_cost":{"base":1,"per_level_above_first":11},"primary_items":"#minecraft:enchantable/melee_weapon","supported_items":"#minecraft:enchantable/sharp_weapon","weight":10,"slots":["mainhand"],"effects":{"minecraft:damage":[{"effect":{"type":"minecraft:add","value":{"type":"minecraft:linear","base":1.0,"per_level_above_first":0.5}}}]}}), + ), + ( + "minecraft:smite", + json!({"anvil_cost":2,"exclusive_set":"#minecraft:exclusive_set/damage","max_cost":{"base":25,"per_level_above_first":8},"max_level":5,"min_cost":{"base":5,"per_level_above_first":8},"primary_items":"#minecraft:enchantable/melee_weapon","supported_items":"#minecraft:enchantable/weapon","weight":5,"effects":{"minecraft:damage":[{"effect":{"type":"minecraft:add","value":{"type":"minecraft:linear","base":2.5,"per_level_above_first":2.5}},"requirements":{"type":"minecraft:entity_properties","entity":"this","predicate":{"minecraft:entity_type":"#minecraft:sensitive_to_smite"}}}]}}), + ), + ( + "minecraft:unbreaking", + json!({"anvil_cost":2,"max_cost":{"base":55,"per_level_above_first":8},"max_level":3,"min_cost":{"base":5,"per_level_above_first":8},"supported_items":"#minecraft:enchantable/durability","weight":5,"effects":{"minecraft:item_damage":[{"effect":{"type":"minecraft:remove_binomial","chance":{"type":"minecraft:fraction","denominator":{"type":"minecraft:linear","base":2.0,"per_level_above_first":1.0},"numerator":{"type":"minecraft:linear","base":1.0,"per_level_above_first":1.0}}}}]}}), + ), + ( + "minecraft:mending", + json!({"anvil_cost":4,"max_cost":{"base":75,"per_level_above_first":25},"max_level":1,"min_cost":{"base":25,"per_level_above_first":25},"supported_items":"#minecraft:enchantable/durability","weight":2}), + ), + ( + "minecraft:feather_falling", + json!({"anvil_cost":2,"max_cost":{"base":11,"per_level_above_first":6},"max_level":4,"min_cost":{"base":5,"per_level_above_first":6},"supported_items":"#minecraft:enchantable/foot_armor","weight":5,"effects":{"minecraft:damage_protection":[{"effect":{"type":"minecraft:add","value":{"type":"minecraft:linear","base":3.0,"per_level_above_first":3.0}},"requirements":{"type":"minecraft:damage_source_properties","predicate":{"tags":[{"expected":true,"id":"#minecraft:is_fall"},{"expected":false,"id":"#minecraft:bypasses_invulnerability"}]}}}]}}), + ), ]; let list: Vec = defs .iter() @@ -571,44 +777,136 @@ pub(crate) mod tests { max_cost: Cost::parse(&v["max_cost"]), supported: string_list(&v["supported_items"]), primary: v.get("primary_items").map(string_list), - exclusive: if v["exclusive_set"].is_null() { HashSet::new() } else { [Arc::from("minecraft:sharpness"), Arc::from("minecraft:smite")].into_iter().collect() }, + exclusive: if v["exclusive_set"].is_null() { + HashSet::new() + } else { + [ + Arc::from("minecraft:sharpness"), + Arc::from("minecraft:smite"), + ] + .into_iter() + .collect() + }, slots: vec![], effects: v["effects"].clone(), }) .collect(); - let index = list.iter().enumerate().map(|(i, e)| (e.id.clone(), i)).collect(); - let pool: Vec> = ["minecraft:feather_falling", "minecraft:sharpness", "minecraft:smite", "minecraft:unbreaking", "minecraft:mending"].iter().map(|s| Arc::from(*s)).collect(); + let index = list + .iter() + .enumerate() + .map(|(i, e)| (e.id.clone(), i)) + .collect(); + let pool: Vec> = [ + "minecraft:feather_falling", + "minecraft:sharpness", + "minecraft:smite", + "minecraft:unbreaking", + "minecraft:mending", + ] + .iter() + .map(|s| Arc::from(*s)) + .collect(); let mut tags = HashMap::new(); - tags.insert("minecraft:in_enchanting_table".to_owned(), pool[..4].to_vec()); - tags.insert("minecraft:tooltip_order".to_owned(), vec![Arc::from("minecraft:sharpness"), Arc::from("minecraft:unbreaking")]); + tags.insert( + "minecraft:in_enchanting_table".to_owned(), + pool[..4].to_vec(), + ); + tags.insert( + "minecraft:tooltip_order".to_owned(), + vec![ + Arc::from("minecraft:sharpness"), + Arc::from("minecraft:unbreaking"), + ], + ); let mut entity_tags = HashMap::new(); - entity_tags.insert("minecraft:sensitive_to_smite".to_owned(), ["minecraft:zombie".to_owned()].into_iter().collect()); + entity_tags.insert( + "minecraft:sensitive_to_smite".to_owned(), + ["minecraft:zombie".to_owned()].into_iter().collect(), + ); let mut damage_tags = HashMap::new(); - damage_tags.insert("minecraft:is_fall".to_owned(), ["minecraft:fall".to_owned()].into_iter().collect()); + damage_tags.insert( + "minecraft:is_fall".to_owned(), + ["minecraft:fall".to_owned()].into_iter().collect(), + ); let mut props = HashMap::new(); - for (item, value) in [("minecraft:diamond_sword", 10), ("minecraft:iron_sword", 14), ("minecraft:book", 1), ("minecraft:iron_boots", 9)] { - props.insert(Arc::from(item), ItemProps { enchantable: value, ..Default::default() }); + for (item, value) in [ + ("minecraft:diamond_sword", 10), + ("minecraft:iron_sword", 14), + ("minecraft:book", 1), + ("minecraft:iron_boots", 9), + ] { + props.insert( + Arc::from(item), + ItemProps { + enchantable: value, + ..Default::default() + }, + ); + } + Enchantments { + list, + index, + tags, + entity_tags, + damage_tags, + props, + lang: HashMap::new(), } - Enchantments { list, index, tags, entity_tags, damage_tags, props, lang: HashMap::new() } } pub fn sample_items() -> Items { let mut item_tags: HashMap> = HashMap::new(); let swords = ["minecraft:diamond_sword", "minecraft:iron_sword"]; - for tag in ["enchantable/melee_weapon", "enchantable/sharp_weapon", "enchantable/weapon", "enchantable/durability"] { - item_tags.insert(format!("minecraft:{tag}"), swords.iter().map(|s| (*s).to_owned()).collect()); + for tag in [ + "enchantable/melee_weapon", + "enchantable/sharp_weapon", + "enchantable/weapon", + "enchantable/durability", + ] { + item_tags.insert( + format!("minecraft:{tag}"), + swords.iter().map(|s| (*s).to_owned()).collect(), + ); } - item_tags.get_mut("minecraft:enchantable/durability").unwrap().insert("minecraft:iron_boots".into()); - item_tags.insert("minecraft:enchantable/foot_armor".into(), ["minecraft:iron_boots".to_owned()].into_iter().collect()); + item_tags + .get_mut("minecraft:enchantable/durability") + .unwrap() + .insert("minecraft:iron_boots".into()); + item_tags.insert( + "minecraft:enchantable/foot_armor".into(), + ["minecraft:iron_boots".to_owned()].into_iter().collect(), + ); Items::for_tests(item_tags) } #[test] fn level_based_values() { - assert_eq!(level_value(&json!({"type":"minecraft:linear","base":1.0,"per_level_above_first":0.5}), 5), 3.0); - assert_eq!(level_value(&json!({"type":"minecraft:levels_squared","added":1.0}), 3), 10.0); - assert_eq!(level_value(&json!({"type":"minecraft:fraction","numerator":{"type":"minecraft:linear","base":1.0,"per_level_above_first":1.0},"denominator":{"type":"minecraft:linear","base":2.0,"per_level_above_first":1.0}}), 3), 0.75); + assert_eq!( + level_value( + &json!({"type":"minecraft:linear","base":1.0,"per_level_above_first":0.5}), + 5 + ), + 3.0 + ); + assert_eq!( + level_value(&json!({"type":"minecraft:levels_squared","added":1.0}), 3), + 10.0 + ); + assert_eq!( + level_value( + &json!({"type":"minecraft:fraction","numerator":{"type":"minecraft:linear","base":1.0,"per_level_above_first":1.0},"denominator":{"type":"minecraft:linear","base":2.0,"per_level_above_first":1.0}}), + 3 + ), + 0.75 + ); assert_eq!(level_name(4), "IV"); - assert_eq!(Cost { base: 1, per_level: 11 }.calculate(5), 45); + assert_eq!( + Cost { + base: 1, + per_level: 11 + } + .calculate(5), + 45 + ); } #[test] @@ -619,11 +917,18 @@ pub(crate) mod tests { for bookcases in [0, 5, 15, 20] { let mut a = LegacyRandom::new(seed); let mut b = LegacyRandom::new(seed); - let costs: Vec = (0..3).map(|slot| e.enchantment_cost(&mut a, slot, bookcases, "minecraft:diamond_sword")).collect(); + let costs: Vec = (0..3) + .map(|slot| { + e.enchantment_cost(&mut a, slot, bookcases, "minecraft:diamond_sword") + }) + .collect(); let bc = bookcases.min(15); let expect: Vec = (0..3) .map(|slot| { - let s = b.next_int_bound(8).unwrap() + 1 + (bc >> 1) + b.next_int_bound(bc + 1).unwrap(); + let s = b.next_int_bound(8).unwrap() + + 1 + + (bc >> 1) + + b.next_int_bound(bc + 1).unwrap(); match slot { 0 => (s / 3).max(1), 1 => s * 2 / 3 + 1, @@ -635,7 +940,10 @@ pub(crate) mod tests { assert!(costs[2] <= 30); } } - assert_eq!(e.enchantment_cost(&mut LegacyRandom::new(0), 0, 15, "minecraft:stick"), 0); + assert_eq!( + e.enchantment_cost(&mut LegacyRandom::new(0), 0, 15, "minecraft:stick"), + 0 + ); } #[test] @@ -648,7 +956,10 @@ pub(crate) mod tests { let picked = e.select(&items, &mut r, "minecraft:diamond_sword", 30, &pool); assert!(!picked.is_empty()); let has = |id: &str| picked.iter().any(|(p, _)| &**p == id); - assert!(!(has("minecraft:sharpness") && has("minecraft:smite")), "{picked:?}"); + assert!( + !(has("minecraft:sharpness") && has("minecraft:smite")), + "{picked:?}" + ); assert!(!has("minecraft:feather_falling")); for (id, l) in &picked { assert!(*l >= 1 && *l <= e.get(id).unwrap().max_level); @@ -657,8 +968,15 @@ pub(crate) mod tests { // Books accept every enchantment in the pool. let mut r = LegacyRandom::new(3); let available = e.available_results(&items, 20, "minecraft:book", &pool); - assert!(available.iter().any(|(id, _)| &**id == "minecraft:feather_falling")); - assert!(e.select(&items, &mut r, "minecraft:stick", 30, &pool).is_empty()); + assert!( + available + .iter() + .any(|(id, _)| &**id == "minecraft:feather_falling") + ); + assert!( + e.select(&items, &mut r, "minecraft:stick", 30, &pool) + .is_empty() + ); } #[test] @@ -668,23 +986,65 @@ pub(crate) mod tests { let mut sword = ItemStack::new("minecraft:diamond_sword", 1); sword.enchant("minecraft:sharpness", 5); let mut r = LegacyRandom::new(1); - let ctx = EffectContext { items: Some(&items), this: Some("minecraft:zombie"), ..Default::default() }; - assert_eq!(e.modify_value(Some(&sword), "minecraft:damage", &ctx, &mut r, 0.0), 3.0); + let ctx = EffectContext { + items: Some(&items), + this: Some("minecraft:zombie"), + ..Default::default() + }; + assert_eq!( + e.modify_value(Some(&sword), "minecraft:damage", &ctx, &mut r, 0.0), + 3.0 + ); let mut smite = ItemStack::new("minecraft:diamond_sword", 1); smite.enchant("minecraft:smite", 2); - assert_eq!(e.modify_value(Some(&smite), "minecraft:damage", &ctx, &mut r, 0.0), 5.0); - let pig = EffectContext { this: Some("minecraft:pig"), ..ctx }; - assert_eq!(e.modify_value(Some(&smite), "minecraft:damage", &pig, &mut r, 0.0), 0.0); + assert_eq!( + e.modify_value(Some(&smite), "minecraft:damage", &ctx, &mut r, 0.0), + 5.0 + ); + let pig = EffectContext { + this: Some("minecraft:pig"), + ..ctx + }; + assert_eq!( + e.modify_value(Some(&smite), "minecraft:damage", &pig, &mut r, 0.0), + 0.0 + ); let mut boots = ItemStack::new("minecraft:iron_boots", 1); boots.enchant("minecraft:feather_falling", 4); - let fall = EffectContext { damage_type: Some("minecraft:fall"), ..Default::default() }; - assert_eq!(e.modify_value(Some(&boots), "minecraft:damage_protection", &fall, &mut r, 0.0), 12.0); - let lava = EffectContext { damage_type: Some("minecraft:lava"), ..Default::default() }; - assert_eq!(e.modify_value(Some(&boots), "minecraft:damage_protection", &lava, &mut r, 0.0), 0.0); + let fall = EffectContext { + damage_type: Some("minecraft:fall"), + ..Default::default() + }; + assert_eq!( + e.modify_value( + Some(&boots), + "minecraft:damage_protection", + &fall, + &mut r, + 0.0 + ), + 12.0 + ); + let lava = EffectContext { + damage_type: Some("minecraft:lava"), + ..Default::default() + }; + assert_eq!( + e.modify_value( + Some(&boots), + "minecraft:damage_protection", + &lava, + &mut r, + 0.0 + ), + 0.0 + ); // Unbreaking III keeps about 1/4 of durability hits. let mut tool = ItemStack::new("minecraft:diamond_sword", 1); tool.enchant("minecraft:unbreaking", 3); - let kept: f32 = (0..4000).map(|_| e.modify_value(Some(&tool), "minecraft:item_damage", &ctx, &mut r, 1.0)).sum(); + let kept: f32 = (0..4000) + .map(|_| e.modify_value(Some(&tool), "minecraft:item_damage", &ctx, &mut r, 1.0)) + .sum(); assert!((800.0..1200.0).contains(&kept), "{kept}"); } @@ -693,7 +1053,11 @@ pub(crate) mod tests { let e = sample(); assert_eq!(e.full_name("minecraft:mending", 1).0, "mending"); assert_eq!(e.full_name("minecraft:sharpness", 1).0, "sharpness I"); - let levels = vec![(Arc::from("minecraft:unbreaking"), 3), (Arc::from("minecraft:mending"), 1), (Arc::from("minecraft:sharpness"), 2)]; + let levels = vec![ + (Arc::from("minecraft:unbreaking"), 3), + (Arc::from("minecraft:mending"), 1), + (Arc::from("minecraft:sharpness"), 2), + ]; let lines: Vec = e.tooltip(&levels).into_iter().map(|l| l.0).collect(); assert_eq!(lines, ["sharpness II", "unbreaking III", "mending"]); assert!(!e.compatible("minecraft:sharpness", "minecraft:smite")); diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index 98fec0e91..e191160a9 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -28,7 +28,11 @@ impl ItemEntity { let h = Self::WIDTH / 2.0; Aabb::new( Vec3::new(self.position.x - h, self.position.y, self.position.z - h), - Vec3::new(self.position.x + h, self.position.y + Self::WIDTH, self.position.z + h), + Vec3::new( + self.position.x + h, + self.position.y + Self::WIDTH, + self.position.z + h, + ), ) } /// Returns false when the item should be removed. @@ -60,7 +64,10 @@ impl ItemEntity { } let horizontal = self.velocity.x * self.velocity.x + self.velocity.z * self.velocity.z; if !self.on_ground || horizontal > 1.0e-5 || (self.age + self.id) % 4 == 0 { - let mut scene = SceneCollisions { world, binding: collision }; + let mut scene = SceneCollisions { + world, + binding: collision, + }; let wanted = self.velocity; let moved = scene .resolve(self.bounds(), wanted, 0.0, self.on_ground) @@ -89,7 +96,11 @@ impl ItemEntity { ); friction = f64::from(facts.get(below).friction) * 0.98; } - self.velocity = Vec3::new(self.velocity.x * friction, self.velocity.y * 0.98, self.velocity.z * friction); + self.velocity = Vec3::new( + self.velocity.x * friction, + self.velocity.y * 0.98, + self.velocity.z * friction, + ); if self.on_ground && self.velocity.y < 0.0 { self.velocity.y *= -0.5; } @@ -116,7 +127,12 @@ pub enum ArrowHit { Player(f32), } impl Arrow { - pub fn tick(&mut self, world: &World, facts: &BlockFacts, player: Option) -> (bool, ArrowHit) { + pub fn tick( + &mut self, + world: &World, + facts: &BlockFacts, + player: Option, + ) -> (bool, ArrowHit) { self.previous = self.position; self.age += 1; if self.stuck { @@ -131,14 +147,27 @@ impl Arrow { ); if let Some(b) = player { let (min, max) = (b.min_position(), b.max_position()); - if next.x >= min.x && next.x <= max.x && next.y >= min.y && next.y <= max.y && next.z >= min.z && next.z <= max.z { - let speed = (self.velocity.x.powi(2) + self.velocity.y.powi(2) + self.velocity.z.powi(2)).sqrt(); + if next.x >= min.x + && next.x <= max.x + && next.y >= min.y + && next.y <= max.y + && next.z >= min.z + && next.z <= max.z + { + let speed = (self.velocity.x.powi(2) + + self.velocity.y.powi(2) + + self.velocity.z.powi(2)) + .sqrt(); // AbstractArrow.onHitEntity: ceil(speed * baseDamage). let damage = (speed * self.base_damage).ceil().max(0.0) as f32; return (false, ArrowHit::Player(damage)); } } - let block = world.block(next.x.floor() as i32, next.y.floor() as i32, next.z.floor() as i32); + let block = world.block( + next.x.floor() as i32, + next.y.floor() as i32, + next.z.floor() as i32, + ); if facts.get(block).full_collision { self.stuck = true; self.age = 0; @@ -146,7 +175,11 @@ impl Arrow { } self.position = next; } - self.velocity = Vec3::new(self.velocity.x * 0.99, self.velocity.y * 0.99 - 0.05, self.velocity.z * 0.99); + self.velocity = Vec3::new( + self.velocity.x * 0.99, + self.velocity.y * 0.99 - 0.05, + self.velocity.z * 0.99, + ); (self.position.y > -128.0 && self.age < 1200, ArrowHit::None) } } @@ -184,16 +217,34 @@ impl ExperienceOrb { _ => 0, } } - pub fn tick(&mut self, world: &World, facts: &BlockFacts, collision: &BlockCollisionRegistry<'_>, player: Option<[f64; 3]>) -> bool { + pub fn tick( + &mut self, + world: &World, + facts: &BlockFacts, + collision: &BlockCollisionRegistry<'_>, + player: Option<[f64; 3]>, + ) -> bool { self.previous = self.position; - let block = world.block(self.position.x.floor() as i32, self.position.y.floor() as i32, self.position.z.floor() as i32); + let block = world.block( + self.position.x.floor() as i32, + self.position.y.floor() as i32, + self.position.z.floor() as i32, + ); if facts.get(block).fluid == Fluid::Water { - self.velocity = Vec3::new(self.velocity.x * 0.99, (self.velocity.y + 5.0e-4).min(0.06), self.velocity.z * 0.99); + self.velocity = Vec3::new( + self.velocity.x * 0.99, + (self.velocity.y + 5.0e-4).min(0.06), + self.velocity.z * 0.99, + ); } else { self.velocity.y -= 0.03; } if let Some(p) = player { - let d = [(p[0] - self.position.x) / 8.0, (p[1] - self.position.y) / 8.0, (p[2] - self.position.z) / 8.0]; + let d = [ + (p[0] - self.position.x) / 8.0, + (p[1] - self.position.y) / 8.0, + (p[2] - self.position.z) / 8.0, + ]; let length = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); let power = 1.0 - length; if power > 0.0 && length > 1e-6 { @@ -208,19 +259,40 @@ impl ExperienceOrb { let h = 0.25; let bounds = Aabb::new( Vec3::new(self.position.x - h, self.position.y, self.position.z - h), - Vec3::new(self.position.x + h, self.position.y + 0.5, self.position.z + h), + Vec3::new( + self.position.x + h, + self.position.y + 0.5, + self.position.z + h, + ), ); - let mut scene = SceneCollisions { world, binding: collision }; + let mut scene = SceneCollisions { + world, + binding: collision, + }; let wanted = self.velocity; - let moved = scene.resolve(bounds, wanted, 0.0, 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 moved = scene + .resolve(bounds, wanted, 0.0, 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, + ); self.on_ground = wanted.y < 0.0 && moved.y != wanted.y; let mut friction = 0.98; if self.on_ground { - let below = world.block(self.position.x.floor() as i32, (self.position.y - 1.0).floor() as i32, self.position.z.floor() as i32); + let below = world.block( + self.position.x.floor() as i32, + (self.position.y - 1.0).floor() as i32, + self.position.z.floor() as i32, + ); friction = f64::from(facts.get(below).friction) * 0.98; } - self.velocity = Vec3::new(self.velocity.x * friction, self.velocity.y * 0.98, self.velocity.z * friction); + self.velocity = Vec3::new( + self.velocity.x * friction, + self.velocity.y * 0.98, + self.velocity.z * friction, + ); if self.on_ground { self.velocity.y *= -0.9; } diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index e023ceb19..d63f5c5cf 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -7,7 +7,10 @@ use crate::{ entities::{Arrow, ExperienceOrb, ItemEntity}, mobs::{Mob, MobType}, - save::{doubles, float, floats, item_from_nbt, item_to_nbt, number, put, read_doubles, text, uuid_from_tag}, + save::{ + doubles, float, floats, item_from_nbt, item_to_nbt, number, put, read_doubles, text, + uuid_from_tag, + }, }; use horizon_core::geometry::Vec3; use horizon_world::nbt::{Compound, Tag}; @@ -54,8 +57,14 @@ impl Base<'_> { for (key, value) in [ ("id", string(self.id)), ("UUID", Tag::IntArray(self.uuid.to_vec())), - ("Pos", doubles(&[self.position.x, self.position.y, self.position.z])), - ("Motion", doubles(&[self.motion.x, self.motion.y, self.motion.z])), + ( + "Pos", + doubles(&[self.position.x, self.position.y, self.position.z]), + ), + ( + "Motion", + doubles(&[self.motion.x, self.motion.y, self.motion.z]), + ), ("Rotation", floats(&self.rotation)), ("OnGround", Tag::Byte(i8::from(self.on_ground))), ("fall_distance", Tag::Double(self.fall_distance.to_bits())), @@ -63,7 +72,12 @@ impl Base<'_> { put(&mut tag, key, value); } if let Tag::Compound(map) = &mut tag { - for (key, value) in [("Fire", Tag::Short(-1)), ("Air", Tag::Short(300)), ("Invulnerable", Tag::Byte(0)), ("PortalCooldown", Tag::Int(0))] { + for (key, value) in [ + ("Fire", Tag::Short(-1)), + ("Air", Tag::Short(300)), + ("Invulnerable", Tag::Byte(0)), + ("PortalCooldown", Tag::Int(0)), + ] { map.entry(key.into()).or_insert(value); } } @@ -85,41 +99,72 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { let mut tag = base.tag(raw); for (key, value) in [ ("Health", Tag::Float(m.health.max(0.0).to_bits())), - ("HurtTime", Tag::Short(m.hurt_time.clamp(0, i32::from(i16::MAX)) as i16)), - ("DeathTime", Tag::Short(m.death_time.clamp(0, i32::from(i16::MAX)) as i16)), + ( + "HurtTime", + Tag::Short(m.hurt_time.clamp(0, i32::from(i16::MAX)) as i16), + ), + ( + "DeathTime", + Tag::Short(m.death_time.clamp(0, i32::from(i16::MAX)) as i16), + ), ("PersistenceRequired", Tag::Byte(i8::from(m.persistent))), ] { put(&mut tag, key, value); } - let Tag::Compound(map) = &mut tag else { return tag }; + let Tag::Compound(map) = &mut tag else { + return tag; + }; for (key, value) in [ ("AbsorptionAmount", Tag::Float(0)), ("FallFlying", Tag::Byte(0)), ("CanPickUpLoot", Tag::Byte(0)), ("LeftHanded", Tag::Byte(0)), - ("Brain", Tag::compound([("memories", Tag::Compound(Compound::new()))])), + ( + "Brain", + Tag::compound([("memories", Tag::Compound(Compound::new()))]), + ), ] { map.entry(key.into()).or_insert(value); } let id = m.kind.id.as_str(); if m.kind.category == "creature" { - for (key, value) in [("Age", Tag::Int(0)), ("ForcedAge", Tag::Int(0)), ("InLove", Tag::Int(0)), ("AgeLocked", Tag::Byte(0))] { + for (key, value) in [ + ("Age", Tag::Int(0)), + ("ForcedAge", Tag::Int(0)), + ("InLove", Tag::Int(0)), + ("AgeLocked", Tag::Byte(0)), + ] { map.entry(key.into()).or_insert(value); } } match id { "minecraft:creeper" => { - for (key, value) in [("Fuse", Tag::Short(30)), ("ExplosionRadius", Tag::Byte(3)), ("powered", Tag::Byte(0)), ("ignited", Tag::Byte(0))] { + for (key, value) in [ + ("Fuse", Tag::Short(30)), + ("ExplosionRadius", Tag::Byte(3)), + ("powered", Tag::Byte(0)), + ("ignited", Tag::Byte(0)), + ] { map.entry(key.into()).or_insert(value); } } // Skeletons are spawned holding a bow (finalizeSpawn); a mob loaded // from NBT keeps only its saved equipment. "minecraft:skeleton" | "minecraft:stray" | "minecraft:bogged" => { - map.entry("equipment".into()).or_insert_with(|| Tag::compound([("mainhand", Tag::compound([("id", string("minecraft:bow")), ("count", Tag::Int(1))]))])); + map.entry("equipment".into()).or_insert_with(|| { + Tag::compound([( + "mainhand", + Tag::compound([("id", string("minecraft:bow")), ("count", Tag::Int(1))]), + )]) + }); } "minecraft:zombie" => { - for (key, value) in [("IsBaby", Tag::Byte(0)), ("CanBreakDoors", Tag::Byte(0)), ("DrownedConversionTime", Tag::Int(-1)), ("InWaterTime", Tag::Int(-1))] { + for (key, value) in [ + ("IsBaby", Tag::Byte(0)), + ("CanBreakDoors", Tag::Byte(0)), + ("DrownedConversionTime", Tag::Int(-1)), + ("InWaterTime", Tag::Int(-1)), + ] { map.entry(key.into()).or_insert(value); } } @@ -169,7 +214,10 @@ pub fn item_entity_to_nbt(e: &ItemEntity, uuid: [i32; 4], raw: Option<&Tag>) -> for (key, value) in [ ("Item", item_to_nbt(&e.stack)), ("Age", Tag::Short(e.age.min(i16::MAX as u32) as i16)), - ("PickupDelay", Tag::Short(e.pickup_delay.min(i16::MAX as u32) as i16)), + ( + "PickupDelay", + Tag::Short(e.pickup_delay.min(i16::MAX as u32) as i16), + ), ] { put(&mut tag, key, value); } @@ -219,7 +267,9 @@ pub fn orb_to_nbt(o: &ExperienceOrb, uuid: [i32; 4]) -> Tag { } /// One Horizon orb per counted orb (vanilla merges orbs of equal value). pub fn orbs_from_nbt(tag: &Tag) -> Vec { - let Some(position) = position(tag) else { return Vec::new() }; + let Some(position) = position(tag) else { + return Vec::new(); + }; let count = number(tag.get("Count")).unwrap_or(1).clamp(1, 64) as usize; let orb = ExperienceOrb { position, @@ -236,7 +286,10 @@ pub fn orbs_from_nbt(tag: &Tag) -> Vec { pub fn arrow_to_nbt(a: &Arrow, uuid: [i32; 4], owner: Option<[i32; 4]>) -> Tag { let v = a.velocity; let horizontal = (v.x * v.x + v.z * v.z).sqrt(); - let rotation = [(v.x.atan2(v.z).to_degrees()) as f32, (v.y.atan2(horizontal).to_degrees()) as f32]; + let rotation = [ + (v.x.atan2(v.z).to_degrees()) as f32, + (v.y.atan2(horizontal).to_degrees()) as f32, + ]; let base = Base { id: "minecraft:arrow", uuid, @@ -251,14 +304,20 @@ pub fn arrow_to_nbt(a: &Arrow, uuid: [i32; 4], owner: Option<[i32; 4]>) -> Tag { ("damage", Tag::Double(a.base_damage.to_bits())), ("crit", Tag::Byte(i8::from(a.critical))), ("inGround", Tag::Byte(i8::from(a.stuck))), - ("life", Tag::Short(if a.stuck { a.age.min(1200) as i16 } else { 0 })), + ( + "life", + Tag::Short(if a.stuck { a.age.min(1200) as i16 } else { 0 }), + ), // Pickup: allowed for the player's arrows, disallowed for mobs'. ("pickup", Tag::Byte(i8::from(a.from_player))), ("shake", Tag::Byte(0)), ("PierceLevel", Tag::Byte(0)), ("HasBeenShot", Tag::Byte(1)), ("SoundEvent", string("minecraft:entity.arrow.hit")), - ("item", Tag::compound([("id", string("minecraft:arrow")), ("count", Tag::Int(1))])), + ( + "item", + Tag::compound([("id", string("minecraft:arrow")), ("count", Tag::Int(1))]), + ), ] { put(&mut tag, key, value); } @@ -271,19 +330,30 @@ pub fn arrow_from_nbt(tag: &Tag, player: Option<[i32; 4]>) -> Option { let position = position(tag)?; let stuck = flag(tag, "inGround"); Some(Arrow { - from_player: player.is_some() && uuid_from_tag(tag.get("Owner")) == player || number(tag.get("pickup")) == Some(1), + from_player: player.is_some() && uuid_from_tag(tag.get("Owner")) == player + || number(tag.get("pickup")) == Some(1), critical: flag(tag, "crit"), position, previous: position, velocity: motion(tag), stuck, - age: if stuck { number(tag.get("life")).unwrap_or(0).max(0) as u32 } else { 0 }, + age: if stuck { + number(tag.get("life")).unwrap_or(0).max(0) as u32 + } else { + 0 + }, base_damage: float(tag.get("damage")).unwrap_or(2.0), }) } /// `FallingBlockEntity`: BlockState, Time, DropItem, HurtEntities. -pub fn falling_block_to_nbt(state: Tag, position: Vec3, motion: Vec3, time: u32, uuid: [i32; 4]) -> Tag { +pub fn falling_block_to_nbt( + state: Tag, + position: Vec3, + motion: Vec3, + time: u32, + uuid: [i32; 4], +) -> Tag { let base = Base { id: "minecraft:falling_block", uuid, @@ -309,7 +379,12 @@ pub fn falling_block_to_nbt(state: Tag, position: Vec3, motion: Vec3, time: u32, } /// (block state tag, position, motion, time) pub fn falling_block_from_nbt(tag: &Tag) -> Option<(Tag, Vec3, Vec3, u32)> { - Some((tag.get("BlockState")?.clone(), position(tag)?, motion(tag), number(tag.get("Time")).unwrap_or(0).max(0) as u32)) + Some(( + tag.get("BlockState")?.clone(), + position(tag)?, + motion(tag), + number(tag.get("Time")).unwrap_or(0).max(0) as u32, + )) } #[cfg(test)] @@ -321,7 +396,12 @@ mod tests { fn item_entities_round_trip() { let e = ItemEntity { id: 7, - stack: ItemStack { item: Arc::from("minecraft:diamond_pickaxe"), count: 1, damage: 5, extra: None }, + stack: ItemStack { + item: Arc::from("minecraft:diamond_pickaxe"), + count: 1, + damage: 5, + extra: None, + }, position: Vec3::new(100.5, 64.0, -31.5), previous: Vec3::ZERO, velocity: Vec3::new(0.0, -0.04, 0.0), @@ -335,12 +415,23 @@ mod tests { assert_eq!(uuid(&tag), Some([1, 2, 3, 4])); let back = item_entity_from_nbt(&tag, 9, 0.0).unwrap(); assert_eq!(back.stack.damage, 5); - assert_eq!((back.age, back.pickup_delay, back.on_ground), (120, 10, true)); + assert_eq!( + (back.age, back.pickup_delay, back.on_ground), + (120, 10, true) + ); assert_eq!(back.position.x, 100.5); } #[test] fn unknown_fields_survive() { - let raw = Tag::compound([("id", string("minecraft:item")), ("CustomName", string("x")), ("Pos", doubles(&[0.5, 64.0, 0.5])), ("Item", Tag::compound([("id", string("minecraft:stone")), ("count", Tag::Int(3))]))]); + let raw = Tag::compound([ + ("id", string("minecraft:item")), + ("CustomName", string("x")), + ("Pos", doubles(&[0.5, 64.0, 0.5])), + ( + "Item", + Tag::compound([("id", string("minecraft:stone")), ("count", Tag::Int(3))]), + ), + ]); let e = item_entity_from_nbt(&raw, 1, 0.0).unwrap(); let tag = item_entity_to_nbt(&e, [0; 4], Some(&raw)); assert_eq!(text(tag.get("CustomName")).as_deref(), Some("x")); @@ -348,7 +439,14 @@ mod tests { } #[test] fn orbs_expand_their_count() { - let o = ExperienceOrb { position: Vec3::new(1.0, 2.0, 3.0), previous: Vec3::ZERO, velocity: Vec3::ZERO, value: 7, age: 3, on_ground: false }; + let o = ExperienceOrb { + position: Vec3::new(1.0, 2.0, 3.0), + previous: Vec3::ZERO, + velocity: Vec3::ZERO, + value: 7, + age: 3, + on_ground: false, + }; let mut tag = orb_to_nbt(&o, [0; 4]); put(&mut tag, "Count", Tag::Int(3)); let back = orbs_from_nbt(&tag); diff --git a/crates/horizon-client/src/environment.rs b/crates/horizon-client/src/environment.rs index 09f00947f..a7d87e75e 100644 --- a/crates/horizon-client/src/environment.rs +++ b/crates/horizon-client/src/environment.rs @@ -17,7 +17,8 @@ impl Easing { Self::Linear => x, Self::Constant => 0.0, Self::Bezier([x1, y1, x2, y2]) => { - let curve = |c1: f32, c2: f32| (3.0 * c1 - 3.0 * c2 + 1.0, -6.0 * c1 + 3.0 * c2, 3.0 * c1); + let curve = + |c1: f32, c2: f32| (3.0 * c1 - 3.0 * c2 + 1.0, -6.0 * c1 + 3.0 * c2, 3.0 * c1); let (ax, bx, cx) = curve(x1, x2); let (ay, by, cy) = curve(y1, y2); let sample = |(a, b, c): (f32, f32, f32), t: f32| ((a * t + b) * t + c) * t; @@ -108,7 +109,9 @@ impl Track { if t >= to_t { return to; } - let alpha = self.easing.apply((t - from_t) as f32 / (to_t - from_t) as f32); + let alpha = self + .easing + .apply((t - from_t) as f32 / (to_t - from_t) as f32); std::array::from_fn(|i| from[i] + (to[i] - from[i]) * alpha) } } @@ -156,9 +159,9 @@ impl Environment { let easing = match &track["ease"] { Value::String(s) if s == "constant" => Easing::Constant, Value::Object(o) => match o.get("cubic_bezier").and_then(Value::as_array) { - Some(a) if a.len() == 4 => Easing::Bezier(std::array::from_fn(|i| { - a[i].as_f64().unwrap_or(0.0) as f32 - })), + Some(a) if a.len() == 4 => { + Easing::Bezier(std::array::from_fn(|i| a[i].as_f64().unwrap_or(0.0) as f32)) + } _ => Easing::Linear, }, _ => Easing::Linear, @@ -189,9 +192,15 @@ impl Environment { .into_iter() .filter_map(|(k, v)| Some((k.to_owned(), parse_value(&Value::String(v.into()))?))) .collect(); - base.insert("minecraft:visual/sky_light_factor".into(), [1.0, 0.0, 0.0, 0.0]); + base.insert( + "minecraft:visual/sky_light_factor".into(), + [1.0, 0.0, 0.0, 0.0], + ); // Sky light level in light levels (the timeline multiplies it). - base.insert("minecraft:gameplay/sky_light_level".into(), [15.0, 0.0, 0.0, 0.0]); + base.insert( + "minecraft:gameplay/sky_light_level".into(), + [15.0, 0.0, 0.0, 0.0], + ); for (k, v) in dimension["attributes"].as_object().into_iter().flatten() { if let Some(v) = parse_value(v) { base.insert(k.clone(), v); @@ -233,7 +242,11 @@ impl Environment { let three = |a: [f32; 4]| [a[0], a[1], a[2]]; let scalar = |name: &str| { let b = self.base(name); - let b = if self.base.contains_key(name) { b } else { [1.0, 0.0, 0.0, 0.0] }; + let b = if self.base.contains_key(name) { + b + } else { + [1.0, 0.0, 0.0, 0.0] + }; let t = self.tracks.get(name); match t { Some(t) if t.multiply => b[0] * t.sample(ticks, self.period)[0], @@ -269,8 +282,14 @@ impl Environment { self.base("minecraft:visual/cloud_color"), ), sky_light_level: scalar("minecraft:gameplay/sky_light_level") / 15.0, - fog_start: self.base.get("minecraft:visual/fog_start_distance").map_or(0.0, |v| v[0]), - fog_end: self.base.get("minecraft:visual/fog_end_distance").map_or(1024.0, |v| v[0]), + fog_start: self + .base + .get("minecraft:visual/fog_start_distance") + .map_or(0.0, |v| v[0]), + fog_end: self + .base + .get("minecraft:visual/fog_end_distance") + .map_or(1024.0, |v| v[0]), } } } @@ -278,14 +297,32 @@ impl Environment { /// (rain counts only the part not covered by thunder). pub fn apply_weather(sky: &mut Sky, rain: f32, thunder: f32) { let grey = |c: [f32; 3]| c[0] * 0.3 + c[1] * 0.59 + c[2] * 0.11; - let lerp3 = |t: f32, a: [f32; 3], b: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| a[i] + (b[i] - a[i]) * t) }; - let lerp4 = |t: f32, a: [f32; 4], b: [f32; 4]| -> [f32; 4] { std::array::from_fn(|i| a[i] + (b[i] - a[i]) * t) }; + let lerp3 = |t: f32, a: [f32; 3], b: [f32; 3]| -> [f32; 3] { + std::array::from_fn(|i| a[i] + (b[i] - a[i]) * t) + }; + let lerp4 = |t: f32, a: [f32; 4], b: [f32; 4]| -> [f32; 4] { + std::array::from_fn(|i| a[i] + (b[i] - a[i]) * t) + }; let lerp = |t: f32, a: f32, b: f32| a + (b - a) * t; let night = [0.48, 0.48, 1.0]; // (level, sky gray (brightness, factor), fog multiplier, cloud gray, alpha, sunrise multiplier) let layers = [ - (rain - thunder, (0.6, 0.75), [0.5, 0.5, 0.6], (0.24, 0.5), 0.3125, [0.5, 0.5, 0.6]), - (thunder, (0.24, 0.94), [0.25, 0.25, 0.3], (0.095, 0.94), 0.527_343_75, [0.25, 0.25, 0.3]), + ( + rain - thunder, + (0.6, 0.75), + [0.5, 0.5, 0.6], + (0.24, 0.5), + 0.3125, + [0.5, 0.5, 0.6], + ), + ( + thunder, + (0.24, 0.94), + [0.25, 0.25, 0.3], + (0.095, 0.94), + 0.527_343_75, + [0.25, 0.25, 0.3], + ), ]; for (level, (sb, sf), fog, (cb, cf), alpha, sunrise) in layers { if level <= 0.0 { @@ -299,14 +336,35 @@ pub fn apply_weather(sky: &mut Sky, rain: f32, thunder: f32) { let cloud3 = [sky.cloud_color[0], sky.cloud_color[1], sky.cloud_color[2]]; let g = grey(cloud3) * cb; let c = lerp3(cf, cloud3, [g; 3]); - sky.cloud_color = lerp4(level, sky.cloud_color, [c[0], c[1], c[2], sky.cloud_color[3]]); + sky.cloud_color = lerp4( + level, + sky.cloud_color, + [c[0], c[1], c[2], sky.cloud_color[3]], + ); // sky_light_level is a fraction of 15 here; the layer blends towards level 4. let target_level = lerp(alpha, sky.sky_light_level * 15.0, 4.0) / 15.0; sky.sky_light_level = lerp(level, sky.sky_light_level, target_level); - sky.sky_light_color = lerp3(level, sky.sky_light_color, lerp3(alpha, sky.sky_light_color, night)); - sky.sky_light_factor = lerp(level, sky.sky_light_factor, lerp(alpha, sky.sky_light_factor, 0.24)); + sky.sky_light_color = lerp3( + level, + sky.sky_light_color, + lerp3(alpha, sky.sky_light_color, night), + ); + sky.sky_light_factor = lerp( + level, + sky.sky_light_factor, + lerp(alpha, sky.sky_light_factor, 0.24), + ); sky.star_brightness = lerp(level, sky.star_brightness, 0.0); let s = sky.sunrise_color; - sky.sunrise_color = lerp4(level, s, [s[0] * sunrise[0], s[1] * sunrise[1], s[2] * sunrise[2], s[3]]); + sky.sunrise_color = lerp4( + level, + s, + [ + s[0] * sunrise[0], + s[1] * sunrise[1], + s[2] * sunrise[2], + s[3], + ], + ); } } diff --git a/crates/horizon-client/src/font.rs b/crates/horizon-client/src/font.rs index adb693e56..80fb5491e 100644 --- a/crates/horizon-client/src/font.rs +++ b/crates/horizon-client/src/font.rs @@ -75,12 +75,19 @@ fn parse_hex_digit(b: u8) -> Option { fn parse_hex(text: &[u8], out: &mut HashMap) { for line in text.split(|b| *b == b'\n') { let line = line.strip_suffix(b"\r").unwrap_or(line); - let Some(colon) = line.iter().position(|b| *b == b':') else { continue }; + let Some(colon) = line.iter().position(|b| *b == b':') else { + continue; + }; let (code, data) = (&line[..colon], &line[colon + 1..]); if !(4..=6).contains(&code.len()) { continue; } - let Some(codepoint) = code.iter().try_fold(0u32, |a, b| parse_hex_digit(*b).map(|d| a << 4 | d)) else { continue }; + let Some(codepoint) = code + .iter() + .try_fold(0u32, |a, b| parse_hex_digit(*b).map(|d| a << 4 | d)) + else { + continue; + }; let digits_per_row = match data.len() { 32 => 2, 64 => 4, @@ -94,7 +101,10 @@ fn parse_hex(text: &[u8], out: &mut HashMap) { let mut ok = true; for (r, row) in rows.iter_mut().enumerate() { let chunk = &data[r * digits_per_row..(r + 1) * digits_per_row]; - match chunk.iter().try_fold(0u32, |a, b| parse_hex_digit(*b).map(|d| a << 4 | d)) { + match chunk + .iter() + .try_fold(0u32, |a, b| parse_hex_digit(*b).map(|d| a << 4 | d)) + { Some(v) => { *row = v << (32 - bit_width); mask |= *row; @@ -106,7 +116,11 @@ fn parse_hex(text: &[u8], out: &mut HashMap) { continue; } // LineData.calculateWidth. - let (left, right) = if mask == 0 { (0, bit_width) } else { (mask.leading_zeros(), 31 - mask.trailing_zeros()) }; + let (left, right) = if mask == 0 { + (0, bit_width) + } else { + (mask.leading_zeros(), 31 - mask.trailing_zeros()) + }; out.insert(codepoint, HexGlyph { rows, left, right }); } } @@ -123,7 +137,9 @@ fn providers(root: &Path, id: &str, depth: u32, out: &mut Vec if depth > 8 { return; } - let Some(def) = read_json(root, &resource_path(id, "font", ".json")) else { return }; + let Some(def) = read_json(root, &resource_path(id, "font", ".json")) else { + return; + }; for p in def["providers"].as_array().into_iter().flatten() { if p["type"] == "reference" { let mut nested = Vec::new(); @@ -131,7 +147,13 @@ fn providers(root: &Path, id: &str, depth: u32, out: &mut Vec for mut n in nested { // A reference's filter applies to everything it includes. if let Some(f) = p["filter"].as_object() { - let merged = n["filter"].as_object().cloned().unwrap_or_default().into_iter().chain(f.clone()).collect(); + let merged = n["filter"] + .as_object() + .cloned() + .unwrap_or_default() + .into_iter() + .chain(f.clone()) + .collect(); n["filter"] = serde_json::Value::Object(merged); } out.push(n); @@ -144,7 +166,14 @@ fn providers(root: &Path, id: &str, depth: u32, out: &mut Vec impl Font { /// Build from the atlas holding the bitmap font sheets. `pixels` is the /// RGBA atlas (for glyph widths) and `region` the reserved rows. - pub fn load(root: &Path, sprites: &HashMap, pixels: &[u8], atlas: (u32, u32), region: (u32, u32), white: Rect) -> Self { + pub fn load( + root: &Path, + sprites: &HashMap, + pixels: &[u8], + atlas: (u32, u32), + region: (u32, u32), + white: Rect, + ) -> Self { let mut bitmap = HashMap::new(); let mut space = HashMap::new(); let mut all = Vec::new(); @@ -161,9 +190,13 @@ impl Font { Some("bitmap") => { // Only non-uniform bitmap sheets exist in the default font. let file = provider["file"].as_str().unwrap_or(""); - let name = file.trim_start_matches("minecraft:").trim_end_matches(".png"); + let name = file + .trim_start_matches("minecraft:") + .trim_end_matches(".png"); let name = format!("{}", name); - let Some(rect) = sprites.get(&name).copied() else { continue }; + let Some(rect) = sprites.get(&name).copied() else { + continue; + }; let rows: Vec> = provider["chars"] .as_array() .into_iter() @@ -178,7 +211,10 @@ impl Font { let height = provider["height"].as_f64().unwrap_or(8.0) as f32; let ascent = provider["ascent"].as_f64().unwrap_or(7.0) as f32; let scale = height / cell_h as f32; - let (ax, ay) = ((rect.u0 * atlas.0 as f32).round() as u32, (rect.v0 * atlas.1 as f32).round() as u32); + let (ax, ay) = ( + (rect.u0 * atlas.0 as f32).round() as u32, + (rect.v0 * atlas.1 as f32).round() as u32, + ); for (r, row) in rows.iter().enumerate() { for (c, ch) in row.iter().enumerate() { if *ch == '\0' || bitmap.contains_key(ch) { @@ -188,7 +224,11 @@ impl Font { // BitmapProvider.getActualGlyphWidth. let mut used = 0; for x in (0..cell_w).rev() { - if (0..cell_h).any(|y| pixels.get((((cy + y) * atlas.0 + cx + x) * 4 + 3) as usize).is_some_and(|a| *a != 0)) { + if (0..cell_h).any(|y| { + pixels + .get((((cy + y) * atlas.0 + cx + x) * 4 + 3) as usize) + .is_some_and(|a| *a != 0) + }) { used = x + 1; break; } @@ -219,7 +259,15 @@ impl Font { _ => {} } } - let missing = Glyph { rect: None, left: 0.0, top: 0.0, right: 5.0, bottom: 8.0, advance: 6.0, offset: 1.0 }; + let missing = Glyph { + rect: None, + left: 0.0, + top: 0.0, + right: 5.0, + bottom: 8.0, + advance: 6.0, + offset: 1.0, + }; Self { bitmap, space, @@ -228,7 +276,12 @@ impl Font { root: root.to_owned(), atlas, region, - cache: RefCell::new(Cache { glyphs: HashMap::new(), cursor: (0, 0), pending: Vec::new(), hex: None }), + cache: RefCell::new(Cache { + glyphs: HashMap::new(), + cursor: (0, 0), + pending: Vec::new(), + hex: None, + }), uniform: false, japanese: false, } @@ -248,20 +301,37 @@ impl Font { continue; } } - let Some(file) = p["hex_file"].as_str() else { continue }; - let path = self.root.join(resource_path(file, "", "").replace("//", "/")); + let Some(file) = p["hex_file"].as_str() else { + continue; + }; + let path = self + .root + .join(resource_path(file, "", "").replace("//", "/")); let Ok(zip) = Zip::open(&path) else { continue }; let mut provider = HexProvider::default(); - let names: Vec = zip.names().filter(|n| n.ends_with(".hex")).map(str::to_owned).collect(); + let names: Vec = zip + .names() + .filter(|n| n.ends_with(".hex")) + .map(str::to_owned) + .collect(); for name in names { if let Ok(bytes) = zip.read(&name) { parse_hex(&bytes, &mut provider.glyphs); } } for o in p["size_overrides"].as_array().into_iter().flatten() { - let from = o["from"].as_str().and_then(|s| s.chars().next()).map_or(0, u32::from); - let to = o["to"].as_str().and_then(|s| s.chars().next()).map_or(0, u32::from); - let (left, right) = (o["left"].as_u64().unwrap_or(0) as u32, o["right"].as_u64().unwrap_or(15) as u32); + let from = o["from"] + .as_str() + .and_then(|s| s.chars().next()) + .map_or(0, u32::from); + let to = o["to"] + .as_str() + .and_then(|s| s.chars().next()) + .map_or(0, u32::from); + let (left, right) = ( + o["left"].as_u64().unwrap_or(0) as u32, + o["right"].as_u64().unwrap_or(15) as u32, + ); for c in from..=to { if let Some(g) = provider.glyphs.get_mut(&c) { g.left = left; @@ -283,7 +353,15 @@ impl Font { /// The glyph for a character (FontSet.getGlyph). pub fn glyph(&self, c: char) -> Glyph { if let Some(a) = self.space.get(&c) { - return Glyph { rect: None, left: 0.0, top: 0.0, right: 0.0, bottom: 0.0, advance: *a, offset: 1.0 }; + return Glyph { + rect: None, + left: 0.0, + top: 0.0, + right: 0.0, + bottom: 0.0, + advance: *a, + offset: 1.0, + }; } if !self.uniform && let Some(g) = self.bitmap.get(&c) @@ -297,7 +375,11 @@ impl Font { if cache.hex.is_none() { cache.hex = Some(self.load_hex()); } - let hex = cache.hex.as_ref().and_then(|providers| providers.iter().find_map(|p| p.glyphs.get(&u32::from(c)).copied())); + let hex = cache.hex.as_ref().and_then(|providers| { + providers + .iter() + .find_map(|p| p.glyphs.get(&u32::from(c)).copied()) + }); let glyph = match hex { Some(h) => self.rasterize(&mut cache, h).unwrap_or(self.missing), None => self.missing, @@ -323,7 +405,13 @@ impl Font { } } let (ax, ay) = (x, self.region.0 + y); - cache.pending.push(Patch { x: ax, y: ay, width, height: 16, rgba }); + cache.pending.push(Patch { + x: ax, + y: ay, + width, + height: 16, + rgba, + }); cache.cursor = (x + width + 1, y); Some(Glyph { rect: Some(Rect { @@ -358,7 +446,10 @@ impl Font { s.chars().map(|c| self.glyph(c).advance).sum::().ceil() } pub fn width_text(&self, t: &Text) -> f32 { - t.chars().map(|(c, s)| self.advance(c, s)).sum::().ceil() + t.chars() + .map(|(c, s)| self.advance(c, s)) + .sum::() + .ceil() } /// StringSplitter.splitLines: wrap at the last space that fits (or /// mid-word when none does); `\n` always breaks. Styles are kept. diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c0eef3845..f8ab56d93 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1,30 +1,30 @@ //! The playable game loop: streaming world, player simulation at 20 ticks/s, //! block interaction, inventory and HUD. mod blockctl; +mod chat; +mod commands; mod control; -mod end; -mod postprocess; -mod persist; +mod creatures; mod enchant_effects; -mod potions; -mod station_control; -mod stations; -mod trading; +mod end; mod explosion; mod growth; mod machines; -mod tnt; -mod remote; -mod chat; -mod commands; +mod music; mod options; mod packs; -mod screens; -mod creatures; +mod persist; +mod postprocess; +mod potions; +mod remote; mod render_control; mod render_tick; +mod screens; mod sign_edit; -mod music; +mod station_control; +mod stations; +mod tnt; +mod trading; use horizon_client::{ Result, assets::Assets, @@ -33,37 +33,37 @@ use horizon_client::{ blocks::{BlockFacts, Fluid}, chunk::{HEIGHT, MIN_Y}, clock::FixedStep, - entities::{Arrow, Experience, ExperienceOrb, ItemEntity}, - mobs::{Mob, MobType, MobTypes}, - particles::Particle, - containers::{BlockEntity, Providers}, - creative::{Creative, Names}, - crafting::Recipes, collisions, + containers::{BlockEntity, Providers}, + crafting::Recipes, + creative::{Creative, Names}, + entities::{Arrow, Experience, ExperienceOrb, ItemEntity}, environment::Environment, gfx::{Frame, Renderer}, hud::{HudAtlas, HudBatch, rgba}, items::{ItemStack, Items}, light::LightTables, mesher::{MeshTables, Vertex}, + mobs::{Mob, MobType, MobTypes}, models, motion::{MotionEvent, MotionResources, MotionWorld, PlayerMotion}, - sprint::Keys, - streaming::{Streaming, WorkerContext}, + particles::Particle, save::{Level, Persistent, SaveDir}, settings::Settings, - title::{Action, Title}, + sprint::Keys, + streaming::{Streaming, WorkerContext}, testgen::TestTerrain, + title::{Action, Title}, vanillagen::VanillaTerrain, world::World, }; -use horizon_core::{geometry::Vec3, random::RandomSource}; use horizon_core::{geometry::Direction, position::BlockPos}; +use horizon_core::{geometry::Vec3, random::RandomSource}; use horizon_world::{ block_collision::BlockCollisionRegistry, level::{ - Behaviours, Dimension as LevelDimension, LevelAccess, LevelEvent, Landing, PlaceContext, PlaceOutcome, PlayerContext, - PlayerEffect, Ticks, flags as level_flags, + Behaviours, Dimension as LevelDimension, Landing, LevelAccess, LevelEvent, PlaceContext, + PlaceOutcome, PlayerContext, PlayerEffect, Ticks, flags as level_flags, }, registry::BlockStateId, }; @@ -150,7 +150,9 @@ impl Options { "--no-pause" => o.no_pause = true, "--control" => o.control = Some(horizon_client::control::default_path()), _ => { - let value = args.next().ok_or_else(|| format!("missing value after {arg}"))?; + let value = args + .next() + .ok_or_else(|| format!("missing value after {arg}"))?; match arg.as_str() { "--resources" => o.resources = value.into(), "--render-distance" | "--radius" => { @@ -165,7 +167,9 @@ impl Options { // Text seeds hash like String.hashCode. value .encode_utf16() - .fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(i32::from(c))) + .fold(0i32, |h, c| { + h.wrapping_mul(31).wrapping_add(i32::from(c)) + }) .into() }) } @@ -179,7 +183,13 @@ impl Options { "--control-socket" => o.control = Some(value.into()), "--time" => o.time = Some(value.parse()?), "--weather" => o.weather = Some(value), - "--dimension" => o.dimension = Some(if value.contains(':') { value } else { format!("minecraft:{value}") }), + "--dimension" => { + o.dimension = Some(if value.contains(':') { + value + } else { + format!("minecraft:{value}") + }) + } "--look" => { let (y, p) = value.split_once(',').ok_or("--look takes YAW,PITCH")?; o.look = Some((y.parse()?, p.parse()?)); @@ -205,7 +215,12 @@ enum Screen { #[derive(Clone)] enum Icon { Flat(String), - Cube { top: String, left: String, right: String, tint: u32 }, + Cube { + top: String, + left: String, + right: String, + tint: u32, + }, } struct Mining { pos: [i32; 3], @@ -242,7 +257,12 @@ impl LevelAccess for GameLevel<'_> { fn is_raining_at(&self, pos: BlockPos) -> bool { self.behaviours.is_raining_at(self, pos) } - fn block_entity_analog_signal(&self, pos: BlockPos, _state: BlockStateId, _direction: Direction) -> i32 { + fn block_entity_analog_signal( + &self, + pos: BlockPos, + _state: BlockStateId, + _direction: Direction, + ) -> i32 { machines::container_signal(self.world, self.behaviours, self.items, self.registry, pos) } fn biome_name(&self, pos: BlockPos) -> Option<&str> { @@ -273,11 +293,19 @@ impl LevelAccess for GameLevel<'_> { self.world.loaded(pos.x, pos.z) } fn min_y(&self) -> i32 { - if self.dimension != LevelDimension::Overworld { 0 } else { MIN_Y } + if self.dimension != LevelDimension::Overworld { + 0 + } else { + MIN_Y + } } fn max_y(&self) -> i32 { // Exclusive, as LevelAccess::max_y documents. - if self.dimension != LevelDimension::Overworld { 256 } else { MIN_Y + HEIGHT } + if self.dimension != LevelDimension::Overworld { + 256 + } else { + MIN_Y + HEIGHT + } } fn random(&mut self) -> &mut horizon_core::random::LegacyRandom { &mut self.world.random @@ -305,12 +333,19 @@ impl LevelAccess for GameLevel<'_> { } /// Level.isUnobstructed against the player for full-collision blocks. fn is_unobstructed(&self, pos: BlockPos, state: BlockStateId) -> bool { - let Some((lo, hi)) = self.player_box else { return true }; + let Some((lo, hi)) = self.player_box else { + return true; + }; if !self.facts.get(state).full_collision { return true; } let (x, y, z) = (f64::from(pos.x), f64::from(pos.y), f64::from(pos.z)); - !(x < hi[0] - 1e-7 && x + 1.0 > lo[0] + 1e-7 && y < hi[1] - 1e-7 && y + 1.0 > lo[1] + 1e-7 && z < hi[2] - 1e-7 && z + 1.0 > lo[2] + 1e-7) + !(x < hi[0] - 1e-7 + && x + 1.0 > lo[0] + 1e-7 + && y < hi[1] - 1e-7 + && y + 1.0 > lo[1] + 1e-7 + && z < hi[2] - 1e-7 + && z + 1.0 > lo[2] + 1e-7) } fn emit(&mut self, event: LevelEvent) { self.events.push(event); @@ -517,7 +552,11 @@ fn view_vector(yaw: f32, pitch: f32) -> [f64; 3] { impl Game<'_> { fn eye_position(&self) -> Option<[f64; 3]> { let p = self.player.as_ref()?; - Some([p.position.x, p.position.y + f64::from(p.dimensions.eye_height), p.position.z]) + Some([ + p.position.x, + p.position.y + f64::from(p.dimensions.eye_height), + p.position.z, + ]) } fn reach(&self) -> f64 { if self.creative { 5.0 } else { 4.5 } @@ -529,11 +568,25 @@ impl Game<'_> { let reach = self.reach(); let mut pos = origin.map(|v| v.floor() as i32); let step = dir.map(|d| if d > 0.0 { 1 } else { -1 }); - let delta = dir.map(|d| if d == 0.0 { f64::INFINITY } else { (1.0 / d).abs() }); + let delta = dir.map(|d| { + if d == 0.0 { + f64::INFINITY + } else { + (1.0 / d).abs() + } + }); let mut t_max = [0.0; 3]; for i in 0..3 { - let boundary = if dir[i] > 0.0 { f64::from(pos[i]) + 1.0 } else { f64::from(pos[i]) }; - t_max[i] = if dir[i] == 0.0 { f64::INFINITY } else { (boundary - origin[i]) / dir[i] }; + let boundary = if dir[i] > 0.0 { + f64::from(pos[i]) + 1.0 + } else { + f64::from(pos[i]) + }; + t_max[i] = if dir[i] == 0.0 { + f64::INFINITY + } else { + (boundary - origin[i]) / dir[i] + }; } let mut face = [0; 3]; let mut t = 0.0; @@ -541,13 +594,23 @@ impl Game<'_> { let state = self.world.block(pos[0], pos[1], pos[2]); let f = self.res.facts.get(state); if !self.res.facts.is_air(state) - && !(f.fluid != Fluid::None && !f.waterlogged && &*f.name != "minecraft:kelp" && f.render_shape != horizon_client::blocks::RenderShape::Model) - && !matches!(&*f.name, "minecraft:water" | "minecraft:lava" | "minecraft:bubble_column") + && !(f.fluid != Fluid::None + && !f.waterlogged + && &*f.name != "minecraft:kelp" + && f.render_shape != horizon_client::blocks::RenderShape::Model) + && !matches!( + &*f.name, + "minecraft:water" | "minecraft:lava" | "minecraft:bubble_column" + ) { return Some(Hit { pos, face, - point: [origin[0] + dir[0] * t, origin[1] + dir[1] * t, origin[2] + dir[2] * t], + point: [ + origin[0] + dir[0] * t, + origin[1] + dir[1] * t, + origin[2] + dir[2] * t, + ], }); } let axis = if t_max[0] < t_max[1] { @@ -572,7 +635,9 @@ impl Game<'_> { fn give(&mut self, mut stack: ItemStack) -> Option { let max = self.res.items.get(&stack.item).map_or(64, |i| i.max_stack); // Prefer the selected slot, then the hotbar, then the main inventory. - let order: Vec = std::iter::once(self.selected).chain((0..36).filter(|&i| i != self.selected)).collect(); + let order: Vec = std::iter::once(self.selected) + .chain((0..36).filter(|&i| i != self.selected)) + .collect(); for &i in &order { if let Some(slot) = &mut self.inventory[i] && slot.same_item_same_components(&stack) @@ -589,7 +654,10 @@ impl Game<'_> { for i in 0..36 { if self.inventory[i].is_none() { let moved = stack.count.min(max); - self.inventory[i] = Some(ItemStack { count: moved, ..stack.clone() }); + self.inventory[i] = Some(ItemStack { + count: moved, + ..stack.clone() + }); stack.count -= moved; if stack.count == 0 { return None; @@ -602,13 +670,27 @@ impl Game<'_> { /// 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 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(); + 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:")))?; + 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 }; + 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(); @@ -616,13 +698,25 @@ impl Game<'_> { None } fn particle_sprite(&self, state: BlockStateId) -> Option<(String, u32)> { - let models = self.res.assets.model_catalog.collect(state, horizon_core::position::BlockPos::new(0, 0, 0)).ok()?; - let face = models.iter().flat_map(|(_, m)| m.faces.iter()).find(|f| f.quad.facing == horizon_assets::model::Direction::Up) + let models = self + .res + .assets + .model_catalog + .collect(state, horizon_core::position::BlockPos::new(0, 0, 0)) + .ok()?; + let face = models + .iter() + .flat_map(|(_, m)| m.faces.iter()) + .find(|f| f.quad.facing == horizon_assets::model::Direction::Up) .or_else(|| models.iter().flat_map(|(_, m)| m.faces.iter()).next())?; let name = self.res.layer_names.get(&face.layer)?.clone(); let tint = if face.quad.tint_index >= 0 { let n = &self.res.facts.get(state).name; - if n.contains("leaves") || n.contains("vine") { 0x48B518 } else { 0x91BD59 } + if n.contains("leaves") || n.contains("vine") { + 0x48B518 + } else { + 0x91BD59 + } } else { 0xFFFFFF }; @@ -630,14 +724,21 @@ impl Game<'_> { } /// ParticleEngine.destroy: a 4x4x4 burst. fn destroy_particles(&mut self, pos: [i32; 3], state: BlockStateId) { - let Some((sprite, tint)) = self.particle_sprite(state) else { return }; + let Some((sprite, tint)) = self.particle_sprite(state) else { + return; + }; for x in 0..4 { for y in 0..4 { for z in 0..4 { let d = |i: i32| (f64::from(i) + 0.5) / 4.0; - let p = [f64::from(pos[0]) + d(x), f64::from(pos[1]) + d(y), f64::from(pos[2]) + d(z)]; + let p = [ + f64::from(pos[0]) + d(x), + f64::from(pos[1]) + d(y), + f64::from(pos[2]) + d(z), + ]; let v = [d(x) - 0.5, d(y) - 0.5, d(z) - 0.5]; - let particle = Particle::terrain(&mut self.world.random, p, v, sprite.clone(), tint); + let particle = + Particle::terrain(&mut self.world.random, p, v, sprite.clone(), tint); self.particles.push(particle); } } @@ -645,7 +746,9 @@ impl Game<'_> { } /// ParticleEngine.crack: one crumb on the face being mined. fn crack_particle(&mut self, pos: [i32; 3], face: [i32; 3], state: BlockStateId) { - let Some((sprite, tint)) = self.particle_sprite(state) else { return }; + let Some((sprite, tint)) = self.particle_sprite(state) else { + return; + }; let r = &mut self.world.random; let mut p = [0.0; 3]; for i in 0..3 { @@ -664,7 +767,13 @@ impl Game<'_> { particle.size *= 0.6; self.particles.push(particle); } - fn spawn_item(&mut self, stack: ItemStack, position: [f64; 3], velocity: [f64; 3], pickup_delay: u32) { + fn spawn_item( + &mut self, + stack: ItemStack, + position: [f64; 3], + velocity: [f64; 3], + pickup_delay: u32, + ) { self.next_entity += 1; let p = Vec3::new(position[0], position[1], position[2]); let bob = self.world.random.next_float() * std::f32::consts::PI * 2.0; @@ -689,20 +798,34 @@ impl Game<'_> { f64::from(pos[1]) + 0.5 + offset() - 0.125, f64::from(pos[2]) + 0.5 + offset(), ]; - let v = [r.next_double() * 0.2 - 0.1, 0.2, r.next_double() * 0.2 - 0.1]; + let v = [ + r.next_double() * 0.2 - 0.1, + 0.2, + r.next_double() * 0.2 - 0.1, + ]; self.spawn_item(stack, p, v, 10); } /// Player.drop: thrown from the eyes along the view direction. fn drop_held(&mut self, all: bool) { - let Some(eye) = self.eye_position() else { return }; - let Some(stack) = self.inventory[self.selected].as_mut() else { return }; + let Some(eye) = self.eye_position() else { + return; + }; + let Some(stack) = self.inventory[self.selected].as_mut() else { + return; + }; let count = if all { stack.count } else { 1 }; - let thrown = ItemStack { count, ..stack.clone() }; + let thrown = ItemStack { + count, + ..stack.clone() + }; stack.count -= count; if stack.count == 0 { self.inventory[self.selected] = None; } - let (yaw, pitch) = (f64::from(self.yaw).to_radians(), f64::from(self.pitch).to_radians()); + let (yaw, pitch) = ( + f64::from(self.yaw).to_radians(), + f64::from(self.pitch).to_radians(), + ); let r = &mut self.world.random; let spread = f64::from(r.next_float()) * std::f64::consts::TAU; let strength = 0.02 * f64::from(r.next_float()); @@ -726,27 +849,44 @@ impl Game<'_> { } let w = f64::from(p.dimensions.width) / 2.0; let (min, max) = ( - [p.position.x - w - 1.0, p.position.y - 0.5, p.position.z - w - 1.0], - [p.position.x + w + 1.0, p.position.y + f64::from(p.dimensions.height) + 0.5, p.position.z + w + 1.0], + [ + p.position.x - w - 1.0, + p.position.y - 0.5, + p.position.z - w - 1.0, + ], + [ + p.position.x + w + 1.0, + p.position.y + f64::from(p.dimensions.height) + 0.5, + p.position.z + w + 1.0, + ], ); let feet = [p.position.x, p.position.y, p.position.z]; let mut kept = Vec::with_capacity(items.len()); for mut item in items { let b = item.bounds(); - let touching = b.min_position().x < max[0] && b.max_position().x > min[0] - && b.min_position().y < max[1] && b.max_position().y > min[1] - && b.min_position().z < max[2] && b.max_position().z > min[2]; + let touching = b.min_position().x < max[0] + && b.max_position().x > min[0] + && b.min_position().y < max[1] + && b.max_position().y > min[1] + && b.min_position().z < max[2] + && b.max_position().z > min[2]; if touching && item.pickup_delay == 0 { let before = item.stack.count; match self.give(item.stack.clone()) { None => { - let pitch = ((self.world.random.next_float() - self.world.random.next_float()) * 0.7 + 1.0) * 2.0; - self.audio.play("minecraft:entity.item.pickup", Some(feet), 0.2, pitch); + let pitch = ((self.world.random.next_float() + - self.world.random.next_float()) + * 0.7 + + 1.0) + * 2.0; + self.audio + .play("minecraft:entity.item.pickup", Some(feet), 0.2, pitch); continue; } Some(rest) => { if rest.count < before { - self.audio.play("minecraft:entity.item.pickup", Some(feet), 0.2, 1.0); + self.audio + .play("minecraft:entity.item.pickup", Some(feet), 0.2, 1.0); } item.stack = rest; } @@ -757,12 +897,22 @@ impl Game<'_> { self.dropped = kept; } /// Run vanilla block behaviour against the world through `LevelAccess`. - fn with_level(&mut self, f: impl FnOnce(&Behaviours, &mut GameLevel<'_>, &mut Ticks) -> R) -> R { + fn with_level( + &mut self, + f: impl FnOnce(&Behaviours, &mut GameLevel<'_>, &mut Ticks) -> R, + ) -> R { let darken = self.sky_darken(); let (rain, thunder) = self.world.weather.levels(1.0); let player_box = self.player.as_ref().map(|p| { let w = f64::from(p.dimensions.width) / 2.0; - ([p.position.x - w, p.position.y, p.position.z - w], [p.position.x + w, p.position.y + f64::from(p.dimensions.height), p.position.z + w]) + ( + [p.position.x - w, p.position.y, p.position.z - w], + [ + p.position.x + w, + p.position.y + f64::from(p.dimensions.height), + p.position.z + w, + ], + ) }); let dimension = match self.dim { Dim::Overworld => LevelDimension::Overworld, @@ -791,7 +941,13 @@ impl Game<'_> { /// Level.setBlock(pos, state, UPDATE_ALL) with neighbour/shape updates. fn level_set(&mut self, pos: [i32; 3], state: BlockStateId) -> Result<()> { self.with_level(|b, level, ticks| { - b.set_block(level, ticks, BlockPos::new(pos[0], pos[1], pos[2]), state, level_flags::UPDATE_ALL); + b.set_block( + level, + ticks, + BlockPos::new(pos[0], pos[1], pos[2]), + state, + level_flags::UPDATE_ALL, + ); }); self.process_level_events() } @@ -802,7 +958,8 @@ impl Game<'_> { self.register_chunk_ticks(*k); } for k in self.tick_chunks.difference(&loaded) { - self.block_ticks.remove_chunk(horizon_core::position::ChunkPos::new(k.0, k.1)); + self.block_ticks + .remove_chunk(horizon_core::position::ChunkPos::new(k.0, k.1)); } self.tick_chunks = loaded; } @@ -810,8 +967,13 @@ impl Game<'_> { /// simulation distance, block events and moving pistons. fn tick_blocks(&mut self) -> Result<()> { self.sync_tick_chunks(); - let Some(p) = self.player.as_ref() else { return Ok(()) }; - let (pcx, pcz) = ((p.position.x.floor() as i32) >> 4, (p.position.z.floor() as i32) >> 4); + let Some(p) = self.player.as_ref() else { + return Ok(()); + }; + let (pcx, pcz) = ( + (p.position.x.floor() as i32) >> 4, + (p.position.z.floor() as i32) >> 4, + ); let simulation = self.settings.render_distance.min(8); let mut ticking = Vec::new(); for (&(x, z), chunk) in &self.world.chunks { @@ -830,7 +992,12 @@ impl Game<'_> { self.with_level(|b, level, ticks| { b.tick_scheduled(level, ticks); for (x, z, sections) in ticking { - b.tick_chunk_random(level, ticks, horizon_core::position::ChunkPos::new(x, z), sections); + b.tick_chunk_random( + level, + ticks, + horizon_core::position::ChunkPos::new(x, z), + sections, + ); } b.run_block_events(level, ticks); b.tick_block_entities(level, ticks); @@ -842,17 +1009,34 @@ impl Game<'_> { let events = std::mem::take(&mut self.level_events); for event in events { match event { - LevelEvent::LevelEvent { id: 2001, pos, data } => { + LevelEvent::LevelEvent { + id: 2001, + pos, + data, + } => { // LevelRenderer: destroy particles and the block's break sound. let state = BlockStateId(data as u32); let p = [pos.x, pos.y, pos.z]; self.destroy_particles(p, state); let sounds = self.res.facts.get(state).sounds.clone(); - let c = [f64::from(pos.x) + 0.5, f64::from(pos.y) + 0.5, f64::from(pos.z) + 0.5]; - self.audio.play(&sounds.break_sound, Some(c), (sounds.volume + 1.0) / 2.0, sounds.pitch * 0.8); + let c = [ + f64::from(pos.x) + 0.5, + f64::from(pos.y) + 0.5, + f64::from(pos.z) + 0.5, + ]; + self.audio.play( + &sounds.break_sound, + Some(c), + (sounds.volume + 1.0) / 2.0, + sounds.pitch * 0.8, + ); } LevelEvent::LevelEvent { id, pos, .. } => { - let c = Some([f64::from(pos.x) + 0.5, f64::from(pos.y) + 0.5, f64::from(pos.z) + 0.5]); + let c = Some([ + f64::from(pos.x) + 0.5, + f64::from(pos.y) + 0.5, + f64::from(pos.z) + 0.5, + ]); let sound = match id { 1501 => Some(("minecraft:block.lava.extinguish", 0.5)), 1009 => Some(("minecraft:block.fire.extinguish", 0.5)), @@ -866,13 +1050,31 @@ impl Game<'_> { self.audio.play(name, c, volume, 1.0); } } - LevelEvent::Sound { pos, sound, volume, pitch } => { - let c = [f64::from(pos.x) + 0.5, f64::from(pos.y) + 0.5, f64::from(pos.z) + 0.5]; - let name = if sound.contains(':') { sound.to_string() } else { format!("minecraft:{sound}") }; + LevelEvent::Sound { + pos, + sound, + volume, + pitch, + } => { + let c = [ + f64::from(pos.x) + 0.5, + f64::from(pos.y) + 0.5, + f64::from(pos.z) + 0.5, + ]; + let name = if sound.contains(':') { + sound.to_string() + } else { + format!("minecraft:{sound}") + }; self.audio.play(&name, Some(c), volume, pitch); } LevelEvent::DropResources { pos, state } => { - let drops = self.res.items.block_drops(&self.res.assets.registry, state, None, &mut self.world.random); + let drops = self.res.items.block_drops( + &self.res.assets.registry, + state, + None, + &mut self.world.random, + ); for d in drops { if &*d.item != "minecraft:air" { self.pop_resource([pos.x, pos.y, pos.z], d); @@ -885,18 +1087,41 @@ impl Game<'_> { } } LevelEvent::FallingBlock { pos, state } => { - let p = Vec3::new(f64::from(pos.x) + 0.5, f64::from(pos.y), f64::from(pos.z) + 0.5); - self.falling.push(FallingBlock { state, position: p, previous: p, velocity: Vec3::ZERO, age: 0 }); + let p = Vec3::new( + f64::from(pos.x) + 0.5, + f64::from(pos.y), + f64::from(pos.z) + 0.5, + ); + self.falling.push(FallingBlock { + state, + position: p, + previous: p, + velocity: Vec3::ZERO, + age: 0, + }); } LevelEvent::Player { pos, effect, .. } => match effect { PlayerEffect::OpenMenu => self.open_menu([pos.x, pos.y, pos.z]), PlayerEffect::Sleep => self.try_sleep([pos.x, pos.y, pos.z]), PlayerEffect::GiveItem(item) => { - if let Some(rest) = self.give(ItemStack { item, count: 1, damage: 0, extra: None }) { + if let Some(rest) = self.give(ItemStack { + item, + count: 1, + damage: 0, + extra: None, + }) { self.pop_resource([pos.x, pos.y, pos.z], rest); } } - PlayerEffect::DropItem(item) => self.pop_resource([pos.x, pos.y + 1, pos.z], ItemStack { item, count: 1, damage: 0, extra: None }), + PlayerEffect::DropItem(item) => self.pop_resource( + [pos.x, pos.y + 1, pos.z], + ItemStack { + item, + count: 1, + damage: 0, + extra: None, + }, + ), PlayerEffect::EatCake => { if let Some(p) = self.player.as_mut() { let food = &mut p.health.food; @@ -907,33 +1132,78 @@ impl Game<'_> { PlayerEffect::InteractLoot(_) | PlayerEffect::RespawnAnchor => {} }, LevelEvent::PrimeTnt { pos } => self.spawn_primed_tnt(pos, false), - LevelEvent::BlockEvent { pos, state, kind: "dispense" } => self.dispense_from(pos, state)?, - LevelEvent::BlockEvent { pos, state, kind: "pop_block_item" } => { + LevelEvent::BlockEvent { + pos, + state, + kind: "dispense", + } => self.dispense_from(pos, state)?, + LevelEvent::BlockEvent { + pos, + state, + kind: "pop_block_item", + } => { let item = self.res.facts.get(state).item.clone(); - self.pop_resource([pos.x, pos.y, pos.z], ItemStack { item, count: 1, damage: 0, extra: None }); + self.pop_resource( + [pos.x, pos.y, pos.z], + ItemStack { + item, + count: 1, + damage: 0, + extra: None, + }, + ); } - LevelEvent::GrowTree { .. } | LevelEvent::PlaceFeature { .. } | LevelEvent::BlockEvent { .. } | LevelEvent::GameEvent { .. } => {} + LevelEvent::GrowTree { .. } + | LevelEvent::PlaceFeature { .. } + | LevelEvent::BlockEvent { .. } + | LevelEvent::GameEvent { .. } => {} } } Ok(()) } /// Menus opened by PlayerEffect::OpenMenu. fn open_menu(&mut self, pos: [i32; 3]) { - let name = self.res.facts.get(self.world.block(pos[0], pos[1], pos[2])).name.clone(); + let name = self + .res + .facts + .get(self.world.block(pos[0], pos[1], pos[2])) + .name + .clone(); let key = (pos[0], pos[1], pos[2]); if &*name == "minecraft:crafting_table" { self.craft_size = 3; } else if let Some(entity) = BlockEntity::for_block(&name) { self.world.block_entities.entry(key).or_insert(entity); self.container = Some(key); - let sound = if name.contains("chest") { Some("minecraft:block.chest.open") } else if &*name == "minecraft:barrel" { Some("minecraft:block.barrel.open") } else { None }; + let sound = if name.contains("chest") { + Some("minecraft:block.chest.open") + } else if &*name == "minecraft:barrel" { + Some("minecraft:block.barrel.open") + } else { + None + }; if let Some(sound) = sound { - self.audio.play(sound, Some([f64::from(key.0) + 0.5, f64::from(key.1) + 0.5, f64::from(key.2) + 0.5]), 0.5, 1.0); + self.audio.play( + sound, + Some([ + f64::from(key.0) + 0.5, + f64::from(key.1) + 0.5, + f64::from(key.2) + 0.5, + ]), + 0.5, + 1.0, + ); } } else if self.open_station(pos, &name) { // Workstation menus: game/stations.rs. } else { - self.message = Some((format!("{} is not available yet", name.trim_start_matches("minecraft:").replace('_', " ")), Instant::now())); + self.message = Some(( + format!( + "{} is not available yet", + name.trim_start_matches("minecraft:").replace('_', " ") + ), + Instant::now(), + )); return; } self.screen = Screen::Inventory; @@ -948,24 +1218,59 @@ impl Game<'_> { f.previous = f.position; f.age += 1; f.velocity.y -= 0.04; - let next = Vec3::new(f.position.x + f.velocity.x, f.position.y + f.velocity.y, f.position.z + f.velocity.z); - let below = self.world.block(next.x.floor() as i32, next.y.floor() as i32, next.z.floor() as i32); + let next = Vec3::new( + f.position.x + f.velocity.x, + f.position.y + f.velocity.y, + f.position.z + f.velocity.z, + ); + let below = self.world.block( + next.x.floor() as i32, + next.y.floor() as i32, + next.z.floor() as i32, + ); let solid = self.res.facts.get(below).full_collision; if solid || f.age > 600 { - landed.push((f.state, [next.x.floor() as i32, next.y.floor() as i32 + 1, next.z.floor() as i32])); + landed.push(( + f.state, + [ + next.x.floor() as i32, + next.y.floor() as i32 + 1, + next.z.floor() as i32, + ], + )); return false; } f.position = next; - f.velocity = Vec3::new(f.velocity.x * 0.98, f.velocity.y * 0.98, f.velocity.z * 0.98); + f.velocity = Vec3::new( + f.velocity.x * 0.98, + f.velocity.y * 0.98, + f.velocity.z * 0.98, + ); true }); self.falling = falling; for (state, pos) in landed { - let landing = self.with_level(|b, level, ticks| b.falling_block_landed(level, ticks, BlockPos::new(pos[0], pos[1], pos[2]), state, false)); + let landing = self.with_level(|b, level, ticks| { + b.falling_block_landed( + level, + ticks, + BlockPos::new(pos[0], pos[1], pos[2]), + state, + false, + ) + }); if matches!(landing, Landing::Broken) { let item = self.res.facts.get(state).item.clone(); if &*item != "minecraft:air" { - self.pop_resource(pos, ItemStack { item, count: 1, damage: 0, extra: None }); + self.pop_resource( + pos, + ItemStack { + item, + count: 1, + damage: 0, + extra: None, + }, + ); } } } @@ -988,21 +1293,39 @@ impl Game<'_> { held.as_ref(), &mut self.world.random, ); - let silk = held.as_ref().is_some_and(|h| h.enchantment_level("minecraft:silk_touch") > 0); + let silk = held + .as_ref() + .is_some_and(|h| h.enchantment_level("minecraft:silk_touch") > 0); for d in drops { if &*d.item != "minecraft:air" { self.pop_resource(pos, d); } } - let xp = if silk { 0 } else { self.block_experience(&facts.name) }; + let xp = if silk { + 0 + } else { + self.block_experience(&facts.name) + }; if xp > 0 { - self.spawn_orbs([f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, f64::from(pos[2]) + 0.5], xp); + self.spawn_orbs( + [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ], + xp, + ); } } // Tools lose durability on blocks with nonzero hardness. if facts.hardness > 0.0 && let Some(stack) = self.inventory[self.selected].clone() - && let Some(max) = self.res.items.get(&stack.item).filter(|i| i.max_damage > 0 && !i.tool.is_empty()).map(|i| i.max_damage) + && let Some(max) = self + .res + .items + .get(&stack.item) + .filter(|i| i.max_damage > 0 && !i.tool.is_empty()) + .map(|i| i.max_damage) { let loss = self.durability_loss(&stack, 1); if let Some(stack) = self.inventory[self.selected].as_mut() { @@ -1034,7 +1357,12 @@ impl Game<'_> { // neighbour and shape updates, and the destroy event (particles, sound). let creative = self.creative; self.with_level(|b, level, ticks| { - b.player_destroy_block(level, ticks, BlockPos::new(pos[0], pos[1], pos[2]), creative); + b.player_destroy_block( + level, + ticks, + BlockPos::new(pos[0], pos[1], pos[2]), + creative, + ); }); self.process_level_events()?; Ok(()) @@ -1060,19 +1388,36 @@ impl Game<'_> { yaw: self.yaw, pitch: self.pitch, may_build: true, - can_eat: self.creative || self.player.as_ref().is_some_and(|p| p.health.food.food < 20), + can_eat: self.creative + || self + .player + .as_ref() + .is_some_and(|p| p.health.food.food < 20), game_master: false, }; let at = Vec3::new(hit.point[0], hit.point[1], hit.point[2]); - let result = self.with_level(|b, level, ticks| b.use_without_item(level, ticks, BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]), face, at, player)); + let result = self.with_level(|b, level, ticks| { + b.use_without_item( + level, + ticks, + BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]), + face, + at, + player, + ) + }); self.process_level_events()?; if result.consumes_action() { self.swing_arm(); return Ok(()); } } - let Some(stack) = self.held().cloned() else { return Ok(()) }; - let Some(info) = self.res.items.get(&stack.item).cloned() else { return Ok(()) }; + let Some(stack) = self.held().cloned() else { + return Ok(()); + }; + let Some(info) = self.res.items.get(&stack.item).cloned() else { + return Ok(()); + }; if self.use_potion_item(&stack)? || self.throw_item(&stack)? { return Ok(()); } @@ -1101,7 +1446,9 @@ impl Game<'_> { if self.use_ender_eye(&stack)? { return Ok(()); } - let Some(hit) = self.pick() else { return Ok(()) }; + let Some(hit) = self.pick() else { + return Ok(()); + }; if info.block.is_none() { return Ok(()); } @@ -1133,15 +1480,26 @@ impl Game<'_> { let target = [pos.x, pos.y, pos.z]; if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) { let sign = matches!(entity, BlockEntity::Sign(_)); - self.world.block_entities.insert((target[0], target[1], target[2]), entity); + self.world + .block_entities + .insert((target[0], target[1], target[2]), entity); if sign { self.open_sign_editor((target[0], target[1], target[2]), true); } } self.swing_arm(); let sounds = self.res.facts.get(state).sounds.clone(); - let center = [f64::from(target[0]) + 0.5, f64::from(target[1]) + 0.5, f64::from(target[2]) + 0.5]; - self.audio.play(&sounds.place, Some(center), (sounds.volume + 1.0) / 2.0, sounds.pitch * 0.8); + let center = [ + f64::from(target[0]) + 0.5, + f64::from(target[1]) + 0.5, + f64::from(target[2]) + 0.5, + ]; + self.audio.play( + &sounds.place, + Some(center), + (sounds.volume + 1.0) / 2.0, + sounds.pitch * 0.8, + ); self.process_level_events()?; self.consume_held(); Ok(()) @@ -1158,7 +1516,9 @@ impl Game<'_> { } } fn tick_using(&mut self) { - let Some((slot, ticks)) = self.using else { return }; + let Some((slot, ticks)) = self.using else { + return; + }; let Some(stack) = self.inventory[slot].clone() else { self.using = None; return; @@ -1187,14 +1547,32 @@ impl Game<'_> { let eye = self.eye_position().unwrap_or_default(); // Consumable.shouldEmitParticlesAndSounds: every 4 ticks in the last 25. if remaining <= 25 && remaining % 4 == 0 { - let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 1.0; - self.audio.play("minecraft:entity.generic.eat", Some(eye), 0.5 + 0.5 * self.world.random.next_int_bound(2).unwrap_or(0) as f32, pitch); + let pitch = + (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 1.0; + self.audio.play( + "minecraft:entity.generic.eat", + Some(eye), + 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) { - let (yaw, pitch) = (f64::from(self.yaw).to_radians(), f64::from(self.pitch).to_radians()); - let at = [eye[0] - yaw.sin() * pitch.cos() * 0.3, eye[1] - 0.1, eye[2] + yaw.cos() * pitch.cos() * 0.3]; + let (yaw, pitch) = ( + f64::from(self.yaw).to_radians(), + f64::from(self.pitch).to_radians(), + ); + let at = [ + eye[0] - yaw.sin() * pitch.cos() * 0.3, + eye[1] - 0.1, + eye[2] + yaw.cos() * pitch.cos() * 0.3, + ]; for _ in 0..5 { - let v = [(f64::from(self.world.random.next_float()) - 0.5) * 0.1, 0.1, (f64::from(self.world.random.next_float()) - 0.5) * 0.1]; - let p = Particle::terrain(&mut self.world.random, at, v, sprite.clone(), 0xFFFFFF); + let v = [ + (f64::from(self.world.random.next_float()) - 0.5) * 0.1, + 0.1, + (f64::from(self.world.random.next_float()) - 0.5) * 0.1, + ]; + let p = + Particle::terrain(&mut self.world.random, at, v, sprite.clone(), 0xFFFFFF); self.particles.push(p); } } @@ -1208,7 +1586,12 @@ impl Game<'_> { let food = &mut p.health.food; food.food = (food.food + nutrition as i32).clamp(0, 20); food.saturation = (food.saturation + saturation).clamp(0.0, food.food as f32); - self.audio.play("minecraft:entity.player.burp", Some(eye), 0.5, self.world.random.next_float() * 0.1 + 0.9); + self.audio.play( + "minecraft:entity.player.burp", + Some(eye), + 0.5, + self.world.random.next_float() * 0.1 + 0.9, + ); self.consume_held(); } } else { @@ -1238,7 +1621,11 @@ impl Game<'_> { return Ok(()); } if self.mining.as_ref().is_none_or(|m| m.pos != hit.pos) { - self.mining = Some(Mining { pos: hit.pos, progress: 0.0, ticks: 0 }); + self.mining = Some(Mining { + pos: hit.pos, + progress: 0.0, + ticks: 0, + }); } let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); let facts = self.res.facts.get(state); @@ -1254,7 +1641,17 @@ impl Game<'_> { speed /= 5.0; } let eye = self.eye_position().unwrap_or_default(); - if self.res.facts.get(self.world.block(eye[0].floor() as i32, eye[1].floor() as i32, eye[2].floor() as i32)).fluid == Fluid::Water { + if self + .res + .facts + .get(self.world.block( + eye[0].floor() as i32, + eye[1].floor() as i32, + eye[2].floor() as i32, + )) + .fluid + == Fluid::Water + { speed *= self.submerged_mining_speed(); } let harvest = !facts.requires_tool || self.res.items.correct_for_drops(held, &facts.name); @@ -1270,8 +1667,17 @@ impl Game<'_> { m.ticks += 1; let crack = (m.pos, hit.face); if m.ticks % 4 == 1 { - let c = [f64::from(m.pos[0]) + 0.5, f64::from(m.pos[1]) + 0.5, f64::from(m.pos[2]) + 0.5]; - self.audio.play(&hit_sound.hit, Some(c), (hit_sound.volume + 1.0) / 8.0, hit_sound.pitch * 0.5); + let c = [ + f64::from(m.pos[0]) + 0.5, + f64::from(m.pos[1]) + 0.5, + f64::from(m.pos[2]) + 0.5, + ]; + self.audio.play( + &hit_sound.hit, + Some(c), + (hit_sound.volume + 1.0) / 8.0, + hit_sound.pitch * 0.5, + ); } self.crack_particle(crack.0, crack.1, state); let m = self.mining.as_mut().ok_or("mining")?; @@ -1314,7 +1720,8 @@ impl Game<'_> { // Below the bedrock ceiling: a solid floor with two air blocks above. for y in (32..120).rev() { let floor = self.res.facts.get(self.world.block(x, y - 1, z)); - if floor.full_collision && floor.fluid == Fluid::None + if floor.full_collision + && floor.fluid == Fluid::None && self.res.facts.is_air(self.world.block(x, y, z)) && self.res.facts.is_air(self.world.block(x, y + 1, z)) { @@ -1328,7 +1735,10 @@ impl Game<'_> { let s = self.world.block(x, y, z); if !self.res.facts.is_air(s) { let f = self.res.facts.get(s); - let ok = f.full_collision && f.fluid == Fluid::None && !f.name.contains("leaves") && f.hardness >= 0.0; + let ok = f.full_collision + && f.fluid == Fluid::None + && !f.name.contains("leaves") + && f.hardness >= 0.0; return ok.then_some(y + 1); } y -= 1; @@ -1340,7 +1750,10 @@ impl Game<'_> { return Ok(()); } if let Some((_, target)) = &self.travelling { - let (cx, cz) = ((target.x.floor() as i32) >> 4, (target.z.floor() as i32) >> 4); + let (cx, cz) = ( + (target.x.floor() as i32) >> 4, + (target.z.floor() as i32) >> 4, + ); self.streaming.center = (cx, cz); if (-2..=2).all(|dz| (-2..=2).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) { let (player, target) = self.travelling.take().ok_or("travel")?; @@ -1354,7 +1767,10 @@ impl Game<'_> { } let saved = self.level.position.map(|p| Vec3::new(p[0], p[1], p[2])); if self.spawn.is_none() { - self.spawn = self.level.spawn.map(|s| Vec3::new(s[0] + 0.5, s[1], s[2] + 0.5)); + self.spawn = self + .level + .spawn + .map(|s| Vec3::new(s[0] + 0.5, s[1], s[2] + 0.5)); } let anchor = match saved.or(self.spawn) { Some(p) => (p.x.floor() as i32, p.z.floor() as i32), @@ -1370,7 +1786,9 @@ impl Game<'_> { p } else if let Some(s) = self.spawn { // WorldSpawn: the stored column, lifted onto its current surface. - let y = self.land_column(s.x.floor() as i32, s.z.floor() as i32).map_or(s.y, f64::from); + let y = self + .land_column(s.x.floor() as i32, s.z.floor() as i32) + .map_or(s.y, f64::from); Vec3::new(s.x, y.max(s.y), s.z) } else { let mut best: Option<(i64, i32, i32, i32)> = None; @@ -1429,9 +1847,14 @@ impl Game<'_> { if self.use_delay > 0 { self.use_delay -= 1; } - let Some(player) = self.player.as_mut() else { return Ok(()) }; + let Some(player) = self.player.as_mut() else { + return Ok(()); + }; // Hold position until the surrounding terrain exists. - let (cx, cz) = ((player.position.x.floor() as i32) >> 4, (player.position.z.floor() as i32) >> 4); + let (cx, cz) = ( + (player.position.x.floor() as i32) >> 4, + (player.position.z.floor() as i32) >> 4, + ); if !self.streaming.is_lit(cx, cz) { return Ok(()); } @@ -1463,44 +1886,74 @@ impl Game<'_> { let crouching = player.pose == horizon_client::pose::Pose::Crouching; for event in events { match event { - MotionEvent::Emission { position, state, .. } if !crouching => { + MotionEvent::Emission { + position, state, .. + } if !crouching => { // Entity.playStepSound: the block's step sound at 0.15 volume. let sounds = self.res.facts.get(state).sounds.clone(); - self.audio.play(&sounds.step, Some(feet), sounds.volume * 0.15, sounds.pitch); + self.audio + .play(&sounds.step, Some(feet), sounds.volume * 0.15, sounds.pitch); let _ = position; } - MotionEvent::Fall(horizon_client::landing::FallEvent::Sound { sound, volume, pitch, .. }) => { + MotionEvent::Fall(horizon_client::landing::FallEvent::Sound { + sound, + volume, + pitch, + .. + }) => { let name = match sound { - horizon_client::landing::SceneSound::BigFall => "minecraft:entity.player.big_fall", - horizon_client::landing::SceneSound::SmallFall => "minecraft:entity.player.small_fall", + horizon_client::landing::SceneSound::BigFall => { + "minecraft:entity.player.big_fall" + } + horizon_client::landing::SceneSound::SmallFall => { + "minecraft:entity.player.small_fall" + } _ => continue, }; self.audio.play(name, Some(feet), volume, pitch); } - MotionEvent::Fall(horizon_client::landing::FallEvent::Write { position, flags, .. }) => { + MotionEvent::Fall(horizon_client::landing::FallEvent::Write { + position, + flags, + .. + }) => { // Landing rules (farmland trampling, turtle eggs) wrote the block raw. - self.with_level(|b, level, ticks| b.notify_written(level, ticks, position, flags as i32)); + self.with_level(|b, level, ticks| { + b.notify_written(level, ticks, position, flags as i32) + }); } - MotionEvent::Fall(horizon_client::landing::FallEvent::Destroy { position, .. }) => { - self.with_level(|b, level, ticks| b.notify_written(level, ticks, position, level_flags::UPDATE_ALL)); + MotionEvent::Fall(horizon_client::landing::FallEvent::Destroy { + position, .. + }) => { + self.with_level(|b, level, ticks| { + b.notify_written(level, ticks, position, level_flags::UPDATE_ALL) + }); } MotionEvent::Fall(horizon_client::landing::FallEvent::Damage { .. }) => { - self.audio.play("minecraft:entity.player.hurt", Some(feet), 1.0, 1.0); + self.audio + .play("minecraft:entity.player.hurt", Some(feet), 1.0, 1.0); } _ => {} } } - let Some(player) = self.player.as_mut() else { return Ok(()) }; + let Some(player) = self.player.as_mut() else { + return Ok(()); + }; if player.position.y < f64::from(MIN_Y - 64) { // Out of the world. let _ = player.set_health(0.0, false); } if player.health.dead_or_dying() && self.screen != Screen::Dead { // Inventory.dropAll: every stack thrown in a random direction. - let at = [player.position.x, player.position.y + 1.32, player.position.z]; + let at = [ + player.position.x, + player.position.y + 1.32, + player.position.z, + ]; self.death_message(); if !self.creative && !self.ui.rules.bool("keep_inventory") { - let stacks: Vec = self.inventory.iter_mut().filter_map(Option::take).collect(); + let stacks: Vec = + self.inventory.iter_mut().filter_map(Option::take).collect(); for stack in stacks { let r = &mut self.world.random; let strength = f64::from(r.next_float()) * 0.5; @@ -1509,7 +1962,8 @@ impl Game<'_> { self.spawn_item(stack, at, v, 40); } } - self.audio.play("minecraft:entity.player.death", Some(at), 1.0, 1.0); + self.audio + .play("minecraft:entity.player.death", Some(at), 1.0, 1.0); self.screen = Screen::Dead; self.capture(false); } @@ -1531,18 +1985,31 @@ impl Game<'_> { 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 (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 }; + 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; } self.tick_block_entities()?; self.tick_brewing_stands()?; if let Some(r) = &self.renderer { - let eye = self.player.as_ref().map(|p| [p.position.x, p.position.y + f64::from(self.eye), p.position.z]); + let eye = self.player.as_ref().map(|p| { + [ + p.position.x, + p.position.y + f64::from(self.eye), + p.position.z, + ] + }); self.res.block_entity_render.tick(r.block_entities(), eye); } self.tick_particles(); @@ -1577,7 +2044,9 @@ impl Game<'_> { 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 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()?, ) @@ -1589,7 +2058,9 @@ impl Game<'_> { 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); } - for key in ["model", "fallback", "on_false", "on_true", "cases", "entries", "tints"] { + 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); } @@ -1602,15 +2073,28 @@ impl Game<'_> { } 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 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 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 { @@ -1618,30 +2102,56 @@ impl Game<'_> { } } match m["parent"].as_str() { - Some(p) if p.ends_with("item/generated") || p.ends_with("item/handheld") || p.contains("handheld") => { + 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())); + 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}")) + 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 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)); + 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 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 } + if name.contains("leaves") || name == "vine" { + 0x48B518 + } else { + 0x91BD59 + } } else { 0xFFFFFF }; @@ -1664,7 +2174,12 @@ impl Game<'_> { let atlas = &self.res.atlas; match icon { Some(Icon::Flat(name)) => batch.sprite_scaled(atlas, &name, x, y, 16.0, 16.0, u32::MAX), - Some(Icon::Cube { top, left, right, tint }) => { + 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) @@ -1672,14 +2187,48 @@ impl Game<'_> { 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); + 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)); + 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)); + 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)), } @@ -1697,7 +2246,10 @@ impl Game<'_> { let f = 1.0 - stack.damage as f32 / info.max_damage as f32; let width = (13.0 * f).round(); let hue = f / 3.0; - let (r, g) = ((255.0 * (1.0 - hue * 3.0).clamp(0.0, 1.0)) as u8, (255.0 * (hue * 3.0).clamp(0.0, 1.0)) as u8); + let (r, g) = ( + (255.0 * (1.0 - hue * 3.0).clamp(0.0, 1.0)) as u8, + (255.0 * (hue * 3.0).clamp(0.0, 1.0)) as u8, + ); batch.fill(atlas, x + 2.0, y + 13.0, 13.0, 2.0, rgba(0, 0, 0, 255)); batch.fill(atlas, x + 2.0, y + 13.0, width, 1.0, rgba(r, g, 0, 255)); } @@ -1719,7 +2271,11 @@ impl Game<'_> { return batch; } if self.player.is_none() { - let text = if self.spawn_search > 0 { "Finding a place to spawn..." } else { "Loading terrain..." }; + let text = if self.spawn_search > 0 { + "Finding a place to spawn..." + } else { + "Loading terrain..." + }; let atlas = &self.res.atlas; let tw = HudBatch::text_width(atlas, text); batch.fill(atlas, 0.0, 0.0, w, h, rgba(20, 20, 20, 255)); @@ -1729,14 +2285,29 @@ impl Game<'_> { { let atlas = &self.res.atlas; // Crosshair. - batch.sprite(atlas, "gui/sprites/hud/crosshair", (w - 15.0) / 2.0, (h - 15.0) / 2.0); + batch.sprite( + atlas, + "gui/sprites/hud/crosshair", + (w - 15.0) / 2.0, + (h - 15.0) / 2.0, + ); // Hotbar. 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); + batch.sprite( + atlas, + "gui/sprites/hud/hotbar_selection", + w / 2.0 - 91.0 - 1.0 + self.selected as f32 * 20.0, + h - 23.0, + ); } for i in 0..9 { if let Some(stack) = self.inventory[i].clone() { - self.draw_item(&mut batch, &stack, w / 2.0 - 90.0 + i as f32 * 20.0 + 2.0, h - 19.0); + self.draw_item( + &mut batch, + &stack, + w / 2.0 - 90.0 + i as f32 * 20.0 + 2.0, + h - 19.0, + ); } } self.draw_effect_icons(&mut batch); @@ -1745,10 +2316,21 @@ impl Game<'_> { && let Some(p) = &self.player { // Experience bar and hearts/food (Gui.renderPlayerHealth). - batch.sprite(atlas, "gui/sprites/hud/experience_bar_background", w / 2.0 - 91.0, h - 29.0); + 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)); + 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. @@ -1764,7 +2346,11 @@ impl Game<'_> { let top = h - 39.0; for i in 0..10 { let x = w / 2.0 - 91.0 + i as f32 * 8.0; - let y = if health <= 4 { top + ((self.ticks + i as u64 * 7) % 3) as f32 - 1.0 } else { top }; + let y = if health <= 4 { + top + ((self.ticks + i as u64 * 7) % 3) as f32 - 1.0 + } else { + top + }; batch.sprite(atlas, "gui/sprites/hud/heart/container", x, y); let v = health - i * 2; if v >= 2 { @@ -1786,13 +2372,23 @@ impl Game<'_> { } } if self.debug { - let p = self.player.as_ref().map(|p| p.position).unwrap_or(Vec3::ZERO); + let p = self + .player + .as_ref() + .map(|p| p.position) + .unwrap_or(Vec3::ZERO); let block = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; let biome = self .world .chunks .get(&(block[0] >> 4, block[2] >> 4)) - .map(|c| self.res.biomes.get(c.biome(block[0], block[1], block[2])).name.clone()) + .map(|c| { + self.res + .biomes + .get(c.biome(block[0], block[1], block[2])) + .name + .clone() + }) .unwrap_or_default(); let light = self.world.light(block[0], block[1], block[2]); let facing = match ((self.yaw.rem_euclid(360.0) + 45.0) / 90.0) as i32 % 4 { @@ -1803,24 +2399,69 @@ impl Game<'_> { }; let lines = [ format!("Horizon 26.3 (Rust) {:.0} fps", self.fps), - format!("C: {} chunks, {} sections drawn / {}", self.world.chunks.len(), self.renderer.as_ref().map_or(0, |r| r.drawn_sections), self.renderer.as_ref().map_or(0, |r| r.section_count())), + format!( + "C: {} chunks, {} sections drawn / {}", + self.world.chunks.len(), + self.renderer.as_ref().map_or(0, |r| r.drawn_sections), + self.renderer.as_ref().map_or(0, |r| r.section_count()) + ), format!("Pending jobs: {}", self.streaming.pending()), String::new(), format!("XYZ: {:.3} / {:.5} / {:.3}", p.x, p.y, p.z), format!("Block: {} {} {}", block[0], block[1], block[2]), - format!("Chunk: {} {} {} in {} {} {}", block[0] & 15, block[1] & 15, block[2] & 15, block[0] >> 4, block[1] >> 4, block[2] >> 4), - format!("Facing: {facing} ({:.1} / {:.1})", self.yaw.rem_euclid(360.0) - if self.yaw.rem_euclid(360.0) > 180.0 { 360.0 } else { 0.0 }, self.pitch), - format!("Light: {} (sky {}, block {})", (light >> 4).max(light & 15), light >> 4, light & 15), + format!( + "Chunk: {} {} {} in {} {} {}", + block[0] & 15, + block[1] & 15, + block[2] & 15, + block[0] >> 4, + block[1] >> 4, + block[2] >> 4 + ), + format!( + "Facing: {facing} ({:.1} / {:.1})", + self.yaw.rem_euclid(360.0) + - if self.yaw.rem_euclid(360.0) > 180.0 { + 360.0 + } else { + 0.0 + }, + self.pitch + ), + format!( + "Light: {} (sky {}, block {})", + (light >> 4).max(light & 15), + light >> 4, + light & 15 + ), format!("Biome: {biome}"), - format!("Day {} time {}", self.world.day_time / 24000, self.world.day_time % 24000), + format!( + "Day {} time {}", + self.world.day_time / 24000, + self.world.day_time % 24000 + ), ]; for (i, line) in lines.iter().enumerate() { if line.is_empty() { continue; } let tw = HudBatch::text_width(atlas, line); - batch.fill(atlas, 1.0, 2.0 + i as f32 * 9.0 - 1.0, tw + 2.0, 9.0, rgba(80, 80, 80, 144)); - batch.text(atlas, line, 2.0, 2.0 + i as f32 * 9.0, rgba(224, 224, 224, 255), false); + batch.fill( + atlas, + 1.0, + 2.0 + i as f32 * 9.0 - 1.0, + tw + 2.0, + 9.0, + rgba(80, 80, 80, 144), + ); + batch.text( + atlas, + line, + 2.0, + 2.0 + i as f32 * 9.0, + rgba(224, 224, 224, 255), + false, + ); } } if let Some((text, at)) = &self.message @@ -1853,11 +2494,15 @@ impl Game<'_> { batch } fn inventory_origin(&self, batch: &HudBatch) -> (f32, f32) { - ((batch.width - 176.0) / 2.0, (batch.height - self.screen_height()) / 2.0) + ( + (batch.width - 176.0) / 2.0, + (batch.height - self.screen_height()) / 2.0, + ) } /// Slot ids: 0..36 player inventory, 100..109 crafting grid, 200 result. fn container_kind(&self) -> Option<&BlockEntity> { - self.container.and_then(|k| self.world.block_entities.get(&k)) + self.container + .and_then(|k| self.world.block_entities.get(&k)) } /// 300.. are the open container's slots. fn slots(&self) -> Vec { @@ -1882,21 +2527,42 @@ impl Game<'_> { } /// InventoryMenu / CraftingMenu slot layouts. fn slot_position(&self, i: usize) -> (f32, f32) { - if let Some(p) = self.station_slot_position(i).or_else(|| self.machine_slot_position(i)) { + if let Some(p) = self + .station_slot_position(i) + .or_else(|| self.machine_slot_position(i)) + { return p; } let table = self.craft_size == 3; // ContainerScreen (3 rows) shifts the player inventory down by one pixel. - let shift = if matches!(self.container_kind(), Some(BlockEntity::Chest(_))) { 1.0 } else { 0.0 }; + let shift = if matches!(self.container_kind(), Some(BlockEntity::Chest(_))) { + 1.0 + } else { + 0.0 + }; match i { 0..9 => (8.0 + i as f32 * 18.0, 142.0 + shift), - 9..36 => (8.0 + ((i - 9) % 9) as f32 * 18.0, 84.0 + shift + ((i - 9) / 9) as f32 * 18.0), + 9..36 => ( + 8.0 + ((i - 9) % 9) as f32 * 18.0, + 84.0 + shift + ((i - 9) / 9) as f32 * 18.0, + ), 500..504 => (8.0, 8.0 + (i - 500) as f32 * 18.0), 300..500 => match self.container_kind() { - Some(BlockEntity::Furnace(_)) => [(56.0, 17.0), (56.0, 53.0), (116.0, 35.0)][(i - 300).min(2)], - _ => (8.0 + ((i - 300) % 9) as f32 * 18.0, 18.0 + ((i - 300) / 9) as f32 * 18.0), + Some(BlockEntity::Furnace(_)) => { + [(56.0, 17.0), (56.0, 53.0), (116.0, 35.0)][(i - 300).min(2)] + } + _ => ( + 8.0 + ((i - 300) % 9) as f32 * 18.0, + 18.0 + ((i - 300) / 9) as f32 * 18.0, + ), }, - 200 => if table { (124.0, 35.0) } else { (154.0, 28.0) }, + 200 => { + if table { + (124.0, 35.0) + } else { + (154.0, 28.0) + } + } _ => { let g = i - 100; let (r, c) = (g / self.craft_size, g % self.craft_size); @@ -1925,7 +2591,10 @@ impl Game<'_> { if i >= 300 { let key = self.container; return match key.and_then(|k| self.world.block_entities.get_mut(&k)) { - Some(e) => e.slots_mut().get_mut(i - 300).unwrap_or(&mut self.scratch_slot), + Some(e) => e + .slots_mut() + .get_mut(i - 300) + .unwrap_or(&mut self.scratch_slot), None => &mut self.scratch_slot, }; } @@ -1947,8 +2616,22 @@ impl Game<'_> { let (ox, oy) = self.inventory_origin(batch); { let atlas = &self.res.atlas; - batch.fill(atlas, 0.0, 0.0, batch.width, batch.height, rgba(16, 16, 16, 160)); - let part = |batch: &mut HudBatch, name: &str, sx: f32, sy: f32, w: f32, h: f32, dx: f32, dy: f32| { + batch.fill( + atlas, + 0.0, + 0.0, + batch.width, + batch.height, + rgba(16, 16, 16, 160), + ); + let part = |batch: &mut HudBatch, + name: &str, + sx: f32, + sy: f32, + w: f32, + h: f32, + dx: f32, + dy: f32| { if let Some(mut r) = atlas.sprites.get(name).copied() { let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32); r.u0 += sx * du; @@ -1959,22 +2642,56 @@ impl Game<'_> { } }; let grey = rgba(64, 64, 64, 255); - match self.container.and_then(|k| self.world.block_entities.get(&k)) { + match self + .container + .and_then(|k| self.world.block_entities.get(&k)) + { Some(BlockEntity::Chest(_)) if self.draw_machine_screen(batch, ox, oy) => {} Some(BlockEntity::Chest(_)) => { // ContainerScreen with 3 rows: top 71px, then the player inventory from v=126. - part(batch, "gui/container/generic_54", 0.0, 0.0, 176.0, 71.0, ox, oy); - part(batch, "gui/container/generic_54", 0.0, 126.0, 176.0, 96.0, ox, oy + 71.0); - let name = self.container.map(|k| self.world.block(k.0, k.1, k.2)).map(|s| self.res.facts.get(s).name.clone()); - let title = if name.as_deref() == Some("minecraft:barrel") { "Barrel" } else { "Chest" }; + part( + batch, + "gui/container/generic_54", + 0.0, + 0.0, + 176.0, + 71.0, + ox, + oy, + ); + part( + batch, + "gui/container/generic_54", + 0.0, + 126.0, + 176.0, + 96.0, + ox, + oy + 71.0, + ); + let name = self + .container + .map(|k| self.world.block(k.0, k.1, k.2)) + .map(|s| self.res.facts.get(s).name.clone()); + let title = if name.as_deref() == Some("minecraft:barrel") { + "Barrel" + } else { + "Chest" + }; batch.text(atlas, title, ox + 8.0, oy + 6.0, grey, false); batch.text(atlas, "Inventory", ox + 8.0, oy + 73.0, grey, false); } Some(BlockEntity::Furnace(f)) => { let (tex, title) = match f.kind { - horizon_client::containers::FurnaceKind::Furnace => ("gui/container/furnace", "Furnace"), - horizon_client::containers::FurnaceKind::BlastFurnace => ("gui/container/blast_furnace", "Blast Furnace"), - horizon_client::containers::FurnaceKind::Smoker => ("gui/container/smoker", "Smoker"), + horizon_client::containers::FurnaceKind::Furnace => { + ("gui/container/furnace", "Furnace") + } + horizon_client::containers::FurnaceKind::BlastFurnace => { + ("gui/container/blast_furnace", "Blast Furnace") + } + horizon_client::containers::FurnaceKind::Smoker => { + ("gui/container/smoker", "Smoker") + } }; part(batch, tex, 0.0, 0.0, 176.0, 166.0, ox, oy); let tw = HudBatch::text_width(atlas, title); @@ -1984,20 +2701,53 @@ impl Game<'_> { // AbstractFurnaceScreen: flame height ceil(lit * 13) + 1. let total = if f.lit_total == 0 { 200 } else { f.lit_total }; let h = ((f.lit_remaining as f32 / total as f32) * 13.0).ceil() + 1.0; - part(batch, "gui/sprites/container/furnace/lit_progress", 0.0, 14.0 - h, 14.0, h, ox + 56.0, oy + 36.0 + 14.0 - h); + part( + batch, + "gui/sprites/container/furnace/lit_progress", + 0.0, + 14.0 - h, + 14.0, + h, + ox + 56.0, + oy + 36.0 + 14.0 - h, + ); } if f.cooking_timer > 0 && f.cooking_total > 0 { let w = ((f.cooking_timer as f32 / f.cooking_total as f32) * 24.0).ceil(); - part(batch, "gui/sprites/container/furnace/burn_progress", 0.0, 0.0, w, 16.0, ox + 79.0, oy + 34.0); + part( + batch, + "gui/sprites/container/furnace/burn_progress", + 0.0, + 0.0, + w, + 16.0, + ox + 79.0, + oy + 34.0, + ); } } Some(BlockEntity::Brewing(_)) => {} Some(BlockEntity::Sign(_)) => {} None => { - let texture = if self.craft_size == 3 { "gui/container/crafting_table" } else { "gui/container/inventory" }; + let texture = if self.craft_size == 3 { + "gui/container/crafting_table" + } else { + "gui/container/inventory" + }; part(batch, texture, 0.0, 0.0, 176.0, 166.0, ox, oy); - let (title, tx) = if self.craft_size == 3 { ("Crafting", 29.0) } else { ("Crafting", 97.0) }; - batch.text(atlas, title, ox + tx, oy + if self.craft_size == 3 { 6.0 } else { 8.0 }, grey, false); + let (title, tx) = if self.craft_size == 3 { + ("Crafting", 29.0) + } else { + ("Crafting", 97.0) + }; + batch.text( + atlas, + title, + ox + tx, + oy + if self.craft_size == 3 { 6.0 } else { 8.0 }, + grey, + false, + ); if self.craft_size == 3 { batch.text(atlas, "Inventory", ox + 8.0, oy + 72.0, grey, false); } @@ -2008,16 +2758,32 @@ impl Game<'_> { let (sx, sy) = self.slot_position(i); if (500..504).contains(&i) && self.armor[i - 500].is_none() { let icon = ["helmet", "chestplate", "leggings", "boots"][i - 500]; - batch.sprite(&self.res.atlas, &format!("gui/sprites/container/slot/{icon}"), ox + sx, oy + sy); + batch.sprite( + &self.res.atlas, + &format!("gui/sprites/container/slot/{icon}"), + ox + sx, + oy + sy, + ); } - let stack = if i == 200 { self.craft_result() } else { self.slot_mut(i).clone() }; + let stack = if i == 200 { + self.craft_result() + } else { + self.slot_mut(i).clone() + }; if let Some(stack) = stack { self.draw_item(batch, &stack, ox + sx, oy + sy); } } if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); - batch.fill(&self.res.atlas, ox + sx, oy + sy, 16.0, 16.0, rgba(255, 255, 255, 128)); + batch.fill( + &self.res.atlas, + ox + sx, + oy + sy, + 16.0, + 16.0, + rgba(255, 255, 255, 128), + ); } if let Some(stack) = self.carried.clone() { self.draw_item(batch, &stack, self.cursor.0 - 8.0, self.cursor.1 - 8.0); @@ -2040,10 +2806,30 @@ impl Game<'_> { } self.craft_size = 2; if let Some(key) = self.container.take() { - let name = self.res.facts.get(self.world.block(key.0, key.1, key.2)).name.clone(); - let sound = if name.contains("chest") { Some("minecraft:block.chest.close") } else if &*name == "minecraft:barrel" { Some("minecraft:block.barrel.close") } else { None }; + let name = self + .res + .facts + .get(self.world.block(key.0, key.1, key.2)) + .name + .clone(); + let sound = if name.contains("chest") { + Some("minecraft:block.chest.close") + } else if &*name == "minecraft:barrel" { + Some("minecraft:block.barrel.close") + } else { + None + }; if let Some(sound) = sound { - self.audio.play(sound, Some([f64::from(key.0) + 0.5, f64::from(key.1) + 0.5, f64::from(key.2) + 0.5]), 0.5, 1.0); + self.audio.play( + sound, + Some([ + f64::from(key.0) + 0.5, + f64::from(key.1) + 0.5, + f64::from(key.2) + 0.5, + ]), + 0.5, + 1.0, + ); } self.world.modified.insert((key.0 >> 4, key.2 >> 4)); } @@ -2055,11 +2841,20 @@ impl Game<'_> { if self.remote.is_some() { return self.remote_click(right); } - let Some(size) = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]) else { return }; + let Some(size) = self + .renderer + .as_ref() + .map(|r| [r.config.width, r.config.height]) + else { + return; + }; let batch = HudBatch::new(size); - let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return }; + let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { + return; + }; let max = |items: &Items, s: &ItemStack| items.get(&s.item).map_or(64, |i| i.max_stack); - let shift = self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight); + let shift = + self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight); if slot >= 300 { if let Some(key) = self.container { self.world.modified.insert((key.0 >> 4, key.2 >> 4)); @@ -2068,17 +2863,26 @@ impl Game<'_> { let is_furnace = matches!(self.container_kind(), Some(BlockEntity::Furnace(_))); if is_furnace && slot == 302 { // FurnaceResultSlot: take only. - let Some(result) = self.slot_mut(302).take() else { return }; + let Some(result) = self.slot_mut(302).take() else { + return; + }; match &mut self.carried { None => self.carried = Some(result), - Some(c) if c.item == result.item && c.count + result.count <= max(&self.res.items, c) => c.count += result.count, + Some(c) + if c.item == result.item + && c.count + result.count <= max(&self.res.items, c) => + { + c.count += result.count + } _ => *self.slot_mut(302) = Some(result), } return; } if is_furnace && slot == 300 - && let Some(BlockEntity::Furnace(f)) = self.container.and_then(|k| self.world.block_entities.get_mut(&k)) + && let Some(BlockEntity::Furnace(f)) = self + .container + .and_then(|k| self.world.block_entities.get_mut(&k)) { // Changing the input restarts cooking (AbstractFurnaceBlockEntity.setItem). f.cooking_timer = 0; @@ -2094,7 +2898,12 @@ impl Game<'_> { } else { match &mut self.carried { None => self.carried = Some(result), - Some(c) if c.item == result.item && c.count + result.count <= max(&self.res.items, c) => c.count += result.count, + Some(c) + if c.item == result.item + && c.count + result.count <= max(&self.res.items, c) => + { + c.count += result.count + } _ => return, } } @@ -2122,7 +2931,9 @@ impl Game<'_> { if let Some(s) = &mut self.inventory[i] && s.same_item_same_components(&stack) { - let moved = max(&self.res.items, s).saturating_sub(s.count).min(stack.count); + let moved = max(&self.res.items, s) + .saturating_sub(s.count) + .min(stack.count); s.count += moved; stack.count -= moved; } @@ -2131,7 +2942,10 @@ impl Game<'_> { && let Some(i) = range.clone().find(|&i| self.inventory[i].is_none()) { self.inventory[i] = Some(stack); - stack = ItemStack { count: 0, ..self.inventory[i].clone().unwrap() }; + stack = ItemStack { + count: 0, + ..self.inventory[i].clone().unwrap() + }; } if stack.count > 0 { self.inventory[slot] = Some(stack); @@ -2141,7 +2955,13 @@ impl Game<'_> { } if (500..504).contains(&slot) { let wanted = ["head", "chest", "legs", "feet"][slot - 500]; - let fits = self.carried.as_ref().is_none_or(|c| self.res.items.get(&c.item).and_then(|i| i.equip_slot.as_deref()) == Some(wanted)); + let fits = self.carried.as_ref().is_none_or(|c| { + self.res + .items + .get(&c.item) + .and_then(|i| i.equip_slot.as_deref()) + == Some(wanted) + }); if !fits { return; } @@ -2156,19 +2976,29 @@ impl Game<'_> { (None, Some(mut s)) if right => { let half = s.count.div_ceil(2); s.count -= half; - let taken = ItemStack { count: half, ..s.clone() }; + let taken = ItemStack { + count: half, + ..s.clone() + }; ((s.count > 0).then_some(s), Some(taken)) } (None, s) => (None, s), (Some(mut c), None) if right => { - let one = ItemStack { count: 1, ..c.clone() }; + let one = ItemStack { + count: 1, + ..c.clone() + }; c.count -= 1; (Some(one), (c.count > 0).then_some(c)) } (Some(c), None) => (Some(c), None), (Some(mut c), Some(mut s)) if c.same_item_same_components(&s) => { let room = max(items, &s).saturating_sub(s.count); - let moved = if right { 1.min(room).min(c.count) } else { room.min(c.count) }; + let moved = if right { + 1.min(room).min(c.count) + } else { + room.min(c.count) + }; s.count += moved; c.count -= moved; (Some(s), (c.count > 0).then_some(c)) @@ -2196,20 +3026,32 @@ impl Game<'_> { 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 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 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 }); + out.push(Vertex { + pos: v.to_array(), + uv, + layer: 0, + color, + light: packed, + }); } }; let copies = match item.stack.count { @@ -2221,20 +3063,90 @@ impl Game<'_> { 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 }) => { + 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); + 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); + quad( + [v(-1., -1.), v(1., -1.), v(1., 1.), v(-1., 1.)], + name, + 1.0, + 0xFFFFFF, + ); } None => {} } @@ -2243,22 +3155,50 @@ impl Game<'_> { // Mobs and their projectiles. self.mob_geometry(camera, alpha, &mut out); // Arrows: two crossed quads along the flight direction. - if let Some(r) = self.res.atlas.sprites.get("entity/projectiles/arrow").copied() { + if let Some(r) = self + .res + .atlas + .sprites + .get("entity/projectiles/arrow") + .copied() + { for a in &self.arrows { let p = glam::DVec3::new( a.previous.x + (a.position.x - a.previous.x) * alpha, a.previous.y + (a.position.y - a.previous.y) * alpha, a.previous.z + (a.position.z - a.previous.z) * alpha, ) - camera; - let dir = glam::Vec3::new(a.velocity.x as f32, a.velocity.y as f32, a.velocity.z as f32).normalize_or(glam::Vec3::X); + let dir = glam::Vec3::new( + a.velocity.x as f32, + a.velocity.y as f32, + a.velocity.z as f32, + ) + .normalize_or(glam::Vec3::X); let side = dir.cross(glam::Vec3::Y).normalize_or(glam::Vec3::Z) * 0.08; let up = dir.cross(side).normalize_or(glam::Vec3::Y) * 0.08; let c = p.as_vec3(); - let (u1, v1) = (r.u0 + (r.u1 - r.u0) * 0.5, r.v0 + (r.v1 - r.v0) * (5.0 / 32.0)); + let (u1, v1) = ( + r.u0 + (r.u1 - r.u0) * 0.5, + r.v0 + (r.v1 - r.v0) * (5.0 / 32.0), + ); for off in [side, up] { - let q = [c - dir * 0.25 - off, c + dir * 0.25 - off, c + dir * 0.25 + off, c - dir * 0.25 + off]; - for (v, uv) in q.iter().zip([[r.u0, v1], [u1, v1], [u1, r.v0], [r.u0, r.v0]]) { - out.push(Vertex { pos: v.to_array(), uv, layer: 0, color: 0xFFFF_FFFF, light: 240 | 240 << 8 }); + let q = [ + c - dir * 0.25 - off, + c + dir * 0.25 - off, + c + dir * 0.25 + off, + c - dir * 0.25 + off, + ]; + for (v, uv) in q + .iter() + .zip([[r.u0, v1], [u1, v1], [u1, r.v0], [r.u0, r.v0]]) + { + out.push(Vertex { + pos: v.to_array(), + uv, + layer: 0, + color: 0xFFFF_FFFF, + light: 240 | 240 << 8, + }); } } } @@ -2268,19 +3208,52 @@ impl Game<'_> { let ambient = if self.dim == Dim::Nether { 0.1 } else { 0.0 }; let darken = self.sky_darken(); let a = alpha; - let lerp = |p: Vec3, q: Vec3| glam::DVec3::new(p.x + (q.x - p.x) * a, p.y + (q.y - p.y) * a, p.z + (q.z - p.z) * a); - let mut casters: Vec<(glam::DVec3, &str)> = self.mobs.iter().map(|m| (lerp(m.previous, m.position), m.kind.id.as_str())).collect(); - casters.extend(self.dropped.iter().map(|i| (lerp(i.previous, i.position), "minecraft:item"))); - casters.extend(self.orbs.iter().map(|o| (lerp(o.previous, o.position), "minecraft:experience_orb"))); + let lerp = |p: Vec3, q: Vec3| { + glam::DVec3::new( + p.x + (q.x - p.x) * a, + p.y + (q.y - p.y) * a, + p.z + (q.z - p.z) * a, + ) + }; + let mut casters: Vec<(glam::DVec3, &str)> = self + .mobs + .iter() + .map(|m| (lerp(m.previous, m.position), m.kind.id.as_str())) + .collect(); + casters.extend( + self.dropped + .iter() + .map(|i| (lerp(i.previous, i.position), "minecraft:item")), + ); + casters.extend( + self.orbs + .iter() + .map(|o| (lerp(o.previous, o.position), "minecraft:experience_orb")), + ); for (pos, id) in casters { let (radius, strength) = horizon_client::shadows::shadow_params(id); - horizon_client::shadows::shadow(&self.world, &self.res.facts, sprite, camera, pos, radius, strength, ambient, darken, &mut out); + horizon_client::shadows::shadow( + &self.world, + &self.res.facts, + sprite, + camera, + pos, + radius, + strength, + ambient, + darken, + &mut out, + ); } } // Block entities (BlockEntityRenderers): chests, shulker boxes, banners, skulls... if let Some(r) = &self.renderer { let lid = |p: [i32; 3]| { - let (prev, cur) = self.chest_open.get(&(p[0], p[1], p[2])).copied().unwrap_or((0.0, 0.0)); + let (prev, cur) = self + .chest_open + .get(&(p[0], p[1], p[2])) + .copied() + .unwrap_or((0.0, 0.0)); prev + (cur - prev) * alpha as f32 }; let scene = horizon_client::block_entity_render::Scene { @@ -2297,12 +3270,18 @@ impl Game<'_> { }, glyph: &|c| self.res.atlas.glyph(c), }; - self.res.block_entity_render.render(&scene, r.block_entities(), &mut out); + self.res + .block_entity_render + .render(&scene, r.block_entities(), &mut out); } // Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet. if let Some(r) = self.res.atlas.sprites.get("entity/experience_orb").copied() { let (yaw, pitch) = (self.yaw.to_radians(), self.pitch.to_radians()); - let forward = glam::Vec3::new(-yaw.sin() * pitch.cos(), -pitch.sin(), yaw.cos() * pitch.cos()); + let forward = glam::Vec3::new( + -yaw.sin() * pitch.cos(), + -pitch.sin(), + yaw.cos() * pitch.cos(), + ); let right = forward.cross(glam::Vec3::Y).normalize_or_zero(); let up = right.cross(forward).normalize_or_zero(); for o in &self.orbs { @@ -2318,70 +3297,181 @@ impl Game<'_> { let red = ((t.sin() + 1.0) * 0.5 * 255.0) as u32; let blue = (((t + 4.188_79).sin() + 1.0) * 0.1 * 255.0) as u32; let color = 0x8000_0000 | blue << 16 | 255 << 8 | red; - let light = self.world.light(o.position.x.floor() as i32, o.position.y.floor() as i32, o.position.z.floor() as i32); - let packed = u32::from(light >> 4).max(10) * 16 | (u32::from(light & 15).max(10) * 16) << 8; + let light = self.world.light( + o.position.x.floor() as i32, + o.position.y.floor() as i32, + o.position.z.floor() as i32, + ); + let packed = + u32::from(light >> 4).max(10) * 16 | (u32::from(light & 15).max(10) * 16) << 8; let c = p.as_vec3(); let s = 0.15; - for (k, uv) in [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)].iter().zip([[u0, v0 + dv], [u0 + du, v0 + dv], [u0 + du, v0], [u0, v0]]) { + for (k, uv) in [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)] + .iter() + .zip([[u0, v0 + dv], [u0 + du, v0 + dv], [u0 + du, v0], [u0, v0]]) + { let v = c + right * (k.0 * s) + up * (k.1 * s); - out.push(Vertex { pos: v.to_array(), uv, layer: 0, color, light: packed }); + out.push(Vertex { + pos: v.to_array(), + uv, + layer: 0, + color, + light: packed, + }); } } } // Falling blocks: a unit cube with the block's texture. for f in self.falling.clone() { - let Some((sprite, tint)) = self.particle_sprite(f.state) else { continue }; - let Some(r) = self.res.atlas.sprites.get(&sprite).copied() else { continue }; + let Some((sprite, tint)) = self.particle_sprite(f.state) else { + continue; + }; + let Some(r) = self.res.atlas.sprites.get(&sprite).copied() else { + continue; + }; let p = glam::DVec3::new( f.previous.x + (f.position.x - f.previous.x) * alpha - 0.5, f.previous.y + (f.position.y - f.previous.y) * alpha, f.previous.z + (f.position.z - f.previous.z) * alpha - 0.5, ) - camera; let o = p.as_vec3(); - let light = self.world.light(f.position.x.floor() as i32, f.position.y.floor() as i32 + 1, f.position.z.floor() as i32); + let light = self.world.light( + f.position.x.floor() as i32, + f.position.y.floor() as i32 + 1, + f.position.z.floor() as i32, + ); let packed = u32::from(light >> 4) * 16 | (u32::from(light & 15) * 16) << 8; let v = |x: f32, y: f32, z: f32| o + glam::Vec3::new(x, y, z); let faces = [ - ([v(0., 1., 1.), v(1., 1., 1.), v(1., 1., 0.), v(0., 1., 0.)], 1.0), - ([v(0., 0., 0.), v(1., 0., 0.), v(1., 0., 1.), v(0., 0., 1.)], 0.5), - ([v(1., 0., 0.), v(0., 0., 0.), v(0., 1., 0.), v(1., 1., 0.)], 0.8), - ([v(0., 0., 1.), v(1., 0., 1.), v(1., 1., 1.), v(0., 1., 1.)], 0.8), - ([v(0., 0., 0.), v(0., 0., 1.), v(0., 1., 1.), v(0., 1., 0.)], 0.6), - ([v(1., 0., 1.), v(1., 0., 0.), v(1., 1., 0.), v(1., 1., 1.)], 0.6), + ( + [v(0., 1., 1.), v(1., 1., 1.), v(1., 1., 0.), v(0., 1., 0.)], + 1.0, + ), + ( + [v(0., 0., 0.), v(1., 0., 0.), v(1., 0., 1.), v(0., 0., 1.)], + 0.5, + ), + ( + [v(1., 0., 0.), v(0., 0., 0.), v(0., 1., 0.), v(1., 1., 0.)], + 0.8, + ), + ( + [v(0., 0., 1.), v(1., 0., 1.), v(1., 1., 1.), v(0., 1., 1.)], + 0.8, + ), + ( + [v(0., 0., 0.), v(0., 0., 1.), v(0., 1., 1.), v(0., 1., 0.)], + 0.6, + ), + ( + [v(1., 0., 1.), v(1., 0., 0.), v(1., 1., 0.), v(1., 1., 1.)], + 0.6, + ), ]; for (corners, shade) in faces { 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([[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]]) { - out.push(Vertex { pos: p.to_array(), uv, layer: 0, color, light: packed }); + for (p, uv) in + corners + .iter() + .zip([[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]]) + { + out.push(Vertex { + pos: p.to_array(), + uv, + layer: 0, + color, + light: packed, + }); } } } self.tnt_geometry(camera, alpha, &mut out); // Particles (ParticleEngine.extract): camera-facing quads. let world = &self.world; - self.particles.render(camera, self.yaw, self.pitch, alpha as f32, &|b| world.light(b[0], b[1], b[2]), &mut out); + self.particles.render( + camera, + self.yaw, + self.pitch, + alpha as f32, + &|b| world.light(b[0], b[1], b[2]), + &mut out, + ); let atlas = &self.res.atlas; // Breaking progress overlay (destroy_stage_0..9). if let Some(m) = &self.mining && m.progress > 0.0 { let stage = ((m.progress * 10.0) as u32).min(9); - if let Some(r) = atlas.sprites.get(&format!("block/destroy_stage_{stage}")).copied() { - let o = (glam::DVec3::new(f64::from(m.pos[0]), f64::from(m.pos[1]), f64::from(m.pos[2])) - camera).as_vec3(); + if let Some(r) = atlas + .sprites + .get(&format!("block/destroy_stage_{stage}")) + .copied() + { + let o = (glam::DVec3::new( + f64::from(m.pos[0]), + f64::from(m.pos[1]), + f64::from(m.pos[2]), + ) - camera) + .as_vec3(); let e = 0.002; - let corner = |x: f32, y: f32, z: f32| o + glam::Vec3::new(x * (1.0 + 2.0 * e) - e, y * (1.0 + 2.0 * e) - e, z * (1.0 + 2.0 * e) - e); + let corner = |x: f32, y: f32, z: f32| { + o + glam::Vec3::new( + x * (1.0 + 2.0 * e) - e, + y * (1.0 + 2.0 * e) - e, + z * (1.0 + 2.0 * e) - e, + ) + }; let faces = [ - [corner(0., 1., 0.), corner(1., 1., 0.), corner(1., 1., 1.), corner(0., 1., 1.)], - [corner(0., 0., 1.), corner(1., 0., 1.), corner(1., 0., 0.), corner(0., 0., 0.)], - [corner(0., 0., 0.), corner(1., 0., 0.), corner(1., 1., 0.), corner(0., 1., 0.)], - [corner(1., 0., 1.), corner(0., 0., 1.), corner(0., 1., 1.), corner(1., 1., 1.)], - [corner(0., 0., 1.), corner(0., 0., 0.), corner(0., 1., 0.), corner(0., 1., 1.)], - [corner(1., 0., 0.), corner(1., 0., 1.), corner(1., 1., 1.), corner(1., 1., 0.)], + [ + corner(0., 1., 0.), + corner(1., 1., 0.), + corner(1., 1., 1.), + corner(0., 1., 1.), + ], + [ + corner(0., 0., 1.), + corner(1., 0., 1.), + corner(1., 0., 0.), + corner(0., 0., 0.), + ], + [ + corner(0., 0., 0.), + corner(1., 0., 0.), + corner(1., 1., 0.), + corner(0., 1., 0.), + ], + [ + corner(1., 0., 1.), + corner(0., 0., 1.), + corner(0., 1., 1.), + corner(1., 1., 1.), + ], + [ + corner(0., 0., 1.), + corner(0., 0., 0.), + corner(0., 1., 0.), + corner(0., 1., 1.), + ], + [ + corner(1., 0., 0.), + corner(1., 0., 1.), + corner(1., 1., 1.), + corner(1., 1., 0.), + ], ]; for f in faces { - for (v, uv) in f.iter().zip([[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]]) { - out.push(Vertex { pos: v.to_array(), uv, layer: 0, color: 0xB4FF_FFFF, light: 15 * 16 | (15 * 16) << 8 }); + for (v, uv) in + f.iter() + .zip([[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]]) + { + out.push(Vertex { + pos: v.to_array(), + uv, + layer: 0, + color: 0xB4FF_FFFF, + light: 15 * 16 | (15 * 16) << 8, + }); } } } @@ -2439,30 +3529,43 @@ impl Game<'_> { } /// Player.attack with the attack-strength charge, crits and knockback. fn attack(&mut self) -> bool { - let Some((index, distance)) = self.mob_hit() else { return false }; + let Some((index, distance)) = self.mob_hit() else { + return false; + }; if let Some(hit) = self.pick() { let eye = self.eye_position().unwrap_or_default(); - let d = ((hit.point[0] - eye[0]).powi(2) + (hit.point[1] - eye[1]).powi(2) + (hit.point[2] - eye[2]).powi(2)).sqrt(); + let d = ((hit.point[0] - eye[0]).powi(2) + + (hit.point[1] - eye[1]).powi(2) + + (hit.point[2] - eye[2]).powi(2)) + .sqrt(); if d < distance { return false; } } let held = self.held().cloned(); - let modifiers = held.as_ref().and_then(|h| self.res.items.get(&h.item)).map(|i| (i.attack_damage, i.attack_speed)).unwrap_or((0.0, 0.0)); + let modifiers = held + .as_ref() + .and_then(|h| self.res.items.get(&h.item)) + .map(|i| (i.attack_damage, i.attack_speed)) + .unwrap_or((0.0, 0.0)); let damage = 1.0 + modifiers.0 + self.effect_attack_bonus(); let speed = (4.0 + modifiers.1).max(0.1); let delay = 20.0 / speed; let scale = ((self.attack_ticks as f32 + 0.5) / delay).clamp(0.0, 1.0); let mut amount = damage * (0.2 + scale * scale * 0.8); let player = self.player.as_ref(); - let falling = player.is_some_and(|p| !p.ground.on_ground && p.velocity.y < 0.0 && !p.sprinting); + let falling = + player.is_some_and(|p| !p.ground.on_ground && p.velocity.y < 0.0 && !p.sprinting); let crit = scale > 0.9 && falling; if crit { amount *= 1.5; } // Enchantment damage (sharpness, smite, bane) scaled by the attack strength. let target_kind = self.mobs[index].kind.id.clone(); - amount += self.enchant_damage_bonus(&format!("minecraft:{}", target_kind.trim_start_matches("minecraft:"))) * scale; + amount += self.enchant_damage_bonus(&format!( + "minecraft:{}", + target_kind.trim_start_matches("minecraft:") + )) * scale; self.attack_ticks = 0; if let Some(p) = self.player.as_mut() && !self.creative @@ -2473,28 +3576,63 @@ impl Game<'_> { let from = player.map(|p| [p.position.x, p.position.y, p.position.z]); self.swing_arm(); let mob = &mut self.mobs[index]; - let center = [mob.position.x, mob.position.y + mob.kind.height / 2.0, mob.position.z]; + let center = [ + mob.position.x, + mob.position.y + mob.kind.height / 2.0, + mob.position.z, + ]; if mob.hurt(amount, from, &mut self.world.random) { // Player.attack: crit emitter and damage indicator hearts. - let (feet, width, height) = ([mob.position.x, mob.position.y, mob.position.z], mob.kind.width, mob.kind.height); + let (feet, width, height) = ( + [mob.position.x, mob.position.y, mob.position.z], + mob.kind.width, + mob.kind.height, + ); if crit { - self.particles.tracking_emitter(horizon_client::particles::ParticleOptions::simple(horizon_client::particles::ParticleType::Crit), feet, width, height); + self.particles.tracking_emitter( + horizon_client::particles::ParticleOptions::simple( + horizon_client::particles::ParticleType::Crit, + ), + feet, + width, + height, + ); } if amount > 2.0 { - let indicator = horizon_client::particles::ParticleOptions::simple(horizon_client::particles::ParticleType::DamageIndicator); - self.particles.send_particles(&indicator, [feet[0], feet[1] + height * 0.5, feet[2]], [0.1, 0.0, 0.1], 0.2, (amount * 0.5) as u32); + let indicator = horizon_client::particles::ParticleOptions::simple( + horizon_client::particles::ParticleType::DamageIndicator, + ); + self.particles.send_particles( + &indicator, + [feet[0], feet[1] + height * 0.5, feet[2]], + [0.1, 0.0, 0.1], + 0.2, + (amount * 0.5) as u32, + ); } self.last_hurt_by_player.insert(mob.id); let kind = mob.kind.clone(); let dead = !mob.alive(); - let sound = if crit { "minecraft:entity.player.attack.crit" } else if scale > 0.9 { "minecraft:entity.player.attack.strong" } else { "minecraft:entity.player.attack.weak" }; + let sound = if crit { + "minecraft:entity.player.attack.crit" + } else if scale > 0.9 { + "minecraft:entity.player.attack.strong" + } else { + "minecraft:entity.player.attack.weak" + }; self.audio.play(sound, Some(center), 1.0, 1.0); let event = format!("minecraft:{}", kind.sounds[if dead { 2 } else { 1 }]); - let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 1.0; + 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); self.post_attack(index); if let Some(stack) = self.inventory[self.selected].clone() - && let Some(max) = self.res.items.get(&stack.item).filter(|i| i.max_damage > 0).map(|i| i.max_damage) + && let Some(max) = self + .res + .items + .get(&stack.item) + .filter(|i| i.max_damage > 0) + .map(|i| i.max_damage) { let loss = self.durability_loss(&stack, 1); if let Some(stack) = self.inventory[self.selected].as_mut() { @@ -2511,7 +3649,12 @@ impl Game<'_> { /// A mob explosion (`Level.ExplosionInteraction.MOB`: drop decay with the /// default mobGriefing rule). fn explode(&mut self, center: [f64; 3], radius: f32) -> Result<()> { - self.server_explode(center, radius, explosion::BlockInteraction::DestroyWithDecay, false) + self.server_explode( + center, + radius, + explosion::BlockInteraction::DestroyWithDecay, + false, + ) } fn tick_block_entities(&mut self) -> Result<()> { self.tick_hoppers()?; @@ -2522,7 +3665,11 @@ impl Game<'_> { let open = self.container; self.chest_open.retain(|k, (prev, cur)| { *prev = *cur; - *cur = if Some(*k) == open { (*cur + 0.1).min(1.0) } else { (*cur - 0.1).max(0.0) }; + *cur = if Some(*k) == open { + (*cur + 0.1).min(1.0) + } else { + (*cur - 0.1).max(0.0) + }; *cur > 0.0 || *prev > 0.0 }); let mut lit_changes = Vec::new(); @@ -2547,7 +3694,10 @@ impl Game<'_> { Ok(()) } /// A copy of a chunk carrying its block entities, for saving. - fn with_entities(&self, chunk: &Arc) -> Arc { + fn with_entities( + &self, + chunk: &Arc, + ) -> Arc { let mut c = (**chunk).clone(); c.block_entities = self .world @@ -2566,21 +3716,51 @@ impl Game<'_> { fn celestial_geometry(&self, sky: &horizon_client::environment::Sky) -> Vec { let mut out = Vec::new(); let atlas = &self.res.atlas; - let frame = |angle: f32| glam::Mat4::from_rotation_y((-90.0f32).to_radians()) * glam::Mat4::from_rotation_x(angle.to_radians()); + let frame = |angle: f32| { + glam::Mat4::from_rotation_y((-90.0f32).to_radians()) + * glam::Mat4::from_rotation_x(angle.to_radians()) + }; let mut body = |name: &str, angle: f32, size: f32, color: u32| { - let Some(r) = atlas.sprites.get(name).copied() else { return }; + let Some(r) = atlas.sprites.get(name).copied() else { + return; + }; let m = frame(angle); let corners = [(-size, -size), (size, -size), (size, size), (-size, size)]; let uv = [[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]]; for ((x, z), uv) in corners.iter().zip(uv) { let p = m.transform_point3(glam::Vec3::new(*x, 100.0, *z)); - out.push(Vertex { pos: p.to_array(), uv, layer: 2, color: color, light: 0 }); + out.push(Vertex { + pos: p.to_array(), + uv, + layer: 2, + color: color, + light: 0, + }); } }; - body("environment/celestial/sun", sky.sun_angle, 30.0, 0xFFFF_FFFF); - let phases = ["full_moon", "waning_gibbous", "third_quarter", "waning_crescent", "new_moon", "waxing_crescent", "first_quarter", "waxing_gibbous"]; + body( + "environment/celestial/sun", + sky.sun_angle, + 30.0, + 0xFFFF_FFFF, + ); + let phases = [ + "full_moon", + "waning_gibbous", + "third_quarter", + "waning_crescent", + "new_moon", + "waxing_crescent", + "first_quarter", + "waxing_gibbous", + ]; let phase = phases[(self.world.day_time / 24000).rem_euclid(8) as usize]; - body(&format!("environment/celestial/moon/{phase}"), sky.moon_angle, 20.0, 0xFFFF_FFFF); + body( + &format!("environment/celestial/moon/{phase}"), + sky.moon_angle, + 20.0, + 0xFFFF_FFFF, + ); if sky.star_brightness > 0.0 { let b = (sky.star_brightness.clamp(0.0, 1.0) * 255.0) as u32; let color = b << 24 | b << 16 | b << 8 | b; @@ -2608,7 +3788,13 @@ impl Game<'_> { let (r2, u2) = (right * c + up * s, up * c - right * s); for (a, b) in [(size, -size), (size, size), (-size, size), (-size, -size)] { let p = m.transform_point3(center + r2 * a + u2 * b); - out.push(Vertex { pos: p.to_array(), uv: [cu, cv], layer: 2, color, light: 0 }); + out.push(Vertex { + pos: p.to_array(), + uv: [cu, cv], + layer: 2, + color, + light: 0, + }); } } } @@ -2616,10 +3802,18 @@ impl Game<'_> { out } /// CloudRenderer (fancy): 12x4x12 cells from clouds.png drifting east. - fn cloud_geometry(&self, sky: &horizon_client::environment::Sky, camera: glam::DVec3, alpha: f64, out: &mut Vec) { + fn cloud_geometry( + &self, + sky: &horizon_client::environment::Sky, + camera: glam::DVec3, + alpha: f64, + out: &mut Vec, + ) { let (w, h, cells) = &self.res.clouds; let (w, h) = (i64::from(*w), i64::from(*h)); - let Some(white) = self.res.atlas.sprites.get("horizon/white").copied() else { return }; + let Some(white) = self.res.atlas.sprites.get("horizon/white").copied() else { + return; + }; let uv = [(white.u0 + white.u1) / 2.0, (white.v0 + white.v1) / 2.0]; let cloud_height = 192.33; let offset = (self.world.game_time.rem_euclid(w * 400)) as f64 + alpha; @@ -2656,28 +3850,58 @@ impl Game<'_> { let mut quad = |p: [[f32; 3]; 4], shade: f32| { for v in p { // Overlay 4: clouds (unlit, faded by the cloud fog end). - out.push(Vertex { pos: v, uv, layer: 4, color: color(shade), light }); + out.push(Vertex { + pos: v, + uv, + layer: 4, + color: color(shade), + light, + }); } }; - quad([[x0, y1, z0], [x0, y1, z1], [x1, y1, z1], [x1, y1, z0]], 1.0); - quad([[x1, y0, z0], [x1, y0, z1], [x0, y0, z1], [x0, y0, z0]], 0.7); + quad( + [[x0, y1, z0], [x0, y1, z1], [x1, y1, z1], [x1, y1, z0]], + 1.0, + ); + quad( + [[x1, y0, z0], [x1, y0, z1], [x0, y0, z1], [x0, y0, z0]], + 0.7, + ); if !filled(cx, cz - 1) { - quad([[x0, y0, z0], [x0, y1, z0], [x1, y1, z0], [x1, y0, z0]], 0.8); + quad( + [[x0, y0, z0], [x0, y1, z0], [x1, y1, z0], [x1, y0, z0]], + 0.8, + ); } if !filled(cx, cz + 1) { - quad([[x1, y0, z1], [x1, y1, z1], [x0, y1, z1], [x0, y0, z1]], 0.8); + quad( + [[x1, y0, z1], [x1, y1, z1], [x0, y1, z1], [x0, y0, z1]], + 0.8, + ); } if !filled(cx - 1, cz) { - quad([[x0, y0, z1], [x0, y1, z1], [x0, y1, z0], [x0, y0, z0]], 0.9); + quad( + [[x0, y0, z1], [x0, y1, z1], [x0, y1, z0], [x0, y0, z0]], + 0.9, + ); } if !filled(cx + 1, cz) { - quad([[x1, y0, z0], [x1, y1, z0], [x1, y1, z1], [x1, y0, z1]], 0.9); + quad( + [[x1, y0, z0], [x1, y1, z0], [x1, y1, z1], [x1, y0, z1]], + 0.9, + ); } } } } /// Load (or create) a world folder under saves/ and start streaming it. - fn open_world(&mut self, folder: &str, name: Option<&str>, seed: Option, creative: bool) -> Result<()> { + fn open_world( + &mut self, + folder: &str, + name: Option<&str>, + seed: Option, + creative: bool, + ) -> Result<()> { let save_root = std::env::current_dir()?.join("saves").join(folder); horizon_client::save::migrate_legacy(&save_root)?; self.persist = Default::default(); @@ -2685,7 +3909,9 @@ impl Game<'_> { name: name.unwrap_or(folder).to_owned(), // WorldOptions.randomSeed when no seed was given. seed: seed.unwrap_or_else(|| { - let t = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos() as u64); + let t = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos() as u64); (t ^ (t >> 29)).wrapping_mul(0x9E37_79B9_7F4A_7C15) as i64 }), creative, @@ -2724,7 +3950,12 @@ impl Game<'_> { let mut inventory = vec![None; 36]; self.armor = [None, None, None, None]; for (slot, id, count, damage) in &level.inventory { - let stack = ItemStack { item: Arc::from(id.as_str()), count: *count, damage: *damage, extra: level.inventory_components.get(slot).cloned() }; + let stack = ItemStack { + item: Arc::from(id.as_str()), + count: *count, + damage: *damage, + extra: level.inventory_components.get(slot).cloned(), + }; if (100..104).contains(slot) { self.armor[usize::from(103 - slot)] = Some(stack); } else if let Some(cell) = inventory.get_mut(usize::from(*slot)) { @@ -2732,11 +3963,32 @@ impl Game<'_> { } } if self.creative && level.inventory.is_empty() && level.position.is_none() { - for (i, name) in ["minecraft:grass_block", "minecraft:stone", "minecraft:oak_planks", "minecraft:glass", "minecraft:torch", "minecraft:oak_log", "minecraft:chest", "minecraft:furnace", "minecraft:diamond_pickaxe"].iter().enumerate() { - inventory[i] = Some(ItemStack { item: Arc::from(*name), count: 1, damage: 0, extra: None }); + for (i, name) in [ + "minecraft:grass_block", + "minecraft:stone", + "minecraft:oak_planks", + "minecraft:glass", + "minecraft:torch", + "minecraft:oak_log", + "minecraft:chest", + "minecraft:furnace", + "minecraft:diamond_pickaxe", + ] + .iter() + .enumerate() + { + inventory[i] = Some(ItemStack { + item: Arc::from(*name), + count: 1, + damage: 0, + extra: None, + }); } } - let (yaw, pitch) = self.options.look.unwrap_or((level.rotation[0], level.rotation[1])); + let (yaw, pitch) = self + .options + .look + .unwrap_or((level.rotation[0], level.rotation[1])); self.yaw = yaw; self.pitch = pitch; self.selected = level.selected_slot.clamp(0, 8) as usize; @@ -2761,7 +4013,11 @@ impl Game<'_> { self.dropped.clear(); self.particles.clear(); self.orbs.clear(); - self.experience = Experience { level: self.level.xp_level, progress: self.level.xp_progress, total: self.level.xp_total }; + self.experience = Experience { + level: self.level.xp_level, + progress: self.level.xp_progress, + total: self.level.xp_total, + }; self.restore_effects(); self.mining = None; self.container = None; @@ -2783,18 +4039,45 @@ impl Game<'_> { Ok(()) } /// Streaming and region storage for one dimension of a world. - fn make_streaming(&self, world_root: &std::path::Path, dim: Dim, seed: i64) -> Result<(Streaming, Arc)> { - let save = Arc::new(SaveDir::new(horizon_client::save::dimension_dir(world_root, dim.id()))); + fn make_streaming( + &self, + world_root: &std::path::Path, + dim: Dim, + seed: i64, + ) -> Result<(Streaming, Arc)> { + let save = Arc::new(SaveDir::new(horizon_client::save::dimension_dir( + world_root, + dim.id(), + ))); let res = &*self.res; let mut streaming = if self.options.test_terrain && dim == Dim::Overworld { let inner = Arc::new(TestTerrain::new(res.assets.registry, &res.biomes)?); - Streaming::new(Arc::new(Persistent { inner, save: save.clone(), registry: res.assets.clone(), biomes: res.biomes.clone() }), res.context.clone(), res.threads) + Streaming::new( + Arc::new(Persistent { + inner, + save: save.clone(), + registry: res.assets.clone(), + biomes: res.biomes.clone(), + }), + res.context.clone(), + res.threads, + ) } else { let inner = Arc::new(VanillaTerrain::for_dimension(&self.options.resources.join("worldgen"), res.assets.registry, &res.biomes, seed, dim.id()).map_err(|e| { format!("{e}\nPrepare the worldgen bundle with: python3 tools/prepare_native_client.py") })?); - self.end.set_locator((dim == Dim::Overworld).then(|| inner.clone())); - Streaming::new(Arc::new(Persistent { inner, save: save.clone(), registry: res.assets.clone(), biomes: res.biomes.clone() }), res.context.clone(), res.threads) + self.end + .set_locator((dim == Dim::Overworld).then(|| inner.clone())); + Streaming::new( + Arc::new(Persistent { + inner, + save: save.clone(), + registry: res.assets.clone(), + biomes: res.biomes.clone(), + }), + res.context.clone(), + res.threads, + ) }; streaming.radius = self.settings.render_distance; streaming.sky_light = dim != Dim::Nether; @@ -2804,11 +4087,18 @@ impl Game<'_> { /// Change dimension through a portal (Entity.changeDimension with /// PortalForcer placement once the destination has loaded). fn enter_dimension(&mut self, target: Dim) -> Result<()> { - let Some(player) = self.player.take() else { return Ok(()) }; + let Some(player) = self.player.take() else { + return Ok(()); + }; // Save the departing dimension's changed chunks. let keys: Vec<_> = self.world.modified.drain().collect(); - let chunks: Vec<_> = keys.iter().filter_map(|k| self.world.chunks.get(k)).map(|c| self.with_entities(c)).collect(); - self.save.save(&chunks, &self.res.assets.registry, &self.res.biomes)?; + let chunks: Vec<_> = keys + .iter() + .filter_map(|k| self.world.chunks.get(k)) + .map(|c| self.with_entities(c)) + .collect(); + self.save + .save(&chunks, &self.res.assets.registry, &self.res.biomes)?; self.save_dimension_entities()?; // Coordinates scale by 8 between the Overworld and the Nether. let scale = match (self.dim, target) { @@ -2817,9 +4107,14 @@ impl Game<'_> { (Dim::End, Dim::Nether) => 1.0 / 8.0, _ => 1.0, }; - let destination = self.end_destination(target).unwrap_or(Vec3::new(player.position.x * scale, player.position.y, player.position.z * scale)); + let destination = self.end_destination(target).unwrap_or(Vec3::new( + player.position.x * scale, + player.position.y, + player.position.z * scale, + )); let from_end = self.dim == Dim::End; - let (streaming, save) = self.make_streaming(&self.world_root.clone(), target, self.level.seed)?; + let (streaming, save) = + self.make_streaming(&self.world_root.clone(), target, self.level.seed)?; let mut world = World::new(self.res.facts.air, self.level.seed); world.game_time = self.world.game_time; world.day_time = self.world.day_time; @@ -2850,10 +4145,23 @@ impl Game<'_> { } /// PortalShape: an obsidian frame around 2..=21 by 3..=21 empty blocks. fn portal_shape(&self, start: [i32; 3], x_axis: bool) -> Option<([i32; 3], i32, i32)> { - let name = |p: [i32; 3]| self.res.facts.get(self.world.block(p[0], p[1], p[2])).name.clone(); + let name = |p: [i32; 3]| { + self.res + .facts + .get(self.world.block(p[0], p[1], p[2])) + .name + .clone() + }; let empty = |p: [i32; 3]| { let n = name(p); - matches!(&*n, "minecraft:air" | "minecraft:cave_air" | "minecraft:fire" | "minecraft:soul_fire" | "minecraft:nether_portal") + matches!( + &*n, + "minecraft:air" + | "minecraft:cave_air" + | "minecraft:fire" + | "minecraft:soul_fire" + | "minecraft:nether_portal" + ) }; let frame = |p: [i32; 3]| &*name(p) == "minecraft:obsidian"; let d = if x_axis { [1, 0, 0] } else { [0, 0, 1] }; @@ -2883,13 +4191,17 @@ impl Game<'_> { } width += 1; } - if !(2..=21).contains(&width) || !frame([left[0] + d[0] * width, left[1], left[2] + d[2] * width]) { + if !(2..=21).contains(&width) + || !frame([left[0] + d[0] * width, left[1], left[2] + d[2] * width]) + { return None; } let mut height = 0; 'rows: while height <= 21 { let y = left[1] + height; - if !frame([left[0] - d[0], y, left[2] - d[2]]) || !frame([left[0] + d[0] * width, y, left[2] + d[2] * width]) { + if !frame([left[0] - d[0], y, left[2] - d[2]]) + || !frame([left[0] + d[0] * width, y, left[2] + d[2] * width]) + { break; } for i in 0..width { @@ -2899,7 +4211,8 @@ impl Game<'_> { } height += 1; } - let top_ok = (0..width).all(|i| frame([left[0] + d[0] * i, left[1] + height, left[2] + d[2] * i])); + let top_ok = + (0..width).all(|i| frame([left[0] + d[0] * i, left[1] + height, left[2] + d[2] * i])); ((3..=21).contains(&height) && top_ok).then_some((left, width, height)) } /// BaseFireBlock.onPlace: lighting fire inside a frame creates a portal. @@ -2908,13 +4221,22 @@ impl Game<'_> { if let Some((origin, width, height)) = self.portal_shape(at, x_axis) { let d = if x_axis { [1, 0, 0] } else { [0, 0, 1] }; let registry = &self.res.assets.registry; - let Some(default) = registry.default_state("minecraft:nether_portal") else { return Ok(false) }; + let Some(default) = registry.default_state("minecraft:nether_portal") else { + return Ok(false); + }; let mut portal = registry.state(default).cloned().ok_or("portal state")?; - portal.properties.insert("axis".into(), if x_axis { "x" } else { "z" }.into()); + portal + .properties + .insert("axis".into(), if x_axis { "x" } else { "z" }.into()); let id = registry.resolve(&portal).unwrap_or(default); for h in 0..height { for w in 0..width { - self.world.set(origin[0] + d[0] * w, origin[1] + h, origin[2] + d[2] * w, id)?; + self.world.set( + origin[0] + d[0] * w, + origin[1] + h, + origin[2] + d[2] * w, + id, + )?; } } return Ok(true); @@ -2926,7 +4248,11 @@ impl Game<'_> { fn place_after_travel(&mut self, mut player: PlayerMotion, target: Vec3) -> Result<()> { let (tx, tz) = (target.x.floor() as i32, target.z.floor() as i32); let radius = if self.dim == Dim::Nether { 16 } else { 32 }; - let (min_y, max_y) = if self.dim == Dim::Nether { (1, 126) } else { (MIN_Y + 1, MIN_Y + HEIGHT - 3) }; + let (min_y, max_y) = if self.dim == Dim::Nether { + (1, 126) + } else { + (MIN_Y + 1, MIN_Y + HEIGHT - 3) + }; let portal_name = "minecraft:nether_portal"; let mut best: Option<(i64, [i32; 3])> = None; for z in tz - radius..=tz + radius { @@ -2938,7 +4264,9 @@ impl Game<'_> { if &*self.res.facts.get(self.world.block(x, y, z)).name == portal_name && &*self.res.facts.get(self.world.block(x, y - 1, z)).name != portal_name { - let d = i64::from(x - tx).pow(2) + i64::from(z - tz).pow(2) + i64::from(y - target.y as i32).pow(2); + let d = i64::from(x - tx).pow(2) + + i64::from(z - tz).pow(2) + + i64::from(y - target.y as i32).pow(2); if best.is_none_or(|b| d < b.0) { best = Some((d, [x, y, z])); } @@ -2976,24 +4304,40 @@ impl Game<'_> { [tx, y, tz] } }; - player.position = Vec3::new(f64::from(spot[0]) + 0.5, f64::from(spot[1]), f64::from(spot[2]) + 0.5); + player.position = Vec3::new( + f64::from(spot[0]) + 0.5, + f64::from(spot[1]), + f64::from(spot[2]) + 0.5, + ); player.velocity = Vec3::ZERO; self.previous_position = player.position; self.player = Some(player); self.apply_equipment(); let at = [f64::from(spot[0]), f64::from(spot[1]), f64::from(spot[2])]; - self.audio.play("minecraft:block.portal.travel", Some(at), 0.25, 1.0); + self.audio + .play("minecraft:block.portal.travel", Some(at), 0.25, 1.0); Ok(()) } fn tick_portal(&mut self) -> Result<()> { - let Some(p) = self.player.as_ref() else { return Ok(()) }; + let Some(p) = self.player.as_ref() else { + return Ok(()); + }; let w = f64::from(p.dimensions.width) / 2.0; - let (lo, hi) = ([p.position.x - w, p.position.y, p.position.z - w], [p.position.x + w, p.position.y + f64::from(p.dimensions.height), p.position.z + w]); + let (lo, hi) = ( + [p.position.x - w, p.position.y, p.position.z - w], + [ + p.position.x + w, + p.position.y + f64::from(p.dimensions.height), + p.position.z + w, + ], + ); let mut inside = false; for x in lo[0].floor() as i32..=hi[0].floor() as i32 { for y in lo[1].floor() as i32..=hi[1].floor() as i32 { for z in lo[2].floor() as i32..=hi[2].floor() as i32 { - if &*self.res.facts.get(self.world.block(x, y, z)).name == "minecraft:nether_portal" { + if &*self.res.facts.get(self.world.block(x, y, z)).name + == "minecraft:nether_portal" + { inside = true; } } @@ -3009,7 +4353,12 @@ impl Game<'_> { } if self.portal_ticks == 0 { let at = self.eye_position(); - self.audio.play("minecraft:block.portal.trigger", at, 0.25, self.world.random.next_float() * 0.4 + 0.8); + self.audio.play( + "minecraft:block.portal.trigger", + at, + 0.25, + self.world.random.next_float() * 0.4 + 0.8, + ); } self.portal_ticks += 1; // Player.getPortalWaitTime: 80 ticks, or 1 when invulnerable (creative). @@ -3017,7 +4366,11 @@ impl Game<'_> { if self.portal_ticks >= wait { self.portal_ticks = 0; // NetherPortalBlock: the Nether leads to the Overworld, anywhere else to the Nether. - let target = if self.dim == Dim::Nether { Dim::Overworld } else { Dim::Nether }; + let target = if self.dim == Dim::Nether { + Dim::Overworld + } else { + Dim::Nether + }; self.end_portal_travel = false; self.enter_dimension(target)?; } @@ -3050,33 +4403,104 @@ impl Game<'_> { let mut out = Vec::new(); let d = 100.0; let faces: [(&str, [glam::Vec3; 4]); 6] = [ - ("0", [glam::Vec3::new(-d, d, -d), glam::Vec3::new(d, d, -d), glam::Vec3::new(d, -d, -d), glam::Vec3::new(-d, -d, -d)]), - ("1", [glam::Vec3::new(d, d, -d), glam::Vec3::new(d, d, d), glam::Vec3::new(d, -d, d), glam::Vec3::new(d, -d, -d)]), - ("2", [glam::Vec3::new(d, d, d), glam::Vec3::new(-d, d, d), glam::Vec3::new(-d, -d, d), glam::Vec3::new(d, -d, d)]), - ("3", [glam::Vec3::new(-d, d, d), glam::Vec3::new(-d, d, -d), glam::Vec3::new(-d, -d, -d), glam::Vec3::new(-d, -d, d)]), - ("4", [glam::Vec3::new(-d, d, d), glam::Vec3::new(d, d, d), glam::Vec3::new(d, d, -d), glam::Vec3::new(-d, d, -d)]), - ("5", [glam::Vec3::new(-d, -d, -d), glam::Vec3::new(d, -d, -d), glam::Vec3::new(d, -d, d), glam::Vec3::new(-d, -d, d)]), + ( + "0", + [ + glam::Vec3::new(-d, d, -d), + glam::Vec3::new(d, d, -d), + glam::Vec3::new(d, -d, -d), + glam::Vec3::new(-d, -d, -d), + ], + ), + ( + "1", + [ + glam::Vec3::new(d, d, -d), + glam::Vec3::new(d, d, d), + glam::Vec3::new(d, -d, d), + glam::Vec3::new(d, -d, -d), + ], + ), + ( + "2", + [ + glam::Vec3::new(d, d, d), + glam::Vec3::new(-d, d, d), + glam::Vec3::new(-d, -d, d), + glam::Vec3::new(d, -d, d), + ], + ), + ( + "3", + [ + glam::Vec3::new(-d, d, d), + glam::Vec3::new(-d, d, -d), + glam::Vec3::new(-d, -d, -d), + glam::Vec3::new(-d, -d, d), + ], + ), + ( + "4", + [ + glam::Vec3::new(-d, d, d), + glam::Vec3::new(d, d, d), + glam::Vec3::new(d, d, -d), + glam::Vec3::new(-d, d, -d), + ], + ), + ( + "5", + [ + glam::Vec3::new(-d, -d, -d), + glam::Vec3::new(d, -d, -d), + glam::Vec3::new(d, -d, d), + glam::Vec3::new(-d, -d, d), + ], + ), ]; for (index, corners) in faces { - let Some(r) = self.res.atlas.sprites.get(&format!("gui/title/background/panorama_{index}")).copied() else { continue }; + let Some(r) = self + .res + .atlas + .sprites + .get(&format!("gui/title/background/panorama_{index}")) + .copied() + else { + continue; + }; let uv = [[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]]; for (p, uv) in corners.iter().zip(uv) { - out.push(Vertex { pos: p.to_array(), uv, layer: 2, color: 0xFFFF_FFFF, light: 0 }); + out.push(Vertex { + pos: p.to_array(), + uv, + layer: 2, + color: 0xFFFF_FFFF, + light: 0, + }); } } out } /// Equipment attribute modifiers (LivingEntity.collectEquipmentChanges). fn apply_equipment(&mut self) { - let Some(player) = self.player.as_mut() else { return }; + let Some(player) = self.player.as_mut() else { + return; + }; for (attribute, id) in std::mem::take(&mut self.applied_modifiers) { let _ = player.set_modifier(&attribute, &id, 0.0, "add_value", false); } let slots = ["head", "chest", "legs", "feet"]; - let mut equipped: Vec<(Option<&ItemStack>, &str)> = self.armor.iter().zip(slots).map(|(s, n)| (s.as_ref(), n)).collect(); + let mut equipped: Vec<(Option<&ItemStack>, &str)> = self + .armor + .iter() + .zip(slots) + .map(|(s, n)| (s.as_ref(), n)) + .collect(); equipped.push((self.inventory[self.selected].as_ref(), "mainhand")); for (stack, slot) in equipped { - let Some(info) = stack.and_then(|s| self.res.items.get(&s.item)) else { continue }; + let Some(info) = stack.and_then(|s| self.res.items.get(&s.item)) else { + continue; + }; for (attribute, id, amount, op, group) in &info.modifiers { let matches = group == slot || group == "any" @@ -3086,7 +4510,10 @@ impl Game<'_> { if !matches || slot == "mainhand" { continue; } - if player.set_modifier(attribute, id, *amount, op, true).is_ok() { + if player + .set_modifier(attribute, id, *amount, op, true) + .is_ok() + { self.applied_modifiers.push((attribute.clone(), id.clone())); } } @@ -3097,7 +4524,13 @@ impl Game<'_> { fn hurt_armor(&mut self, damage: f32) { let amount = ((damage / 4.0) as u32).max(1); let mut broke = false; - let losses: Vec = (0..4).map(|i| self.armor[i].clone().map_or(amount, |s| self.durability_loss(&s, amount))).collect(); + let losses: Vec = (0..4) + .map(|i| { + self.armor[i] + .clone() + .map_or(amount, |s| self.durability_loss(&s, amount)) + }) + .collect(); for (slot, amount) in self.armor.iter_mut().zip(losses) { if let Some(stack) = slot.as_mut() && let Some(info) = self.res.items.get(&stack.item) @@ -3112,7 +4545,12 @@ impl Game<'_> { } if broke { if let Some(eye) = self.eye_position() { - self.audio.play("minecraft:entity.item.break", Some(eye), 0.8, 0.8 + self.world.random.next_float() * 0.4); + self.audio.play( + "minecraft:entity.item.break", + Some(eye), + 0.8, + 0.8 + self.world.random.next_float() * 0.4, + ); } self.apply_equipment(); } @@ -3124,17 +4562,34 @@ impl Game<'_> { let mut t = 0.0; let mut last = origin.map(|v| v.floor() as i32); while t <= self.reach() { - let p = [origin[0] + dir[0] * t, origin[1] + dir[1] * t, origin[2] + dir[2] * t]; + let p = [ + origin[0] + dir[0] * t, + origin[1] + dir[1] * t, + origin[2] + dir[2] * t, + ]; let b = p.map(|v| v.floor() as i32); if b != last { let state = self.world.block(b[0], b[1], b[2]); let f = self.res.facts.get(state); let face = [last[0] - b[0], last[1] - b[1], last[2] - b[2]]; - if f.fluid != Fluid::None && f.fluid_level == 8 && !f.fluid_falling && !f.waterlogged && f.render_shape != horizon_client::blocks::RenderShape::Model { - return Some(Hit { pos: b, face, point: p }); + if f.fluid != Fluid::None + && f.fluid_level == 8 + && !f.fluid_falling + && !f.waterlogged + && f.render_shape != horizon_client::blocks::RenderShape::Model + { + return Some(Hit { + pos: b, + face, + point: p, + }); } if !self.res.facts.is_air(state) && f.fluid == Fluid::None { - return Some(Hit { pos: b, face, point: p }); + return Some(Hit { + pos: b, + face, + point: p, + }); } last = b; } @@ -3145,7 +4600,9 @@ impl Game<'_> { fn set_state_named(&mut self, pos: [i32; 3], name: &str, keep: &[&str]) -> Result { let registry = &self.res.assets.registry; let old = self.world.block(pos[0], pos[1], pos[2]); - let Some(default) = registry.default_state(name) else { return Ok(false) }; + let Some(default) = registry.default_state(name) else { + return Ok(false); + }; let mut state = registry.state(default).cloned().ok_or("state")?; if let Some(previous) = registry.state(old) { for k in keep { @@ -3174,7 +4631,12 @@ impl Game<'_> { if stack.damage >= info.max_damage { self.inventory[self.selected] = None; if let Some(eye) = self.eye_position() { - self.audio.play("minecraft:entity.item.break", Some(eye), 0.8, 0.8 + self.world.random.next_float() * 0.4); + self.audio.play( + "minecraft:entity.item.break", + Some(eye), + 0.8, + 0.8 + self.world.random.next_float() * 0.4, + ); } } } @@ -3182,9 +4644,17 @@ impl Game<'_> { /// Item use on blocks for tools, buckets and fire starters; returns true if handled. fn use_tool(&mut self, stack: &ItemStack) -> Result { let item = stack.item.trim_start_matches("minecraft:").to_owned(); - let at = |p: [i32; 3]| [f64::from(p[0]) + 0.5, f64::from(p[1]) + 0.5, f64::from(p[2]) + 0.5]; + let at = |p: [i32; 3]| { + [ + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, + ] + }; if item == "bucket" { - let Some(hit) = self.pick_fluid() else { return Ok(false) }; + let Some(hit) = self.pick_fluid() else { + return Ok(false); + }; let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); let f = self.res.facts.get(state).clone(); if f.fluid == Fluid::None || f.fluid_level != 8 || f.fluid_falling { @@ -3194,11 +4664,17 @@ impl Game<'_> { Fluid::Water => ("minecraft:water_bucket", "minecraft:item.bucket.fill"), _ => ("minecraft:lava_bucket", "minecraft:item.bucket.fill_lava"), }; - self.world.set(hit.pos[0], hit.pos[1], hit.pos[2], self.world.air)?; + self.world + .set(hit.pos[0], hit.pos[1], hit.pos[2], self.world.air)?; self.audio.play(sound, Some(at(hit.pos)), 1.0, 1.0); if !self.creative { self.consume_held(); - let filled = ItemStack { item: Arc::from(filled), count: 1, damage: 0, extra: None }; + let filled = ItemStack { + item: Arc::from(filled), + count: 1, + damage: 0, + extra: None, + }; if self.inventory[self.selected].is_none() { self.inventory[self.selected] = Some(filled); } else if let Some(rest) = self.give(filled) @@ -3209,22 +4685,54 @@ impl Game<'_> { } return Ok(true); } - let Some(hit) = self.pick() else { return Ok(false) }; + let Some(hit) = self.pick() else { + return Ok(false); + }; let clicked = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); - let name = self.res.facts.get(clicked).name.trim_start_matches("minecraft:").to_owned(); - let above_air = self.res.facts.is_air(self.world.block(hit.pos[0], hit.pos[1] + 1, hit.pos[2])); + let name = self + .res + .facts + .get(clicked) + .name + .trim_start_matches("minecraft:") + .to_owned(); + let above_air = + self.res + .facts + .is_air(self.world.block(hit.pos[0], hit.pos[1] + 1, hit.pos[2])); if item == "water_bucket" || item == "lava_bucket" { - let target = if self.res.facts.get(clicked).replaceable { hit.pos } else { [hit.pos[0] + hit.face[0], hit.pos[1] + hit.face[1], hit.pos[2] + hit.face[2]] }; + let target = if self.res.facts.get(clicked).replaceable { + hit.pos + } else { + [ + hit.pos[0] + hit.face[0], + hit.pos[1] + hit.face[1], + hit.pos[2] + hit.face[2], + ] + }; let existing = self.world.block(target[0], target[1], target[2]); if !self.res.facts.get(existing).replaceable && !self.res.facts.is_air(existing) { return Ok(true); } - let fluid = if item == "water_bucket" { "minecraft:water" } else { "minecraft:lava" }; + let fluid = if item == "water_bucket" { + "minecraft:water" + } else { + "minecraft:lava" + }; self.set_state_named(target, fluid, &[])?; - let sound = if item == "water_bucket" { "minecraft:item.bucket.empty" } else { "minecraft:item.bucket.empty_lava" }; + let sound = if item == "water_bucket" { + "minecraft:item.bucket.empty" + } else { + "minecraft:item.bucket.empty_lava" + }; self.audio.play(sound, Some(at(target)), 1.0, 1.0); if !self.creative { - self.inventory[self.selected] = Some(ItemStack { item: Arc::from("minecraft:bucket"), count: 1, damage: 0, extra: None }); + self.inventory[self.selected] = Some(ItemStack { + item: Arc::from("minecraft:bucket"), + count: 1, + damage: 0, + extra: None, + }); } return Ok(true); } @@ -3238,41 +4746,78 @@ impl Game<'_> { if let Some(result) = result { self.set_state_named(hit.pos, result, &[])?; if name == "rooted_dirt" { - self.pop_resource([hit.pos[0], hit.pos[1] - 1, hit.pos[2]], ItemStack { item: Arc::from("minecraft:hanging_roots"), count: 1, damage: 0, extra: None }); + self.pop_resource( + [hit.pos[0], hit.pos[1] - 1, hit.pos[2]], + ItemStack { + item: Arc::from("minecraft:hanging_roots"), + count: 1, + damage: 0, + extra: None, + }, + ); } - self.audio.play("minecraft:item.hoe.till", Some(at(hit.pos)), 1.0, 1.0); + self.audio + .play("minecraft:item.hoe.till", Some(at(hit.pos)), 1.0, 1.0); self.damage_held(1); return Ok(true); } } - if item.ends_with("_shovel") && hit.face != [0, -1, 0] && above_air - && matches!(name.as_str(), "grass_block" | "dirt" | "podzol" | "coarse_dirt" | "mycelium" | "rooted_dirt") + if item.ends_with("_shovel") + && hit.face != [0, -1, 0] + && above_air + && matches!( + name.as_str(), + "grass_block" | "dirt" | "podzol" | "coarse_dirt" | "mycelium" | "rooted_dirt" + ) { // ShovelItem.FLATTENABLES self.set_state_named(hit.pos, "minecraft:dirt_path", &[])?; - self.audio.play("minecraft:item.shovel.flatten", Some(at(hit.pos)), 1.0, 1.0); + self.audio + .play("minecraft:item.shovel.flatten", Some(at(hit.pos)), 1.0, 1.0); self.damage_held(1); return Ok(true); } if item.ends_with("_axe") && !name.starts_with("stripped_") { // AxeItem.STRIPPABLES - let strippable = name.ends_with("_log") || name.ends_with("_wood") || name.ends_with("_stem") || name.ends_with("_hyphae") || name == "bamboo_block"; + let strippable = name.ends_with("_log") + || name.ends_with("_wood") + || name.ends_with("_stem") + || name.ends_with("_hyphae") + || name == "bamboo_block"; let stripped = format!("minecraft:stripped_{name}"); if strippable && self.res.assets.registry.default_state(&stripped).is_some() { self.set_state_named(hit.pos, &stripped, &["axis"])?; - self.audio.play("minecraft:item.axe.strip", Some(at(hit.pos)), 1.0, 1.0); + self.audio + .play("minecraft:item.axe.strip", Some(at(hit.pos)), 1.0, 1.0); self.damage_held(1); return Ok(true); } } if item == "flint_and_steel" || item == "fire_charge" { - let target = [hit.pos[0] + hit.face[0], hit.pos[1] + hit.face[1], hit.pos[2] + hit.face[2]]; - if self.res.facts.is_air(self.world.block(target[0], target[1], target[2])) { + let target = [ + hit.pos[0] + hit.face[0], + hit.pos[1] + hit.face[1], + hit.pos[2] + hit.face[2], + ]; + if self + .res + .facts + .is_air(self.world.block(target[0], target[1], target[2])) + { if !self.try_light_portal(target)? { self.set_state_named(target, "minecraft:fire", &[])?; } - let sound = if item == "fire_charge" { "minecraft:item.firecharge.use" } else { "minecraft:item.flintandsteel.use" }; - self.audio.play(sound, Some(at(target)), 1.0, self.world.random.next_float() * 0.4 + 0.8); + let sound = if item == "fire_charge" { + "minecraft:item.firecharge.use" + } else { + "minecraft:item.flintandsteel.use" + }; + self.audio.play( + sound, + Some(at(target)), + 1.0, + self.world.random.next_float() * 0.4 + 0.8, + ); if item == "fire_charge" { self.consume_held(); } else { @@ -3282,7 +4827,12 @@ impl Game<'_> { } } // Equippable items swap into their armor slot (Equippable.swapWithEquipmentSlot). - if let Some(slot) = self.res.items.get(&stack.item).and_then(|i| i.equip_slot.clone()) { + if let Some(slot) = self + .res + .items + .get(&stack.item) + .and_then(|i| i.equip_slot.clone()) + { let index = match slot.as_str() { "head" => 0, "chest" => 1, @@ -3294,7 +4844,8 @@ impl Game<'_> { self.inventory[self.selected] = self.armor[index].take(); self.armor[index] = held; if let Some(eye) = self.eye_position() { - self.audio.play("minecraft:item.armor.equip_generic", Some(eye), 1.0, 1.0); + self.audio + .play("minecraft:item.armor.equip_generic", Some(eye), 1.0, 1.0); } self.apply_equipment(); return Ok(true); @@ -3311,7 +4862,11 @@ impl Game<'_> { self.orbs.push(ExperienceOrb { position: p, previous: p, - velocity: Vec3::new((r.next_double() * 0.2 - 0.1) * 2.0, r.next_double() * 0.2 * 2.0, (r.next_double() * 0.2 - 0.1) * 2.0), + velocity: Vec3::new( + (r.next_double() * 0.2 - 0.1) * 2.0, + r.next_double() * 0.2 * 2.0, + (r.next_double() * 0.2 - 0.1) * 2.0, + ), value: v, age: 0, on_ground: false, @@ -3324,10 +4879,14 @@ impl Game<'_> { "coal_ore" | "deepslate_coal_ore" => (0, 2), "nether_gold_ore" => (0, 1), "lapis_ore" | "deepslate_lapis_ore" | "nether_quartz_ore" => (2, 5), - "diamond_ore" | "deepslate_diamond_ore" | "emerald_ore" | "deepslate_emerald_ore" => (3, 7), + "diamond_ore" | "deepslate_diamond_ore" | "emerald_ore" | "deepslate_emerald_ore" => { + (3, 7) + } "redstone_ore" | "deepslate_redstone_ore" => (1, 5), "sculk" => (1, 1), - "sculk_catalyst" | "sculk_sensor" | "calibrated_sculk_sensor" | "sculk_shrieker" => (5, 5), + "sculk_catalyst" | "sculk_sensor" | "calibrated_sculk_sensor" | "sculk_shrieker" => { + (5, 5) + } "spawner" => (15, 43), _ => (0, 0), }; @@ -3341,19 +4900,35 @@ impl Game<'_> { self.xp_delay -= 1; } let player = self.player.as_ref().filter(|p| !p.health.dead_or_dying()); - let target = player.map(|p| [p.position.x, p.position.y + f64::from(p.dimensions.eye_height) / 2.0, p.position.z]); + let target = player.map(|p| { + [ + p.position.x, + p.position.y + f64::from(p.dimensions.eye_height) / 2.0, + p.position.z, + ] + }); let bounds = player.map(|p| { let w = f64::from(p.dimensions.width) / 2.0; - ([p.position.x - w, p.position.y, p.position.z - w], [p.position.x + w, p.position.y + f64::from(p.dimensions.height), p.position.z + w]) + ( + [p.position.x - w, p.position.y, p.position.z - w], + [ + p.position.x + w, + p.position.y + f64::from(p.dimensions.height), + p.position.z + w, + ], + ) }); let mut orbs = std::mem::take(&mut self.orbs); orbs.retain_mut(|o| o.tick(&self.world, &self.res.facts, self.collision, target)); let mut gained = 0; if let Some((min, max)) = bounds { orbs.retain(|o| { - let touching = o.position.x + 0.25 > min[0] && o.position.x - 0.25 < max[0] - && o.position.y + 0.5 > min[1] && o.position.y < max[1] - && o.position.z + 0.25 > min[2] && o.position.z - 0.25 < max[2]; + let touching = o.position.x + 0.25 > min[0] + && o.position.x - 0.25 < max[0] + && o.position.y + 0.5 > min[1] + && o.position.y < max[1] + && o.position.z + 0.25 > min[2] + && o.position.z - 0.25 < max[2]; if touching && self.xp_delay == 0 { // ExperienceOrb.playerTouch: one orb every 2 ticks. self.xp_delay = 2; @@ -3369,12 +4944,22 @@ impl Game<'_> { } if gained > 0 { let at = self.eye_position(); - let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.35 + 0.9; - self.audio.play("minecraft:entity.experience_orb.pickup", at, 0.1, pitch); - if self.experience.give(gained as i32) && self.experience.level % 5 == 0 && self.ticks > self.last_level_up + 100 { + let pitch = + (self.world.random.next_float() - self.world.random.next_float()) * 0.35 + 0.9; + self.audio + .play("minecraft:entity.experience_orb.pickup", at, 0.1, pitch); + if self.experience.give(gained as i32) + && self.experience.level % 5 == 0 + && self.ticks > self.last_level_up + 100 + { self.last_level_up = self.ticks; - let volume = if self.experience.level > 30 { 1.0 } else { self.experience.level as f32 / 30.0 }; - self.audio.play("minecraft:entity.player.levelup", at, volume * 0.75, 1.0); + let volume = if self.experience.level > 30 { + 1.0 + } else { + self.experience.level as f32 / 30.0 + }; + self.audio + .play("minecraft:entity.player.levelup", at, volume * 0.75, 1.0); } } } @@ -3385,21 +4970,47 @@ impl Game<'_> { if power < 0.1 { return; } - let arrow_slot = self.inventory.iter().position(|s| s.as_ref().is_some_and(|s| &*s.item == "minecraft:arrow")); + let arrow_slot = self + .inventory + .iter() + .position(|s| s.as_ref().is_some_and(|s| &*s.item == "minecraft:arrow")); if arrow_slot.is_none() && !self.creative { return; } - let Some(eye) = self.eye_position() else { return }; + let Some(eye) = self.eye_position() else { + return; + }; // BowItem.shootProjectile: shootFromRotation(power * 3, inaccuracy 1). let p = Vec3::new(eye[0], eye[1] - 0.1, eye[2]); let (power_bonus, infinity) = self.bow_enchantments(); - let kind = horizon_client::projectiles::ProjectileKind::Arrow { base_damage: 2.0 + power_bonus, critical: power >= 1.0, effect: None }; - let mut arrow = horizon_client::projectiles::Projectile::new(kind, p, Some(horizon_client::mobs::Who::Player)); - let (velocity, on_ground) = self.player.as_ref().map_or((Vec3::ZERO, true), |pl| (pl.velocity, pl.ground.on_ground)); - arrow.shoot_from_rotation(&mut self.world.random, self.pitch, self.yaw, 0.0, power * 3.0, 1.0, velocity, on_ground); + let kind = horizon_client::projectiles::ProjectileKind::Arrow { + base_damage: 2.0 + power_bonus, + critical: power >= 1.0, + effect: None, + }; + let mut arrow = horizon_client::projectiles::Projectile::new( + kind, + p, + Some(horizon_client::mobs::Who::Player), + ); + let (velocity, on_ground) = self + .player + .as_ref() + .map_or((Vec3::ZERO, true), |pl| (pl.velocity, pl.ground.on_ground)); + arrow.shoot_from_rotation( + &mut self.world.random, + self.pitch, + self.yaw, + 0.0, + power * 3.0, + 1.0, + velocity, + on_ground, + ); self.creatures.projectiles.push(arrow); let pitch = 1.0 / (self.world.random.next_float() * 0.4 + 1.2) + power * 0.5; - self.audio.play("minecraft:entity.arrow.shoot", Some(eye), 1.0, pitch); + self.audio + .play("minecraft:entity.arrow.shoot", Some(eye), 1.0, pitch); if !self.creative && !infinity && let Some(i) = arrow_slot @@ -3450,9 +5061,14 @@ impl Game<'_> { } 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 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 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 { @@ -3471,12 +5087,22 @@ impl Game<'_> { 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 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)) + 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; @@ -3490,27 +5116,54 @@ impl Game<'_> { /// space, converted to camera-relative world space. fn hand_geometry(&mut self, alpha: f64) -> Vec { let mut out = Vec::new(); - if self.player.as_ref().is_none_or(|p| p.health.dead_or_dying()) || self.screen == Screen::Dead { + if self + .player + .as_ref() + .is_none_or(|p| p.health.dead_or_dying()) + || self.screen == Screen::Dead + { return out; } let a = alpha as f32; let attack = self.swing_anim.0 + (self.swing_anim.1 - self.swing_anim.0) * a; - let attack = if self.swing.is_none() && self.swing_anim.1 == 0.0 { 0.0 } else { attack }; + let attack = if self.swing.is_none() && self.swing_anim.1 == 0.0 { + 0.0 + } else { + attack + }; let height = self.hand_height.0 + (self.hand_height.1 - self.hand_height.0) * a; let inverse_height = 1.0 - height; let (yaw, pitch) = (self.yaw.to_radians(), self.pitch.to_radians()); - let forward = glam::Vec3::new(-yaw.sin() * pitch.cos(), -pitch.sin(), yaw.cos() * pitch.cos()); + let forward = glam::Vec3::new( + -yaw.sin() * pitch.cos(), + -pitch.sin(), + yaw.cos() * pitch.cos(), + ); let view = glam::Mat4::look_to_rh(glam::Vec3::ZERO, forward, glam::Vec3::Y); let to_world = view.inverse(); let eye = self.eye_position().unwrap_or_default(); - let light = self.world.light(eye[0].floor() as i32, eye[1].floor() as i32, eye[2].floor() as i32); + let light = self.world.light( + eye[0].floor() as i32, + eye[1].floor() as i32, + eye[2].floor() as i32, + ); let packed = u32::from(light >> 4) * 16 | (u32::from(light & 15) * 16) << 8; let deg = |d: f32| d.to_radians(); let sqrt_attack = attack.sqrt(); match self.hand_item.clone() { None => { - let Some(arm) = self.res.player_arm.clone() else { return out }; - let Some(r) = self.res.atlas.sprites.get("entity/player/wide/steve").copied() else { return out }; + let Some(arm) = self.res.player_arm.clone() else { + return out; + }; + let Some(r) = self + .res + .atlas + .sprites + .get("entity/player/wide/steve") + .copied() + else { + return out; + }; // renderPlayerArm (right arm) let x_swing = -0.3 * (sqrt_attack * std::f32::consts::PI).sin(); let y_swing = 0.4 * (sqrt_attack * std::f32::consts::TAU).sin(); @@ -3518,7 +5171,11 @@ impl Game<'_> { let z_rot = (attack * attack * std::f32::consts::PI).sin(); let y_rot = (sqrt_attack * std::f32::consts::PI).sin(); let m = to_world - * glam::Mat4::from_translation(glam::Vec3::new(x_swing + 0.64, y_swing - 0.6 + inverse_height * -0.6, z_swing - 0.72)) + * glam::Mat4::from_translation(glam::Vec3::new( + x_swing + 0.64, + y_swing - 0.6 + inverse_height * -0.6, + z_swing - 0.72, + )) * glam::Mat4::from_rotation_y(deg(45.0)) * glam::Mat4::from_rotation_y(deg(y_rot * 70.0)) * glam::Mat4::from_rotation_z(deg(z_rot * -20.0)) @@ -3534,10 +5191,20 @@ impl Game<'_> { pose[5] = 0.0; pose }; - horizon_client::mobs::render_model(&arm, m, &pose, [r.u0, r.v0, r.u1, r.v1], packed, 0, &mut out); + horizon_client::mobs::render_model( + &arm, + m, + &pose, + [r.u0, r.v0, r.u1, r.v1], + packed, + 0, + &mut out, + ); } Some(stack) => { - let display = self.display_transform(&stack.item).unwrap_or(([0.0; 3], [0.0; 3], [1.0; 3])); + 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(); @@ -3559,27 +5226,85 @@ impl Game<'_> { * glam::Mat4::from_scale(glam::Vec3::from(scale)) * glam::Mat4::from_translation(glam::Vec3::splat(-0.5)); 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 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 }); + 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::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); + 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 => {} } @@ -3590,7 +5315,10 @@ impl Game<'_> { fn apply_settings(&mut self) { self.streaming.radius = self.settings.render_distance; self.audio.master = self.settings.master_volume; - horizon_client::hud::GUI_SCALE.store(self.settings.gui_scale, std::sync::atomic::Ordering::Relaxed); + horizon_client::hud::GUI_SCALE.store( + self.settings.gui_scale, + std::sync::atomic::Ordering::Relaxed, + ); self.apply_ui_settings(); } /// Whether precipitation at a column is snow (Biome.coldEnoughToSnow: @@ -3601,7 +5329,11 @@ impl Game<'_> { if !b.precipitation { return None; } - let t = if y > 80 { b.temperature - (y - 80) as f32 * 0.05 / 40.0 } else { b.temperature }; + let t = if y > 80 { + b.temperature - (y - 80) as f32 * 0.05 / 40.0 + } else { + b.temperature + }; Some(t < 0.15) } /// The first motion-blocking block from the top (Heightmap MOTION_BLOCKING). @@ -3622,30 +5354,66 @@ impl Game<'_> { self.flash -= 1; } let (rain, thunder) = self.world.weather.levels(1.0); - let Some(eye) = self.eye_position() else { return }; + let Some(eye) = self.eye_position() else { + return; + }; // WeatherEffectRenderer.tickRainParticles: occasional rain sounds. if rain > 0.0 && self.world.random.next_int_bound(3).unwrap_or(1) < (rain * 3.0) as i32 { let r = &mut self.world.random; - let (dx, dz) = (r.next_int_bound(21).unwrap_or(10) - 10, r.next_int_bound(21).unwrap_or(10) - 10); + let (dx, dz) = ( + r.next_int_bound(21).unwrap_or(10) - 10, + r.next_int_bound(21).unwrap_or(10) - 10, + ); let (x, z) = (eye[0].floor() as i32 + dx, eye[2].floor() as i32 + dz); let top = self.rain_height(x, z, eye[1] as i32 + 10); - if self.precipitation(x, top, z) == Some(false) && (top - eye[1] as i32).abs() < 10 && self.world.random.next_int_bound(5).unwrap_or(1) == 0 { + if self.precipitation(x, top, z) == Some(false) + && (top - eye[1] as i32).abs() < 10 + && self.world.random.next_int_bound(5).unwrap_or(1) == 0 + { let above = f64::from(top) > eye[1] + 1.0; - let (name, volume, pitch) = if above { ("minecraft:weather.rain.above", 0.1, 0.5) } else { ("minecraft:weather.rain", 0.2, 1.0) }; - self.audio.play(name, Some([f64::from(x) + 0.5, f64::from(top), f64::from(z) + 0.5]), volume, pitch); + let (name, volume, pitch) = if above { + ("minecraft:weather.rain.above", 0.1, 0.5) + } else { + ("minecraft:weather.rain", 0.2, 1.0) + }; + self.audio.play( + name, + Some([f64::from(x) + 0.5, f64::from(top), f64::from(z) + 0.5]), + volume, + pitch, + ); } } // ServerLevel.tickChunk lightning: 1 in 100000 per chunk per tick while thundering. if thunder > 0.0 && self.world.weather.thundering { let chunks = self.world.chunks.len().max(1) as i32; - if self.world.random.next_int_bound((100_000 / chunks).max(1)).unwrap_or(1) == 0 { + if self + .world + .random + .next_int_bound((100_000 / chunks).max(1)) + .unwrap_or(1) + == 0 + { self.flash = 2; let r = &mut self.world.random; - let (dx, dz) = (f64::from(r.next_int_bound(160).unwrap_or(0) - 80), f64::from(r.next_int_bound(160).unwrap_or(0) - 80)); + let (dx, dz) = ( + f64::from(r.next_int_bound(160).unwrap_or(0) - 80), + f64::from(r.next_int_bound(160).unwrap_or(0) - 80), + ); let at = [eye[0] + dx, eye[1], eye[2] + dz]; let pitch = 0.8 + self.world.random.next_float() * 0.2; - self.audio.play("minecraft:entity.lightning_bolt.thunder", Some(at), 10000.0, pitch); - self.audio.play("minecraft:entity.lightning_bolt.impact", Some(at), 2.0, 0.5 + self.world.random.next_float() * 0.2); + self.audio.play( + "minecraft:entity.lightning_bolt.thunder", + Some(at), + 10000.0, + pitch, + ); + self.audio.play( + "minecraft:entity.lightning_bolt.impact", + Some(at), + 2.0, + 0.5 + self.world.random.next_float() * 0.2, + ); } } } @@ -3656,8 +5424,17 @@ impl Game<'_> { return; } let atlas = &self.res.atlas; - let (Some(rain_tex), Some(snow_tex)) = (atlas.sprites.get("environment/rain").copied(), atlas.sprites.get("environment/snow").copied()) else { return }; - let (cx, cy, cz) = (camera.x.floor() as i32, camera.y.floor() as i32, camera.z.floor() as i32); + let (Some(rain_tex), Some(snow_tex)) = ( + atlas.sprites.get("environment/rain").copied(), + atlas.sprites.get("environment/snow").copied(), + ) else { + return; + }; + let (cx, cy, cz) = ( + camera.x.floor() as i32, + camera.y.floor() as i32, + camera.z.floor() as i32, + ); let radius = 10; let time = self.ticks as f32 + alpha as f32; for dz in -radius..=radius { @@ -3673,8 +5450,17 @@ impl Game<'_> { if y0 >= y1 { continue; } - let Some(snow) = self.precipitation(x, top, z) else { continue }; - let hash = (x.wrapping_mul(x).wrapping_mul(3121).wrapping_add(x.wrapping_mul(45_238_971)) ^ z.wrapping_mul(z).wrapping_mul(418_711).wrapping_add(z.wrapping_mul(13761))) & 31; + let Some(snow) = self.precipitation(x, top, z) else { + continue; + }; + let hash = (x + .wrapping_mul(x) + .wrapping_mul(3121) + .wrapping_add(x.wrapping_mul(45_238_971)) + ^ z.wrapping_mul(z) + .wrapping_mul(418_711) + .wrapping_add(z.wrapping_mul(13761))) + & 31; let r = if snow { snow_tex } else { rain_tex }; // Columns face the camera horizontally. let (fx, fz) = (f64::from(x) + 0.5 - camera.x, f64::from(z) + 0.5 - camera.z); @@ -3691,7 +5477,10 @@ impl Game<'_> { let color = a << 24 | 0xFF_FFFF; let light = self.world.light(x, top.max(cy), z); let packed = u32::from(light >> 4) * 16 | (u32::from(light & 15) * 16) << 8; - let (b, t) = ((f64::from(y0) - camera.y) as f32, (f64::from(y1) - camera.y) as f32); + let (b, t) = ( + (f64::from(y0) - camera.y) as f32, + (f64::from(y1) - camera.y) as f32, + ); let vh = r.v1 - r.v0; let corners = [ center + glam::Vec3::new(-sx, b, -sz), @@ -3705,7 +5494,13 @@ impl Game<'_> { let uv1 = r.v0 + vh * (s0 + 0.25); let uvs = [[r.u0, uv1], [r.u1, uv1], [r.u1, uv0], [r.u0, uv0]]; for (p, uv) in corners.iter().zip(uvs) { - out.push(Vertex { pos: p.to_array(), uv, layer: 0, color, light: packed }); + out.push(Vertex { + pos: p.to_array(), + uv, + layer: 0, + color, + light: packed, + }); } } } @@ -3713,46 +5508,88 @@ impl Game<'_> { /// Player.startSleepInBed: night or thunder, no monsters within 8 blocks; /// the bed becomes the respawn point either way. fn try_sleep(&mut self, pos: [i32; 3]) { - let Some(p) = self.player.as_ref() else { return }; + let Some(p) = self.player.as_ref() else { + return; + }; let time = self.world.day_time.rem_euclid(24000); let night = (12542..23460).contains(&time) || self.world.weather.thundering; let state = self.world.block(pos[0], pos[1], pos[2]); - let props = self.res.assets.registry.state(state).map(|s| s.properties.clone()).unwrap_or_default(); + let props = self + .res + .assets + .registry + .state(state) + .map(|s| s.properties.clone()) + .unwrap_or_default(); let head = if props.get("part").map(String::as_str) == Some("foot") { let d = facing_offset(props.get("facing").map_or("north", String::as_str)); [pos[0] + d[0], pos[1], pos[2] + d[2]] } else { pos }; - self.spawn = Some(Vec3::new(f64::from(head[0]) + 0.5, f64::from(head[1]) + 0.6, f64::from(head[2]) + 0.5)); - self.level.spawn = Some([f64::from(head[0]), f64::from(head[1]) + 1.0, f64::from(head[2])]); - let dist = ((p.position.x - f64::from(head[0]) - 0.5).powi(2) + (p.position.z - f64::from(head[2]) - 0.5).powi(2)).sqrt(); + self.spawn = Some(Vec3::new( + f64::from(head[0]) + 0.5, + f64::from(head[1]) + 0.6, + f64::from(head[2]) + 0.5, + )); + self.level.spawn = Some([ + f64::from(head[0]), + f64::from(head[1]) + 1.0, + f64::from(head[2]), + ]); + let dist = ((p.position.x - f64::from(head[0]) - 0.5).powi(2) + + (p.position.z - f64::from(head[2]) - 0.5).powi(2)) + .sqrt(); if !night { - self.message = Some(("You can sleep only at night or during thunderstorms".into(), Instant::now())); + self.message = Some(( + "You can sleep only at night or during thunderstorms".into(), + Instant::now(), + )); return; } if dist > 3.0 { - self.message = Some(("You may not rest now; the bed is too far away".into(), Instant::now())); + self.message = Some(( + "You may not rest now; the bed is too far away".into(), + Instant::now(), + )); return; } let monsters = self.mobs.iter().any(|m| { - m.hostile() && m.alive() && (m.position.x - p.position.x).abs() < 8.0 && (m.position.y - p.position.y).abs() < 5.0 && (m.position.z - p.position.z).abs() < 8.0 + m.hostile() + && m.alive() + && (m.position.x - p.position.x).abs() < 8.0 + && (m.position.y - p.position.y).abs() < 5.0 + && (m.position.z - p.position.z).abs() < 8.0 }); if monsters { - self.message = Some(("You may not rest now; there are monsters nearby".into(), Instant::now())); + self.message = Some(( + "You may not rest now; there are monsters nearby".into(), + Instant::now(), + )); return; } self.message = Some(("Respawn point set".into(), Instant::now())); self.sleeping = Some((head, 0)); } fn tick_sleep(&mut self) { - let Some((head, ticks)) = self.sleeping else { return }; - if self.keys.contains(&KeyCode::ShiftLeft) || self.player.as_ref().is_none_or(|p| p.health.dead_or_dying()) { + let Some((head, ticks)) = self.sleeping else { + return; + }; + if self.keys.contains(&KeyCode::ShiftLeft) + || self + .player + .as_ref() + .is_none_or(|p| p.health.dead_or_dying()) + { self.sleeping = None; return; } if let Some(p) = self.player.as_mut() { - p.position = Vec3::new(f64::from(head[0]) + 0.5, f64::from(head[1]) + 0.5625, f64::from(head[2]) + 0.5); + p.position = Vec3::new( + f64::from(head[0]) + 0.5, + f64::from(head[1]) + 0.5625, + f64::from(head[2]) + 0.5, + ); p.velocity = Vec3::ZERO; } let ticks = ticks + 1; @@ -3770,7 +5607,10 @@ impl Game<'_> { } } fn creative_origin(batch: &HudBatch) -> (f32, f32) { - ((batch.width - Creative::WIDTH) / 2.0, (batch.height - Creative::HEIGHT) / 2.0) + ( + (batch.width - Creative::WIDTH) / 2.0, + (batch.height - Creative::HEIGHT) / 2.0, + ) } /// Vanilla tooltip: dark box with a purple gradient border. fn tooltip(&self, batch: &mut HudBatch, text: &str, x: f32, y: f32) { @@ -3788,9 +5628,21 @@ impl Game<'_> { let tabs = self.creative_screen.tabs.clone(); let tab = self.creative_screen.tab().clone(); let tab_sprite = |t: &horizon_client::creative::Tab, on: bool| { - format!("gui/sprites/container/creative_inventory/tab_{}_{}_{}", if t.top { "top" } else { "bottom" }, if on { "selected" } else { "unselected" }, t.column + 1) + format!( + "gui/sprites/container/creative_inventory/tab_{}_{}_{}", + if t.top { "top" } else { "bottom" }, + if on { "selected" } else { "unselected" }, + t.column + 1 + ) }; - batch.fill(&self.res.atlas, 0.0, 0.0, batch.width, batch.height, rgba(16, 16, 16, 160)); + batch.fill( + &self.res.atlas, + 0.0, + 0.0, + batch.width, + batch.height, + rgba(16, 16, 16, 160), + ); // Unselected tabs behind the panel, then the panel, then the selected tab. for (i, t) in tabs.iter().enumerate() { if i != selected { @@ -3814,11 +5666,28 @@ impl Game<'_> { batch.sprite(&self.res.atlas, &tab_sprite(&tab, true), ox + tx, oy + ty); for t in &tabs { let (tx, ty) = Creative::tab_position(t); - let stack = ItemStack { item: Arc::from(t.icon.as_str()), count: 1, damage: 0, extra: None }; - self.draw_item(batch, &stack, ox + tx + 5.0, oy + ty + if t.top { 9.0 } else { 7.0 }); + let stack = ItemStack { + item: Arc::from(t.icon.as_str()), + count: 1, + damage: 0, + extra: None, + }; + self.draw_item( + batch, + &stack, + ox + tx + 5.0, + oy + ty + if t.top { 9.0 } else { 7.0 }, + ); } let atlas = &self.res.atlas; - batch.text(atlas, &tab.title, ox + 8.0, oy + 6.0, rgba(64, 64, 64, 255), false); + batch.text( + atlas, + &tab.title, + ox + 8.0, + oy + 6.0, + rgba(64, 64, 64, 255), + false, + ); if tab.search { let shown = format!("{}_", self.creative_screen.search); batch.text(atlas, &shown, ox + 82.0, oy + 6.0, u32::MAX, true); @@ -3828,11 +5697,22 @@ impl Game<'_> { let mut hovered: Option = None; for r in 0..5 { for c in 0..9 { - let Some(item) = items.get((first + r) * 9 + c) else { continue }; + let Some(item) = items.get((first + r) * 9 + c) else { + continue; + }; let (x, y) = (ox + 9.0 + c as f32 * 18.0, oy + 18.0 + r as f32 * 18.0); - let stack = ItemStack { item: Arc::from(item.as_str()), count: 1, damage: 0, extra: None }; + let stack = ItemStack { + item: Arc::from(item.as_str()), + count: 1, + damage: 0, + extra: None, + }; self.draw_item(batch, &stack, x, y); - if self.cursor.0 >= x && self.cursor.0 < x + 16.0 && self.cursor.1 >= y && self.cursor.1 < y + 16.0 { + if self.cursor.0 >= x + && self.cursor.0 < x + 16.0 + && self.cursor.1 >= y + && self.cursor.1 < y + 16.0 + { batch.fill(&self.res.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); hovered = Some(item.clone()); } @@ -3842,7 +5722,11 @@ impl Game<'_> { let (x, y) = (ox + 9.0 + c as f32 * 18.0, oy + 112.0); if let Some(stack) = self.inventory[c].clone() { self.draw_item(batch, &stack, x, y); - if self.cursor.0 >= x && self.cursor.0 < x + 16.0 && self.cursor.1 >= y && self.cursor.1 < y + 16.0 { + if self.cursor.0 >= x + && self.cursor.0 < x + 16.0 + && self.cursor.1 >= y + && self.cursor.1 < y + 16.0 + { hovered = Some(stack.item.to_string()); } } @@ -3853,10 +5737,19 @@ impl Game<'_> { } else { "gui/sprites/container/creative_inventory/scroller_disabled" }; - batch.sprite(&self.res.atlas, scroller, ox + 175.0, oy + 18.0 + self.creative_screen.scroll * (112.0 - 15.0)); + batch.sprite( + &self.res.atlas, + scroller, + ox + 175.0, + oy + 18.0 + self.creative_screen.scroll * (112.0 - 15.0), + ); for t in &tabs { let (tx, ty) = Creative::tab_position(t); - if self.cursor.0 >= ox + tx && self.cursor.0 < ox + tx + 26.0 && self.cursor.1 >= oy + ty && self.cursor.1 < oy + ty + 32.0 { + if self.cursor.0 >= ox + tx + && self.cursor.0 < ox + tx + 26.0 + && self.cursor.1 >= oy + ty + && self.cursor.1 < oy + ty + 32.0 + { self.tooltip(batch, &t.title, self.cursor.0, self.cursor.1); } } @@ -3868,7 +5761,13 @@ impl Game<'_> { } } fn click_creative(&mut self, right: bool) { - let Some(size) = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]) else { return }; + let Some(size) = self + .renderer + .as_ref() + .map(|r| [r.config.width, r.config.height]) + else { + return; + }; let batch = HudBatch::new(size); let (ox, oy) = Self::creative_origin(&batch); let (cx, cy) = self.cursor; @@ -3902,9 +5801,16 @@ impl Game<'_> { if self.carried.take().is_some() { return; } - let Some(item) = items.get((first + r) * 9 + c) else { return }; + let Some(item) = items.get((first + r) * 9 + c) else { + return; + }; let max = self.res.items.get(item).map_or(64, |i| i.max_stack); - let stack = ItemStack { item: Arc::from(item.as_str()), count: if right { 1 } else { max }, damage: 0, extra: None }; + let stack = ItemStack { + item: Arc::from(item.as_str()), + count: if right { 1 } else { max }, + damage: 0, + extra: None, + }; if shift { let _ = self.give(stack); } else { @@ -3935,7 +5841,8 @@ impl Game<'_> { .filter_map(|k| self.world.chunks.get(k)) .map(|c| self.with_entities(c)) .collect(); - self.save.save(&chunks, &self.res.assets.registry, &self.res.biomes)?; + self.save + .save(&chunks, &self.res.assets.registry, &self.res.biomes)?; self.save_entities()?; self.level.selected_slot = self.selected as i32; let level = &mut self.level; @@ -3958,27 +5865,55 @@ impl Game<'_> { .inventory .iter() .enumerate() - .filter_map(|(i, s)| s.as_ref().map(|s| (i as u8, s.item.to_string(), s.count, s.damage))) + .filter_map(|(i, s)| { + s.as_ref() + .map(|s| (i as u8, s.item.to_string(), s.count, s.damage)) + }) + .collect(); + level.inventory_components = self + .inventory + .iter() + .enumerate() + .filter_map(|(i, s)| Some((i as u8, s.as_ref()?.extra.clone()?))) .collect(); - level.inventory_components = self.inventory.iter().enumerate().filter_map(|(i, s)| Some((i as u8, s.as_ref()?.extra.clone()?))).collect(); // Vanilla stores armor in slots 100 (feet) to 103 (head). for (i, s) in self.armor.iter().enumerate() { if let Some(s) = s { - level.inventory.push((103 - i as u8, s.item.to_string(), s.count, s.damage)); + level + .inventory + .push((103 - i as u8, s.item.to_string(), s.count, s.damage)); if let Some(extra) = s.extra.clone() { level.inventory_components.insert(103 - i as u8, extra); } } } level.dimension = self.dim.id().to_owned(); - level.active_effects = self.potions.effects.list.iter().map(|e| (format!("minecraft:{}", e.id), e.duration, e.amplifier, e.ambient, e.visible)).collect(); + level.active_effects = self + .potions + .effects + .list + .iter() + .map(|e| { + ( + format!("minecraft:{}", e.id), + e.duration, + e.amplifier, + e.ambient, + e.visible, + ) + }) + .collect(); level.write(&self.world_root)?; self.save_world_state(); self.message = Some(("Saved the game".into(), Instant::now())); Ok(()) } fn render(&mut self) -> Result { - let Some(size) = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]) else { + let Some(size) = self + .renderer + .as_ref() + .map(|r| [r.config.width, r.config.height]) + else { return Ok(false); }; let alpha = self.clock.fraction(); @@ -3991,14 +5926,20 @@ impl Game<'_> { a.y + (b.y - a.y) * alpha + f64::from(eye), a.z + (b.z - a.z) * alpha, ); - let s = self.world.block(c.x.floor() as i32, c.y.floor() as i32, c.z.floor() as i32); + let s = + self.world + .block(c.x.floor() as i32, c.y.floor() as i32, c.z.floor() as i32); (c, self.res.facts.get(s).fluid == Fluid::Water) } None => (glam::DVec3::new(0.5, 100.0, 0.5), false), }; self.audio.listener = [camera.x, camera.y, camera.z]; self.audio.listener_yaw = self.yaw; - let block = [camera.x.floor() as i32, camera.y.floor() as i32, camera.z.floor() as i32]; + let block = [ + camera.x.floor() as i32, + camera.y.floor() as i32, + camera.z.floor() as i32, + ]; let biome = self .world .chunks @@ -4008,7 +5949,11 @@ impl Game<'_> { let info = self.res.biomes.get(biome).clone(); let environment = self.dim_environment(); let mut sky = environment.sample(self.world.day_time, info.sky, info.fog); - let (rain, thunder) = if self.dim == Dim::Overworld { self.world.weather.levels(alpha as f32) } else { (0.0, 0.0) }; + let (rain, thunder) = if self.dim == Dim::Overworld { + self.world.weather.levels(alpha as f32) + } else { + (0.0, 0.0) + }; horizon_client::environment::apply_weather(&mut sky, rain, thunder); self.end_flash_sky(&mut sky, alpha); if self.flash > 0 { @@ -4026,7 +5971,11 @@ impl Game<'_> { }; let hud = self.hud(size); let title = self.title.is_some(); - let entities = if title { Vec::new() } else { self.entity_geometry(camera, alpha) }; + let entities = if title { + Vec::new() + } else { + self.entity_geometry(camera, alpha) + }; let celestial = if title { self.panorama_geometry() } else if self.dim == Dim::Overworld { @@ -4036,8 +5985,16 @@ impl Game<'_> { } else { Vec::new() }; - let hand = if title || self.screen == Screen::Inventory { Vec::new() } else { self.hand_geometry(alpha) }; - let screen = if title { Vec::new() } else { self.screen_quads(alpha as f32, size) }; + let hand = if title || self.screen == Screen::Inventory { + Vec::new() + } else { + self.hand_geometry(alpha) + }; + let screen = if title { + Vec::new() + } else { + self.screen_quads(alpha as f32, size) + }; let mut entities = entities; if !title { self.end_geometry(camera, &mut entities); @@ -4047,10 +6004,18 @@ impl Game<'_> { self.weather_geometry(camera, alpha, &mut entities); } // PanoramaRenderer: the title cube spins at 0.1 degrees per tick, pitched 10 degrees. - let (yaw, pitch) = if title { (-(self.started.elapsed().as_secs_f32() * 2.0) % 360.0, 10.0) } else { (self.yaw, self.pitch) }; + let (yaw, pitch) = if title { + (-(self.started.elapsed().as_secs_f32() * 2.0) % 360.0, 10.0) + } else { + (self.yaw, self.pitch) + }; let water_fog = { let c = info.water_fog; - [(c >> 16 & 255) as f32 / 255.0, (c >> 8 & 255) as f32 / 255.0, (c & 255) as f32 / 255.0] + [ + (c >> 16 & 255) as f32 / 255.0, + (c >> 8 & 255) as f32 / 255.0, + (c & 255) as f32 / 255.0, + ] }; let frame = Frame { camera, @@ -4059,7 +6024,10 @@ impl Game<'_> { fov_degrees: if title { 85.0 } else { self.settings.fov }, 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) + ( + self.walk.0 + (self.walk.1 - self.walk.0) * a, + self.bob.0 + (self.bob.1 - self.bob.0) * a, + ) }), sky, distance: (self.streaming.radius * 16) as f32, @@ -4069,7 +6037,11 @@ impl Game<'_> { end_sky: self.dim == Dim::End, environment_fog: (self.dim == Dim::Nether).then_some((sky.fog_start, sky.fog_end)), // The camera inside an opaque block sees nothing through it: disable. - cave_culling: !self.res.facts.get(self.world.block(block[0], block[1], block[2])).solid_render, + cave_culling: !self + .res + .facts + .get(self.world.block(block[0], block[1], block[2])) + .solid_render, water_fog, fog: Some(self.frame_fog(camera, &sky, biome)), dark_disc: self.dark_disc(camera), @@ -4114,10 +6086,15 @@ impl Game<'_> { KeyCode::F1 => self.toggle_hide_gui(), KeyCode::F11 => self.toggle_fullscreen(), KeyCode::F2 => self.take_screenshot(), - KeyCode::KeyE if self.screen == Screen::Creative && self.creative_screen.tab().search => {} + KeyCode::KeyE + if self.screen == Screen::Creative && self.creative_screen.tab().search => {} KeyCode::KeyE => match self.screen { Screen::Playing => { - self.screen = if self.creative { Screen::Creative } else { Screen::Inventory }; + self.screen = if self.creative { + Screen::Creative + } else { + Screen::Inventory + }; self.capture(false); } Screen::Creative => { @@ -4139,7 +6116,15 @@ impl Game<'_> { let all = self.keys.contains(&KeyCode::ControlLeft); self.drop_held(all); } - KeyCode::Digit1 | KeyCode::Digit2 | KeyCode::Digit3 | KeyCode::Digit4 | KeyCode::Digit5 | KeyCode::Digit6 | KeyCode::Digit7 | KeyCode::Digit8 | KeyCode::Digit9 => { + KeyCode::Digit1 + | KeyCode::Digit2 + | KeyCode::Digit3 + | KeyCode::Digit4 + | KeyCode::Digit5 + | KeyCode::Digit6 + | KeyCode::Digit7 + | KeyCode::Digit8 + | KeyCode::Digit9 => { self.selected = match key { KeyCode::Digit1 => 0, KeyCode::Digit2 => 1, @@ -4183,7 +6168,12 @@ impl Game<'_> { let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); let item = self.res.facts.get(state).item.clone(); if &*item != "minecraft:air" { - self.inventory[self.selected] = Some(ItemStack { item, count: 1, damage: 0, extra: None }); + self.inventory[self.selected] = Some(ItemStack { + item, + count: 1, + damage: 0, + extra: None, + }); } } } @@ -4196,7 +6186,10 @@ impl Game<'_> { eprintln!("Horizon: {e}"); } if let Some(p) = &self.player { - self.streaming.center = ((p.position.x.floor() as i32) >> 4, (p.position.z.floor() as i32) >> 4); + self.streaming.center = ( + (p.position.x.floor() as i32) >> 4, + (p.position.z.floor() as i32) >> 4, + ); } let (uploads, unloaded) = self.streaming.update(&mut self.world); let dirty: Vec<_> = unloaded @@ -4207,10 +6200,14 @@ impl Game<'_> { let modified: Vec<_> = dirty.iter().map(|c| self.with_entities(c)).collect(); self.unload_entities(&unloaded); for c in &unloaded { - self.world.block_entities.retain(|p, _| !(p.0 >> 4 == c.x && p.2 >> 4 == c.z)); + self.world + .block_entities + .retain(|p, _| !(p.0 >> 4 == c.x && p.2 >> 4 == c.z)); } if !modified.is_empty() - && let Err(e) = self.save.save(&modified, &self.res.assets.registry, &self.res.biomes) + && let Err(e) = self + .save + .save(&modified, &self.res.assets.registry, &self.res.biomes) { eprintln!("Horizon: failed to save unloaded chunks: {e}"); } @@ -4250,7 +6247,11 @@ impl ApplicationHandler for Game<'_> { assets.sprite_size, assets.texture_layers, &assets.animations, - (&self.res.atlas.pixels, self.res.atlas.width, self.res.atlas.height), + ( + &self.res.atlas.pixels, + self.res.atlas.width, + self.res.atlas.height, + ), )) { Ok(r) => self.renderer = Some(r), Err(e) => { @@ -4286,7 +6287,10 @@ impl ApplicationHandler for Game<'_> { self.left = false; self.right = false; self.capture(false); - if self.screen == Screen::Playing && self.player.is_some() && !self.options.no_pause { + if self.screen == Screen::Playing + && self.player.is_some() + && !self.options.no_pause + { self.screen = Screen::Paused; } } @@ -4313,42 +6317,70 @@ impl ApplicationHandler for Game<'_> { self.options_scroll(d); } if self.screen == Screen::Creative && d != 0.0 { - let rows = self.creative_screen.rows(&self.res.names).saturating_sub(5).max(1) as f32; - self.creative_screen.scroll = (self.creative_screen.scroll - d.signum() / rows).clamp(0.0, 1.0); + let rows = self + .creative_screen + .rows(&self.res.names) + .saturating_sub(5) + .max(1) as f32; + self.creative_screen.scroll = + (self.creative_screen.scroll - d.signum() / rows).clamp(0.0, 1.0); } if self.screen == Screen::Inventory && d != 0.0 { self.station_scroll(d); } if self.screen == Screen::Playing && d != 0.0 { - self.selected = (self.selected as i32 - d.signum() as i32).rem_euclid(9) as usize; + self.selected = + (self.selected as i32 - d.signum() as i32).rem_euclid(9) as usize; } } WindowEvent::MouseInput { state, button, .. } if self.screen == Screen::Options => { if self.options_waiting_for_key() && state == ElementState::Pressed { self.options_bind_mouse(button)?; } else if matches!(button, MouseButton::Left | MouseButton::Right) { - self.options_mouse(state == ElementState::Pressed, button == MouseButton::Right)?; + self.options_mouse( + state == ElementState::Pressed, + button == MouseButton::Right, + )?; } } - WindowEvent::MouseInput { state, button: MouseButton::Left, .. } - if self.title.is_some() && state == ElementState::Pressed => - { - let size = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]).unwrap_or([1, 1]); + WindowEvent::MouseInput { + state, + button: MouseButton::Left, + .. + } if self.title.is_some() && state == ElementState::Pressed => { + let size = self + .renderer + .as_ref() + .map(|r| [r.config.width, r.config.height]) + .unwrap_or([1, 1]); let b = HudBatch::new(size); - let action = self.title.as_mut().map_or(Action::None, |t| t.click(self.cursor.0, self.cursor.1, (b.width, b.height))); + let action = self.title.as_mut().map_or(Action::None, |t| { + t.click(self.cursor.0, self.cursor.1, (b.width, b.height)) + }); match action { Action::Quit => event_loop.exit(), Action::Options => self.open_options(true), Action::Play { folder } => self.open_world(&folder, None, None, false)?, - Action::Create { folder, name, seed, creative } => self.open_world(&folder, Some(&name), seed, creative)?, - Action::Connect { address } => self.connect_server(&address, &self.options.player_name.clone())?, + Action::Create { + folder, + name, + seed, + creative, + } => self.open_world(&folder, Some(&name), seed, creative)?, + Action::Connect { address } => { + self.connect_server(&address, &self.options.player_name.clone())? + } Action::None => {} } } WindowEvent::MouseInput { .. } if self.title.is_some() => {} WindowEvent::MouseInput { state, button, .. } if self.sign_edit.is_some() => { if state == ElementState::Pressed && button == MouseButton::Left { - let size = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]).unwrap_or([1, 1]); + let size = self + .renderer + .as_ref() + .map(|r| [r.config.width, r.config.height]) + .unwrap_or([1, 1]); self.sign_edit_click(size); } } @@ -4387,7 +6419,9 @@ impl ApplicationHandler for Game<'_> { _ => {} } } - WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::Chat && self.title.is_none() => { + WindowEvent::KeyboardInput { event, .. } + if self.screen == Screen::Chat && self.title.is_none() => + { if let PhysicalKey::Code(key) = event.physical_key { if event.state == ElementState::Pressed { self.keys.insert(key); @@ -4397,9 +6431,13 @@ impl ApplicationHandler for Game<'_> { } } } - WindowEvent::KeyboardInput { event, .. } if self.sign_edit.is_some() => self.sign_edit_key(&event), + WindowEvent::KeyboardInput { event, .. } if self.sign_edit.is_some() => { + self.sign_edit_key(&event) + } WindowEvent::KeyboardInput { event, .. } - if self.screen == Screen::Creative && self.creative_screen.tab().search && event.state == ElementState::Pressed + if self.screen == Screen::Creative + && self.creative_screen.tab().search + && event.state == ElementState::Pressed && !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) => { match event.physical_key { @@ -4408,21 +6446,26 @@ impl ApplicationHandler for Game<'_> { } _ => { if let Some(text) = &event.text { - self.creative_screen.search.extend(text.chars().filter(|c| !c.is_control())); + self.creative_screen + .search + .extend(text.chars().filter(|c| !c.is_control())); } } } self.creative_screen.scroll = 0.0; } WindowEvent::KeyboardInput { event, .. } - if self.station_typing() && event.state == ElementState::Pressed + if self.station_typing() + && event.state == ElementState::Pressed && !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) => { // The anvil rename box takes every key but Escape (AnvilScreen.keyPressed). let backspace = event.physical_key == PhysicalKey::Code(KeyCode::Backspace); self.station_text(event.text.as_deref(), backspace); } - WindowEvent::KeyboardInput { event, .. } if self.remote_chat_open() => self.remote_chat_key(&event), + WindowEvent::KeyboardInput { event, .. } if self.remote_chat_open() => { + self.remote_chat_key(&event) + } WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::Options => { if event.state == ElementState::Pressed && let PhysicalKey::Code(key) = event.physical_key @@ -4447,7 +6490,9 @@ impl ApplicationHandler for Game<'_> { } } WindowEvent::KeyboardInput { event, .. } => { - let PhysicalKey::Code(key) = event.physical_key else { return Ok(()) }; + let PhysicalKey::Code(key) = event.physical_key else { + return Ok(()); + }; // Key binds: act as the default key of the bound mapping. let key = match self.settings.keys.translate(key) { Some(Ok(k)) => k, @@ -4476,8 +6521,11 @@ impl ApplicationHandler for Game<'_> { // Arrow keys turn the camera (accessibility / scripted testing). let turn = |k| f32::from(u8::from(self.keys.contains(&k))); let secs = elapsed.as_secs_f32().min(0.1); - self.yaw += (turn(KeyCode::ArrowRight) - turn(KeyCode::ArrowLeft)) * 90.0 * secs; - self.pitch = (self.pitch + (turn(KeyCode::ArrowDown) - turn(KeyCode::ArrowUp)) * 90.0 * secs).clamp(-90.0, 90.0); + self.yaw += + (turn(KeyCode::ArrowRight) - turn(KeyCode::ArrowLeft)) * 90.0 * secs; + self.pitch = (self.pitch + + (turn(KeyCode::ArrowDown) - turn(KeyCode::ArrowUp)) * 90.0 * secs) + .clamp(-90.0, 90.0); if self.title.is_none() { self.update_world(); self.spawn_player()?; @@ -4491,7 +6539,10 @@ impl ApplicationHandler for Game<'_> { self.tick_music(); } let rendered = self.render()?; - let finished = self.renderer.as_mut().and_then(|r| r.screenshot_result.take()); + let finished = self + .renderer + .as_mut() + .and_then(|r| r.screenshot_result.take()); if let Some(result) = &finished && self.ui.screenshot_message.is_some() { @@ -4500,10 +6551,15 @@ impl ApplicationHandler for Game<'_> { if let Some(result) = finished && let Some(reply) = self.pending_screenshot.take() { - let _ = reply.send(match result { - Ok([w, h]) => serde_json::json!({ "ok": true, "width": w, "height": h }), - Err(e) => serde_json::json!({ "error": e }), - }.to_string()); + let _ = reply.send( + match result { + Ok([w, h]) => { + serde_json::json!({ "ok": true, "width": w, "height": h }) + } + Err(e) => serde_json::json!({ "error": e }), + } + .to_string(), + ); } if rendered { self.frame_stats.record(elapsed.as_secs_f32() * 1000.0); @@ -4559,7 +6615,9 @@ impl ApplicationHandler for Game<'_> { } } pub fn run() -> Result<()> { - let Some(mut options) = Options::read()? else { return Ok(()) }; + let Some(mut options) = Options::read()? else { + return Ok(()); + }; let started = Instant::now(); let vanilla_root = options.resources.clone(); let early_settings = Settings::load(&std::env::current_dir()?.join("options.txt")); @@ -4585,7 +6643,10 @@ pub fn run() -> Result<()> { eprintln!("load tables: {:.2}s", started.elapsed().as_secs_f32()); let atlas = HudAtlas::build(&root)?; horizon_client::ui::load_metadata(&root); - horizon_client::lang::set(horizon_client::lang::Language::load(&[&root], &early_settings.language)); + horizon_client::lang::set(horizon_client::lang::Language::load( + &[&root], + &early_settings.language, + )); eprintln!("load atlas: {:.2}s", started.elapsed().as_secs_f32()); let layer_names = assets .sprite_layers @@ -4595,14 +6656,20 @@ pub fn run() -> Result<()> { let registry_owner = assets.clone(); let collision = collisions::load(&root, ®istry_owner.registry)?; let motion = MotionResources::load(&root, ®istry_owner)?; - eprintln!("load collision+motion: {:.2}s", started.elapsed().as_secs_f32()); + eprintln!( + "load collision+motion: {:.2}s", + started.elapsed().as_secs_f32() + ); let context = Arc::new(WorkerContext { assets: assets.clone(), tables, biomes: biomes.clone(), light, }); - let threads = std::thread::available_parallelism().map_or(2, |n| n.get()).saturating_sub(1).max(1); + let threads = std::thread::available_parallelism() + .map_or(2, |n| n.get()) + .saturating_sub(1) + .max(1); eprintln!( "Horizon: resources loaded in {:.1}s; {} block states, {} items, {} biomes; {} worker threads", started.elapsed().as_secs_f32(), @@ -4619,12 +6686,17 @@ pub fn run() -> Result<()> { ); streaming.paused = true; let level = Level::default(); - let save = Arc::new(SaveDir::new(std::env::current_dir()?.join("saves").join(".horizon-title"))); + let save = Arc::new(SaveDir::new( + std::env::current_dir()? + .join("saves") + .join(".horizon-title"), + )); let audio = Audio::new(&root); let world = World::new(facts.air, 0); let creative = options.creative; let stations = horizon_client::stations::StationData::load(&root, &items); - let animate = horizon_client::animate_tick::AnimateTables::load(&root, registry_owner.registry, &biomes)?; + let animate = + horizon_client::animate_tick::AnimateTables::load(&root, registry_owner.registry, &biomes)?; let fog = horizon_client::fog::FogRenderer::load(&root, &biomes); let mut resources = Resources { stations, @@ -4638,7 +6710,10 @@ pub fn run() -> Result<()> { icons: HashMap::new(), layer_names, providers: Providers::load(&root), - block_entity_render: horizon_client::block_entity_render::BlockEntityRenderer::load(&root, ®istry_owner.registry)?, + block_entity_render: horizon_client::block_entity_render::BlockEntityRenderer::load( + &root, + ®istry_owner.registry, + )?, animate, fog, music: horizon_client::music::MusicTables::load(&root), @@ -4648,10 +6723,16 @@ pub fn run() -> Result<()> { end_environment: Environment::load_dimension(&root, "the_end", false)?, behaviours: Behaviours::load(registry_owner.registry, &root)?, names: Names::load(&root), - clouds: horizon_client::hud::decode(&root.join("assets/minecraft/textures/environment/clouds.png")) - .map(|(w, h, px)| (w, h, px.chunks_exact(4).map(|p| p[3] > 0).collect())) - .unwrap_or((1, 1, vec![false])), - mob_types: MobTypes::load(&root)?.types.into_iter().map(|(k, v)| (k, Arc::new(v))).collect(), + clouds: horizon_client::hud::decode( + &root.join("assets/minecraft/textures/environment/clouds.png"), + ) + .map(|(w, h, px)| (w, h, px.chunks_exact(4).map(|p| p[3] > 0).collect())) + .unwrap_or((1, 1, vec![false])), + mob_types: MobTypes::load(&root)? + .types + .into_iter() + .map(|(k, v)| (k, Arc::new(v))) + .collect(), mob_data, context, threads, @@ -4785,7 +6866,10 @@ pub fn run() -> Result<()> { } match game.options.world.clone() { _ if game.options.server.is_some() => { - let (address, name) = (game.options.server.clone().unwrap_or_default(), game.options.player_name.clone()); + let (address, name) = ( + game.options.server.clone().unwrap_or_default(), + game.options.player_name.clone(), + ); game.connect_server(&address, &name)?; } Some(folder) => { diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 8424d957d..c7a043d66 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -9,7 +9,10 @@ use horizon_client::{ text::Text, }; use std::collections::BTreeMap; -use winit::{event::KeyEvent, keyboard::{KeyCode, PhysicalKey}}; +use winit::{ + event::KeyEvent, + keyboard::{KeyCode, PhysicalKey}, +}; /// The local player's name (offline single player). pub const PLAYER_NAME: &str = "Player"; @@ -24,7 +27,11 @@ pub struct WorldClock { } impl Default for WorldClock { fn default() -> Self { - Self { partial: 0.0, rate: 1.0, paused: false } + Self { + partial: 0.0, + rate: 1.0, + paused: false, + } } } /// A clock time marker from the timelines (ClockTimeMarker). @@ -87,14 +94,29 @@ impl Game<'_> { let mut items: Vec = self.res.items.order.iter().map(|s| s.to_string()).collect(); items.sort(); reg.items = items; - reg.item_tags = self.res.items.item_tags.keys().map(|k| horizon_client::command::args::normalize(k)).collect(); + reg.item_tags = self + .res + .items + .item_tags + .keys() + .map(|k| horizon_client::command::args::normalize(k)) + .collect(); reg.item_tags.sort(); - reg.block_tags = self.res.items.block_tags.keys().map(|k| horizon_client::command::args::normalize(k)).collect(); + reg.block_tags = self + .res + .items + .block_tags + .keys() + .map(|k| horizon_client::command::args::normalize(k)) + .collect(); reg.block_tags.sort(); let registry = self.res.assets.registry; let mut blocks: BTreeMap>> = BTreeMap::new(); for id in 0..registry.len() { - let Some(state) = registry.state(horizon_world::registry::BlockStateId(id as u32)) else { continue }; + let Some(state) = registry.state(horizon_world::registry::BlockStateId(id as u32)) + else { + continue; + }; let props = blocks.entry(state.name.clone()).or_default(); for (k, v) in &state.properties { let values = props.entry(k.clone()).or_default(); @@ -103,17 +125,41 @@ impl Game<'_> { } } } - reg.blocks = blocks.into_iter().map(|(k, v)| (k, v.into_iter().collect())).collect(); - let mut summonable: Vec = self.res.mob_types.keys().map(|k| horizon_client::command::args::normalize(k)).collect(); - summonable.extend(["minecraft:item", "minecraft:experience_orb", "minecraft:falling_block", "minecraft:arrow"].map(String::from)); + reg.blocks = blocks + .into_iter() + .map(|(k, v)| (k, v.into_iter().collect())) + .collect(); + let mut summonable: Vec = self + .res + .mob_types + .keys() + .map(|k| horizon_client::command::args::normalize(k)) + .collect(); + summonable.extend( + [ + "minecraft:item", + "minecraft:experience_orb", + "minecraft:falling_block", + "minecraft:arrow", + ] + .map(String::from), + ); summonable.sort(); summonable.dedup(); reg.summonable = summonable; let root = self.options.resources.clone(); - let mut types: Vec = serde_json::from_slice::(&std::fs::read(root.join("entity-types.json")).unwrap_or_default()) - .ok() - .and_then(|v| v.as_object().map(|o| o.keys().map(|k| horizon_client::command::args::normalize(k)).collect())) - .unwrap_or_default(); + let mut types: Vec = serde_json::from_slice::( + &std::fs::read(root.join("entity-types.json")).unwrap_or_default(), + ) + .ok() + .and_then(|v| { + v.as_object().map(|o| { + o.keys() + .map(|k| horizon_client::command::args::normalize(k)) + .collect() + }) + }) + .unwrap_or_default(); if types.is_empty() { types = reg.summonable.clone(); types.push("minecraft:player".into()); @@ -125,7 +171,12 @@ impl Game<'_> { .into_iter() .flatten() .flatten() - .filter_map(|e| e.file_name().to_str()?.strip_suffix(".json").map(|n| format!("minecraft:{n}"))) + .filter_map(|e| { + e.file_name() + .to_str()? + .strip_suffix(".json") + .map(|n| format!("minecraft:{n}")) + }) .collect(); out.sort(); out @@ -140,8 +191,15 @@ impl Game<'_> { self.ui.markers.clear(); self.ui.timelines.clear(); for name in list("data/minecraft/timeline") { - let path = root.join(format!("data/minecraft/timeline/{}.json", name.trim_start_matches("minecraft:"))); - let Ok(v) = serde_json::from_slice::(&std::fs::read(path).unwrap_or_default()) else { continue }; + let path = root.join(format!( + "data/minecraft/timeline/{}.json", + name.trim_start_matches("minecraft:") + )); + let Ok(v) = serde_json::from_slice::( + &std::fs::read(path).unwrap_or_default(), + ) else { + continue; + }; if v["clock"].as_str() != Some("minecraft:overworld") { continue; } @@ -150,14 +208,30 @@ impl Game<'_> { for (marker, def) in v["time_markers"].as_object().into_iter().flatten() { let (ticks, show) = match def { serde_json::Value::Number(n) => (n.as_i64().unwrap_or(0), false), - other => (other["ticks"].as_i64().unwrap_or(0), other["show_in_commands"].as_bool().unwrap_or(false)), + other => ( + other["ticks"].as_i64().unwrap_or(0), + other["show_in_commands"].as_bool().unwrap_or(false), + ), }; - self.ui.markers.insert(marker.clone(), TimeMarker { ticks, period, show }); + self.ui.markers.insert( + marker.clone(), + TimeMarker { + ticks, + period, + show, + }, + ); } } let reg = &mut self.ui.registries; reg.timelines = self.ui.timelines.keys().cloned().collect(); - reg.time_markers = self.ui.markers.iter().filter(|(_, m)| m.show).map(|(k, _)| k.clone()).collect(); + reg.time_markers = self + .ui + .markers + .iter() + .filter(|(_, m)| m.show) + .map(|(k, _)| k.clone()) + .collect(); } /// The block the player is looking at, for coordinate suggestions. fn refresh_dynamic_registries(&mut self) { @@ -168,7 +242,10 @@ impl Game<'_> { return; } self.refresh_dynamic_registries(); - let size = self.renderer.as_ref().map_or([1280, 720], |r| [r.config.width, r.config.height]); + let size = self + .renderer + .as_ref() + .map_or([1280, 720], |r| [r.config.width, r.config.height]); let b = HudBatch::new(size); let mut screen = ChatScreen::new(initial, self.ui.chat.recent.len(), b.width, b.height); screen.auto_suggestions = true; @@ -190,18 +267,30 @@ impl Game<'_> { /// A chat message from the game (ChatComponent.addServerSystemMessage). pub(super) fn system_message(&mut self, text: Text) { let focused = self.screen == Screen::Chat; - self.ui.chat.add(&self.res.atlas, text, Some(SYSTEM_INDICATOR), self.ticks, focused); + self.ui.chat.add( + &self.res.atlas, + text, + Some(SYSTEM_INDICATOR), + self.ticks, + focused, + ); } /// Keys while the chat screen is open. pub(super) fn chat_key(&mut self, event: &KeyEvent) { - let PhysicalKey::Code(key) = event.physical_key else { return }; + let PhysicalKey::Code(key) = event.physical_key else { + return; + }; self.chat_key_code(key, event.text.as_deref()); } /// A key (and the text it typed) while the chat screen is open. pub(super) fn chat_key_code(&mut self, key: KeyCode, typed_text: Option<&str>) { - let ctrl = self.keys.contains(&KeyCode::ControlLeft) || self.keys.contains(&KeyCode::ControlRight); - let shift = self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight); - let Some(mut screen) = self.ui.chat_screen.take() else { return }; + let ctrl = + self.keys.contains(&KeyCode::ControlLeft) || self.keys.contains(&KeyCode::ControlRight); + let shift = + self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight); + let Some(mut screen) = self.ui.chat_screen.take() else { + return; + }; let atlas = &self.res.atlas; let d = vanilla::dispatcher(); if screen.suggestion_key(atlas, d, &self.ui.registries, key, shift) { @@ -264,14 +353,21 @@ impl Game<'_> { if let Some(command) = message.strip_prefix('/') { self.run_command(command); } else { - let line = Text::translate("chat.type.text", &[Text::literal(PLAYER_NAME), Text::literal(message)]); + let line = Text::translate( + "chat.type.text", + &[Text::literal(PLAYER_NAME), Text::literal(message)], + ); let focused = self.screen == Screen::Chat; - self.ui.chat.add(&self.res.atlas, line, None, self.ticks, focused); + self.ui + .chat + .add(&self.res.atlas, line, None, self.ticks, focused); } } pub(super) fn chat_scroll(&mut self, amount: f32) { let cursor = self.cursor; - let height = self.renderer.as_ref().map_or(720.0, |r| HudBatch::new([r.config.width, r.config.height]).height); + let height = self.renderer.as_ref().map_or(720.0, |r| { + HudBatch::new([r.config.width, r.config.height]).height + }); if let Some(screen) = self.ui.chat_screen.as_mut() && screen.scroll_suggestions(cursor, height, amount) { @@ -283,7 +379,9 @@ impl Game<'_> { } pub(super) fn chat_click(&mut self) { let cursor = self.cursor; - let height = self.renderer.as_ref().map_or(720.0, |r| HudBatch::new([r.config.width, r.config.height]).height); + let height = self.renderer.as_ref().map_or(720.0, |r| { + HudBatch::new([r.config.width, r.config.height]).height + }); if let Some(screen) = self.ui.chat_screen.as_mut() && !screen.click(cursor, height) && screen.input.y <= cursor.1 @@ -298,19 +396,33 @@ impl Game<'_> { if self.ui.hide_gui && !focused { return; } - self.ui.chat.draw(batch, &self.res.atlas, self.ticks, focused); + self.ui + .chat + .draw(batch, &self.res.atlas, self.ticks, focused); } pub(super) fn draw_chat_screen(&mut self, batch: &mut HudBatch) { - let Some(mut screen) = self.ui.chat_screen.take() else { return }; + let Some(mut screen) = self.ui.chat_screen.take() else { + return; + }; screen.resize(batch.width, batch.height); let bg = self.ui.chat.options.background_opacity; - screen.draw(batch, &self.res.atlas, vanilla::dispatcher(), &self.ui.registries, self.cursor, bg); + screen.draw( + batch, + &self.res.atlas, + vanilla::dispatcher(), + &self.ui.registries, + self.cursor, + bg, + ); self.ui.chat_screen = Some(screen); } /// Advance the overworld clock (ServerClockManager.tick) when /// `advance_time` allows it. pub(super) fn advance_clock(&mut self) { - if !self.ui.rules.bool("advance_time") || self.ui.clock.paused || self.dim == Dim::Nether && false { + if !self.ui.rules.bool("advance_time") + || self.ui.clock.paused + || self.dim == Dim::Nether && false + { return; } let c = &mut self.ui.clock; @@ -333,7 +445,8 @@ impl Game<'_> { } /// Apply rules mirrored in other state (natural regeneration, difficulty). pub(super) fn sync_rules(&mut self) { - self.world.health_rules.natural_regeneration = self.ui.rules.bool("natural_health_regeneration"); + self.world.health_rules.natural_regeneration = + self.ui.rules.bool("natural_health_regeneration"); use horizon_world::food::Difficulty; self.world.health_rules.difficulty = match self.ui.difficulty { 0 => Difficulty::Peaceful, @@ -349,8 +462,12 @@ impl Game<'_> { self.ui.difficulty = read_difficulty(&self.world_root).unwrap_or(2); if let Ok(bytes) = std::fs::read(self.world_root.join("data/minecraft/world_clocks.dat")) && let Ok(raw) = horizon_world::compression::Compression::Gzip.decode(&bytes, 1 << 20) - && let Ok((root, _)) = horizon_world::nbt::read_named(&raw, horizon_world::nbt::Limits::default()) - && let Some(c) = root.tag.get("data").and_then(|d| d.get("minecraft:overworld")) + && let Ok((root, _)) = + horizon_world::nbt::read_named(&raw, horizon_world::nbt::Limits::default()) + && let Some(c) = root + .tag + .get("data") + .and_then(|d| d.get("minecraft:overworld")) { use horizon_world::nbt::Tag; if let Some(Tag::Float(r)) = c.get("rate") { @@ -385,7 +502,10 @@ impl Game<'_> { ]); let root = NamedTag { name: "".into(), - tag: Tag::compound([("data", Tag::compound([("minecraft:overworld", clock)])), ("DataVersion", Tag::Int(horizon_world::DATA_VERSION))]), + tag: Tag::compound([ + ("data", Tag::compound([("minecraft:overworld", clock)])), + ("DataVersion", Tag::Int(horizon_world::DATA_VERSION)), + ]), }; if let Ok(bytes) = horizon_world::nbt::write_named(&root, Limits::default()) && let Ok(gz) = horizon_world::compression::Compression::Gzip.encode(&bytes) @@ -405,10 +525,20 @@ impl Game<'_> { if !self.ui.rules.bool("show_death_messages") { return; } - let Some(p) = self.player.as_ref() else { return }; + let Some(p) = self.player.as_ref() else { + return; + }; let key = cause.unwrap_or_else(|| { - let feet = [p.position.x.floor() as i32, p.position.y.floor() as i32, p.position.z.floor() as i32]; - let fluid = self.res.facts.get(self.world.block(feet[0], feet[1], feet[2])).fluid; + let feet = [ + p.position.x.floor() as i32, + p.position.y.floor() as i32, + p.position.z.floor() as i32, + ]; + let fluid = self + .res + .facts + .get(self.world.block(feet[0], feet[1], feet[2])) + .fluid; if p.position.y < f64::from(horizon_client::chunk::MIN_Y - 64) { "death.attack.outOfWorld".into() } else if fluid == horizon_client::blocks::Fluid::Lava { @@ -429,24 +559,32 @@ impl Game<'_> { } /// F2: ScreenShot.grab into `screenshots/` with vanilla's file name. pub(super) fn take_screenshot(&mut self) { - let dir = std::env::current_dir().unwrap_or_default().join("screenshots"); + let dir = std::env::current_dir() + .unwrap_or_default() + .join("screenshots"); if std::fs::create_dir_all(&dir).is_err() { return; } let name = screenshot_name(&dir); - let Some(renderer) = self.renderer.as_mut() else { return }; + let Some(renderer) = self.renderer.as_mut() else { + return; + }; renderer.screenshot = Some(dir.join(&name)); self.ui.screenshot_message = Some(name); } /// After a frame: report a finished F2 screenshot in chat. pub(super) fn finish_screenshot(&mut self, result: &std::result::Result<[u32; 2], String>) { - let Some(name) = self.ui.screenshot_message.take() else { return }; + let Some(name) = self.ui.screenshot_message.take() else { + return; + }; let message = match result { Ok(_) => Text::translate("screenshot.success", &[Text::literal(name).underlined()]), Err(e) => Text::translate("screenshot.failure", &[Text::literal(e.clone())]), }; let focused = self.screen == Screen::Chat; - self.ui.chat.add(&self.res.atlas, message, None, self.ticks, focused); + self.ui + .chat + .add(&self.res.atlas, message, None, self.ticks, focused); } #[allow(dead_code)] fn chat_debug_fill(&self, batch: &mut HudBatch) { @@ -456,7 +594,9 @@ impl Game<'_> { /// `yyyy-MM-dd_HH.mm.ss[_n].png` (Util.getFilenameFormattedDateTime, local time /// approximated as UTC). pub fn screenshot_name(dir: &std::path::Path) -> String { - let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()); + let secs = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()); let days = (secs / 86400) as i64; let (h, m, s) = ((secs % 86400) / 3600, (secs % 3600) / 60, secs % 60); let z = days + 719_468; @@ -471,7 +611,11 @@ pub fn screenshot_name(dir: &std::path::Path) -> String { let base = format!("{y}-{mo:02}-{d:02}_{h:02}.{m:02}.{s:02}"); let mut n = 1; loop { - let name = if n == 1 { format!("{base}.png") } else { format!("{base}_{n}.png") }; + let name = if n == 1 { + format!("{base}.png") + } else { + format!("{base}_{n}.png") + }; if !dir.join(&name).exists() { return name; } @@ -480,8 +624,11 @@ pub fn screenshot_name(dir: &std::path::Path) -> String { } fn read_difficulty(world: &std::path::Path) -> Option { let bytes = std::fs::read(world.join("level.dat")).ok()?; - let raw = horizon_world::compression::Compression::Gzip.decode(&bytes, 64 << 20).ok()?; - let (root, _) = horizon_world::nbt::read_named(&raw, horizon_world::nbt::Limits::default()).ok()?; + let raw = horizon_world::compression::Compression::Gzip + .decode(&bytes, 64 << 20) + .ok()?; + let (root, _) = + horizon_world::nbt::read_named(&raw, horizon_world::nbt::Limits::default()).ok()?; match root.tag.get("Data")?.get("Difficulty")? { horizon_world::nbt::Tag::Byte(b) => Some((*b).clamp(0, 3) as u8), _ => None, diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 317739f8d..aacca4cf9 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -35,7 +35,11 @@ fn texts(args: &[Text]) -> Vec { } /// Java's String.valueOf(float/double) for the values commands print. fn java_float(v: f64) -> String { - if v == v.trunc() && v.abs() < 1.0e7 { format!("{v:.1}") } else { format!("{v}") } + if v == v.trunc() && v.abs() < 1.0e7 { + format!("{v:.1}") + } else { + format!("{v}") + } } /// String.format(Locale.ROOT, "%f"). fn format_double(v: f64) -> String { @@ -69,7 +73,10 @@ impl Game<'_> { self.command_failure(e.message.clone()); let Some(input) = &e.input else { return }; let cursor = e.cursor.min(input.len()); - let suggest = Style { suggest: Some(format!("/{command}")), ..Style::default() }; + let suggest = Style { + suggest: Some(format!("/{command}")), + ..Style::default() + }; let mut context = Text::empty(); if cursor > 10 { context.push("..."); @@ -77,9 +84,17 @@ impl Game<'_> { let start = input.floor_char_boundary(cursor.saturating_sub(10)); context.push(&input[start..cursor]); if cursor < input.len() { - context.push(Text::literal(&input[cursor..]).with_color(text::RED).underlined()); + context.push( + Text::literal(&input[cursor..]) + .with_color(text::RED) + .underlined(), + ); } - context.push(Text::translate("command.context.here", &[]).with_color(text::RED).italic()); + context.push( + Text::translate("command.context.here", &[]) + .with_color(text::RED) + .italic(), + ); self.command_failure(context.with_color(text::GRAY).with_style(&suggest)); } /// CommandSourceStack.sendFailure: red text. @@ -108,16 +123,21 @@ impl Game<'_> { } } fn position_arg(&self, ctx: &Context, name: &str) -> Option<[f64; 3]> { - self.coords(ctx, name).map(|c| c.position(self.source_position(), self.source_rotation())) + self.coords(ctx, name) + .map(|c| c.position(self.source_position(), self.source_rotation())) } /// BlockPosArgument.getLoadedBlockPos. fn block_pos_arg(&self, ctx: &Context, name: &str) -> R<[i32; 3]> { - let c = self.coords(ctx, name).ok_or_else(|| err("argument.pos.missing.int", &[]))?; + let c = self + .coords(ctx, name) + .ok_or_else(|| err("argument.pos.missing.int", &[]))?; let p = c.block(self.source_position(), self.source_rotation()); if !self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) { return Err(err("argument.pos.unloaded", &[])); } - if p[1] < horizon_client::chunk::MIN_Y || p[1] >= horizon_client::chunk::MIN_Y + horizon_client::chunk::HEIGHT { + if p[1] < horizon_client::chunk::MIN_Y + || p[1] >= horizon_client::chunk::MIN_Y + horizon_client::chunk::HEIGHT + { return Err(err("argument.pos.outofworld", &[])); } Ok(p) @@ -132,17 +152,40 @@ impl Game<'_> { fn target_position(&self, t: Target) -> Option<[f64; 3]> { match t { - Target::Player => self.player.as_ref().map(|p| [p.position.x, p.position.y, p.position.z]), - Target::Mob(id) => self.mobs.iter().find(|m| m.id == id).map(|m| [m.position.x, m.position.y, m.position.z]), - Target::Item(id) => self.dropped.iter().find(|i| i.id == id).map(|i| [i.position.x, i.position.y, i.position.z]), - Target::Orb(i) => self.orbs.get(i).map(|o| [o.position.x, o.position.y, o.position.z]), - Target::Arrow(i) => self.arrows.get(i).map(|a| [a.position.x, a.position.y, a.position.z]), + Target::Player => self + .player + .as_ref() + .map(|p| [p.position.x, p.position.y, p.position.z]), + Target::Mob(id) => self + .mobs + .iter() + .find(|m| m.id == id) + .map(|m| [m.position.x, m.position.y, m.position.z]), + Target::Item(id) => self + .dropped + .iter() + .find(|i| i.id == id) + .map(|i| [i.position.x, i.position.y, i.position.z]), + Target::Orb(i) => self + .orbs + .get(i) + .map(|o| [o.position.x, o.position.y, o.position.z]), + Target::Arrow(i) => self + .arrows + .get(i) + .map(|a| [a.position.x, a.position.y, a.position.z]), } } fn target_type(&self, t: Target) -> String { match t { Target::Player => "minecraft:player".into(), - Target::Mob(id) => self.mobs.iter().find(|m| m.id == id).map_or_else(String::new, |m| horizon_client::command::args::normalize(&m.kind.id)), + Target::Mob(id) => self + .mobs + .iter() + .find(|m| m.id == id) + .map_or_else(String::new, |m| { + horizon_client::command::args::normalize(&m.kind.id) + }), Target::Item(_) => "minecraft:item".into(), Target::Orb(_) => "minecraft:experience_orb".into(), Target::Arrow(_) => "minecraft:arrow".into(), @@ -153,7 +196,12 @@ impl Game<'_> { match t { Target::Player => Text::literal(PLAYER_NAME), Target::Item(id) => { - let item = self.dropped.iter().find(|i| i.id == id).map(|i| i.stack.item.to_string()).unwrap_or_default(); + let item = self + .dropped + .iter() + .find(|i| i.id == id) + .map(|i| i.stack.item.to_string()) + .unwrap_or_default(); Text::literal(self.res.names.item(&item)) } other => { @@ -165,18 +213,31 @@ impl Game<'_> { /// EntitySelector.findEntities. fn select(&mut self, s: &Selector) -> Vec { if let Some(name) = &s.player_name { - return if name.eq_ignore_ascii_case(PLAYER_NAME) && self.player.is_some() { vec![Target::Player] } else { Vec::new() }; + return if name.eq_ignore_ascii_case(PLAYER_NAME) && self.player.is_some() { + vec![Target::Player] + } else { + Vec::new() + }; } let origin = { let p = self.source_position(); - [s.pos[0].unwrap_or(p[0]), s.pos[1].unwrap_or(p[1]), s.pos[2].unwrap_or(p[2])] + [ + s.pos[0].unwrap_or(p[0]), + s.pos[1].unwrap_or(p[1]), + s.pos[2].unwrap_or(p[2]), + ] }; let mut candidates: Vec = Vec::new(); if self.player.is_some() { candidates.push(Target::Player); } if s.kind != 's' { - candidates.extend(self.mobs.iter().filter(|m| m.death_time == 0).map(|m| Target::Mob(m.id))); + candidates.extend( + self.mobs + .iter() + .filter(|m| m.death_time == 0) + .map(|m| Target::Mob(m.id)), + ); candidates.extend(self.dropped.iter().map(|i| Target::Item(i.id))); candidates.extend((0..self.orbs.len()).map(Target::Orb)); candidates.extend((0..self.arrows.len()).map(Target::Arrow)); @@ -190,12 +251,21 @@ impl Game<'_> { let ty = self.target_type(t); // type=: every positive must match, no negative may match. for (want, neg) in &s.types { - let matches = if let Some(tag) = want.strip_prefix('#') { self.entity_tag_matches(tag, &ty) } else { *want == ty }; + let matches = if let Some(tag) = want.strip_prefix('#') { + self.entity_tag_matches(tag, &ty) + } else { + *want == ty + }; if matches == *neg { return None; } } - if !s.include_entities && t != Target::Player && s.types.iter().all(|(w, n)| *n || w != &ty) && s.kind != 'e' && s.kind != 'n' { + if !s.include_entities + && t != Target::Player + && s.types.iter().all(|(w, n)| *n || w != &ty) + && s.kind != 'e' + && s.kind != 'n' + { return None; } for (name, neg) in &s.names { @@ -210,7 +280,10 @@ impl Game<'_> { } } if let Some((lo, hi)) = s.level { - if t != Target::Player || lo.is_some_and(|l| level < l) || hi.is_some_and(|h| level > h) { + if t != Target::Player + || lo.is_some_and(|l| level < l) + || hi.is_some_and(|h| level > h) + { return None; } } @@ -220,7 +293,9 @@ impl Game<'_> { return None; } } - let d2 = (p[0] - origin[0]).powi(2) + (p[1] - origin[1]).powi(2) + (p[2] - origin[2]).powi(2); + let d2 = (p[0] - origin[0]).powi(2) + + (p[1] - origin[1]).powi(2) + + (p[2] - origin[2]).powi(2); if let Some((lo, hi)) = s.distance && (lo.is_some_and(|l| d2 < l * l) || hi.is_some_and(|h| d2 > h * h)) { @@ -229,7 +304,10 @@ impl Game<'_> { if s.delta.iter().any(Option::is_some) { let d = s.delta.map(|v| v.unwrap_or(0.0)); for i in 0..3 { - let (a, b) = (origin[i].min(origin[i] + d[i]), origin[i].max(origin[i] + d[i]) + 1.0); + let (a, b) = ( + origin[i].min(origin[i] + d[i]), + origin[i].max(origin[i] + d[i]) + 1.0, + ); if p[i] < a || p[i] >= b { return None; } @@ -249,20 +327,43 @@ impl Game<'_> { } Sort::Arbitrary => {} } - out.into_iter().take(s.limit.max(1)).map(|(t, _)| t).collect() + out.into_iter() + .take(s.limit.max(1)) + .map(|(t, _)| t) + .collect() } fn entity_tag_matches(&self, tag: &str, ty: &str) -> bool { - let path = self.options.resources.join(format!("data/minecraft/tags/entity_type/{}.json", tag.trim_start_matches("minecraft:"))); + let path = self.options.resources.join(format!( + "data/minecraft/tags/entity_type/{}.json", + tag.trim_start_matches("minecraft:") + )); serde_json::from_slice::(&std::fs::read(path).unwrap_or_default()) .ok() - .is_some_and(|v| v["values"].as_array().is_some_and(|a| a.iter().any(|e| e.as_str() == Some(ty)))) + .is_some_and(|v| { + v["values"] + .as_array() + .is_some_and(|a| a.iter().any(|e| e.as_str() == Some(ty))) + }) } /// EntityArgument.getEntities / getPlayers / getEntity / getPlayer. fn entities(&mut self, ctx: &Context, name: &str, players: bool) -> R> { - let Some(Arg::Entity(s)) = ctx.get(name).cloned() else { return Ok(vec![Target::Player]) }; - let found: Vec = self.select(&s).into_iter().filter(|t| !players || *t == Target::Player).collect(); + let Some(Arg::Entity(s)) = ctx.get(name).cloned() else { + return Ok(vec![Target::Player]); + }; + let found: Vec = self + .select(&s) + .into_iter() + .filter(|t| !players || *t == Target::Player) + .collect(); if found.is_empty() { - return Err(err(if players { "argument.entity.notfound.player" } else { "argument.entity.notfound.entity" }, &[])); + return Err(err( + if players { + "argument.entity.notfound.player" + } else { + "argument.entity.notfound.entity" + }, + &[], + )); } Ok(found) } @@ -273,12 +374,20 @@ impl Game<'_> { "help" => self.cmd_help(ctx), "gamemode" => self.cmd_gamemode(ctx), "defaultgamemode" => { - let Some(Arg::GameMode(m)) = ctx.get("gamemode") else { return Ok(0) }; - self.feedback(Text::translate("commands.defaultgamemode.success", &[Text::translate(&format!("gameMode.{}", m.name()), &[])])); + let Some(Arg::GameMode(m)) = ctx.get("gamemode") else { + return Ok(0); + }; + self.feedback(Text::translate( + "commands.defaultgamemode.success", + &[Text::translate(&format!("gameMode.{}", m.name()), &[])], + )); Ok(0) } "give" => self.cmd_give(ctx), - "teleport.location" | "teleport.destination" | "teleport.targets.location" | "teleport.targets.destination" => self.cmd_teleport(id, ctx), + "teleport.location" + | "teleport.destination" + | "teleport.targets.location" + | "teleport.targets.destination" => self.cmd_teleport(id, ctx), id if id.starts_with("time.") => self.cmd_time(id, ctx), "weather" => self.cmd_weather(ctx), "kill" => self.cmd_kill(ctx), @@ -294,8 +403,14 @@ impl Game<'_> { "difficulty" => self.cmd_difficulty(ctx), "seed" => { let seed = self.level.seed.to_string(); - let green = Style { color: Some(text::GREEN), suggest: None, ..Style::default() }; - let value = Text::literal("[").append(Text::styled(seed.clone(), green)).append("]"); + let green = Style { + color: Some(text::GREEN), + suggest: None, + ..Style::default() + }; + let value = Text::literal("[") + .append(Text::styled(seed.clone(), green)) + .append("]"); self.system_message(Text::translate("commands.seed.success", &[value])); Ok(self.level.seed as i32) } @@ -306,11 +421,20 @@ impl Game<'_> { "say" | "me" | "msg" => self.cmd_say(id, ctx), "list" => { let names = if ctx.has("uuids") { - Text::translate("commands.list.nameAndId", &[Text::literal(PLAYER_NAME), Text::literal("00000000-0000-0000-0000-000000000000")]) + Text::translate( + "commands.list.nameAndId", + &[ + Text::literal(PLAYER_NAME), + Text::literal("00000000-0000-0000-0000-000000000000"), + ], + ) } else { Text::literal(PLAYER_NAME) }; - self.system_message(Text::translate("commands.list.players", &[Text::literal("1"), Text::literal("8"), names])); + self.system_message(Text::translate( + "commands.list.players", + &[Text::literal("1"), Text::literal("8"), names], + )); Ok(1) } _ => Err(err("command.failed", &[])), @@ -359,8 +483,14 @@ impl Game<'_> { true } fn cmd_gamemode(&mut self, ctx: &Context) -> R { - let Some(Arg::GameMode(mode)) = ctx.get("gamemode").cloned() else { return Ok(0) }; - let targets = if ctx.get("target").is_some() { self.entities(ctx, "target", true)? } else { vec![Target::Player] }; + let Some(Arg::GameMode(mode)) = ctx.get("gamemode").cloned() else { + return Ok(0); + }; + let targets = if ctx.get("target").is_some() { + self.entities(ctx, "target", true)? + } else { + vec![Target::Player] + }; let mut count = 0; for t in targets { if t != Target::Player || !self.set_game_mode(mode) { @@ -369,10 +499,16 @@ impl Game<'_> { count += 1; let mode_name = Text::translate(&format!("gameMode.{}", mode.name()), &[]); if ctx.get("target").is_none() { - self.feedback(Text::translate("commands.gamemode.success.self", &[mode_name])); + self.feedback(Text::translate( + "commands.gamemode.success.self", + &[mode_name], + )); } else { self.system_message(Text::translate("gameMode.changed", &[mode_name.clone()])); - self.feedback(Text::translate("commands.gamemode.success.other", &[Text::literal(PLAYER_NAME), mode_name])); + self.feedback(Text::translate( + "commands.gamemode.success.other", + &[Text::literal(PLAYER_NAME), mode_name], + )); } } Ok(count) @@ -386,32 +522,60 @@ impl Game<'_> { "epic" => text::LIGHT_PURPLE, _ => text::WHITE, }; - Text::literal("[").append(Text::literal(self.res.names.item(item))).append("]").with_color(color) + Text::literal("[") + .append(Text::literal(self.res.names.item(item))) + .append("]") + .with_color(color) } fn item_rarity(&self, item: &str) -> String { - static RARITY: std::sync::OnceLock> = std::sync::OnceLock::new(); + static RARITY: std::sync::OnceLock> = + std::sync::OnceLock::new(); let map = RARITY.get_or_init(|| { - let v: serde_json::Value = serde_json::from_slice(&std::fs::read(self.options.resources.join("items.json")).unwrap_or_default()).unwrap_or_default(); + let v: serde_json::Value = serde_json::from_slice( + &std::fs::read(self.options.resources.join("items.json")).unwrap_or_default(), + ) + .unwrap_or_default(); v.as_object() - .map(|o| o.iter().filter_map(|(k, c)| c["minecraft:rarity"].as_str().map(|r| (k.clone(), r.to_owned()))).collect()) + .map(|o| { + o.iter() + .filter_map(|(k, c)| { + c["minecraft:rarity"] + .as_str() + .map(|r| (k.clone(), r.to_owned())) + }) + .collect() + }) .unwrap_or_default() }); map.get(item).cloned().unwrap_or_else(|| "common".into()) } fn cmd_give(&mut self, ctx: &Context) -> R { - let Some(Arg::Item(ItemInput { id, .. })) = ctx.get("item").cloned() else { return Ok(0) }; + let Some(Arg::Item(ItemInput { id, .. })) = ctx.get("item").cloned() else { + return Ok(0); + }; let count = Self::int(ctx, "count").unwrap_or(1); let targets = self.entities(ctx, "targets", true)?; let max_stack = self.res.items.get(&id).map_or(64, |i| i.max_stack) as i32; if count > max_stack * 100 { - return Err(CommandError::new(Text::translate("commands.give.failed.toomanyitems", &[Text::literal((max_stack * 100).to_string()), self.item_display_name(&id)]))); + return Err(CommandError::new(Text::translate( + "commands.give.failed.toomanyitems", + &[ + Text::literal((max_stack * 100).to_string()), + self.item_display_name(&id), + ], + ))); } for _ in &targets { let mut remaining = count; while remaining > 0 { let size = remaining.min(max_stack); remaining -= size; - let left = self.give(ItemStack { item: id.as_str().into(), count: size as u32, damage: 0, extra: None }); + let left = self.give(ItemStack { + item: id.as_str().into(), + count: size as u32, + damage: 0, + extra: None, + }); if let Some(rest) = left { // Inventory full: drop the rest at the player's feet without pickup delay. let p = self.source_position(); @@ -420,15 +584,30 @@ impl Game<'_> { let r = &mut self.world.random; let pitch = ((r.next_float() - r.next_float()) * 0.7 + 1.0) * 2.0; let p = self.source_position(); - self.audio.play("minecraft:entity.item.pickup", Some(p), 0.2, pitch); + self.audio + .play("minecraft:entity.item.pickup", Some(p), 0.2, pitch); } } } let name = self.item_display_name(&id); let message = if targets.len() == 1 { - Text::translate("commands.give.success.single", &[Text::literal(count.to_string()), name, Text::literal(PLAYER_NAME)]) + Text::translate( + "commands.give.success.single", + &[ + Text::literal(count.to_string()), + name, + Text::literal(PLAYER_NAME), + ], + ) } else { - Text::translate("commands.give.success.multiple", &texts(&[Text::literal(count.to_string()), name, Text::literal(targets.len().to_string())])) + Text::translate( + "commands.give.success.multiple", + &texts(&[ + Text::literal(count.to_string()), + name, + Text::literal(targets.len().to_string()), + ]), + ) }; self.feedback(message); Ok(targets.len() as i32) @@ -480,7 +659,11 @@ impl Game<'_> { } } fn cmd_teleport(&mut self, id: &str, ctx: &Context) -> R { - let targets = if id.starts_with("teleport.targets") { self.entities(ctx, "targets", false)? } else { vec![Target::Player] }; + let targets = if id.starts_with("teleport.targets") { + self.entities(ctx, "targets", false)? + } else { + vec![Target::Player] + }; if id.ends_with("destination") { let dest = self.entities(ctx, "destination", false)?[0]; let pos = self.target_position(dest).unwrap_or(self.source_position()); @@ -488,15 +671,29 @@ impl Game<'_> { self.teleport_to(t, pos, None); } let message = if targets.len() == 1 { - Text::translate("commands.teleport.success.entity.single", &[self.target_name(targets[0]), self.target_name(dest)]) + Text::translate( + "commands.teleport.success.entity.single", + &[self.target_name(targets[0]), self.target_name(dest)], + ) } else { - Text::translate("commands.teleport.success.entity.multiple", &[Text::literal(targets.len().to_string()), self.target_name(dest)]) + Text::translate( + "commands.teleport.success.entity.multiple", + &[ + Text::literal(targets.len().to_string()), + self.target_name(dest), + ], + ) }; self.feedback(message); return Ok(targets.len() as i32); } - let pos = self.position_arg(ctx, "location").unwrap_or(self.source_position()); - if !(-30_000_000.0..30_000_000.0).contains(&pos[0]) || !(-30_000_000.0..30_000_000.0).contains(&pos[2]) || !(-20_000_000.0..20_000_000.0).contains(&pos[1]) { + let pos = self + .position_arg(ctx, "location") + .unwrap_or(self.source_position()); + if !(-30_000_000.0..30_000_000.0).contains(&pos[0]) + || !(-30_000_000.0..30_000_000.0).contains(&pos[2]) + || !(-20_000_000.0..20_000_000.0).contains(&pos[1]) + { return Err(err("commands.teleport.invalidPosition", &[])); } let mut rotation = match ctx.get("rotation") { @@ -505,7 +702,9 @@ impl Game<'_> { }; // facing: look from the new position at a location or entity. let facing = self.position_arg(ctx, "facingLocation").or_else(|| { - let Some(Arg::Entity(_)) = ctx.get("facingEntity") else { return None }; + let Some(Arg::Entity(_)) = ctx.get("facingEntity") else { + return None; + }; None }); let facing = match (facing, ctx.get("facingEntity")) { @@ -513,7 +712,8 @@ impl Game<'_> { (None, Some(_)) => { let e = self.entities(ctx, "facingEntity", false)?[0]; let eyes = matches!(ctx.get("facingAnchor"), Some(Arg::Anchor(true))); - self.target_position(e).map(|p| [p[0], p[1] + if eyes { 1.62 } else { 0.0 }, p[2]]) + self.target_position(e) + .map(|p| [p[0], p[1] + if eyes { 1.62 } else { 0.0 }, p[2]]) } _ => None, }; @@ -521,16 +721,25 @@ impl Game<'_> { let eye = pos[1] + 1.62; let (dx, dy, dz) = (f[0] - pos[0], f[1] - eye, f[2] - pos[2]); let horizontal = (dx * dx + dz * dz).sqrt(); - rotation = Some([((dz.atan2(dx).to_degrees()) - 90.0) as f32, (-(dy.atan2(horizontal).to_degrees())) as f32]); + rotation = Some([ + ((dz.atan2(dx).to_degrees()) - 90.0) as f32, + (-(dy.atan2(horizontal).to_degrees())) as f32, + ]); } for &t in &targets { self.teleport_to(t, pos, rotation); } let [x, y, z] = pos.map(|v| Text::literal(format_double(v))); let message = if targets.len() == 1 { - Text::translate("commands.teleport.success.location.single", &[self.target_name(targets[0]), x, y, z]) + Text::translate( + "commands.teleport.success.location.single", + &[self.target_name(targets[0]), x, y, z], + ) } else { - Text::translate("commands.teleport.success.location.multiple", &[Text::literal(targets.len().to_string()), x, y, z]) + Text::translate( + "commands.teleport.success.location.multiple", + &[Text::literal(targets.len().to_string()), x, y, z], + ) }; self.feedback(message); Ok(targets.len() as i32) @@ -546,7 +755,10 @@ impl Game<'_> { Some(Arg::Resource(c)) => c.clone(), _ => { if self.dim == Dim::Nether { - return Err(err("commands.time.no_default_clock", &[&"minecraft:the_nether"])); + return Err(err( + "commands.time.no_default_clock", + &[&"minecraft:the_nether"], + )); } "minecraft:overworld".to_owned() } @@ -568,16 +780,27 @@ impl Game<'_> { Ok(t as i32) } "time.set.marker" => { - let Some(Arg::Resource(marker)) = ctx.get("timemarker").cloned() else { return Ok(0) }; + let Some(Arg::Resource(marker)) = ctx.get("timemarker").cloned() else { + return Ok(0); + }; let Some(m) = self.ui.markers.get(&marker).copied() else { - return Err(err("commands.time.no_time_marker_found", &[&marker, &clock])); + return Err(err( + "commands.time.no_time_marker_found", + &[&marker, &clock], + )); }; if m.occurs_at(total) { - return Err(err("commands.time.set.already_at_time_marker", &[&clock, &marker])); + return Err(err( + "commands.time.set.already_at_time_marker", + &[&clock, &marker], + )); } self.world.day_time = m.resolve(total); self.ui.clock.partial = 0.0; - self.feedback(Text::tr("commands.time.set.time_marker", &[&clock, &marker])); + self.feedback(Text::tr( + "commands.time.set.time_marker", + &[&clock, &marker], + )); Ok((self.world.day_time % i64::from(i32::MAX)) as i32) } "time.add" => { @@ -590,10 +813,24 @@ impl Game<'_> { "time.pause" | "time.resume" => { let pause = id == "time.pause"; if self.ui.clock.paused == pause { - return Err(err(if pause { "commands.time.pause.already_paused" } else { "commands.time.pause.already_running" }, &[&clock])); + return Err(err( + if pause { + "commands.time.pause.already_paused" + } else { + "commands.time.pause.already_running" + }, + &[&clock], + )); } self.ui.clock.paused = pause; - self.feedback(Text::tr(if pause { "commands.time.pause" } else { "commands.time.resume" }, &[&clock])); + self.feedback(Text::tr( + if pause { + "commands.time.pause" + } else { + "commands.time.resume" + }, + &[&clock], + )); Ok(1) } "time.rate" => { @@ -602,10 +839,16 @@ impl Game<'_> { _ => 1.0, }; if self.ui.clock.rate == rate { - return Err(err("commands.time.rate.already_same", &[&clock, &java_float(f64::from(rate))])); + return Err(err( + "commands.time.rate.already_same", + &[&clock, &java_float(f64::from(rate))], + )); } self.ui.clock.rate = rate; - self.feedback(Text::tr("commands.time.rate", &[&clock, &java_float(f64::from(rate))])); + self.feedback(Text::tr( + "commands.time.rate", + &[&clock, &java_float(f64::from(rate))], + )); Ok(1) } "time.query.time" => { @@ -613,17 +856,28 @@ impl Game<'_> { Ok((total % i64::from(i32::MAX)) as i32) } "time.query.timeline" | "time.query.repetition" => { - let Some(Arg::Resource(timeline)) = ctx.get("timeline").cloned() else { return Ok(0) }; + let Some(Arg::Resource(timeline)) = ctx.get("timeline").cloned() else { + return Ok(0); + }; let Some(period) = self.ui.timelines.get(&timeline).copied() else { - return Err(err("commands.time.wrong_timeline_for_clock", &[&clock, &timeline])); + return Err(err( + "commands.time.wrong_timeline_for_clock", + &[&clock, &timeline], + )); }; if id == "time.query.timeline" { let ticks = period.map_or(total, |p| total.rem_euclid(p)); - self.system_message(Text::tr("commands.time.query.timeline", &[&timeline, &ticks])); + self.system_message(Text::tr( + "commands.time.query.timeline", + &[&timeline, &ticks], + )); Ok(ticks as i32) } else { let reps = period.map_or(0, |p| total / p); - self.system_message(Text::tr("commands.time.query.timeline.repetitions", &[&timeline, &reps])); + self.system_message(Text::tr( + "commands.time.query.timeline.repetitions", + &[&timeline, &reps], + )); Ok(reps as i32) } } @@ -632,15 +886,35 @@ impl Game<'_> { } fn cmd_weather(&mut self, ctx: &Context) -> R { let duration = Self::int(ctx, "duration"); - let sample = |min: i32, max: i32, r: &mut horizon_core::random::LegacyRandom| min + r.next_int_bound(max - min + 1).unwrap_or(0); + let sample = |min: i32, max: i32, r: &mut horizon_core::random::LegacyRandom| { + min + r.next_int_bound(max - min + 1).unwrap_or(0) + }; let w = &mut self.world.weather; let r = &mut self.world.random; let (key, clear, time, raining, thundering) = if ctx.has("clear") { - ("commands.weather.set.clear", duration.unwrap_or_else(|| sample(12_000, 180_000, r)), 0, false, false) + ( + "commands.weather.set.clear", + duration.unwrap_or_else(|| sample(12_000, 180_000, r)), + 0, + false, + false, + ) } else if ctx.has("rain") { - ("commands.weather.set.rain", 0, duration.unwrap_or_else(|| sample(12_000, 24_000, r)), true, false) + ( + "commands.weather.set.rain", + 0, + duration.unwrap_or_else(|| sample(12_000, 24_000, r)), + true, + false, + ) } else { - ("commands.weather.set.thunder", 0, duration.unwrap_or_else(|| sample(3_600, 15_600, r)), true, true) + ( + "commands.weather.set.thunder", + 0, + duration.unwrap_or_else(|| sample(3_600, 15_600, r)), + true, + true, + ) }; // ServerLevel.setWeatherParameters. w.clear_time = clear; @@ -681,14 +955,20 @@ impl Game<'_> { } } fn cmd_kill(&mut self, ctx: &Context) -> R { - let targets = if ctx.get("targets").is_some() { self.entities(ctx, "targets", false)? } else { vec![Target::Player] }; + let targets = if ctx.get("targets").is_some() { + self.entities(ctx, "targets", false)? + } else { + vec![Target::Player] + }; let names: Vec = targets.iter().map(|&t| self.target_name(t)).collect(); // Remove indexed entities from the back so earlier indices stay valid. let mut ordered = targets.clone(); - ordered.sort_by_key(|t| std::cmp::Reverse(match t { - Target::Orb(i) | Target::Arrow(i) => *i, - _ => 0, - })); + ordered.sort_by_key(|t| { + std::cmp::Reverse(match t { + Target::Orb(i) | Target::Arrow(i) => *i, + _ => 0, + }) + }); for t in ordered { self.kill_target(t); } @@ -703,15 +983,27 @@ impl Game<'_> { Ok(targets.len() as i32) } fn cmd_summon(&mut self, ctx: &Context) -> R { - let Some(Arg::Resource(kind)) = ctx.get("entity").cloned() else { return Ok(0) }; - let pos = self.position_arg(ctx, "pos").unwrap_or(self.source_position()); + let Some(Arg::Resource(kind)) = ctx.get("entity").cloned() else { + return Ok(0); + }; + let pos = self + .position_arg(ctx, "pos") + .unwrap_or(self.source_position()); let block_y = pos[1].floor() as i32; - if !(-30_000_000.0..30_000_000.0).contains(&pos[0]) || !(-20_000_000..20_000_000).contains(&block_y) || !(-30_000_000.0..30_000_000.0).contains(&pos[2]) { + if !(-30_000_000.0..30_000_000.0).contains(&pos[0]) + || !(-20_000_000..20_000_000).contains(&block_y) + || !(-30_000_000.0..30_000_000.0).contains(&pos[2]) + { return Err(err("commands.summon.invalidPosition", &[])); } let short = kind.trim_start_matches("minecraft:").to_owned(); let name; - if let Some(t) = self.res.mob_types.get(&format!("minecraft:{short}")).cloned() { + if let Some(t) = self + .res + .mob_types + .get(&format!("minecraft:{short}")) + .cloned() + { if self.ui.difficulty == 0 && t.category == "monster" { return Err(err("commands.summon.failed.peaceful", &[])); } @@ -742,19 +1034,38 @@ impl Game<'_> { } /// BlockStateArgument -> registry state. fn block_state(&self, b: &BlockInput) -> R { - let state = horizon_world::chunk::BlockState { name: b.id.clone(), properties: b.properties.iter().cloned().collect() }; - self.res.assets.registry.resolve(&state).map_err(|_| err("argument.block.id.invalid", &[&b.id])) + let state = horizon_world::chunk::BlockState { + name: b.id.clone(), + properties: b.properties.iter().cloned().collect(), + }; + self.res + .assets + .registry + .resolve(&state) + .map_err(|_| err("argument.block.id.invalid", &[&b.id])) } /// BlockPredicateArgument test. fn block_matches(&self, b: &BlockInput, state: BlockStateId) -> bool { - let Some(s) = self.res.assets.registry.state(state) else { return false }; + let Some(s) = self.res.assets.registry.state(state) else { + return false; + }; let name_ok = if b.tag { let tag = b.id.trim_start_matches("minecraft:"); - self.res.items.block_tags.get(tag).or_else(|| self.res.items.block_tags.get(&b.id)).is_some_and(|set| set.contains(&s.name) || set.contains(s.name.trim_start_matches("minecraft:"))) + self.res + .items + .block_tags + .get(tag) + .or_else(|| self.res.items.block_tags.get(&b.id)) + .is_some_and(|set| { + set.contains(&s.name) || set.contains(s.name.trim_start_matches("minecraft:")) + }) } else { s.name == b.id }; - name_ok && b.properties.iter().all(|(k, v)| s.properties.get(k) == Some(v)) + name_ok + && b.properties + .iter() + .all(|(k, v)| s.properties.get(k) == Some(v)) } /// Place a state like BlockInput.place: false when nothing changed. fn place_state(&mut self, pos: [i32; 3], state: BlockStateId, strict: bool) -> R { @@ -763,17 +1074,28 @@ impl Game<'_> { } if strict { self.with_level(|b, level, ticks| { - b.set_block(level, ticks, horizon_core::position::BlockPos::new(pos[0], pos[1], pos[2]), state, horizon_world::level::flags::UPDATE_CLIENTS | horizon_world::level::flags::UPDATE_SKIP_ALL_SIDEEFFECTS); + b.set_block( + level, + ticks, + horizon_core::position::BlockPos::new(pos[0], pos[1], pos[2]), + state, + horizon_world::level::flags::UPDATE_CLIENTS + | horizon_world::level::flags::UPDATE_SKIP_ALL_SIDEEFFECTS, + ); }); - self.process_level_events().map_err(|e| CommandError::new(Text::literal(e.to_string())))?; + self.process_level_events() + .map_err(|e| CommandError::new(Text::literal(e.to_string())))?; } else { - self.level_set(pos, state).map_err(|e| CommandError::new(Text::literal(e.to_string())))?; + self.level_set(pos, state) + .map_err(|e| CommandError::new(Text::literal(e.to_string())))?; } Ok(true) } fn cmd_setblock(&mut self, ctx: &Context) -> R { let pos = self.block_pos_arg(ctx, "pos")?; - let Some(Arg::Block(b)) = ctx.get("block").cloned() else { return Ok(0) }; + let Some(Arg::Block(b)) = ctx.get("block").cloned() else { + return Ok(0); + }; let state = self.block_state(&b)?; let current = self.world.block(pos[0], pos[1], pos[2]); if ctx.has("keep") && current != self.world.air { @@ -788,27 +1110,40 @@ impl Game<'_> { if !self.place_state(pos, state, ctx.has("strict"))? { return Err(err("commands.setblock.failed", &[])); } - self.feedback(Text::tr("commands.setblock.success", &[&pos[0], &pos[1], &pos[2]])); + self.feedback(Text::tr( + "commands.setblock.success", + &[&pos[0], &pos[1], &pos[2]], + )); Ok(1) } fn cmd_fill(&mut self, ctx: &Context) -> R { let a = self.block_pos_arg(ctx, "from")?; let b = self.block_pos_arg(ctx, "to")?; - let Some(Arg::Block(block)) = ctx.get("block").cloned() else { return Ok(0) }; + let Some(Arg::Block(block)) = ctx.get("block").cloned() else { + return Ok(0); + }; let filter = match ctx.get("filter") { Some(Arg::Block(f)) => Some(f.clone()), _ => None, }; let min = [a[0].min(b[0]), a[1].min(b[1]), a[2].min(b[2])]; let max = [a[0].max(b[0]), a[1].max(b[1]), a[2].max(b[2])]; - let area = (0..3).map(|i| i64::from(max[i] - min[i] + 1)).product::(); + let area = (0..3) + .map(|i| i64::from(max[i] - min[i] + 1)) + .product::(); let limit = self.ui.rules.int("max_block_modifications"); if area > i64::from(limit) { return Err(err("commands.fill.toobig", &[&limit, &area])); } let state = self.block_state(&block)?; let air = self.world.air; - let (hollow, outline, destroy, strict, keep) = (ctx.has("hollow"), ctx.has("outline"), ctx.has("destroy"), ctx.has("strict"), ctx.has("keep")); + let (hollow, outline, destroy, strict, keep) = ( + ctx.has("hollow"), + ctx.has("outline"), + ctx.has("destroy"), + ctx.has("strict"), + ctx.has("keep"), + ); let mut count = 0; for y in min[1]..=max[1] { for z in min[2]..=max[2] { @@ -822,7 +1157,12 @@ impl Game<'_> { { continue; } - let edge = x == min[0] || x == max[0] || y == min[1] || y == max[1] || z == min[2] || z == max[2]; + let edge = x == min[0] + || x == max[0] + || y == min[1] + || y == max[1] + || z == min[2] + || z == max[2]; let mut affected = false; if destroy && current != air { let creative = self.creative; @@ -896,7 +1236,15 @@ impl Game<'_> { { continue; } - copies.push(([x, y, z], [dest[0] + x - min[0], dest[1] + y - min[1], dest[2] + z - min[2]], s)); + copies.push(( + [x, y, z], + [ + dest[0] + x - min[0], + dest[1] + y - min[1], + dest[2] + z - min[2], + ], + s, + )); } } } @@ -934,7 +1282,8 @@ impl Game<'_> { } } while e.progress >= 1.0 { - e.progress = (e.progress - 1.0) * horizon_client::entities::Experience::needed(e.level) as f32; + e.progress = + (e.progress - 1.0) * horizon_client::entities::Experience::needed(e.level) as f32; e.level += 1; e.progress /= horizon_client::entities::Experience::needed(e.level) as f32; } @@ -945,8 +1294,15 @@ impl Game<'_> { if ctx.has("query") { let _ = self.entities(ctx, "target", true)?; let e = &self.experience; - let value = if levels { e.level } else { (e.progress * horizon_client::entities::Experience::needed(e.level) as f32) as i32 }; - self.system_message(Text::translate(&format!("commands.experience.query.{unit}"), &[Text::literal(PLAYER_NAME), Text::literal(value.to_string())])); + let value = if levels { + e.level + } else { + (e.progress * horizon_client::entities::Experience::needed(e.level) as f32) as i32 + }; + self.system_message(Text::translate( + &format!("commands.experience.query.{unit}"), + &[Text::literal(PLAYER_NAME), Text::literal(value.to_string())], + )); return Ok(value); } let targets = self.entities(ctx, "target", true)?; @@ -970,13 +1326,30 @@ impl Game<'_> { } self.experience.progress = amount as f32 / needed as f32; } - let key = format!("commands.experience.{op}.{unit}.success.{}", if targets.len() == 1 { "single" } else { "multiple" }); - self.feedback(Text::translate(&key, &[Text::literal(amount.to_string()), Text::literal(PLAYER_NAME)])); + let key = format!( + "commands.experience.{op}.{unit}.success.{}", + if targets.len() == 1 { + "single" + } else { + "multiple" + } + ); + self.feedback(Text::translate( + &key, + &[ + Text::literal(amount.to_string()), + Text::literal(PLAYER_NAME), + ], + )); Ok(targets.len() as i32) } fn cmd_gamerule(&mut self, ctx: &Context) -> R { - let Some(name) = ctx.literals.get(1).cloned() else { return Ok(0) }; - let Some(rule) = gamerules::rule(&name) else { return Ok(0) }; + let Some(name) = ctx.literals.get(1).cloned() else { + return Ok(0); + }; + let Some(rule) = gamerules::rule(&name) else { + return Ok(0); + }; let current = self.ui.rules.get(rule.name).unwrap_or(rule.default); let value = match ctx.get("value") { Some(Arg::Bool(b)) => Value::Bool(*b), @@ -1001,15 +1374,26 @@ impl Game<'_> { }) } fn cmd_difficulty(&mut self, ctx: &Context) -> R { - let name = |d: u8| Text::translate(&format!("options.difficulty.{}", DIFFICULTIES[d as usize]), &[]); + let name = |d: u8| { + Text::translate( + &format!("options.difficulty.{}", DIFFICULTIES[d as usize]), + &[], + ) + }; let Some(i) = DIFFICULTIES.iter().position(|d| ctx.has(d)) else { let current = self.ui.difficulty; - self.system_message(Text::translate("commands.difficulty.query", &[name(current)])); + self.system_message(Text::translate( + "commands.difficulty.query", + &[name(current)], + )); return Ok(i32::from(current)); }; let i = i as u8; if self.ui.difficulty == i { - return Err(CommandError::new(Text::translate("commands.difficulty.failure", &[Text::literal(DIFFICULTIES[i as usize])]))); + return Err(CommandError::new(Text::translate( + "commands.difficulty.failure", + &[Text::literal(DIFFICULTIES[i as usize])], + ))); } self.ui.difficulty = i; self.sync_rules(); @@ -1021,12 +1405,20 @@ impl Game<'_> { Ok(0) } fn cmd_spawnpoint(&mut self, ctx: &Context) -> R { - let targets = if ctx.get("targets").is_some() { self.entities(ctx, "targets", true)? } else { vec![Target::Player] }; + let targets = if ctx.get("targets").is_some() { + self.entities(ctx, "targets", true)? + } else { + vec![Target::Player] + }; let pos = if ctx.get("pos").is_some() { self.block_pos_arg(ctx, "pos")? } else { let p = self.source_position(); - [p[0].floor() as i32, p[1].floor() as i32, p[2].floor() as i32] + [ + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32, + ] }; let rot = match ctx.get("rotation") { Some(Arg::Coords(c)) => c.rotation(self.source_rotation()), @@ -1034,10 +1426,21 @@ impl Game<'_> { }; let yaw = ((rot[0] + 180.0).rem_euclid(360.0)) - 180.0; let pitch = rot[1].clamp(-90.0, 90.0); - self.spawn = Some(Vec3::new(f64::from(pos[0]) + 0.5, f64::from(pos[1]), f64::from(pos[2]) + 0.5)); + self.spawn = Some(Vec3::new( + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + )); let dim = Text::literal(self.dim.id()); let p = pos.map(|v| Text::literal(v.to_string())); - let mut args = vec![p[0].clone(), p[1].clone(), p[2].clone(), Text::literal(java_float(f64::from(yaw))), Text::literal(java_float(f64::from(pitch))), dim]; + let mut args = vec![ + p[0].clone(), + p[1].clone(), + p[2].clone(), + Text::literal(java_float(f64::from(yaw))), + Text::literal(java_float(f64::from(pitch))), + dim, + ]; let key = if targets.len() == 1 { args.push(Text::literal(PLAYER_NAME)); "commands.spawnpoint.success.single" @@ -1053,7 +1456,11 @@ impl Game<'_> { self.block_pos_arg(ctx, "pos")? } else { let p = self.source_position(); - [p[0].floor() as i32, p[1].floor() as i32, p[2].floor() as i32] + [ + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32, + ] }; if self.dim != Dim::Overworld { return Err(err("commands.setworldspawn.failure.not_overworld", &[])); @@ -1080,15 +1487,32 @@ impl Game<'_> { } if predicate.tag { let tag = predicate.id.trim_start_matches("minecraft:"); - return self.res.items.item_tags.get(tag).or_else(|| self.res.items.item_tags.get(&predicate.id)).is_some_and(|s| s.contains(item) || s.contains(item.trim_start_matches("minecraft:"))); + return self + .res + .items + .item_tags + .get(tag) + .or_else(|| self.res.items.item_tags.get(&predicate.id)) + .is_some_and(|s| { + s.contains(item) || s.contains(item.trim_start_matches("minecraft:")) + }); } predicate.id == item } fn cmd_clear(&mut self, ctx: &Context) -> R { - let targets = if ctx.get("targets").is_some() { self.entities(ctx, "targets", true)? } else { vec![Target::Player] }; + let targets = if ctx.get("targets").is_some() { + self.entities(ctx, "targets", true)? + } else { + vec![Target::Player] + }; let predicate = match ctx.get("item") { Some(Arg::Item(i)) => i.clone(), - _ => ItemInput { id: "*".into(), tag: false, any: true, components: None }, + _ => ItemInput { + id: "*".into(), + tag: false, + any: true, + components: None, + }, }; let max = Self::int(ctx, "maxCount").unwrap_or(-1); let counting = max == 0; @@ -1108,7 +1532,11 @@ impl Game<'_> { if predicate.tag { continue; } - let take = if counting { stack.count as i32 } else { (stack.count as i32).min(budget) }; + let take = if counting { + stack.count as i32 + } else { + (stack.count as i32).min(budget) + }; removed += take; if !counting { budget -= take; @@ -1125,12 +1553,21 @@ impl Game<'_> { // Tag predicates: match against item tags. let pred = predicate.clone(); let mut budget = if max < 0 { i32::MAX } else { max }; - let items: Vec<(usize, String, u32)> = self.inventory.iter().enumerate().filter_map(|(i, s)| s.as_ref().map(|s| (i, s.item.to_string(), s.count))).collect(); + let items: Vec<(usize, String, u32)> = self + .inventory + .iter() + .enumerate() + .filter_map(|(i, s)| s.as_ref().map(|s| (i, s.item.to_string(), s.count))) + .collect(); for (i, item, count) in items { if !self.item_matches(&pred, &item) { continue; } - let take = if counting { count as i32 } else { (count as i32).min(budget) }; + let take = if counting { + count as i32 + } else { + (count as i32).min(budget) + }; removed += take; if !counting && let Some(s) = self.inventory[i].as_mut() { budget -= take; @@ -1143,19 +1580,30 @@ impl Game<'_> { } if removed == 0 { return Err(if targets.len() == 1 { - CommandError::new(Text::translate("clear.failed.single", &[Text::literal(PLAYER_NAME)])) + CommandError::new(Text::translate( + "clear.failed.single", + &[Text::literal(PLAYER_NAME)], + )) } else { err("clear.failed.multiple", &[&targets.len()]) }); } let kind = if counting { "test" } else { "success" }; - self.feedback(Text::translate(&format!("commands.clear.{kind}.single"), &[Text::literal(removed.to_string()), Text::literal(PLAYER_NAME)])); + self.feedback(Text::translate( + &format!("commands.clear.{kind}.single"), + &[ + Text::literal(removed.to_string()), + Text::literal(PLAYER_NAME), + ], + )); Ok(removed) } fn cmd_locate(&mut self, id: &str, ctx: &Context) -> R { let origin = self.source_position(); if id == "locate.biome" { - let Some(Arg::Resource(biome)) = ctx.get("biome").cloned() else { return Ok(0) }; + let Some(Arg::Resource(biome)) = ctx.get("biome").cloned() else { + return Ok(0); + }; // Search loaded chunks around the player (BiomeSource.findClosestBiome3d // samples a 6400-block radius; Horizon searches what is generated). let (px, pz) = (origin[0].floor() as i32, origin[2].floor() as i32); @@ -1174,16 +1622,38 @@ impl Game<'_> { } } let Some((p, d2)) = best else { - return Err(CommandError::new(Text::tr("commands.locate.biome.not_found", &[&biome]))); + return Err(CommandError::new(Text::tr( + "commands.locate.biome.not_found", + &[&biome], + ))); }; let coords = Text::tr("chat.coordinates", &[&p[0], &p[1], &p[2]]); - let link = Text::literal("[").append(coords).append("]").with_style(&Style { color: Some(text::GREEN), suggest: Some(format!("/tp @s {} {} {}", p[0], p[1], p[2])), ..Style::default() }); + let link = Text::literal("[") + .append(coords) + .append("]") + .with_style(&Style { + color: Some(text::GREEN), + suggest: Some(format!("/tp @s {} {} {}", p[0], p[1], p[2])), + ..Style::default() + }); let distance = d2.sqrt().floor() as i32; - self.system_message(Text::translate("commands.locate.biome.success", &[Text::literal(biome), link, Text::literal(distance.to_string())])); + self.system_message(Text::translate( + "commands.locate.biome.success", + &[ + Text::literal(biome), + link, + Text::literal(distance.to_string()), + ], + )); return Ok(distance); } - let Some(Arg::Resource(s)) = ctx.get("structure").cloned() else { return Ok(0) }; - Err(CommandError::new(Text::tr("commands.locate.structure.not_found", &[&s]))) + let Some(Arg::Resource(s)) = ctx.get("structure").cloned() else { + return Ok(0); + }; + Err(CommandError::new(Text::tr( + "commands.locate.structure.not_found", + &[&s], + ))) } fn cmd_say(&mut self, id: &str, ctx: &Context) -> R { let raw = match ctx.get(if id == "me" { "action" } else { "message" }) { @@ -1192,18 +1662,33 @@ impl Game<'_> { }; let message = self.expand_selectors(&raw); let line = match id { - "say" => Text::translate("chat.type.announcement", &[Text::literal(PLAYER_NAME), message]), + "say" => Text::translate( + "chat.type.announcement", + &[Text::literal(PLAYER_NAME), message], + ), "me" => Text::translate("chat.type.emote", &[Text::literal(PLAYER_NAME), message]), _ => { let _ = self.entities(ctx, "targets", true)?; // Whispering to yourself: the incoming and outgoing lines. - let out = Text::translate("commands.message.display.outgoing", &[Text::literal(PLAYER_NAME), message.clone()]).with_color(text::GRAY).italic(); + let out = Text::translate( + "commands.message.display.outgoing", + &[Text::literal(PLAYER_NAME), message.clone()], + ) + .with_color(text::GRAY) + .italic(); self.system_message(out); - Text::translate("commands.message.display.incoming", &[Text::literal(PLAYER_NAME), message]).with_color(text::GRAY).italic() + Text::translate( + "commands.message.display.incoming", + &[Text::literal(PLAYER_NAME), message], + ) + .with_color(text::GRAY) + .italic() } }; let focused = self.screen == Screen::Chat; - self.ui.chat.add(&self.res.atlas, line, None, self.ticks, focused); + self.ui + .chat + .add(&self.res.atlas, line, None, self.ticks, focused); Ok(1) } /// MessageArgument: `@p`-style selectors in a message become names. @@ -1213,7 +1698,12 @@ impl Game<'_> { while let Some(at) = rest.find('@') { out.push(&rest[..at]); let mut reader = Reader::new(&rest[at..]); - match (horizon_client::command::ArgType::Entity { single: false, players: false }).parse(&mut reader, &self.ui.registries) { + match (horizon_client::command::ArgType::Entity { + single: false, + players: false, + }) + .parse(&mut reader, &self.ui.registries) + { Ok(Arg::Entity(s)) if reader.cursor > 1 => { let found = self.select(&s); for (i, t) in found.iter().enumerate() { diff --git a/crates/horizon-client/src/game/commands/effects.rs b/crates/horizon-client/src/game/commands/effects.rs index 9bb9e598c..ffa44d745 100644 --- a/crates/horizon-client/src/game/commands/effects.rs +++ b/crates/horizon-client/src/game/commands/effects.rs @@ -25,7 +25,15 @@ impl Tracker { fn namespaced(id: &'static str) -> &'static str { static IDS: OnceLock> = OnceLock::new(); IDS.get_or_init(|| { - brewing::EFFECTS.iter().map(|e| (e.id, &*Box::leak(format!("minecraft:{}", e.id).into_boxed_str()))).collect() + brewing::EFFECTS + .iter() + .map(|e| { + ( + e.id, + &*Box::leak(format!("minecraft:{}", e.id).into_boxed_str()), + ) + }) + .collect() }) .get(id) .copied() @@ -36,17 +44,32 @@ fn effect_name(id: &str) -> Text { } impl Game<'_> { fn effect_arg(ctx: &Context) -> R<&'static brewing::EffectDef> { - let Some(Arg::Resource(id)) = ctx.get("effect") else { return Err(err("argument.resource.invalid_type", &[])) }; - brewing::effect(id).ok_or_else(|| err("argument.resource.not_found", &[id, &"minecraft:mob_effect"])) + let Some(Arg::Resource(id)) = ctx.get("effect") else { + return Err(err("argument.resource.invalid_type", &[])); + }; + brewing::effect(id).ok_or_else(|| { + err( + "argument.resource.not_found", + &[id, &"minecraft:mob_effect"], + ) + }) } /// The executing entity for argument-less forms (the player). fn living_targets(&mut self, ctx: &Context) -> R> { - if ctx.get("targets").is_some() { self.entities(ctx, "targets", false) } else { Ok(vec![Target::Player]) } + if ctx.get("targets").is_some() { + self.entities(ctx, "targets", false) + } else { + Ok(vec![Target::Player]) + } } /// `EffectCommands.giveEffect`. pub(super) fn cmd_effect_give(&mut self, ctx: &Context) -> R { let effect = Self::effect_arg(ctx)?; - let seconds = if ctx.has("infinite") { Some(-1) } else { Self::int(ctx, "seconds") }; + let seconds = if ctx.has("infinite") { + Some(-1) + } else { + Self::int(ctx, "seconds") + }; let amplifier = Self::int(ctx, "amplifier").unwrap_or(0); let particles = !matches!(ctx.get("hideParticles"), Some(Arg::Bool(true))); // computeDurationInTicks @@ -80,11 +103,19 @@ impl Game<'_> { [] => return Err(err("commands.effect.give.failed", &[])), [one] => Text::translate( "commands.effect.give.success.single", - &[effect_name(effect.id), self.target_name(*one), Text::literal((duration / 20).to_string())], + &[ + effect_name(effect.id), + self.target_name(*one), + Text::literal((duration / 20).to_string()), + ], ), many => Text::translate( "commands.effect.give.success.multiple", - &texts(&[effect_name(effect.id), Text::literal(many.len().to_string()), Text::literal((duration / 20).to_string())]), + &texts(&[ + effect_name(effect.id), + Text::literal(many.len().to_string()), + Text::literal((duration / 20).to_string()), + ]), ), }; self.feedback(message); @@ -92,7 +123,11 @@ impl Game<'_> { } /// `EffectCommands.clearEffects` / `clearEffect`. pub(super) fn cmd_effect_clear(&mut self, ctx: &Context) -> R { - let effect = if ctx.get("effect").is_some() { Some(Self::effect_arg(ctx)?) } else { None }; + let effect = if ctx.get("effect").is_some() { + Some(Self::effect_arg(ctx)?) + } else { + None + }; let mut tracker = Tracker::default(); for t in self.living_targets(ctx)? { let changed = match (t, effect) { @@ -109,7 +144,9 @@ impl Game<'_> { (Target::Mob(id), e) => match self.mobs.iter_mut().find(|m| m.id == id) { Some(m) => { let before = m.extra.effects.len(); - m.extra.effects.retain(|x| e.is_some_and(|e| x.0 != namespaced(e.id))); + m.extra + .effects + .retain(|x| e.is_some_and(|e| x.0 != namespaced(e.id))); m.extra.effects.len() != before } None => false, @@ -121,9 +158,18 @@ impl Game<'_> { let message = match (tracker.changed.as_slice(), effect) { ([], None) => return Err(err("commands.effect.clear.everything.failed", &[])), ([], Some(_)) => return Err(err("commands.effect.clear.specific.failed", &[])), - ([one], None) => Text::translate("commands.effect.clear.everything.success.single", &[self.target_name(*one)]), - (many, None) => Text::translate("commands.effect.clear.everything.success.multiple", &[Text::literal(many.len().to_string())]), - ([one], Some(e)) => Text::translate("commands.effect.clear.specific.success.single", &[effect_name(e.id), self.target_name(*one)]), + ([one], None) => Text::translate( + "commands.effect.clear.everything.success.single", + &[self.target_name(*one)], + ), + (many, None) => Text::translate( + "commands.effect.clear.everything.success.multiple", + &[Text::literal(many.len().to_string())], + ), + ([one], Some(e)) => Text::translate( + "commands.effect.clear.specific.success.single", + &[effect_name(e.id), self.target_name(*one)], + ), (many, Some(e)) => Text::translate( "commands.effect.clear.specific.success.multiple", &texts(&[effect_name(e.id), Text::literal(many.len().to_string())]), @@ -135,10 +181,17 @@ impl Game<'_> { /// `EnchantCommand.enchant` (mobs hold bare item ids, so only the player's /// main hand item can carry the enchantment). pub(super) fn cmd_enchant(&mut self, ctx: &Context) -> R { - let Some(Arg::Resource(id)) = ctx.get("enchantment").cloned() else { return Ok(0) }; + let Some(Arg::Resource(id)) = ctx.get("enchantment").cloned() else { + return Ok(0); + }; let level = Self::int(ctx, "level").unwrap_or(1); let enchantments = &self.res.stations.enchantments; - let Some(def) = enchantments.get(&id) else { return Err(err("argument.resource.not_found", &[&id, &"minecraft:enchantment"])) }; + let Some(def) = enchantments.get(&id) else { + return Err(err( + "argument.resource.not_found", + &[&id, &"minecraft:enchantment"], + )); + }; let max = def.max_level as i32; if level > max { return Err(err("commands.enchant.failed.level", &[&level, &max])); @@ -151,13 +204,19 @@ impl Game<'_> { Target::Player => { let Some(stack) = self.inventory[self.selected].clone() else { if single { - return Err(err("commands.enchant.failed.itemless", &[&self.target_name(t).plain()])); + return Err(err( + "commands.enchant.failed.itemless", + &[&self.target_name(t).plain()], + )); } continue; }; let e = &self.res.stations.enchantments; let compatible = e.can_enchant(&self.res.items, &id, &stack.item) - && stack.crafting_enchantments().iter().all(|(other, _)| e.compatible(other, &id)); + && stack + .crafting_enchantments() + .iter() + .all(|(other, _)| e.compatible(other, &id)); if compatible { if let Some(s) = self.inventory[self.selected].as_mut() { s.enchant(&id, level.max(0) as u32); @@ -165,29 +224,63 @@ impl Game<'_> { tracker.track(t, true); } else if single { // getHoverName().getString(): the custom or item name, no brackets. - return Err(err("commands.enchant.failed.incompatible", &[&stack.custom_name().map_or_else(|| self.res.names.item(&stack.item).to_string(), str::to_owned)])); + return Err(err( + "commands.enchant.failed.incompatible", + &[&stack.custom_name().map_or_else( + || self.res.names.item(&stack.item).to_string(), + str::to_owned, + )], + )); } } Target::Mob(mob) => { - let held = self.mobs.iter().find(|m| m.id == mob).and_then(|m| m.extra.main_hand.clone()); + let held = self + .mobs + .iter() + .find(|m| m.id == mob) + .and_then(|m| m.extra.main_hand.clone()); if single { return Err(match held { - None => err("commands.enchant.failed.itemless", &[&self.target_name(t).plain()]), - Some(item) => err("commands.enchant.failed.incompatible", &[&self.res.names.item(&item)]), + None => err( + "commands.enchant.failed.itemless", + &[&self.target_name(t).plain()], + ), + Some(item) => err( + "commands.enchant.failed.incompatible", + &[&self.res.names.item(&item)], + ), }); } } - _ if single => return Err(err("commands.enchant.failed.entity", &[&self.target_name(t).plain()])), + _ if single => { + return Err(err( + "commands.enchant.failed.entity", + &[&self.target_name(t).plain()], + )); + } _ => {} } } - let (name, curse) = self.res.stations.enchantments.full_name(&id, level.max(0) as u32); - let style = Style { color: Some(if curse { text::RED } else { text::GRAY }), ..Style::default() }; + let (name, curse) = self + .res + .stations + .enchantments + .full_name(&id, level.max(0) as u32); + let style = Style { + color: Some(if curse { text::RED } else { text::GRAY }), + ..Style::default() + }; let full = Text::styled(name, style); let message = match tracker.changed.as_slice() { [] => return Err(err("commands.enchant.failed", &[])), - [one] => Text::translate("commands.enchant.success.single", &[full, self.target_name(*one)]), - many => Text::translate("commands.enchant.success.multiple", &texts(&[full, Text::literal(many.len().to_string())])), + [one] => Text::translate( + "commands.enchant.success.single", + &[full, self.target_name(*one)], + ), + many => Text::translate( + "commands.enchant.success.multiple", + &texts(&[full, Text::literal(many.len().to_string())]), + ), }; self.feedback(message); Ok(tracker.total) diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 88b78fe76..827c3caca 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -274,15 +274,26 @@ impl Game<'_> { } self.require_world()?; self.handle_chat_input(text); - Ok(Some(json!({ "ok": true, "chat": self.ui.chat.recent_lines(5) }))) + Ok(Some( + json!({ "ok": true, "chat": self.ui.chat.recent_lines(5) }), + )) } "type" => { self.require_world()?; - let text = line.trim_start().strip_prefix("type").unwrap_or("").strip_prefix(' ').unwrap_or(""); + let text = line + .trim_start() + .strip_prefix("type") + .unwrap_or("") + .strip_prefix(' ') + .unwrap_or(""); match self.screen { Screen::Chat => self.chat_type(text), Screen::Options => self.ui.options.type_text(text), - _ => return Err("type needs the chat screen (key t tap) or the language search".into()), + _ => { + return Err( + "type needs the chat screen (key t tap) or the language search".into(), + ); + } } ok() } @@ -346,7 +357,9 @@ impl Game<'_> { if self.title.is_none() { return Err("leave the current world first".into()); } - let name = words.get(2).map_or_else(|| self.options.player_name.clone(), |n| (*n).to_owned()); + let name = words + .get(2) + .map_or_else(|| self.options.player_name.clone(), |n| (*n).to_owned()); self.connect_server(arg(1)?, &name)?; ok() } diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index a562c2953..88268379a 100644 --- a/crates/horizon-client/src/game/enchant_effects.rs +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -14,7 +14,11 @@ impl Game<'_> { pub(super) fn modify_destroy_speed(&self, mut speed: f32) -> f32 { if speed > 1.0 { let held = self.inventory[self.selected].as_ref(); - speed += self.res.stations.enchantments.attribute_add(held, "minecraft:mining_efficiency") as f32; + speed += self + .res + .stations + .enchantments + .attribute_add(held, "minecraft:mining_efficiency") as f32; } speed * self.potions.effects.mining_speed_factor() } @@ -36,48 +40,121 @@ impl Game<'_> { if !e.has_component(stack, "minecraft:item_damage") { return amount; } - let ctx = EffectContext { tool: Some(&stack.item), items: Some(&self.res.items), ..Default::default() }; - e.modify_value(Some(stack), "minecraft:item_damage", &ctx, &mut self.world.random, amount as f32).max(0.0) as u32 + let ctx = EffectContext { + tool: Some(&stack.item), + items: Some(&self.res.items), + ..Default::default() + }; + e.modify_value( + Some(stack), + "minecraft:item_damage", + &ctx, + &mut self.world.random, + amount as f32, + ) + .max(0.0) as u32 } /// `getEnchantedDamage - base`: damage bonus of the held weapon against a mob type. pub(super) fn enchant_damage_bonus(&mut self, target: &str) -> f32 { - let Some(held) = self.inventory[self.selected].clone() else { return 0.0 }; - let ctx = EffectContext { this: Some(target), attacker: Some("minecraft:player"), direct_attacker: Some("minecraft:player"), is_direct: true, damage_type: Some("minecraft:player_attack"), items: Some(&self.res.items), ..Default::default() }; - self.res.stations.enchantments.modify_value(Some(&held), "minecraft:damage", &ctx, &mut self.world.random, 0.0) + let Some(held) = self.inventory[self.selected].clone() else { + return 0.0; + }; + let ctx = EffectContext { + this: Some(target), + attacker: Some("minecraft:player"), + direct_attacker: Some("minecraft:player"), + is_direct: true, + damage_type: Some("minecraft:player_attack"), + items: Some(&self.res.items), + ..Default::default() + }; + self.res.stations.enchantments.modify_value( + Some(&held), + "minecraft:damage", + &ctx, + &mut self.world.random, + 0.0, + ) } /// Strength / weakness on the attack damage attribute. pub(super) fn effect_attack_bonus(&self) -> f32 { let fx = &self.potions.effects; - fx.amplifier("strength").map_or(0.0, |a| 3.0 * (a + 1) as f32) - fx.amplifier("weakness").map_or(0.0, |a| 4.0 * (a + 1) as f32) + fx.amplifier("strength") + .map_or(0.0, |a| 3.0 * (a + 1) as f32) + - fx.amplifier("weakness") + .map_or(0.0, |a| 4.0 * (a + 1) as f32) } /// After a successful melee hit: knockback enchantment and fire aspect. pub(super) fn post_attack(&mut self, mob: usize) { - let Some(held) = self.inventory[self.selected].clone() else { return }; + let Some(held) = self.inventory[self.selected].clone() else { + return; + }; let Some(m) = self.mobs.get(mob) else { return }; let kind = m.kind.id.clone(); - let ctx = EffectContext { this: Some(&kind), attacker: Some("minecraft:player"), direct_attacker: Some("minecraft:player"), is_direct: true, items: Some(&self.res.items), ..Default::default() }; - let knockback = self.res.stations.enchantments.modify_value(Some(&held), "minecraft:knockback", &ctx, &mut self.world.random, 0.0); + let ctx = EffectContext { + this: Some(&kind), + attacker: Some("minecraft:player"), + direct_attacker: Some("minecraft:player"), + is_direct: true, + items: Some(&self.res.items), + ..Default::default() + }; + let knockback = self.res.stations.enchantments.modify_value( + Some(&held), + "minecraft:knockback", + &ctx, + &mut self.world.random, + 0.0, + ); if knockback > 0.0 { // LivingEntity.knockback(strength * 0.5, sin(yRot), -cos(yRot)). let strength = f64::from(knockback) * 0.5; - let (s, c) = (f64::from(self.yaw.to_radians().sin()), f64::from(self.yaw.to_radians().cos())); + let (s, c) = ( + f64::from(self.yaw.to_radians().sin()), + f64::from(self.yaw.to_radians().cos()), + ); let (dx, dz) = (s, -c); let l = (dx * dx + dz * dz).sqrt().max(1e-5); let m = &mut self.mobs[mob]; let v = m.velocity; - m.velocity = Vec3::new(v.x / 2.0 - dx / l * strength, if m.on_ground { (v.y / 2.0 + strength).min(0.4) } else { v.y }, v.z / 2.0 - dz / l * strength); + m.velocity = Vec3::new( + v.x / 2.0 - dx / l * strength, + if m.on_ground { + (v.y / 2.0 + strength).min(0.4) + } else { + v.y + }, + v.z / 2.0 - dz / l * strength, + ); } // minecraft:post_attack ignite effects of the attacker's weapon (fire aspect). let mut ignite = 0.0f32; for (id, level) in held.enchantments() { - let Some(def) = self.res.stations.enchantments.get(id) else { continue }; - for effect in def.effects["minecraft:post_attack"].as_array().into_iter().flatten() { - if effect["enchanted"] == "attacker" && effect["affected"] == "victim" && effect["effect"]["type"] == "minecraft:ignite" { + let Some(def) = self.res.stations.enchantments.get(id) else { + continue; + }; + for effect in def.effects["minecraft:post_attack"] + .as_array() + .into_iter() + .flatten() + { + if effect["enchanted"] == "attacker" + && effect["affected"] == "victim" + && effect["effect"]["type"] == "minecraft:ignite" + { let mut random = self.world.random.clone(); - let ok = effect.get("requirements").is_none_or(|r| self.res.stations.enchantments.condition(r, *level, &ctx, &mut random)); + let ok = effect.get("requirements").is_none_or(|r| { + self.res + .stations + .enchantments + .condition(r, *level, &ctx, &mut random) + }); self.world.random = random; if ok { - ignite = ignite.max(horizon_client::enchant::level_value(&effect["effect"]["duration"], *level)); + ignite = ignite.max(horizon_client::enchant::level_value( + &effect["effect"]["duration"], + *level, + )); } } } @@ -94,7 +171,9 @@ impl Game<'_> { let mut burning = std::mem::take(&mut self.potions.burning); burning.retain_mut(|(id, ticks)| { *ticks -= 1; - let Some(m) = self.mobs.iter_mut().find(|m| m.id == *id && m.alive()) else { return false }; + let Some(m) = self.mobs.iter_mut().find(|m| m.id == *id && m.alive()) else { + return false; + }; if *ticks % 20 == 0 { let at = [m.position.x, m.position.y, m.position.z]; if m.hurt(1.0, None, &mut self.world.random) { @@ -114,22 +193,38 @@ impl Game<'_> { .enumerate() .filter(|(_, m)| m.alive()) .min_by(|a, b| { - let d = |m: &horizon_client::mobs::Mob| (m.position.x - from[0]).powi(2) + (m.position.y - from[1]).powi(2) + (m.position.z - from[2]).powi(2); + let d = |m: &horizon_client::mobs::Mob| { + (m.position.x - from[0]).powi(2) + + (m.position.y - from[1]).powi(2) + + (m.position.z - from[2]).powi(2) + }; d(a.1).total_cmp(&d(b.1)) }) .map(|(i, _)| i); let Some(attacker) = attacker else { return }; for slot in 0..4 { - let Some(stack) = self.armor[slot].clone() else { continue }; + let Some(stack) = self.armor[slot].clone() else { + continue; + }; let level = stack.enchantment_level("minecraft:thorns"); if level == 0 { continue; } - let Some(def) = self.res.stations.enchantments.get("minecraft:thorns") else { continue }; + let Some(def) = self.res.stations.enchantments.get("minecraft:thorns") else { + continue; + }; let effect = def.effects["minecraft:post_attack"][0].clone(); - let ctx = EffectContext { items: Some(&self.res.items), ..Default::default() }; + let ctx = EffectContext { + items: Some(&self.res.items), + ..Default::default() + }; let mut random = self.world.random.clone(); - let ok = self.res.stations.enchantments.condition(&effect["requirements"], level, &ctx, &mut random); + let ok = self.res.stations.enchantments.condition( + &effect["requirements"], + level, + &ctx, + &mut random, + ); self.world.random = random; if !ok { continue; @@ -141,10 +236,16 @@ impl Game<'_> { m.hurt(damage, None, &mut self.world.random); [m.position.x, m.position.y, m.position.z] }; - self.audio.play("minecraft:enchant.thorns.hit", Some(center), 1.0, 1.0); + self.audio + .play("minecraft:enchant.thorns.hit", Some(center), 1.0, 1.0); if let Some(s) = self.armor[slot].as_mut() { s.damage += 2; - if self.res.items.get(&s.item).is_some_and(|i| s.damage >= i.max_damage) { + if self + .res + .items + .get(&s.item) + .is_some_and(|i| s.damage >= i.max_damage) + { self.armor[slot] = None; } } @@ -173,13 +274,34 @@ impl Game<'_> { if candidates.is_empty() { return amount; } - let (armor, i) = candidates[self.world.random.next_int_bound(candidates.len() as i32).unwrap_or(0) as usize]; - let stack = if armor { self.armor[i].clone() } else { self.inventory[i].clone() }; + let (armor, i) = candidates[self + .world + .random + .next_int_bound(candidates.len() as i32) + .unwrap_or(0) as usize]; + let stack = if armor { + self.armor[i].clone() + } else { + self.inventory[i].clone() + }; let Some(stack) = stack else { return amount }; - let ctx = EffectContext { items: Some(&self.res.items), ..Default::default() }; - let to_repair_xp = self.res.stations.enchantments.modify_value(Some(&stack), "minecraft:repair_with_xp", &ctx, &mut self.world.random, amount as f32) as u32; + let ctx = EffectContext { + items: Some(&self.res.items), + ..Default::default() + }; + let to_repair_xp = self.res.stations.enchantments.modify_value( + Some(&stack), + "minecraft:repair_with_xp", + &ctx, + &mut self.world.random, + amount as f32, + ) as u32; let repaired = to_repair_xp.min(stack.damage); - let slot = if armor { &mut self.armor[i] } else { &mut self.inventory[i] }; + let slot = if armor { + &mut self.armor[i] + } else { + &mut self.inventory[i] + }; if let Some(s) = slot.as_mut() { s.damage -= repaired; } @@ -195,12 +317,36 @@ impl Game<'_> { } /// Bow enchantments at release: (extra base damage, infinity keeps the arrow). pub(super) fn bow_enchantments(&mut self) -> (f64, bool) { - let Some(bow) = self.inventory[self.selected].clone() else { return (0.0, false) }; + let Some(bow) = self.inventory[self.selected].clone() else { + return (0.0, false); + }; let e = &self.res.stations.enchantments; - let ctx = EffectContext { direct_attacker: Some("minecraft:arrow"), attacker: Some("minecraft:player"), items: Some(&self.res.items), ..Default::default() }; - let power = e.modify_value(Some(&bow), "minecraft:damage", &ctx, &mut self.world.random, 0.0); - let ammo_ctx = EffectContext { tool: Some("minecraft:arrow"), items: Some(&self.res.items), ..Default::default() }; - let infinity = e.has_component(&bow, "minecraft:ammo_use") && e.modify_value(Some(&bow), "minecraft:ammo_use", &ammo_ctx, &mut self.world.random, 1.0) == 0.0; + let ctx = EffectContext { + direct_attacker: Some("minecraft:arrow"), + attacker: Some("minecraft:player"), + items: Some(&self.res.items), + ..Default::default() + }; + let power = e.modify_value( + Some(&bow), + "minecraft:damage", + &ctx, + &mut self.world.random, + 0.0, + ); + let ammo_ctx = EffectContext { + tool: Some("minecraft:arrow"), + items: Some(&self.res.items), + ..Default::default() + }; + let infinity = e.has_component(&bow, "minecraft:ammo_use") + && e.modify_value( + Some(&bow), + "minecraft:ammo_use", + &ammo_ctx, + &mut self.world.random, + 1.0, + ) == 0.0; (f64::from(power), infinity) } /// Enchantment attribute modifiers of worn armor (respiration, depth strider...). @@ -209,7 +355,9 @@ impl Game<'_> { for stack in self.armor.iter().flatten() { wanted.extend(self.res.stations.enchantments.attributes(stack)); } - let Some(p) = self.player.as_mut() else { return }; + let Some(p) = self.player.as_mut() else { + return; + }; for (attr, id, _, op) in std::mem::take(&mut self.potions.enchant_modifiers) { let _ = p.set_modifier(&attr, &id, 0.0, &op, false); } diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index 0e2975d9b..fc24fd7b4 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -644,7 +644,8 @@ impl Game<'_> { fn gateway_exits(&mut self) -> &mut HashMap<[i32; 3], ([i32; 3], bool)> { if self.end.exits.is_none() { - let path = horizon_client::save::dimension_dir(&self.world_root, "minecraft:the_end").join(GATEWAY_FILE); + let path = horizon_client::save::dimension_dir(&self.world_root, "minecraft:the_end") + .join(GATEWAY_FILE); let parsed: Option> = std::fs::read(&path) .ok() .and_then(|b| serde_json::from_slice(&b).ok()); diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 9f552ffa7..ca7abaa98 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -247,7 +247,11 @@ impl Game<'_> { [feet[0] - w, feet[1], feet[2] - w], [feet[0] + w, feet[1] + h, feet[2] + w], ); - let source = horizon_client::mobs::Damage { kind: horizon_client::mobs::DamageKind::Explosion, attacker: None, from: Some(center) }; + let source = horizon_client::mobs::Damage { + kind: horizon_client::mobs::DamageKind::Explosion, + attacker: None, + from: Some(center), + }; if !m.damage(damage(dist, exposure), source) { continue; } @@ -357,10 +361,15 @@ impl Game<'_> { let pitch = (1.0 + (client_float() - client_float()) * 0.2) * 0.7; self.audio .play("minecraft:entity.generic.explode", Some(center), 4.0, pitch); - let block_count = if interaction == BlockInteraction::Keep { 0 } else { targets.len() }; + let block_count = if interaction == BlockInteraction::Keep { + 0 + } else { + targets.len() + }; let (world, facts) = (&self.world, &self.res.facts); - self.particles - .explosion(center, radius, block_count, &|b| facts.is_air(world.block(b[0], b[1], b[2]))); + self.particles.explosion(center, radius, block_count, &|b| { + facts.is_air(world.block(b[0], b[1], b[2])) + }); Ok(()) } /// `BlockBehaviour.onExplosionHit` (TNT: `wasExploded` primes a short fuse). diff --git a/crates/horizon-client/src/game/music.rs b/crates/horizon-client/src/game/music.rs index b0198046f..110517d6e 100644 --- a/crates/horizon-client/src/game/music.rs +++ b/crates/horizon-client/src/game/music.rs @@ -8,25 +8,39 @@ impl Game<'_> { let (music, volume) = self.situational_music(); // LevelLoadingScreen: no new track before the player is in the world. let loading = self.title.is_none() && self.player.is_none(); - self.music.tick(music.as_ref(), volume, loading, &mut self.audio); + self.music + .tick(music.as_ref(), volume, loading, &mut self.audio); } 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 (x, y, z) = (eye[0].floor() as i32, eye[1].floor() as i32, eye[2].floor() as i32); + 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 .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()); + .map_or("minecraft:plains", |c| { + self.res.biomes.list[c.biome(x, y, z) as usize] + .name + .as_str() + }); 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(); + let music = tables + .background(dimension, biome) + .select(self.creative, underwater) + .cloned(); (music, tables.volume(dimension, biome)) } } @@ -34,7 +48,9 @@ impl Game<'_> { impl Game<'_> { /// The local player's ambient sound handlers (LocalPlayer.tick). pub(super) fn tick_ambience(&mut self) { - let Some(p) = self.player.as_ref() else { return }; + let Some(p) = self.player.as_ref() else { + return; + }; 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); @@ -42,14 +58,29 @@ impl Game<'_> { 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()); + .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 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) }; - let ctx = horizon_client::ambience::AmbientContext { sounds: &sounds, position: feet, eye_y, underwater, light: &light }; + let ctx = horizon_client::ambience::AmbientContext { + sounds: &sounds, + position: feet, + eye_y, + underwater, + light: &light, + }; self.ambience.tick(&ctx, &mut self.audio); } } diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index e1c886bb0..c14d0b1da 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -11,10 +11,15 @@ use winit::{event::MouseButton, keyboard::KeyCode, window::Fullscreen}; impl Game<'_> { fn options_path() -> std::path::PathBuf { - std::env::current_dir().unwrap_or_default().join("options.txt") + std::env::current_dir() + .unwrap_or_default() + .join("options.txt") } fn gui_size(&self) -> (f32, f32) { - let size = self.renderer.as_ref().map_or([1280, 720], |r| [r.config.width, r.config.height]); + let size = self + .renderer + .as_ref() + .map_or([1280, 720], |r| [r.config.width, r.config.height]); let b = HudBatch::new(size); (b.width, b.height) } @@ -42,14 +47,30 @@ impl Game<'_> { self.dragging = true; let size = self.gui_size(); let mut ui = std::mem::take(&mut self.ui.options); - let events = ui.click(&mut self.settings, &self.res.atlas, self.cursor.0, self.cursor.1, size, false, right); + let events = ui.click( + &mut self.settings, + &self.res.atlas, + self.cursor.0, + self.cursor.1, + size, + false, + right, + ); self.ui.options = ui; self.handle_option_events(events) } pub(super) fn options_drag(&mut self) -> Result<()> { let size = self.gui_size(); let mut ui = std::mem::take(&mut self.ui.options); - let events = ui.click(&mut self.settings, &self.res.atlas, self.cursor.0, self.cursor.1, size, true, false); + let events = ui.click( + &mut self.settings, + &self.res.atlas, + self.cursor.0, + self.cursor.1, + size, + true, + false, + ); self.ui.options = ui; self.handle_option_events(events) } @@ -68,7 +89,9 @@ impl Game<'_> { } pub(super) fn options_bind_mouse(&mut self, button: MouseButton) -> Result<()> { if let Some(name) = self.ui.options.selected_key.take() { - self.settings.keys.set(name, &horizon_client::keybinds::mouse_name(button)); + self.settings + .keys + .set(name, &horizon_client::keybinds::mouse_name(button)); self.handle_option_events(vec![Event::Changed])?; } Ok(()) @@ -82,7 +105,11 @@ impl Game<'_> { } Event::Close => { self.settings.save(&Self::options_path()); - self.screen = if self.options_from_title { Screen::Playing } else { Screen::Paused }; + self.screen = if self.options_from_title { + Screen::Playing + } else { + Screen::Paused + }; self.dragging = false; } Event::Language(code) => { @@ -93,7 +120,9 @@ impl Game<'_> { self.reload_packs(); } Event::OpenPackFolder => { - let dir = std::env::current_dir().unwrap_or_default().join("resourcepacks"); + let dir = std::env::current_dir() + .unwrap_or_default() + .join("resourcepacks"); let _ = std::fs::create_dir_all(&dir); let _ = std::process::Command::new("xdg-open").arg(&dir).spawn(); } @@ -153,7 +182,11 @@ impl Game<'_> { return None; } // Menus without a world run at 60 fps like vanilla's title screen. - let fps = if self.title.is_some() { fps.min(60) } else { fps }; + let fps = if self.title.is_some() { + fps.min(60) + } else { + fps + }; let due = self.previous + std::time::Duration::from_secs_f64(1.0 / f64::from(fps)); (due > std::time::Instant::now()).then_some(due) } diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index 787dfbb5b..a1f4b8c25 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -13,10 +13,14 @@ use std::path::{Path, PathBuf}; /// Where overlay roots are built (beside options.txt). pub fn cache_dir() -> PathBuf { - std::env::current_dir().unwrap_or_default().join(".horizon-cache/resourcepacks") + std::env::current_dir() + .unwrap_or_default() + .join(".horizon-cache/resourcepacks") } pub fn packs_dir() -> PathBuf { - std::env::current_dir().unwrap_or_default().join("resourcepacks") + std::env::current_dir() + .unwrap_or_default() + .join("resourcepacks") } /// The resource root to load from, given the vanilla root and the selection. pub fn startup_root(vanilla: &Path, selected: &[String]) -> PathBuf { @@ -25,7 +29,13 @@ pub fn startup_root(vanilla: &Path, selected: &[String]) -> PathBuf { packs::resource_root(vanilla, &enabled, &cache_dir()) } fn entry(p: &Pack) -> PackEntry { - PackEntry { id: p.id.clone(), title: p.title.clone(), description: p.description.clone(), compatible: p.compatible, required: false } + PackEntry { + id: p.id.clone(), + title: p.title.clone(), + description: p.description.clone(), + compatible: p.compatible, + required: false, + } } fn vanilla_entry() -> PackEntry { PackEntry { @@ -38,7 +48,11 @@ fn vanilla_entry() -> PackEntry { } impl Game<'_> { fn vanilla_root(&self) -> PathBuf { - if self.ui.vanilla_root.as_os_str().is_empty() { self.options.resources.clone() } else { self.ui.vanilla_root.clone() } + if self.ui.vanilla_root.as_os_str().is_empty() { + self.options.resources.clone() + } else { + self.ui.vanilla_root.clone() + } } /// PackSelectionModel: available (unselected) and selected (top first). pub(super) fn refresh_pack_lists(&mut self) { @@ -47,12 +61,22 @@ impl Game<'_> { let mut selected: Vec = selected_ids .iter() .rev() - .filter_map(|id| if id == "vanilla" { Some(vanilla_entry()) } else { all.iter().find(|p| &p.id == id).map(entry) }) + .filter_map(|id| { + if id == "vanilla" { + Some(vanilla_entry()) + } else { + all.iter().find(|p| &p.id == id).map(entry) + } + }) .collect(); if !selected.iter().any(|p| p.id == "vanilla") { selected.push(vanilla_entry()); } - let available = all.iter().filter(|p| !selected_ids.contains(&p.id)).map(entry).collect(); + let available = all + .iter() + .filter(|p| !selected_ids.contains(&p.id)) + .map(entry) + .collect(); self.ui.options.available = available; self.ui.options.selected = selected; } @@ -69,23 +93,42 @@ impl Game<'_> { Ok(mut atlas) => { atlas.font.uniform = self.settings.force_unicode; atlas.font.japanese = self.settings.japanese_glyphs; - let same_size = atlas.width == self.res.atlas.width && atlas.height == self.res.atlas.height; + let same_size = + atlas.width == self.res.atlas.width && atlas.height == self.res.atlas.height; if same_size { - if let Some(texture) = self.renderer.as_ref().and_then(|r| r.hud.atlas_texture.clone()) + if let Some(texture) = self + .renderer + .as_ref() + .and_then(|r| r.hud.atlas_texture.clone()) && let Some(r) = self.renderer.as_ref() { r.queue.write_texture( - wgpu::TexelCopyTextureInfo { texture: &texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + wgpu::TexelCopyTextureInfo { + texture: &texture, + mip_level: 0, + origin: wgpu::Origin3d::ZERO, + aspect: wgpu::TextureAspect::All, + }, &atlas.pixels, - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(atlas.width * 4), rows_per_image: None }, - wgpu::Extent3d { width: atlas.width, height: atlas.height, depth_or_array_layers: 1 }, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(atlas.width * 4), + rows_per_image: None, + }, + wgpu::Extent3d { + width: atlas.width, + height: atlas.height, + depth_or_array_layers: 1, + }, ); } self.res.atlas = atlas; self.res.icons.clear(); self.res.displays.clear(); } else { - eprintln!("Horizon: resource pack atlas size changed; restart to apply GUI textures"); + eprintln!( + "Horizon: resource pack atlas size changed; restart to apply GUI textures" + ); } } Err(e) => eprintln!("Horizon: resource pack reload failed: {e}"), diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 592bbe34e..96b260381 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -8,12 +8,7 @@ use horizon_client::{ entity_nbt, save::{ChunkExtras, random_uuid}, }; -use horizon_core::{ - geometry::Vec3, - position::ChunkPos, - random::RandomSource, - ticks::ChunkTicks, -}; +use horizon_core::{geometry::Vec3, position::ChunkPos, random::RandomSource, ticks::ChunkTicks}; use horizon_world::{chunk::BlockState, nbt::Tag, registry::BlockStateId}; use std::{ collections::{HashMap, HashSet}, @@ -60,9 +55,20 @@ impl Game<'_> { pub(super) fn register_chunk_ticks(&mut self, key: (i32, i32)) { let pos = ChunkPos::new(key.0, key.1); let saved = self.world.chunks.get(&key).and_then(|c| c.saved.clone()); - let (blocks, fluids) = saved.as_deref().map_or((Vec::new(), Vec::new()), |s| (s.block_ticks.clone(), s.fluid_ticks.clone())); + let (blocks, fluids) = saved.as_deref().map_or((Vec::new(), Vec::new()), |s| { + (s.block_ticks.clone(), s.fluid_ticks.clone()) + }); let loaded = !blocks.is_empty() || !fluids.is_empty(); - if self.block_ticks.add_chunk(pos, ChunkTicks::from_saved(blocks), ChunkTicks::from_saved(fluids)).is_ok() && loaded { + if self + .block_ticks + .add_chunk( + pos, + ChunkTicks::from_saved(blocks), + ChunkTicks::from_saved(fluids), + ) + .is_ok() + && loaded + { let time = self.world.game_time; self.block_ticks.blocks.unpack_chunk(pos, time); self.block_ticks.fluids.unpack_chunk(pos, time); @@ -89,7 +95,9 @@ impl Game<'_> { "minecraft:item" => { self.next_entity += 1; let bob = self.world.random.next_float() * std::f32::consts::PI * 2.0; - if let Some(e) = entity_nbt::item_entity_from_nbt(&tag, self.next_entity, bob) { + if let Some(e) = + entity_nbt::item_entity_from_nbt(&tag, self.next_entity, bob) + { self.remember(e.id, uuid, tag); self.dropped.push(e); } @@ -101,15 +109,24 @@ impl Game<'_> { } } "minecraft:falling_block" => { - if let Some((state, position, velocity, age)) = entity_nbt::falling_block_from_nbt(&tag) + if let Some((state, position, velocity, age)) = + entity_nbt::falling_block_from_nbt(&tag) && let Some(state) = self.state_from_nbt(&state) { - self.falling.push(FallingBlock { state, position, previous: position, velocity, age }); + self.falling.push(FallingBlock { + state, + position, + previous: position, + velocity, + age, + }); } } _ if self.res.mob_types.contains_key(&kind) => { self.next_entity += 1; - if let Some(m) = entity_nbt::mob_from_nbt(&tag, &self.res.mob_types, self.next_entity) { + if let Some(m) = + entity_nbt::mob_from_nbt(&tag, &self.res.mob_types, self.next_entity) + { self.remember(m.id, uuid, tag); self.mobs.push(m); } @@ -147,12 +164,16 @@ impl Game<'_> { }, _ => BlockState::from_nbt(tag).ok()?, }; - registry.id(&state).or_else(|| registry.default_state(&state.name)) + registry + .id(&state) + .or_else(|| registry.default_state(&state.name)) } fn state_to_nbt(&self, state: BlockStateId) -> Tag { let registry = self.res.assets.registry; match registry.state(state) { - Some(s) if registry.default_state(&s.name) == Some(state) => Tag::String(s.name.as_str().into()), + Some(s) if registry.default_state(&s.name) == Some(state) => { + Tag::String(s.name.as_str().into()) + } Some(s) => s.to_nbt(), None => Tag::String("minecraft:air".into()), } @@ -160,42 +181,70 @@ impl Game<'_> { /// The entity NBT of every simulated entity in `keys`, plus the unknown /// entities kept for them. With `remove`, the entities leave the world /// (their chunks unload). - fn entity_chunks(&mut self, keys: &HashSet<(i32, i32)>, remove: bool) -> Vec<((i32, i32), Vec)> { - let mut out: HashMap<(i32, i32), Vec> = keys.iter().map(|k| (*k, Vec::new())).collect(); + fn entity_chunks( + &mut self, + keys: &HashSet<(i32, i32)>, + remove: bool, + ) -> Vec<((i32, i32), Vec)> { + let mut out: HashMap<(i32, i32), Vec> = + keys.iter().map(|k| (*k, Vec::new())).collect(); let player_uuid = self.level.player_uuid; - let mobs: Vec = (0..self.mobs.len()).filter(|&i| keys.contains(&chunk_of(self.mobs[i].position)) && self.mobs[i].alive()).collect(); + let mobs: Vec = (0..self.mobs.len()) + .filter(|&i| keys.contains(&chunk_of(self.mobs[i].position)) && self.mobs[i].alive()) + .collect(); for i in mobs { let id = self.mobs[i].id; let uuid = self.uuid_for(id); let tag = entity_nbt::mob_to_nbt(&self.mobs[i], uuid, self.persist.raw.get(&id)); - out.entry(chunk_of(self.mobs[i].position)).or_default().push(tag); + out.entry(chunk_of(self.mobs[i].position)) + .or_default() + .push(tag); } - let items: Vec = (0..self.dropped.len()).filter(|&i| keys.contains(&chunk_of(self.dropped[i].position))).collect(); + let items: Vec = (0..self.dropped.len()) + .filter(|&i| keys.contains(&chunk_of(self.dropped[i].position))) + .collect(); for i in items { let id = self.dropped[i].id; let uuid = self.uuid_for(id); - let tag = entity_nbt::item_entity_to_nbt(&self.dropped[i], uuid, self.persist.raw.get(&id)); - out.entry(chunk_of(self.dropped[i].position)).or_default().push(tag); + let tag = + entity_nbt::item_entity_to_nbt(&self.dropped[i], uuid, self.persist.raw.get(&id)); + out.entry(chunk_of(self.dropped[i].position)) + .or_default() + .push(tag); } for o in &self.orbs { if keys.contains(&chunk_of(o.position)) { - out.entry(chunk_of(o.position)).or_default().push(entity_nbt::orb_to_nbt(o, random_uuid())); + out.entry(chunk_of(o.position)) + .or_default() + .push(entity_nbt::orb_to_nbt(o, random_uuid())); } } for a in &self.arrows { if keys.contains(&chunk_of(a.position)) { let owner = if a.from_player { player_uuid } else { None }; - out.entry(chunk_of(a.position)).or_default().push(entity_nbt::arrow_to_nbt(a, random_uuid(), owner)); + out.entry(chunk_of(a.position)) + .or_default() + .push(entity_nbt::arrow_to_nbt(a, random_uuid(), owner)); } } for f in &self.falling { if keys.contains(&chunk_of(f.position)) { - let tag = entity_nbt::falling_block_to_nbt(self.state_to_nbt(f.state), f.position, f.velocity, f.age, random_uuid()); + let tag = entity_nbt::falling_block_to_nbt( + self.state_to_nbt(f.state), + f.position, + f.velocity, + f.age, + random_uuid(), + ); out.entry(chunk_of(f.position)).or_default().push(tag); } } for key in keys { - let unknown = if remove { self.persist.unknown.remove(key) } else { self.persist.unknown.get(key).cloned() }; + let unknown = if remove { + self.persist.unknown.remove(key) + } else { + self.persist.unknown.get(key).cloned() + }; if let Some(list) = unknown { out.entry(*key).or_default().extend(list); } @@ -233,7 +282,12 @@ impl Game<'_> { let keys: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect(); let chunks = self.entity_chunks(&keys, false); // Forget entities that no longer exist. - let alive: HashSet = self.mobs.iter().map(|m| m.id).chain(self.dropped.iter().map(|e| e.id)).collect(); + let alive: HashSet = self + .mobs + .iter() + .map(|m| m.id) + .chain(self.dropped.iter().map(|e| e.id)) + .collect(); self.persist.uuids.retain(|id, _| alive.contains(id)); self.persist.raw.retain(|id, _| alive.contains(id)); self.save.save_entities(chunks) diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index a75409681..e03729568 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -32,7 +32,8 @@ pub(super) struct PotionState { /// Enchantment attribute modifiers on the player: (attribute, id, amount, operation). pub(super) enchant_modifiers: Vec<(String, String, f64, String)>, /// The level's trade-set `RandomSequence`s, by sequence id. - pub(super) trade_randoms: std::collections::HashMap, + pub(super) trade_randoms: + std::collections::HashMap, } impl Game<'_> { @@ -46,34 +47,72 @@ impl Game<'_> { Ok(true) } "minecraft:splash_potion" | "minecraft:lingering_potion" => { - let Some(eye) = self.eye_position() else { return Ok(true) }; + let Some(eye) = self.eye_position() else { + return Ok(true); + }; let pitch = 0.4 / (self.world.random.next_float() * 0.4 + 0.8); - let sound = if &*stack.item == "minecraft:splash_potion" { "minecraft:entity.splash_potion.throw" } else { "minecraft:entity.lingering_potion.throw" }; + let sound = if &*stack.item == "minecraft:splash_potion" { + "minecraft:entity.splash_potion.throw" + } else { + "minecraft:entity.lingering_potion.throw" + }; self.audio.play(sound, Some(eye), 0.5, pitch); // Projectile.shootFromRotation(xRot, yRot, -20, 0.5, 1.0). let (yaw, pitch) = (self.yaw.to_radians(), self.pitch.to_radians()); - let dir = [-yaw.sin() * pitch.cos(), -(self.pitch - 20.0).to_radians().sin(), yaw.cos() * pitch.cos()]; - let l = dir.iter().map(|c| f64::from(*c).powi(2)).sum::().sqrt().max(1e-9); + let dir = [ + -yaw.sin() * pitch.cos(), + -(self.pitch - 20.0).to_radians().sin(), + yaw.cos() * pitch.cos(), + ]; + let l = dir + .iter() + .map(|c| f64::from(*c).powi(2)) + .sum::() + .sqrt() + .max(1e-9); // getMovementToShoot: normalize, add triangle(0, 0.0172275 * uncertainty), scale. let r = &mut self.world.random; let mut jitter = || r.triangle(0.0, 0.0172275); - let v = Vec3::new((f64::from(dir[0]) / l + jitter()) * 0.5, (f64::from(dir[1]) / l + jitter()) * 0.5, (f64::from(dir[2]) / l + jitter()) * 0.5); + let v = Vec3::new( + (f64::from(dir[0]) / l + jitter()) * 0.5, + (f64::from(dir[1]) / l + jitter()) * 0.5, + (f64::from(dir[2]) / l + jitter()) * 0.5, + ); let pv = self.player.as_ref().map_or(Vec3::ZERO, |p| p.velocity); let on_ground = self.player.as_ref().is_some_and(|p| p.ground.on_ground); - let v = Vec3::new(v.x + pv.x, v.y + if on_ground { 0.0 } else { pv.y }, v.z + pv.z); - self.potions.thrown.push(ThrownPotion { stack: ItemStack { count: 1, ..stack.clone() }, position: Vec3::new(eye[0], eye[1] - 0.1, eye[2]), velocity: v, age: 0 }); + let v = Vec3::new( + v.x + pv.x, + v.y + if on_ground { 0.0 } else { pv.y }, + v.z + pv.z, + ); + self.potions.thrown.push(ThrownPotion { + stack: ItemStack { + count: 1, + ..stack.clone() + }, + position: Vec3::new(eye[0], eye[1] - 0.1, eye[2]), + velocity: v, + age: 0, + }); self.swing_arm(); self.consume_held(); Ok(true) } "minecraft:glass_bottle" => { - let Some(hit) = self.pick_fluid() else { return Ok(false) }; + let Some(hit) = self.pick_fluid() else { + return Ok(false); + }; let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); if self.res.facts.get(state).fluid != horizon_client::blocks::Fluid::Water { return Ok(false); } - let at = [f64::from(hit.pos[0]) + 0.5, f64::from(hit.pos[1]) + 0.5, f64::from(hit.pos[2]) + 0.5]; - self.audio.play("minecraft:item.bottle.fill", Some(at), 1.0, 1.0); + let at = [ + f64::from(hit.pos[0]) + 0.5, + f64::from(hit.pos[1]) + 0.5, + f64::from(hit.pos[2]) + 0.5, + ]; + self.audio + .play("minecraft:item.bottle.fill", Some(at), 1.0, 1.0); let water = ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"); self.fill_held(water); Ok(true) @@ -107,7 +146,8 @@ impl Game<'_> { // Consumable.emitParticlesAndSounds: the drink sound every 4 ticks near the end. if remaining <= 25 && remaining.is_multiple_of(4) { let pitch = self.world.random.next_float() * 0.1 + 0.9; - self.audio.play("minecraft:entity.generic.drink", Some(eye), 0.5, pitch); + self.audio + .play("minecraft:entity.generic.drink", Some(eye), 0.5, pitch); } if ticks < 32 { self.using = Some((slot, ticks)); @@ -140,7 +180,9 @@ impl Game<'_> { fn apply_effect_action(&mut self, action: EffectAction) { let creative = self.creative; let rules = self.world.health_rules; - let Some(p) = self.player.as_mut() else { return }; + let Some(p) = self.player.as_mut() else { + return; + }; match action { EffectAction::Heal(amount) => { let max = p.attribute("minecraft:max_health").unwrap_or(20.0) as f32; @@ -163,13 +205,16 @@ impl Game<'_> { EffectAction::Eat(nutrition, saturation) => { let food = &mut p.health.food; food.food = (food.food + nutrition).clamp(0, 20); - food.saturation = (food.saturation + nutrition as f32 * saturation * 2.0).clamp(0.0, food.food as f32); + food.saturation = (food.saturation + nutrition as f32 * saturation * 2.0) + .clamp(0.0, food.food as f32); } } } /// `LivingEntity.tickEffects`, attribute modifiers and the status flags. pub(super) fn tick_effects(&mut self) { - let Some(player) = self.player.as_ref() else { return }; + let Some(player) = self.player.as_ref() else { + return; + }; if player.health.dead_or_dying() { // LivingEntity.die → removeAllEffects. self.potions.effects.clear(); @@ -196,8 +241,25 @@ impl Game<'_> { let e = &self.res.stations.enchantments; let mut random = horizon_core::random::LegacyRandom::new(0); for (_, def) in self.motion.health.damage.entries() { - let ctx = horizon_client::enchant::EffectContext { items: Some(&self.res.items), damage_type: Some(&def.name), this: Some("minecraft:player"), ..Default::default() }; - let total: f32 = armor.iter().flatten().map(|s| e.modify_value(Some(s), "minecraft:damage_protection", &ctx, &mut random, 0.0)).sum(); + let ctx = horizon_client::enchant::EffectContext { + items: Some(&self.res.items), + damage_type: Some(&def.name), + this: Some("minecraft:player"), + ..Default::default() + }; + let total: f32 = armor + .iter() + .flatten() + .map(|s| { + e.modify_value( + Some(s), + "minecraft:damage_protection", + &ctx, + &mut random, + 0.0, + ) + }) + .sum(); if total > 0.0 { table.push((def.name.clone(), total)); } @@ -219,15 +281,33 @@ impl Game<'_> { let mut landed = Vec::new(); thrown.retain_mut(|t| { t.age += 1; - let next = Vec3::new(t.position.x + t.velocity.x, t.position.y + t.velocity.y, t.position.z + t.velocity.z); + let next = Vec3::new( + t.position.x + t.velocity.x, + t.position.y + t.velocity.y, + t.position.z + t.velocity.z, + ); // Hit a block along the step (sampled), a mob, or fell out of the world. let steps = 4; let mut hit = None; for i in 1..=steps { let f = f64::from(i) / f64::from(steps); - let p = Vec3::new(t.position.x + t.velocity.x * f, t.position.y + t.velocity.y * f, t.position.z + t.velocity.z * f); - let state = self.world.block(p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); - if self.res.facts.get(state).full_collision || self.mobs.iter().any(|m| m.alive() && (m.position.x - p.x).abs() < m.kind.width / 2.0 + 0.125 && (m.position.z - p.z).abs() < m.kind.width / 2.0 + 0.125 && p.y >= m.position.y && p.y <= m.position.y + m.kind.height) { + let p = Vec3::new( + t.position.x + t.velocity.x * f, + t.position.y + t.velocity.y * f, + t.position.z + t.velocity.z * f, + ); + let state = + self.world + .block(p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); + if self.res.facts.get(state).full_collision + || self.mobs.iter().any(|m| { + m.alive() + && (m.position.x - p.x).abs() < m.kind.width / 2.0 + 0.125 + && (m.position.z - p.z).abs() < m.kind.width / 2.0 + 0.125 + && p.y >= m.position.y + && p.y <= m.position.y + m.kind.height + }) + { hit = Some(p); break; } @@ -238,14 +318,28 @@ impl Game<'_> { } t.position = next; // ThrowableItemProjectile: drag 0.99 then gravity 0.05. - t.velocity = Vec3::new(t.velocity.x * 0.99, t.velocity.y * 0.99 - 0.05, t.velocity.z * 0.99); + t.velocity = Vec3::new( + t.velocity.x * 0.99, + t.velocity.y * 0.99 - 0.05, + t.velocity.z * 0.99, + ); t.age < 1200 && t.position.y > -128.0 }); // ThrownItemRenderer stand-in: a short-lived sprite of the potion at its position. for t in &thrown { - let sprite = if &*t.stack.item == "minecraft:lingering_potion" { "item/lingering_potion" } else { "item/splash_potion" }; + let sprite = if &*t.stack.item == "minecraft:lingering_potion" { + "item/lingering_potion" + } else { + "item/splash_potion" + }; let mut fixed = horizon_core::random::LegacyRandom::new(0); - let mut p = horizon_client::particles::Particle::terrain(&mut fixed, [t.position.x, t.position.y, t.position.z], [0.0; 3], sprite.into(), 0xFFFFFF); + let mut p = horizon_client::particles::Particle::terrain( + &mut fixed, + [t.position.x, t.position.y, t.position.z], + [0.0; 3], + sprite.into(), + 0xFFFFFF, + ); p.velocity = [0.0; 3]; p.gravity = 0.0; p.lifetime = 2; @@ -261,21 +355,42 @@ impl Game<'_> { /// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash). fn splash(&mut self, stack: &ItemStack, at: Vec3) { let lingering = &*stack.item == "minecraft:lingering_potion"; - let event = if lingering { "minecraft:entity.lingering_potion.break" } else { "minecraft:entity.splash_potion.break" }; + let event = if lingering { + "minecraft:entity.lingering_potion.break" + } else { + "minecraft:entity.splash_potion.break" + }; let pitch = self.world.random.next_float() * 0.1 + 0.9; self.audio.play(event, Some([at.x, at.y, at.z]), 1.0, pitch); let color = brewing::potion_color(stack.potion()); for _ in 0..8 { - let v = [f64::from(self.world.random.next_float() - 0.5) * 0.3, 0.2, f64::from(self.world.random.next_float() - 0.5) * 0.3]; - let p = horizon_client::particles::Particle::terrain(&mut self.world.random, [at.x, at.y, at.z], v, "item/splash_potion".into(), color); + let v = [ + f64::from(self.world.random.next_float() - 0.5) * 0.3, + 0.2, + f64::from(self.world.random.next_float() - 0.5) * 0.3, + ]; + let p = horizon_client::particles::Particle::terrain( + &mut self.world.random, + [at.x, at.y, at.z], + v, + "item/splash_potion".into(), + color, + ); self.particles.push(p); } let scale = if lingering { 0.25 } else { 1.0 }; - let Some(def) = stack.potion().and_then(brewing::potion) else { return }; + let Some(def) = stack.potion().and_then(brewing::potion) else { + return; + }; // The player. if let Some(p) = self.player.as_ref() { - let center = Vec3::new(p.position.x, p.position.y + f64::from(p.dimensions.height) / 2.0, p.position.z); - let d2 = (center.x - at.x).powi(2) + (center.y - at.y).powi(2) + (center.z - at.z).powi(2); + let center = Vec3::new( + p.position.x, + p.position.y + f64::from(p.dimensions.height) / 2.0, + p.position.z, + ); + let d2 = + (center.x - at.x).powi(2) + (center.y - at.y).powi(2) + (center.z - at.z).powi(2); if d2 < 16.0 && (center.y - at.y).abs() <= 2.0 + f64::from(p.dimensions.height) { let intensity = 1.0 - d2.sqrt() / 4.0; for (id, duration, amp) in def.effects { @@ -299,9 +414,13 @@ impl Game<'_> { let undead = &self.res.stations.enchantments.entity_tags; let mut hits = Vec::new(); for (i, m) in self.mobs.iter().enumerate() { - let d2 = (m.position.x - at.x).powi(2) + (m.position.y + m.kind.height / 2.0 - at.y).powi(2) + (m.position.z - at.z).powi(2); + let d2 = (m.position.x - at.x).powi(2) + + (m.position.y + m.kind.height / 2.0 - at.y).powi(2) + + (m.position.z - at.z).powi(2); if m.alive() && d2 < 16.0 { - let inverted = undead.get("minecraft:inverted_healing_and_harm").is_some_and(|t| t.contains(&m.kind.id)); + let inverted = undead + .get("minecraft:inverted_healing_and_harm") + .is_some_and(|t| t.contains(&m.kind.id)); hits.push((i, 1.0 - d2.sqrt() / 4.0, inverted)); } } @@ -314,9 +433,14 @@ impl Game<'_> { }; let m = &mut self.mobs[i]; if harm { - m.hurt((intensity * f64::from(6 << amp)) as i32 as f32, Some([at.x, at.y, at.z]), &mut self.world.random); + m.hurt( + (intensity * f64::from(6 << amp)) as i32 as f32, + Some([at.x, at.y, at.z]), + &mut self.world.random, + ); } else { - m.health = (m.health + (intensity * f64::from(4 << amp)) as i32 as f32).min(m.kind.max_health); + m.health = (m.health + (intensity * f64::from(4 << amp)) as i32 as f32) + .min(m.kind.max_health); } } } @@ -328,11 +452,16 @@ impl Game<'_> { } let mut list: Vec<&EffectInstance> = self.potions.effects.list.iter().collect(); let color = |e: &EffectInstance| brewing::effect(e.id).map_or(0, |d| d.color); - list.sort_by(|a, b| (a.ambient, a.duration == -1, a.duration, color(a)).cmp(&(b.ambient, b.duration == -1, b.duration, color(b))).reverse()); + list.sort_by(|a, b| { + (a.ambient, a.duration == -1, a.duration, color(a)) + .cmp(&(b.ambient, b.duration == -1, b.duration, color(b))) + .reverse() + }); let (mut good, mut bad) = (0, 0); let atlas = &self.res.atlas; for e in list { - let beneficial = brewing::effect(e.id).is_some_and(|d| d.category == brewing::Category::Beneficial); + let beneficial = + brewing::effect(e.id).is_some_and(|d| d.category == brewing::Category::Beneficial); let mut x = batch.width; let mut y = 1.0; if beneficial { @@ -351,10 +480,21 @@ impl Game<'_> { if e.duration != -1 && e.duration <= 200 { let d = e.duration as f32; let used = 10.0 - (e.duration / 20) as f32; - alpha = ((d / 10.0 / 5.0 * 0.5).clamp(0.0, 0.5) + (d * std::f32::consts::PI / 5.0).cos() * (used / 10.0 * 0.25).clamp(0.0, 0.25)).clamp(0.0, 1.0); + alpha = ((d / 10.0 / 5.0 * 0.5).clamp(0.0, 0.5) + + (d * std::f32::consts::PI / 5.0).cos() + * (used / 10.0 * 0.25).clamp(0.0, 0.25)) + .clamp(0.0, 1.0); } } - batch.sprite_scaled(atlas, &format!("mob_effect/{}", e.id), x + 3.0, y + 3.0, 18.0, 18.0, rgba(255, 255, 255, (alpha * 255.0) as u8)); + batch.sprite_scaled( + atlas, + &format!("mob_effect/{}", e.id), + x + 3.0, + y + 3.0, + 18.0, + 18.0, + rgba(255, 255, 255, (alpha * 255.0) as u8), + ); } } /// Effects saved in level.dat (`Player.active_effects`). diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index d8728f52e..a5cae32ec 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -136,55 +136,66 @@ impl Game<'_> { let lang = Arc::new(horizon_client::net::load_language(&root)); let view = self.settings.render_distance.clamp(2, 32) as i8; let session = Session::connect(address, name, view, lang.clone()); - let player_type = horizon_client::mobs::load_model(&root, "minecraft:player#main").map(|model| { - Arc::new(MobType { - id: "minecraft:player".into(), - // Players render as a humanoid; the species only drives local AI. - species: horizon_client::mobs::Species::Zombie, - width: 0.6, - height: 1.8, - eye_height: 1.62, - category: "misc".into(), - max_health: 20.0, - speed: 0.1, - flying_speed: 0.02, - attack_damage: 1.0, - attack_knockback: 0.0, - follow_range: 0.0, - step_height: 0.6, - armor: 0.0, - armor_toughness: 0.0, - knockback_resistance: 0.0, - jump_strength: 0.42, - gravity: 0.08, - safe_fall_distance: 3.0, - fall_damage_multiplier: 1.0, - water_efficiency: 0.0, - water_slowdown: 0.8, - air_speed: 0.02, - baby_scale: 0.5, - head_rot_speed: 10.0, - max_head_x_rot: 40.0, - max_head_y_rot: 75.0, - ambient_interval: 80, - flags: Default::default(), - model: Arc::new(model), - layers: Default::default(), - texture: "entity/player/wide/steve".into(), - brain: Brain::Passive, - anim: Anim::Humanoid { zombie_arms: false }, - sounds: ["entity.player.hurt", "entity.player.hurt", "entity.player.death"], - step_sound: None, - food: Arc::from([]), - tempt: Arc::from([]), - }) - }); - let mut streaming = Streaming::new(Arc::new(NoTerrain), self.res.context.clone(), self.res.threads); + let player_type = + horizon_client::mobs::load_model(&root, "minecraft:player#main").map(|model| { + Arc::new(MobType { + id: "minecraft:player".into(), + // Players render as a humanoid; the species only drives local AI. + species: horizon_client::mobs::Species::Zombie, + width: 0.6, + height: 1.8, + eye_height: 1.62, + category: "misc".into(), + max_health: 20.0, + speed: 0.1, + flying_speed: 0.02, + attack_damage: 1.0, + attack_knockback: 0.0, + follow_range: 0.0, + step_height: 0.6, + armor: 0.0, + armor_toughness: 0.0, + knockback_resistance: 0.0, + jump_strength: 0.42, + gravity: 0.08, + safe_fall_distance: 3.0, + fall_damage_multiplier: 1.0, + water_efficiency: 0.0, + water_slowdown: 0.8, + air_speed: 0.02, + baby_scale: 0.5, + head_rot_speed: 10.0, + max_head_x_rot: 40.0, + max_head_y_rot: 75.0, + ambient_interval: 80, + flags: Default::default(), + model: Arc::new(model), + layers: Default::default(), + texture: "entity/player/wide/steve".into(), + brain: Brain::Passive, + anim: Anim::Humanoid { zombie_arms: false }, + sounds: [ + "entity.player.hurt", + "entity.player.hurt", + "entity.player.death", + ], + step_sound: None, + food: Arc::from([]), + tempt: Arc::from([]), + }) + }); + let mut streaming = Streaming::new( + Arc::new(NoTerrain), + self.res.context.clone(), + self.res.threads, + ); streaming.remote = true; streaming.radius = self.settings.render_distance; self.streaming = streaming; self.world = World::new(self.res.facts.air, 0); - self.save = Arc::new(SaveDir::new(std::env::temp_dir().join("horizon-remote-unused"))); + self.save = Arc::new(SaveDir::new( + std::env::temp_dir().join("horizon-remote-unused"), + )); self.inventory = vec![None; 36]; self.armor = [None, None, None, None]; self.craft_grid = vec![None; 9]; @@ -203,7 +214,11 @@ impl Game<'_> { self.carried = None; self.using = None; self.creative = false; - self.experience = Experience { level: 0, progress: 0.0, total: 0 }; + self.experience = Experience { + level: 0, + progress: 0.0, + total: 0, + }; self.screen = Screen::Playing; self.title = None; self.dim = Dim::Overworld; @@ -298,21 +313,37 @@ impl Game<'_> { } fn item_name(&self, id: i32) -> Arc { let r = self.remote.as_ref().expect("remote"); - Arc::from(r.builtin.get("minecraft:item").and_then(|i| i.name(id)).unwrap_or("minecraft:air")) + Arc::from( + r.builtin + .get("minecraft:item") + .and_then(|i| i.name(id)) + .unwrap_or("minecraft:air"), + ) } fn item_id(&self, name: &str) -> i32 { let r = self.remote.as_ref().expect("remote"); - r.builtin.get("minecraft:item").and_then(|i| i.id(name)).unwrap_or(0) + r.builtin + .get("minecraft:item") + .and_then(|i| i.id(name)) + .unwrap_or(0) } fn to_stack(&self, s: &Option) -> Option { let s = s.as_ref()?; - Some(ItemStack { item: self.item_name(s.item), count: s.count.max(0) as u32, damage: s.damage().max(0) as u32, extra: None }) + Some(ItemStack { + item: self.item_name(s.item), + count: s.count.max(0) as u32, + damage: s.damage().max(0) as u32, + extra: None, + }) } fn to_network(&self, s: &Option) -> Option { let s = s.as_ref()?; let mut stack = Stack::new(self.item_id(&s.item), s.count as i32); if s.damage > 0 { - stack.added.push((horizon_protocol::item::component::DAMAGE, horizon_protocol::item::Component::Int(s.damage as i32))); + stack.added.push(( + horizon_protocol::item::component::DAMAGE, + horizon_protocol::item::Component::Int(s.damage as i32), + )); } Some(stack) } @@ -338,7 +369,9 @@ impl Game<'_> { r.status = s; } } - Event::Joined { registries, name, .. } => { + Event::Joined { + registries, name, .. + } => { self.set_registries(registries); if let Some(r) = self.remote.as_mut() { r.joined = true; @@ -370,7 +403,11 @@ impl Game<'_> { let biomes: Vec = registries .registries .get("minecraft:worldgen/biome") - .map(|list| list.iter().map(|(name, _)| self.res.biomes.id(name)).collect()) + .map(|list| { + list.iter() + .map(|(name, _)| self.res.biomes.id(name)) + .collect() + }) .unwrap_or_default(); if let Some(r) = self.remote.as_mut() { r.biome_bits = ceil_log2(biomes.len()); @@ -380,20 +417,34 @@ impl Game<'_> { } /// Switch to a (possibly new) dimension: a fresh client level. fn enter_remote_dimension(&mut self, spawn: &play::SpawnInfo, keep_world: bool) { - let Some(r) = self.remote.as_mut() else { return }; + let Some(r) = self.remote.as_mut() else { + return; + }; let dimension = r.registries.dimension(spawn.dimension_type); let same = r.dimension.name == dimension.name && keep_world; r.dimension = dimension; r.game_mode = spawn.game_type; r.loaded_sent = false; self.creative = spawn.game_type == 1; - self.dim = if spawn.dimension == "minecraft:the_nether" { Dim::Nether } else { Dim::Overworld }; + self.dim = if spawn.dimension == "minecraft:the_nether" { + Dim::Nether + } else { + Dim::Overworld + }; if !same { - let mut streaming = Streaming::new(Arc::new(NoTerrain), self.res.context.clone(), self.res.threads); + let mut streaming = Streaming::new( + Arc::new(NoTerrain), + self.res.context.clone(), + self.res.threads, + ); streaming.remote = true; streaming.radius = self.streaming.radius; self.streaming = streaming; - let (time, day, weather) = (self.world.game_time, self.world.day_time, self.world.weather); + let (time, day, weather) = ( + self.world.game_time, + self.world.day_time, + self.world.weather, + ); self.world = World::new(self.res.facts.air, spawn.seed); self.world.game_time = time; self.world.day_time = day; @@ -410,7 +461,10 @@ impl Game<'_> { renderer.clear_sections(); } } - let has_sky = self.remote.as_ref().is_none_or(|r| r.dimension.has_skylight); + let has_sky = self + .remote + .as_ref() + .is_none_or(|r| r.dimension.has_skylight); self.streaming.sky_light = has_sky; self.streaming.nether_shading = self.dim == Dim::Nether; self.player = None; @@ -420,7 +474,10 @@ impl Game<'_> { /// LevelChunkSection data into the client's fixed -64..320 column. fn remote_chunk(&self, p: &play::LevelChunkWithLight) -> std::result::Result { let r = self.remote.as_ref().ok_or("no connection")?; - let sections = p.chunk.sections(r.dimension.sections(), 16, r.biome_bits).map_err(|e| e.to_string())?; + let sections = p + .chunk + .sections(r.dimension.sections(), 16, r.biome_bits) + .map_err(|e| e.to_string())?; let mut chunk = Chunk::empty(p.x, p.z); let mut biomes = vec![0u16; chunk.biomes.len()]; let offset = (r.dimension.min_y - MIN_Y).div_euclid(16); @@ -438,18 +495,28 @@ impl Game<'_> { } Blocks::Full(a) }; - let mut section = Section { blocks, light: Light::Uniform(0xF0) }; + let mut section = Section { + blocks, + light: Light::Uniform(0xF0), + }; section.compact(); chunk.sections[target as usize] = Arc::new(section); for j in 0..64 { - let biome = r.biome_map.get(s.biomes.get(j) as usize).copied().unwrap_or(0); + let biome = r + .biome_map + .get(s.biomes.get(j) as usize) + .copied() + .unwrap_or(0); if let Some(cell) = biomes.get_mut(target as usize * 64 + j) { *cell = biome; } } } // Columns outside the dimension's range take its nearest biome. - let (lo, hi) = (offset.max(0) as usize * 64, ((offset + sections.len() as i32).min(SECTIONS as i32)) as usize * 64); + let (lo, hi) = ( + offset.max(0) as usize * 64, + ((offset + sections.len() as i32).min(SECTIONS as i32)) as usize * 64, + ); if lo < hi { for j in 0..biomes.len() { if j < lo { @@ -467,7 +534,11 @@ impl Game<'_> { let name = self.res.facts.get(state).name.clone(); match BlockEntity::for_block(&name) { Some(entity) => { - let same = self.world.block_entities.get(&pos).is_some_and(|e| e.id() == entity.id()); + let same = self + .world + .block_entities + .get(&pos) + .is_some_and(|e| e.id() == entity.id()); if !same { self.world.block_entities.insert(pos, entity); } @@ -479,7 +550,9 @@ impl Game<'_> { } fn set_block(&mut self, pos: [i32; 3], state: i32) { let state = BlockStateId(state.max(0) as u32); - if self.world.loaded(pos[0], pos[2]) && self.world.set(pos[0], pos[1], pos[2], state).is_ok() { + if self.world.loaded(pos[0], pos[2]) + && self.world.set(pos[0], pos[1], pos[2], state).is_ok() + { self.sync_block_entity((pos[0], pos[1], pos[2]), state); } // A block we just placed: play its place sound (the server skips the placer). @@ -488,8 +561,13 @@ impl Game<'_> { && !self.res.facts.is_air(state) { let s = self.res.facts.get(state).sounds.clone(); - let at = [f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, f64::from(pos[2]) + 0.5]; - self.audio.play(&s.place, Some(at), (s.volume + 1.0) / 2.0, s.pitch * 0.8); + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + self.audio + .play(&s.place, Some(at), (s.volume + 1.0) / 2.0, s.pitch * 0.8); if let Some(r) = self.remote.as_mut() { r.placing = None; } @@ -514,15 +592,33 @@ impl Game<'_> { if kind == "minecraft:item" { r.pending_items.insert(id, position); } - r.entities.insert(id, Tracked { kind: kind.to_owned(), position }); + r.entities.insert( + id, + Tracked { + kind: kind.to_owned(), + position, + }, + ); } } - fn move_entity(&mut self, id: i32, position: [f64; 3], rotation: Option<(f32, f32)>, on_ground: bool) { + fn move_entity( + &mut self, + id: i32, + position: [f64; 3], + rotation: Option<(f32, f32)>, + on_ground: bool, + ) { if let Some(r) = self.remote.as_mut() { if let Some(t) = r.entities.get_mut(&id) { t.position = position; } - r.lerps.insert(id, Lerp { target: position, steps: 3 }); + r.lerps.insert( + id, + Lerp { + target: position, + steps: 3, + }, + ); if let Some(p) = r.pending_items.get_mut(&id) { *p = position; } @@ -597,7 +693,9 @@ impl Game<'_> { if container != 0 && menu == "inventory" { return; } - let Some(internal) = Self::menu_slot(&menu, slot) else { return }; + let Some(internal) = Self::menu_slot(&menu, slot) else { + return; + }; if internal == 200 { return; // the result slot is recomputed from the grid } @@ -611,9 +709,14 @@ impl Game<'_> { r.entity_id = p.player_id; r.view_distance = p.chunk_radius; } - self.streaming.radius = self.settings.render_distance.min(p.chunk_radius + 1).max(2); + self.streaming.radius = + self.settings.render_distance.min(p.chunk_radius + 1).max(2); self.enter_remote_dimension(&p.spawn, false); - self.send(S::ClientInformation(horizon_protocol::packets::configuration::ClientInformation::new(self.settings.render_distance.clamp(2, 32) as i8))); + self.send(S::ClientInformation( + horizon_protocol::packets::configuration::ClientInformation::new( + self.settings.render_distance.clamp(2, 32) as i8, + ), + )); } C::Respawn(p) => { self.enter_remote_dimension(&p.spawn, true); @@ -626,16 +729,31 @@ impl Game<'_> { } C::PlayerPosition(p) => self.remote_teleport(&p)?, C::PlayerRotation(p) => { - self.yaw = if p.relative_yaw { self.yaw + p.yaw } else { p.yaw }; - self.pitch = (if p.relative_pitch { self.pitch + p.pitch } else { p.pitch }).clamp(-90.0, 90.0); + self.yaw = if p.relative_yaw { + self.yaw + p.yaw + } else { + p.yaw + }; + self.pitch = (if p.relative_pitch { + self.pitch + p.pitch + } else { + p.pitch + }) + .clamp(-90.0, 90.0); } C::LevelChunkWithLight(p) => match self.remote_chunk(&p) { Ok(chunk) => { let (x, z) = (p.x, p.z); self.streaming.insert_remote(&mut self.world, chunk); - self.world.block_entities.retain(|k, _| (k.0 >> 4, k.2 >> 4) != (x, z)); + self.world + .block_entities + .retain(|k, _| (k.0 >> 4, k.2 >> 4) != (x, z)); for info in &p.chunk.block_entities { - let pos = (x * 16 + i32::from(info.packed_xz as u8 >> 4), i32::from(info.y), z * 16 + i32::from(info.packed_xz as u8 & 15)); + let pos = ( + x * 16 + i32::from(info.packed_xz as u8 >> 4), + i32::from(info.y), + z * 16 + i32::from(info.packed_xz as u8 & 15), + ); let state = self.world.block(pos.0, pos.1, pos.2); self.sync_block_entity(pos, state); } @@ -645,7 +763,9 @@ impl Game<'_> { C::ForgetLevelChunk(p) => { let [x, z] = p.pos; self.streaming.forget(&mut self.world, x, z); - self.world.block_entities.retain(|k, _| (k.0 >> 4, k.2 >> 4) != (x, z)); + self.world + .block_entities + .retain(|k, _| (k.0 >> 4, k.2 >> 4) != (x, z)); if let Some(renderer) = self.renderer.as_mut() { for sy in 0..SECTIONS as i32 { renderer.remove((x, sy, z)); @@ -654,14 +774,20 @@ impl Game<'_> { } C::ChunkBatchFinished(_) => { // ChunkBatchSizeCalculator's ceiling; meshing runs on workers. - self.send(S::ChunkBatchReceived(play::ChunkBatchReceived { chunks_per_tick: 64.0 })); + self.send(S::ChunkBatchReceived(play::ChunkBatchReceived { + chunks_per_tick: 64.0, + })); } C::BlockUpdate(p) => self.set_block(p.pos, p.state), C::SectionBlocksUpdate(p) => { let [sx, sy, sz] = p.section; for change in p.changes { let local = (change & 0xFFF) as i32; - let pos = [sx * 16 + (local >> 8 & 15), sy * 16 + (local & 15), sz * 16 + (local >> 4 & 15)]; + let pos = [ + sx * 16 + (local >> 8 & 15), + sy * 16 + (local & 15), + sz * 16 + (local >> 4 & 15), + ]; self.set_block(pos, (change >> 12) as i32); } } @@ -670,22 +796,49 @@ impl Game<'_> { // LevelEvent.PARTICLES_DESTROY_BLOCK: someone else broke a block. let state = BlockStateId(p.data.max(0) as u32); let s = self.res.facts.get(state).sounds.clone(); - let at = [f64::from(p.pos[0]) + 0.5, f64::from(p.pos[1]) + 0.5, f64::from(p.pos[2]) + 0.5]; - self.audio.play(&s.break_sound, Some(at), (s.volume + 1.0) / 2.0, s.pitch * 0.8); + let at = [ + f64::from(p.pos[0]) + 0.5, + f64::from(p.pos[1]) + 0.5, + f64::from(p.pos[2]) + 0.5, + ]; + self.audio.play( + &s.break_sound, + Some(at), + (s.volume + 1.0) / 2.0, + s.pitch * 0.8, + ); self.destroy_particles(p.pos, state); } C::Sound(p) => { let name = match &p.sound.1 { Some((location, _)) => Some(location.clone()), - None => self.remote.as_ref().and_then(|r| r.builtin.get("minecraft:sound_event")?.name(p.sound.0).map(str::to_owned)), + None => self.remote.as_ref().and_then(|r| { + r.builtin + .get("minecraft:sound_event")? + .name(p.sound.0) + .map(str::to_owned) + }), }; if let Some(name) = name { - let at = [f64::from(p.x) / 8.0, f64::from(p.y) / 8.0, f64::from(p.z) / 8.0]; + let at = [ + f64::from(p.x) / 8.0, + f64::from(p.y) / 8.0, + f64::from(p.z) / 8.0, + ]; self.audio.play(&name, Some(at), p.volume, p.pitch); } } C::AddEntity(p) => { - let kind = self.remote.as_ref().and_then(|r| r.builtin.get("minecraft:entity_type")?.name(p.kind).map(str::to_owned)).unwrap_or_default(); + let kind = self + .remote + .as_ref() + .and_then(|r| { + r.builtin + .get("minecraft:entity_type")? + .name(p.kind) + .map(str::to_owned) + }) + .unwrap_or_default(); let yaw = horizon_protocol::buf::unpack_degrees(p.yaw); let head = horizon_protocol::buf::unpack_degrees(p.head_yaw); self.spawn_entity(p.id, &kind, p.position, yaw, head); @@ -695,18 +848,45 @@ impl Game<'_> { self.remove_entity(id); } } - C::MoveEntityPos(play::MoveEntityPos(m)) | C::MoveEntityPosRot(play::MoveEntityPosRot(m)) | C::MoveEntityRot(play::MoveEntityRot(m)) => { - let base = self.remote.as_ref().and_then(|r| r.entities.get(&m.id)).map(|t| t.position); + C::MoveEntityPos(play::MoveEntityPos(m)) + | C::MoveEntityPosRot(play::MoveEntityPosRot(m)) + | C::MoveEntityRot(play::MoveEntityRot(m)) => { + let base = self + .remote + .as_ref() + .and_then(|r| r.entities.get(&m.id)) + .map(|t| t.position); let Some(base) = base else { return Ok(()) }; let position = m.delta.as_ref().map_or(base, |d| d.end(base)); - let rotation = m.rotation.map(|(y, x)| (horizon_protocol::buf::unpack_degrees(y), horizon_protocol::buf::unpack_degrees(x))); + let rotation = m.rotation.map(|(y, x)| { + ( + horizon_protocol::buf::unpack_degrees(y), + horizon_protocol::buf::unpack_degrees(x), + ) + }); self.move_entity(m.id, position, rotation, m.on_ground); } - C::EntityPositionSync(p) => self.move_entity(p.id, p.path.end(), Some((p.yaw, p.pitch)), p.on_ground), + C::EntityPositionSync(p) => { + self.move_entity(p.id, p.path.end(), Some((p.yaw, p.pitch)), p.on_ground) + } C::TeleportEntity(p) => { - let base = self.remote.as_ref().and_then(|r| r.entities.get(&p.id)).map_or([0.0; 3], |t| t.position); - let rel = |bit: i32, i: usize| if p.relatives & bit != 0 { base[i] + p.position[i] } else { p.position[i] }; - let position = [rel(play::relative::X, 0), rel(play::relative::Y, 1), rel(play::relative::Z, 2)]; + let base = self + .remote + .as_ref() + .and_then(|r| r.entities.get(&p.id)) + .map_or([0.0; 3], |t| t.position); + let rel = |bit: i32, i: usize| { + if p.relatives & bit != 0 { + base[i] + p.position[i] + } else { + p.position[i] + } + }; + let position = [ + rel(play::relative::X, 0), + rel(play::relative::Y, 1), + rel(play::relative::Z, 2), + ]; self.move_entity(p.id, position, Some((p.yaw, p.pitch)), p.on_ground); } C::RotateHead(p) => { @@ -724,11 +904,18 @@ impl Game<'_> { } } C::TakeItemEntity(p) => { - if self.remote.as_ref().is_some_and(|r| r.entity_id == p.player) + if self + .remote + .as_ref() + .is_some_and(|r| r.entity_id == p.player) && let Some(eye) = self.eye_position() { - let pitch = ((self.world.random.next_float() - self.world.random.next_float()) * 0.7 + 1.0) * 2.0; - self.audio.play("minecraft:entity.item.pickup", Some(eye), 0.2, pitch); + let pitch = ((self.world.random.next_float() - self.world.random.next_float()) + * 0.7 + + 1.0) + * 2.0; + self.audio + .play("minecraft:entity.item.pickup", Some(eye), 0.2, pitch); } self.remove_entity(p.item); } @@ -757,22 +944,37 @@ impl Game<'_> { } } C::PlayerCombatKill(p) => { - let lang = self.remote.as_ref().map(|r| r.lang.clone()).unwrap_or_default(); + let lang = self + .remote + .as_ref() + .map(|r| r.lang.clone()) + .unwrap_or_default(); let message = plain(&p.message, &lang); if let Some(r) = self.remote.as_mut() { r.death_message = Some(message); } } - C::SetExperience(p) => self.experience = Experience { level: p.level, progress: p.progress, total: p.total }, + C::SetExperience(p) => { + self.experience = Experience { + level: p.level, + progress: p.progress, + total: p.total, + } + } C::SetTime(p) => { self.world.game_time = p.game_time; let clock = { let r = self.remote.as_ref(); - let names = r.and_then(|r| r.registries.registries.get("minecraft:world_clock")); + let names = + r.and_then(|r| r.registries.registries.get("minecraft:world_clock")); let wanted = r.map(|r| r.dimension.name.clone()).unwrap_or_default(); p.clocks .iter() - .find(|c| names.and_then(|n| n.get(c.clock as usize)).is_some_and(|(n, _)| *n == wanted)) + .find(|c| { + names + .and_then(|n| n.get(c.clock as usize)) + .is_some_and(|(n, _)| *n == wanted) + }) .or_else(|| p.clocks.first()) .cloned() }; @@ -869,7 +1071,14 @@ impl Game<'_> { } } C::SystemChat(p) => { - let text = plain(&p.content, &self.remote.as_ref().map(|r| r.lang.clone()).unwrap_or_default()); + let text = plain( + &p.content, + &self + .remote + .as_ref() + .map(|r| r.lang.clone()) + .unwrap_or_default(), + ); if p.overlay { if let Some(r) = self.remote.as_mut() { r.action_bar = Some((text, Instant::now())); @@ -879,13 +1088,24 @@ impl Game<'_> { } } C::PlayerChat(p) => { - let lang = self.remote.as_ref().map(|r| r.lang.clone()).unwrap_or_default(); - let content = p.unsigned_content.as_ref().map_or_else(|| p.content.clone(), |t| plain(t, &lang)); + let lang = self + .remote + .as_ref() + .map(|r| r.lang.clone()) + .unwrap_or_default(); + let content = p + .unsigned_content + .as_ref() + .map_or_else(|| p.content.clone(), |t| plain(t, &lang)); let line = self.format_chat(&p.chat_type, &content); self.chat_line(line); } C::DisguisedChat(p) => { - let lang = self.remote.as_ref().map(|r| r.lang.clone()).unwrap_or_default(); + let lang = self + .remote + .as_ref() + .map(|r| r.lang.clone()) + .unwrap_or_default(); let content = plain(&p.message, &lang); let line = self.format_chat(&p.chat_type, &content); self.chat_line(line); @@ -913,7 +1133,11 @@ impl Game<'_> { } } C::SetActionBarText(p) | C::SetTitleText(p) => { - let lang = self.remote.as_ref().map(|r| r.lang.clone()).unwrap_or_default(); + let lang = self + .remote + .as_ref() + .map(|r| r.lang.clone()) + .unwrap_or_default(); let text = plain(&p.text, &lang); if let Some(r) = self.remote.as_mut() { r.action_bar = Some((text, Instant::now())); @@ -925,9 +1149,14 @@ impl Game<'_> { } /// ChatType decoration: `chat.translation_key` with sender/content parameters. fn format_chat(&self, bound: &play::ChatTypeBound, content: &str) -> String { - let Some(r) = self.remote.as_ref() else { return content.to_owned() }; + let Some(r) = self.remote.as_ref() else { + return content.to_owned(); + }; let sender = plain(&bound.name, &r.lang); - let decoration = r.registries.data("minecraft:chat_type", bound.chat_type).and_then(|t| t.get("chat")); + let decoration = r + .registries + .data("minecraft:chat_type", bound.chat_type) + .and_then(|t| t.get("chat")); let key = match decoration.and_then(|d| d.get("translation_key")) { Some(Tag::String(s)) => s.to_string_lossy(), _ => "chat.type.text".into(), @@ -938,7 +1167,11 @@ impl Game<'_> { .map(|p| match p { Tag::String(s) => match s.to_string_lossy().as_str() { "sender" => sender.clone(), - "target" => bound.target.as_ref().map(|t| plain(t, &r.lang)).unwrap_or_default(), + "target" => bound + .target + .as_ref() + .map(|t| plain(t, &r.lang)) + .unwrap_or_default(), _ => content.to_owned(), }, _ => String::new(), @@ -946,12 +1179,21 @@ impl Game<'_> { .collect(), _ => vec![sender, content.to_owned()], }; - let pattern = r.lang.get(&key).cloned().unwrap_or_else(|| "<%s> %s".into()); + let pattern = r + .lang + .get(&key) + .cloned() + .unwrap_or_else(|| "<%s> %s".into()); format_java(&pattern, ¶ms) } fn remote_item_data(&mut self, id: i32, stack: &Option) { - let Some(stack) = self.to_stack(stack) else { return }; - let position = self.remote.as_mut().and_then(|r| r.pending_items.remove(&id)); + let Some(stack) = self.to_stack(stack) else { + return; + }; + let position = self + .remote + .as_mut() + .and_then(|r| r.pending_items.remove(&id)); if let Some(item) = self.dropped.iter_mut().find(|d| d.id == id as u32) { item.stack = stack; return; @@ -972,7 +1214,9 @@ impl Game<'_> { }); } fn apply_remote_health(&mut self) { - let Some((health, food, saturation)) = self.remote.as_ref().map(|r| r.health) else { return }; + let Some((health, food, saturation)) = self.remote.as_ref().map(|r| r.health) else { + return; + }; if let Some(p) = self.player.as_mut() { if (p.health.health() - health).abs() > f32::EPSILON { let _ = p.set_health(health.max(0.0), false); @@ -984,12 +1228,33 @@ impl Game<'_> { /// ClientPacketListener.handleMovePlayer. fn remote_teleport(&mut self, p: &play::PlayerPosition) -> Result<()> { use play::relative as rel; - let current = self.player.as_ref().map(|pl| pl.position).unwrap_or(Vec3::ZERO); - let velocity = self.player.as_ref().map(|pl| pl.velocity).unwrap_or(Vec3::ZERO); + let current = self + .player + .as_ref() + .map(|pl| pl.position) + .unwrap_or(Vec3::ZERO); + let velocity = self + .player + .as_ref() + .map(|pl| pl.velocity) + .unwrap_or(Vec3::ZERO); let pick = |bit: i32, base: f64, v: f64| if p.relatives & bit != 0 { base + v } else { v }; - let position = Vec3::new(pick(rel::X, current.x, p.position[0]), pick(rel::Y, current.y, p.position[1]), pick(rel::Z, current.z, p.position[2])); - let yaw = if p.relatives & rel::Y_ROT != 0 { self.yaw + p.yaw } else { p.yaw }; - let pitch = (if p.relatives & rel::X_ROT != 0 { self.pitch + p.pitch } else { p.pitch }).clamp(-90.0, 90.0); + let position = Vec3::new( + pick(rel::X, current.x, p.position[0]), + pick(rel::Y, current.y, p.position[1]), + pick(rel::Z, current.z, p.position[2]), + ); + let yaw = if p.relatives & rel::Y_ROT != 0 { + self.yaw + p.yaw + } else { + p.yaw + }; + let pitch = (if p.relatives & rel::X_ROT != 0 { + self.pitch + p.pitch + } else { + p.pitch + }) + .clamp(-90.0, 90.0); let delta = Vec3::new( pick(rel::DELTA_X, velocity.x, p.delta[0]), pick(rel::DELTA_Y, velocity.y, p.delta[1]), @@ -1019,7 +1284,14 @@ impl Game<'_> { r.destroying = None; } self.mining = None; - self.send(S::AcceptTeleportation(play::AcceptTeleportation { id: p.teleport, x: position.x, y: position.y, z: position.z, yaw, pitch })); + self.send(S::AcceptTeleportation(play::AcceptTeleportation { + id: p.teleport, + x: position.x, + y: position.y, + z: position.z, + yaw, + pitch, + })); Ok(()) } @@ -1041,8 +1313,13 @@ impl Game<'_> { self.tick_remote_entities(); self.tick_hand(); self.tick_particles(); - let Some(player) = self.player.as_mut() else { return Ok(()) }; - let (cx, cz) = ((player.position.x.floor() as i32) >> 4, (player.position.z.floor() as i32) >> 4); + let Some(player) = self.player.as_mut() else { + return Ok(()); + }; + let (cx, cz) = ( + (player.position.x.floor() as i32) >> 4, + (player.position.z.floor() as i32) >> 4, + ); if !self.streaming.is_lit(cx, cz) { return Ok(()); } @@ -1053,7 +1330,9 @@ impl Game<'_> { r.loaded_sent = true; } } - let Some(player) = self.player.as_mut() else { return Ok(()) }; + let Some(player) = self.player.as_mut() else { + return Ok(()); + }; let chatting = self.remote.as_ref().is_some_and(|r| r.chat_input.is_some()); let playing = self.screen == Screen::Playing && !chatting; let held = |k| playing && self.keys.contains(&k); @@ -1077,8 +1356,14 @@ impl Game<'_> { player.yaw = self.yaw; let dead = self.screen == Screen::Dead; if !dead { - MotionWorld { player, scene: &mut self.world, assets: &self.res.assets, collision_binding: self.collision, resources: self.motion } - .controlled_simulation_tick(keys)?; + MotionWorld { + player, + scene: &mut self.world, + assets: &self.res.assets, + collision_binding: self.collision, + resources: self.motion, + } + .controlled_simulation_tick(keys)?; } let events = std::mem::take(&mut player.events); self.previous_eye = self.eye; @@ -1090,13 +1375,17 @@ impl Game<'_> { && !crouching { let sounds = self.res.facts.get(state).sounds.clone(); - self.audio.play(&sounds.step, Some(feet), sounds.volume * 0.15, sounds.pitch); + self.audio + .play(&sounds.step, Some(feet), sounds.volume * 0.15, sounds.pitch); } } // 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 (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; @@ -1116,7 +1405,9 @@ impl Game<'_> { Ok(()) } fn tick_remote_entities(&mut self) { - let Some(r) = self.remote.as_mut() else { return }; + let Some(r) = self.remote.as_mut() else { + return; + }; let mut lerps = std::mem::take(&mut r.lerps); for m in &mut self.mobs { m.previous = m.position; @@ -1171,14 +1462,25 @@ impl Game<'_> { } /// LocalPlayer.sendPosition plus input, sprint and held-slot updates. fn remote_send_state(&mut self, input: u8) { - let Some(p) = self.player.as_ref() else { return }; - let (pos, on_ground, collision, sprinting) = ([p.position.x, p.position.y, p.position.z], p.ground.on_ground, p.collision.horizontal, p.sprinting); + let Some(p) = self.player.as_ref() else { + return; + }; + let (pos, on_ground, collision, sprinting) = ( + [p.position.x, p.position.y, p.position.z], + p.ground.on_ground, + p.collision.horizontal, + p.sprinting, + ); let (yaw, pitch, selected) = (self.yaw, self.pitch, self.selected); - let Some(r) = self.remote.as_mut() else { return }; + let Some(r) = self.remote.as_mut() else { + return; + }; let mut out = Vec::new(); if r.carried != Some(selected) { r.carried = Some(selected); - out.push(S::SetCarriedItem(play::SetCarriedItem { slot: selected as i16 })); + out.push(S::SetCarriedItem(play::SetCarriedItem { + slot: selected as i16, + })); } if input != r.last_input { r.last_input = input; @@ -1186,16 +1488,31 @@ impl Game<'_> { } if sprinting != r.was_sprinting { r.was_sprinting = sprinting; - out.push(S::PlayerCommand(play::PlayerCommand { id: r.entity_id, action: if sprinting { 1 } else { 2 }, data: 0 })); + out.push(S::PlayerCommand(play::PlayerCommand { + id: r.entity_id, + action: if sprinting { 1 } else { 2 }, + data: 0, + })); } r.reminder += 1; - let d = [pos[0] - r.last_pos[0], pos[1] - r.last_pos[1], pos[2] - r.last_pos[2]]; + let d = [ + pos[0] - r.last_pos[0], + pos[1] - r.last_pos[1], + pos[2] - r.last_pos[2], + ]; let moved = d[0] * d[0] + d[1] * d[1] + d[2] * d[2] > 2.0e-4 * 2.0e-4 || r.reminder >= 20; let rotated = yaw != r.last_rot.0 || pitch != r.last_rot.1; let flags = u8::from(on_ground) | u8::from(collision) << 1; let [x, y, z] = pos; if moved && rotated { - out.push(S::MovePlayerPosRot(play::MovePlayerPosRot { x, y, z, yaw, pitch, flags })); + out.push(S::MovePlayerPosRot(play::MovePlayerPosRot { + x, + y, + z, + yaw, + pitch, + flags, + })); } else if moved { out.push(S::MovePlayerPos(play::MovePlayerPos { x, y, z, flags })); } else if rotated { @@ -1228,7 +1545,10 @@ impl Game<'_> { for i in creative_slots { let slot = if i < 9 { 36 + i } else { i } as i16; let item = self.to_network(&self.inventory[i]); - self.send(S::SetCreativeModeSlot(play::SetCreativeModeSlot { slot, item })); + self.send(S::SetCreativeModeSlot(play::SetCreativeModeSlot { + slot, + item, + })); } } /// Inventory as the server last described it. @@ -1241,14 +1561,21 @@ impl Game<'_> { /// MultiPlayerGameMode.startDestroyBlock / continueDestroyBlock. fn remote_mining(&mut self) { - let Some(r) = self.remote.as_mut() else { return }; + let Some(r) = self.remote.as_mut() else { + return; + }; if r.destroy_delay > 0 { r.destroy_delay -= 1; } let chatting = r.chat_input.is_some(); if !self.left || self.screen != Screen::Playing || chatting { if let Some((pos, _, _)) = r.destroying.take() { - self.send(S::PlayerAction(play::PlayerAction { action: 2, pos, direction: 0, sequence: 0 })); + self.send(S::PlayerAction(play::PlayerAction { + action: 2, + pos, + direction: 0, + sequence: 0, + })); } self.mining = None; return; @@ -1270,7 +1597,12 @@ impl Game<'_> { if self.creative { let seq = self.next_sequence(); self.predict_break(hit.pos, state); - self.send(S::PlayerAction(play::PlayerAction { action: 0, pos: hit.pos, direction: face, sequence: seq })); + self.send(S::PlayerAction(play::PlayerAction { + action: 0, + pos: hit.pos, + direction: face, + sequence: seq, + })); if let Some(r) = self.remote.as_mut() { r.destroy_delay = 5; } @@ -1282,7 +1614,8 @@ impl Game<'_> { if self.player.as_ref().is_some_and(|p| !p.ground.on_ground) { speed /= 5.0; } - let harvest = !facts.requires_tool || self.res.items.correct_for_drops(held.as_ref(), &facts.name); + let harvest = + !facts.requires_tool || self.res.items.correct_for_drops(held.as_ref(), &facts.name); let progress = if facts.hardness < 0.0 { 0.0 } else if facts.hardness == 0.0 { @@ -1290,13 +1623,27 @@ impl Game<'_> { } else { speed / facts.hardness / if harvest { 30.0 } else { 100.0 } }; - let same = self.remote.as_ref().and_then(|r| r.destroying).is_some_and(|(p, _, _)| p == hit.pos); + let same = self + .remote + .as_ref() + .and_then(|r| r.destroying) + .is_some_and(|(p, _, _)| p == hit.pos); if !same { if let Some((old, _, _)) = self.remote.as_mut().and_then(|r| r.destroying.take()) { - self.send(S::PlayerAction(play::PlayerAction { action: 2, pos: old, direction: face, sequence: 0 })); + self.send(S::PlayerAction(play::PlayerAction { + action: 2, + pos: old, + direction: face, + sequence: 0, + })); } let seq = self.next_sequence(); - self.send(S::PlayerAction(play::PlayerAction { action: 0, pos: hit.pos, direction: face, sequence: seq })); + self.send(S::PlayerAction(play::PlayerAction { + action: 0, + pos: hit.pos, + direction: face, + sequence: seq, + })); if progress >= 1.0 { self.predict_break(hit.pos, state); if let Some(r) = self.remote.as_mut() { @@ -1307,21 +1654,41 @@ impl Game<'_> { if let Some(r) = self.remote.as_mut() { r.destroying = Some((hit.pos, face, 0.0)); } - self.mining = Some(Mining { pos: hit.pos, progress: 0.0, ticks: 0 }); + self.mining = Some(Mining { + pos: hit.pos, + progress: 0.0, + ticks: 0, + }); return; } - let Some((pos, last_face, done)) = self.remote.as_ref().and_then(|r| r.destroying) else { return }; + let Some((pos, last_face, done)) = self.remote.as_ref().and_then(|r| r.destroying) else { + return; + }; let done = done + progress; let ticks = self.mining.as_ref().map_or(0, |m| m.ticks) + 1; if ticks % 4 == 1 { - let c = [f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, f64::from(pos[2]) + 0.5]; - self.audio.play(&facts.sounds.hit, Some(c), (facts.sounds.volume + 1.0) / 8.0, facts.sounds.pitch * 0.5); + let c = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + self.audio.play( + &facts.sounds.hit, + Some(c), + (facts.sounds.volume + 1.0) / 8.0, + facts.sounds.pitch * 0.5, + ); } self.crack_particle(pos, hit.face, state); if done >= 1.0 { let seq = self.next_sequence(); self.predict_break(pos, state); - self.send(S::PlayerAction(play::PlayerAction { action: 3, pos, direction: face, sequence: seq })); + self.send(S::PlayerAction(play::PlayerAction { + action: 3, + pos, + direction: face, + sequence: seq, + })); if let Some(r) = self.remote.as_mut() { r.destroying = None; r.destroy_delay = 5; @@ -1329,19 +1696,37 @@ impl Game<'_> { self.mining = None; } else { if last_face != face { - self.send(S::PlayerAction(play::PlayerAction { action: 1, pos, direction: face, sequence: 0 })); + self.send(S::PlayerAction(play::PlayerAction { + action: 1, + pos, + direction: face, + sequence: 0, + })); } if let Some(r) = self.remote.as_mut() { r.destroying = Some((pos, face, done)); } - self.mining = Some(Mining { pos, progress: done, ticks }); + self.mining = Some(Mining { + pos, + progress: done, + ticks, + }); } } /// MultiPlayerGameMode.destroyBlock: the predicted break. fn predict_break(&mut self, pos: [i32; 3], state: BlockStateId) { let s = self.res.facts.get(state).sounds.clone(); - let at = [f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, f64::from(pos[2]) + 0.5]; - self.audio.play(&s.break_sound, Some(at), (s.volume + 1.0) / 2.0, s.pitch * 0.8); + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + self.audio.play( + &s.break_sound, + Some(at), + (s.volume + 1.0) / 2.0, + s.pitch * 0.8, + ); self.destroy_particles(pos, state); // The server's block update follows (waterlogged blocks leave water). let air = self.world.air; @@ -1352,12 +1737,20 @@ impl Game<'_> { } /// Minecraft.startUseItem: use on the targeted block, then the item itself. fn remote_use(&mut self) { - let held_block = self.held().and_then(|h| self.res.items.get(&h.item)).is_some_and(|i| i.block.is_some()); + let held_block = self + .held() + .and_then(|h| self.res.items.get(&h.item)) + .is_some_and(|i| i.block.is_some()); let sneaking = self.keys.contains(&KeyCode::ShiftLeft); // Entities first (interact), like the hit result order. if let Some((i, _)) = self.mob_hit() { let id = self.mobs[i].id as i32; - self.send(S::Interact(play::Interact { id, hand: 0, location: [0.0, 1.0, 0.0], secondary: sneaking })); + self.send(S::Interact(play::Interact { + id, + hand: 0, + location: [0.0, 1.0, 0.0], + secondary: sneaking, + })); self.swing_arm(); return; } @@ -1377,7 +1770,11 @@ impl Game<'_> { world_border: false, sequence: seq, })); - let target = [hit.pos[0] + hit.face[0], hit.pos[1] + hit.face[1], hit.pos[2] + hit.face[2]]; + let target = [ + hit.pos[0] + hit.face[0], + hit.pos[1] + hit.face[1], + hit.pos[2] + hit.face[2], + ]; let ticks = self.ticks; if let Some(r) = self.remote.as_mut() { r.use_target = Some(hit.pos); @@ -1390,7 +1787,12 @@ impl Game<'_> { } if self.held().is_some() { let seq = self.next_sequence(); - self.send(S::UseItem(play::UseItem { hand: 0, sequence: seq, yaw: self.yaw, pitch: self.pitch })); + self.send(S::UseItem(play::UseItem { + hand: 0, + sequence: seq, + yaw: self.yaw, + pitch: self.pitch, + })); } } /// Left click: attack the targeted entity (MultiPlayerGameMode.attack). @@ -1419,12 +1821,20 @@ impl Game<'_> { self.remote_use(); self.use_delay = 4; } else { - self.send(S::PlayerAction(play::PlayerAction { action: 6, pos: [0; 3], direction: 0, sequence: 0 })); + self.send(S::PlayerAction(play::PlayerAction { + action: 6, + pos: [0; 3], + direction: 0, + sequence: 0, + })); } } MouseButton::Middle if pressed => { if let Some(hit) = self.pick() { - self.send(S::PickItemFromBlock(play::PickItemFromBlock { pos: hit.pos, include_data: false })); + self.send(S::PickItemFromBlock(play::PickItemFromBlock { + pos: hit.pos, + include_data: false, + })); } } _ => {} @@ -1434,7 +1844,9 @@ impl Game<'_> { /// Keys with a multiplayer meaning; returns true when consumed. pub(super) fn remote_key(&mut self, key: KeyCode) -> Result { if self.screen != Screen::Playing { - if key == KeyCode::KeyE && self.screen == Screen::Inventory || key == KeyCode::Escape && self.screen == Screen::Inventory { + if key == KeyCode::KeyE && self.screen == Screen::Inventory + || key == KeyCode::Escape && self.screen == Screen::Inventory + { self.remote_close_container(); self.screen = Screen::Playing; self.capture(true); @@ -1456,7 +1868,12 @@ impl Game<'_> { } KeyCode::KeyQ => { let all = self.keys.contains(&KeyCode::ControlLeft); - self.send(S::PlayerAction(play::PlayerAction { action: if all { 4 } else { 5 }, pos: [0; 3], direction: 0, sequence: 0 })); + self.send(S::PlayerAction(play::PlayerAction { + action: if all { 4 } else { 5 }, + pos: [0; 3], + direction: 0, + sequence: 0, + })); // Inventory.removeFromSelected (prediction). let slot = &mut self.inventory[self.selected]; if let Some(s) = slot { @@ -1471,7 +1888,11 @@ impl Game<'_> { } KeyCode::KeyE => { // The inventory opens without telling the server. - self.screen = if self.creative { Screen::Creative } else { Screen::Inventory }; + self.screen = if self.creative { + Screen::Creative + } else { + Screen::Inventory + }; self.craft_size = 2; self.capture(false); Ok(true) @@ -1488,8 +1909,12 @@ impl Game<'_> { if event.state != winit::event::ElementState::Pressed { return; } - let Some(r) = self.remote.as_mut() else { return }; - let Some(input) = r.chat_input.as_mut() else { return }; + let Some(r) = self.remote.as_mut() else { + return; + }; + let Some(input) = r.chat_input.as_mut() else { + return; + }; // Logical keys: the text, not the scancode, decides (layouts, virtual keyboards). match &event.logical_key { Key::Named(NamedKey::Escape) => { @@ -1522,30 +1947,47 @@ impl Game<'_> { return; } if let Some(command) = message.strip_prefix('/') { - self.send(S::ChatCommand(play::ChatCommand { command: command.to_owned() })); + self.send(S::ChatCommand(play::ChatCommand { + command: command.to_owned(), + })); } else { - let timestamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64); + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as i64); self.send(S::Chat(play::Chat { message: message.chars().take(256).collect(), timestamp, salt: 0, signature: None, - last_seen: play::LastSeenUpdate { offset: 0, acknowledged: [0; 3], checksum: 0 }, + last_seen: play::LastSeenUpdate { + offset: 0, + acknowledged: [0; 3], + checksum: 0, + }, })); } } /// A container click: the server answers with the authoritative slots. pub(super) fn remote_click(&mut self, right: bool) { - let Some(size) = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]) else { return }; + let Some(size) = self + .renderer + .as_ref() + .map(|r| [r.config.width, r.config.height]) + else { + return; + }; let batch = HudBatch::new(size); - let Some(internal) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return }; + let Some(internal) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { + return; + }; let (container, menu) = match self.remote.as_ref().and_then(|r| r.menu.clone()) { Some((id, name)) => (id, name), None => (0, "inventory".to_owned()), }; let slot = (0..64).find(|&s| Self::menu_slot(&menu, s) == Some(internal)); let Some(slot) = slot else { return }; - let shift = self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight); + let shift = + self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight); let carried = self.to_network(&self.carried).map(|s| Hashed::of(&s)); let state = self.remote.as_ref().map_or(0, |r| r.state_id); self.send(S::ContainerClick(play::ContainerClick { @@ -1559,7 +2001,11 @@ impl Game<'_> { })); } pub(super) fn remote_close_container(&mut self) { - let id = self.remote.as_ref().and_then(|r| r.menu.as_ref().map(|m| m.0)).unwrap_or(0); + let id = self + .remote + .as_ref() + .and_then(|r| r.menu.as_ref().map(|m| m.0)) + .unwrap_or(0); self.send(S::ContainerClose(play::ContainerClose { container: id })); self.remote_close_local(); } @@ -1579,8 +2025,21 @@ impl Game<'_> { } /// ClientboundOpenScreenPacket for the menus Horizon draws. fn remote_open_screen(&mut self, p: play::OpenScreen) { - let menu = self.remote.as_ref().and_then(|r| r.builtin.get("minecraft:menu")?.name(p.menu).map(str::to_owned)).unwrap_or_default(); - let target = self.remote.as_ref().and_then(|r| r.use_target).map(|t| (t[0], t[1], t[2])); + let menu = self + .remote + .as_ref() + .and_then(|r| { + r.builtin + .get("minecraft:menu")? + .name(p.menu) + .map(str::to_owned) + }) + .unwrap_or_default(); + let target = self + .remote + .as_ref() + .and_then(|r| r.use_target) + .map(|t| (t[0], t[1], t[2])); let entity = match menu.as_str() { "minecraft:crafting" => None, "minecraft:furnace" | "minecraft:blast_furnace" | "minecraft:smoker" => { @@ -1600,12 +2059,17 @@ impl Game<'_> { })) } m if m.starts_with("minecraft:generic_9x") || m == "minecraft:shulker_box" => { - let rows = m.strip_prefix("minecraft:generic_9x").and_then(|r| r.parse::().ok()).unwrap_or(3); + let rows = m + .strip_prefix("minecraft:generic_9x") + .and_then(|r| r.parse::().ok()) + .unwrap_or(3); Some(BlockEntity::Chest(vec![None; rows * 9])) } _ => { // Unsupported menu: tell the server we closed it. - self.send(S::ContainerClose(play::ContainerClose { container: p.container })); + self.send(S::ContainerClose(play::ContainerClose { + container: p.container, + })); self.chat_line(format!("(Horizon cannot show {menu} screens yet)")); return; } @@ -1636,9 +2100,23 @@ impl Game<'_> { let atlas = &self.res.atlas; let (w, h) = (batch.width, batch.height); batch.fill(atlas, 0.0, 0.0, w, h, rgba(20, 20, 20, 255)); - for (i, line) in [r.status.as_str(), r.session.address.as_str()].iter().enumerate() { + for (i, line) in [r.status.as_str(), r.session.address.as_str()] + .iter() + .enumerate() + { let tw = HudBatch::text_width(atlas, line); - batch.text(atlas, line, (w - tw) / 2.0, h / 2.0 - 12.0 + i as f32 * 12.0, if i == 0 { u32::MAX } else { rgba(160, 160, 160, 255) }, true); + batch.text( + atlas, + line, + (w - tw) / 2.0, + h / 2.0 - 12.0 + i as f32 * 12.0, + if i == 0 { + u32::MAX + } else { + rgba(160, 160, 160, 255) + }, + true, + ); } let _ = r.joined; true @@ -1652,23 +2130,42 @@ impl Game<'_> { let now = Instant::now(); let mut y = h - 48.0; // Container screens cover the chat (vanilla draws them over the HUD). - let shown = if matches!(self.screen, Screen::Playing | Screen::Dead) { if open { 20 } else { 10 } } else { 0 }; + let shown = if matches!(self.screen, Screen::Playing | Screen::Dead) { + if open { 20 } else { 10 } + } else { + 0 + }; for (text, at) in r.chat.iter().rev().take(shown) { let age = now.duration_since(*at); // Lines fade out after ten seconds unless the chat is open. - let alpha = if open { 1.0 } else { (1.0 - (age.as_secs_f32() - 9.0).max(0.0)).clamp(0.0, 1.0) }; + let alpha = if open { + 1.0 + } else { + (1.0 - (age.as_secs_f32() - 9.0).max(0.0)).clamp(0.0, 1.0) + }; if alpha <= 0.0 { break; } let a = (alpha * 255.0) as u8; - batch.fill(atlas, 2.0, y - 1.0, 320.0, 9.0, rgba(0, 0, 0, (alpha * 128.0) as u8)); + batch.fill( + atlas, + 2.0, + y - 1.0, + 320.0, + 9.0, + rgba(0, 0, 0, (alpha * 128.0) as u8), + ); batch.text(atlas, text, 4.0, y, rgba(255, 255, 255, a), true); y -= 9.0; } if let Some(input) = &r.chat_input { batch.fill(atlas, 2.0, h - 14.0, w - 4.0, 12.0, rgba(0, 0, 0, 128)); let blink = (self.started.elapsed().as_millis() / 300).is_multiple_of(2); - let shown = if blink { format!("{input}_") } else { input.clone() }; + let shown = if blink { + format!("{input}_") + } else { + input.clone() + }; batch.text(atlas, &shown, 4.0, h - 12.0, rgba(224, 224, 224, 255), true); } if let Some((text, at)) = &r.action_bar diff --git a/crates/horizon-client/src/game/render_control.rs b/crates/horizon-client/src/game/render_control.rs index c5a70aea6..cf57a9abe 100644 --- a/crates/horizon-client/src/game/render_control.rs +++ b/crates/horizon-client/src/game/render_control.rs @@ -105,7 +105,12 @@ impl Game<'_> { } "signedit" => { let key = (int(1)?, int(2)?, int(3)?); - let name = self.res.facts.get(self.world.block(key.0, key.1, key.2)).name.clone(); + let name = self + .res + .facts + .get(self.world.block(key.0, key.1, key.2)) + .name + .clone(); let entity = horizon_client::containers::BlockEntity::for_block(&name) .filter(|e| matches!(e, horizon_client::containers::BlockEntity::Sign(_))) .ok_or("no sign there")?; diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index 0f77713e8..99c98ddc4 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -18,7 +18,14 @@ fn pause_buttons(w: f32, h: f32) -> Vec<(f32, f32, f32, &'static str, u8, bool)> (x0 + 4.0, y0 + 74.0, 98.0, "gui.advancements", 9, false), (x0 + 110.0, y0 + 74.0, 98.0, "gui.stats", 9, false), (x0 + 4.0, y0 + 122.0, 98.0, "menu.options", 1, true), - (x0 + 110.0, y0 + 122.0, 98.0, "options.worldOptions.button", 9, false), + ( + x0 + 110.0, + y0 + 122.0, + 98.0, + "options.worldOptions.button", + 9, + false, + ), (x0 + 4.0, y0 + 146.0, 204.0, "menu.returnToMenu", 2, true), ] } @@ -34,7 +41,15 @@ fn pause_icons(w: f32, h: f32) -> [(f32, f32, &'static str); 4] { ] } fn death_buttons(w: f32, h: f32) -> [(f32, f32, &'static str, u8); 2] { - [(w / 2.0 - 100.0, h / 4.0 + 72.0, "deathScreen.respawn", 0), (w / 2.0 - 100.0, h / 4.0 + 96.0, "deathScreen.titleScreen", 1)] + [ + (w / 2.0 - 100.0, h / 4.0 + 72.0, "deathScreen.respawn", 0), + ( + w / 2.0 - 100.0, + h / 4.0 + 96.0, + "deathScreen.titleScreen", + 1, + ), + ] } impl Game<'_> { pub(super) fn draw_pause_menu(&mut self, batch: &mut HudBatch) { @@ -43,23 +58,54 @@ impl Game<'_> { ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); let title = Text::translate("menu.game", &[]); let tw = atlas.font.width_text(&title); - batch.text_styled(atlas, &title, ((w - tw) / 2.0).floor(), 40.0, u32::MAX, true); + batch.text_styled( + atlas, + &title, + ((w - tw) / 2.0).floor(), + 40.0, + u32::MAX, + true, + ); for (x, y, bw, key, _, active) in pause_buttons(w, h) { let hover = active && ui::hovered(self.cursor, x, y, bw, 20.0); - ui::button(batch, atlas, x, y, bw, 20.0, &Text::translate(key, &[]), active, hover); + ui::button( + batch, + atlas, + x, + y, + bw, + 20.0, + &Text::translate(key, &[]), + active, + hover, + ); } for (x, y, sprite) in pause_icons(w, h) { ui::button(batch, atlas, x, y, 20.0, 20.0, &Text::empty(), false, false); - batch.sprite_scaled(atlas, sprite, x + 2.0, y + 2.0, 15.0, 15.0, rgba(160, 160, 160, 255)); + batch.sprite_scaled( + atlas, + sprite, + x + 2.0, + y + 2.0, + 15.0, + 15.0, + rgba(160, 160, 160, 255), + ); } } pub(super) fn pause_click(&mut self) -> Result<()> { let (w, h) = { - let size = self.renderer.as_ref().map_or([1, 1], |r| [r.config.width, r.config.height]); + let size = self + .renderer + .as_ref() + .map_or([1, 1], |r| [r.config.width, r.config.height]); let b = HudBatch::new(size); (b.width, b.height) }; - let hit = pause_buttons(w, h).into_iter().find(|b| b.5 && ui::hovered(self.cursor, b.0, b.1, b.2, 20.0)).map(|b| b.4); + let hit = pause_buttons(w, h) + .into_iter() + .find(|b| b.5 && ui::hovered(self.cursor, b.0, b.1, b.2, 20.0)) + .map(|b| b.4); match hit { Some(0) => { self.screen = Screen::Playing; @@ -80,31 +126,87 @@ impl Game<'_> { for y in 0..rows { let t = y as f32 / h.max(1.0); let lerp = |a: f32, b: f32| (a + (b - a) * t) as u8; - batch.fill(atlas, 0.0, y as f32, w, 1.0, rgba(lerp(80.0, 128.0), lerp(0.0, 48.0), lerp(0.0, 48.0), lerp(96.0, 160.0))); + batch.fill( + atlas, + 0.0, + y as f32, + w, + 1.0, + rgba( + lerp(80.0, 128.0), + lerp(0.0, 48.0), + lerp(0.0, 48.0), + lerp(96.0, 160.0), + ), + ); } let title = Text::translate("deathScreen.title", &[]); let tw = atlas.font.width_text(&title); - ui::text_scaled(batch, atlas, &title, (w / 2.0 - tw).floor(), 60.0, 2.0, u32::MAX); + ui::text_scaled( + batch, + atlas, + &title, + (w / 2.0 - tw).floor(), + 60.0, + 2.0, + u32::MAX, + ); if let Some(cause) = &self.ui.death_text { let cw = atlas.font.width_text(cause); batch.text_styled(atlas, cause, ((w - cw) / 2.0).floor(), 85.0, u32::MAX, true); } - let score = Text::translate("deathScreen.score.value", &[Text::colored(self.experience.total.to_string(), text::YELLOW)]); + let score = Text::translate( + "deathScreen.score.value", + &[Text::colored( + self.experience.total.to_string(), + text::YELLOW, + )], + ); let sw = atlas.font.width_text(&score); - batch.text_styled(atlas, &score, ((w - sw) / 2.0).floor(), 100.0, u32::MAX, true); - let active = self.ui.died_at.is_none_or(|t| t.elapsed().as_millis() >= 1000); + batch.text_styled( + atlas, + &score, + ((w - sw) / 2.0).floor(), + 100.0, + u32::MAX, + true, + ); + let active = self + .ui + .died_at + .is_none_or(|t| t.elapsed().as_millis() >= 1000); for (x, y, key, _) in death_buttons(w, h) { let hover = active && ui::hovered(self.cursor, x, y, 200.0, 20.0); - ui::button(batch, atlas, x, y, 200.0, 20.0, &Text::translate(key, &[]), active, hover); + ui::button( + batch, + atlas, + x, + y, + 200.0, + 20.0, + &Text::translate(key, &[]), + active, + hover, + ); } } pub(super) fn death_click(&mut self) -> Result<()> { - if self.ui.died_at.is_some_and(|t| t.elapsed().as_millis() < 1000) { + if self + .ui + .died_at + .is_some_and(|t| t.elapsed().as_millis() < 1000) + { return Ok(()); } - let size = self.renderer.as_ref().map_or([1, 1], |r| [r.config.width, r.config.height]); + let size = self + .renderer + .as_ref() + .map_or([1, 1], |r| [r.config.width, r.config.height]); let b = HudBatch::new(size); - let hit = death_buttons(b.width, b.height).into_iter().find(|d| ui::hovered(self.cursor, d.0, d.1, 200.0, 20.0)).map(|d| d.3); + let hit = death_buttons(b.width, b.height) + .into_iter() + .find(|d| ui::hovered(self.cursor, d.0, d.1, 200.0, 20.0)) + .map(|d| d.3); match hit { Some(0) if self.remote.is_some() => { self.ui.death_text = None; diff --git a/crates/horizon-client/src/game/sign_edit.rs b/crates/horizon-client/src/game/sign_edit.rs index 795b29457..c67a3e880 100644 --- a/crates/horizon-client/src/game/sign_edit.rs +++ b/crates/horizon-client/src/game/sign_edit.rs @@ -30,14 +30,21 @@ impl Game<'_> { } /// `SignBlock.openTextEdit` for the front side after placement. pub(super) fn open_sign_editor(&mut self, pos: (i32, i32, i32), front: bool) { - self.sign_edit = Some(SignEditor { pos, front, line: 0, opened: Instant::now() }); + self.sign_edit = Some(SignEditor { + pos, + front, + line: 0, + opened: Instant::now(), + }); self.keys.clear(); self.right = false; self.capture(false); } fn close_sign_editor(&mut self) { if let Some(edit) = self.sign_edit.take() { - self.world.modified.insert((edit.pos.0 >> 4, edit.pos.2 >> 4)); + self.world + .modified + .insert((edit.pos.0 >> 4, edit.pos.2 >> 4)); } self.capture(true); } @@ -45,28 +52,44 @@ impl Game<'_> { if event.state != ElementState::Pressed { return; } - let Some(edit) = self.sign_edit.as_mut() else { return }; + let Some(edit) = self.sign_edit.as_mut() else { + return; + }; let front = edit.front; match event.physical_key { PhysicalKey::Code(KeyCode::Escape) => self.close_sign_editor(), PhysicalKey::Code(KeyCode::ArrowUp) => edit.line = (edit.line + 3) & 3, - PhysicalKey::Code(KeyCode::ArrowDown | KeyCode::Enter | KeyCode::NumpadEnter) => edit.line = (edit.line + 1) & 3, + PhysicalKey::Code(KeyCode::ArrowDown | KeyCode::Enter | KeyCode::NumpadEnter) => { + edit.line = (edit.line + 1) & 3 + } PhysicalKey::Code(KeyCode::Backspace) => { let line = edit.line; if let Some(sign) = self.edited_sign() { - let text = if front { &mut sign.front } else { &mut sign.back }; + let text = if front { + &mut sign.front + } else { + &mut sign.back + }; text.lines[line].pop(); } } _ => { - let Some(typed) = event.text.as_ref().map(|t| t.to_string()) else { return }; + let Some(typed) = event.text.as_ref().map(|t| t.to_string()) else { + return; + }; let line = edit.line; let atlas = &self.res.atlas; let width = |s: &str| HudBatch::text_width(atlas, s); - let Some(key) = self.sign_edit.as_ref().map(|e| e.pos) else { return }; + let Some(key) = self.sign_edit.as_ref().map(|e| e.pos) else { + return; + }; if let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&key) { let max = sign.max_line_width(); - let text = if front { &mut sign.front } else { &mut sign.back }; + let text = if front { + &mut sign.front + } else { + &mut sign.back + }; for ch in typed.chars().filter(|c| !c.is_control()) { let mut next = text.lines[line].clone(); next.push(ch); @@ -90,20 +113,39 @@ impl Game<'_> { } pub(super) fn draw_sign_editor(&self, batch: &mut HudBatch) { let Some(edit) = &self.sign_edit else { return }; - let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&edit.pos) else { return }; + let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&edit.pos) else { + return; + }; let atlas = &self.res.atlas; let (w, h) = (batch.width, batch.height); batch.fill(atlas, 0.0, 0.0, w, h, rgba(16, 16, 16, 160)); - let title = if sign.hanging { "Edit Hanging Sign Message" } else { "Edit Sign Message" }; + let title = if sign.hanging { + "Edit Hanging Sign Message" + } else { + "Edit Sign Message" + }; let tw = HudBatch::text_width(atlas, title); batch.text(atlas, title, (w - tw) / 2.0, 40.0, u32::MAX, true); - let name = self.res.facts.get(self.world.block(edit.pos.0, edit.pos.1, edit.pos.2)).name.clone(); + let name = self + .res + .facts + .get(self.world.block(edit.pos.0, edit.pos.1, edit.pos.2)) + .name + .clone(); let wood = wood_type(&name); let cx = w / 2.0; let y = if sign.hanging { // HangingSignEditScreen: 16x16 texture scaled 4.5 at (0, -13). let s = 4.5; - batch.sprite_scaled(atlas, &format!("gui/hanging_signs/{wood}"), cx - 8.0 * s, 125.0 - 13.0 - 8.0 * s, 16.0 * s, 16.0 * s, u32::MAX); + batch.sprite_scaled( + atlas, + &format!("gui/hanging_signs/{wood}"), + cx - 8.0 * s, + 125.0 - 13.0 - 8.0 * s, + 16.0 * s, + 16.0 * s, + u32::MAX, + ); 125.0 } else { // SignEditScreen: 24x26 texture scaled 3.9 at (0, 27); wall signs show 12 rows. @@ -112,12 +154,23 @@ impl Game<'_> { let rows = if wall { 12.0 } else { 26.0 }; if let Some(mut r) = atlas.sprites.get(&format!("gui/signs/{wood}")).copied() { r.v1 = r.v0 + (r.v1 - r.v0) * rows / 26.0; - batch.rect_uv(cx - 12.0 * s, 90.0 + 27.0 - 13.0 * s, 24.0 * s, rows * s, r, u32::MAX); + batch.rect_uv( + cx - 12.0 * s, + 90.0 + 27.0 - 13.0 * s, + 24.0 * s, + rows * s, + r, + u32::MAX, + ); } 90.0 }; let text = if edit.front { &sign.front } else { &sign.back }; - let color = if text.glowing { text.text_color() } else { text.dark_color() }; + let color = if text.glowing { + text.text_color() + } else { + text.dark_color() + }; let color = rgba((color >> 16) as u8, (color >> 8) as u8, color as u8, 255); let line_height = sign.line_height(); let midpoint = (4.0 * line_height / 2.0).floor(); @@ -133,8 +186,23 @@ impl Game<'_> { } } let (bx, by) = (w / 2.0 - 100.0, h / 4.0 + 144.0); - batch.sprite_scaled(atlas, "gui/sprites/widget/button", bx, by, 200.0, 20.0, u32::MAX); + batch.sprite_scaled( + atlas, + "gui/sprites/widget/button", + bx, + by, + 200.0, + 20.0, + u32::MAX, + ); let tw = HudBatch::text_width(atlas, "Done"); - batch.text(atlas, "Done", bx + (200.0 - tw) / 2.0, by + 6.0, u32::MAX, true); + batch.text( + atlas, + "Done", + bx + (200.0 - tw) / 2.0, + by + 6.0, + u32::MAX, + true, + ); } } diff --git a/crates/horizon-client/src/game/station_control.rs b/crates/horizon-client/src/game/station_control.rs index a30e15b52..7ef770bbd 100644 --- a/crates/horizon-client/src/game/station_control.rs +++ b/crates/horizon-client/src/game/station_control.rs @@ -20,7 +20,11 @@ pub(super) const HELP: &[&str] = &[ "close close the open menu", ]; fn id(name: &str) -> String { - if name.contains(':') { name.to_owned() } else { format!("minecraft:{name}") } + if name.contains(':') { + name.to_owned() + } else { + format!("minecraft:{name}") + } } fn stack_json(s: &ItemStack) -> Value { json!({ @@ -52,12 +56,21 @@ impl Game<'_> { self.cursor = saved; } fn gui_origin(&self) -> Result<(f32, f32)> { - let size = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]).ok_or("no renderer yet")?; + let size = self + .renderer + .as_ref() + .map(|r| [r.config.width, r.config.height]) + .ok_or("no renderer yet")?; Ok(self.inventory_origin(&horizon_client::hud::HudBatch::new(size))) } /// Commands not known to control.rs; None when unknown here too. pub(super) fn station_command(&mut self, words: &[&str]) -> Result> { - let arg = |i: usize| words.get(i).copied().ok_or_else(|| format!("{} needs more arguments", words[0])); + let arg = |i: usize| { + words + .get(i) + .copied() + .ok_or_else(|| format!("{} needs more arguments", words[0])) + }; let flag = |name: &str| words.iter().skip(1).any(|w| *w == name); let ok = || Ok(Some(json!({ "ok": true }))); match words.first().copied().unwrap_or("") { @@ -73,7 +86,9 @@ impl Game<'_> { return Err(format!("cannot place {name}").into()); } if let Some(entity) = horizon_client::containers::BlockEntity::for_block(&name) { - self.world.block_entities.insert((pos[0], pos[1], pos[2]), entity); + self.world + .block_entities + .insert((pos[0], pos[1], pos[2]), entity); } self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); ok() @@ -81,7 +96,9 @@ impl Game<'_> { "use" => { let pos = [arg(1)?.parse()?, arg(2)?.parse()?, arg(3)?.parse()?]; self.open_menu(pos); - Ok(Some(json!({ "ok": true, "station": self.station.as_ref().map(|s| format!("{:?}", s.kind)) }))) + Ok(Some( + json!({ "ok": true, "station": self.station.as_ref().map(|s| format!("{:?}", s.kind)) }), + )) } "click-slot" => { let slot: usize = arg(1)?.parse()?; @@ -111,7 +128,9 @@ impl Game<'_> { if self.res.stations.enchantments.get(&e).is_none() { return Err(format!("unknown enchantment {e}").into()); } - let held = self.inventory[self.selected].as_mut().ok_or("no held item")?; + let held = self.inventory[self.selected] + .as_mut() + .ok_or("no held item")?; held.enchant(&e, level); self.apply_equipment(); ok() @@ -126,7 +145,11 @@ impl Game<'_> { .slots() .into_iter() .filter_map(|i| { - let s = if i == 200 { self.craft_result() } else { self.slot_mut(i).clone() }; + let s = if i == 200 { + self.craft_result() + } else { + self.slot_mut(i).clone() + }; s.map(|s| json!({ "slot": i, "stack": stack_json(&s) })) }) .collect(); @@ -149,7 +172,13 @@ impl Game<'_> { let def = horizon_client::brewing::effect(arg(1)?).ok_or("unknown effect")?; let seconds: i32 = arg(2)?.parse()?; let amp: i32 = words.get(3).map_or(Ok(0), |a| a.parse())?; - self.potions.effects.add(horizon_client::effects::EffectInstance::new(def.id, seconds * 20, amp)); + self.potions + .effects + .add(horizon_client::effects::EffectInstance::new( + def.id, + seconds * 20, + amp, + )); ok() } "trade" => { @@ -162,7 +191,9 @@ impl Game<'_> { self.open_merchant(&profession, &variant, level); ok() } - "effects" => Ok(Some(json!({ "effects": self.effects_json(), "health": self.player.as_ref().map(|p| p.health.health()) }))), + "effects" => Ok(Some( + json!({ "effects": self.effects_json(), "health": self.player.as_ref().map(|p| p.health.health()) }), + )), "close" => { self.close_container(); self.screen = Screen::Playing; diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index e85e4d83c..59e8e1277 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -33,7 +33,9 @@ impl Kind { fn from_block(name: &str) -> Option { Some(match name { "minecraft:enchanting_table" => Self::Enchanting, - "minecraft:anvil" | "minecraft:chipped_anvil" | "minecraft:damaged_anvil" => Self::Anvil, + "minecraft:anvil" | "minecraft:chipped_anvil" | "minecraft:damaged_anvil" => { + Self::Anvil + } "minecraft:grindstone" => Self::Grindstone, "minecraft:smithing_table" => Self::Smithing, "minecraft:stonecutter" => Self::Stonecutter, @@ -154,12 +156,78 @@ fn inside(p: (f32, f32), x: f32, y: f32, w: f32, h: f32) -> bool { } /// `EnchantmentNames` word list. const WORDS: &[&str] = &[ - "the", "elder", "scrolls", "klaatu", "berata", "niktu", "xyzzy", "bless", "curse", "light", "darkness", "fire", "air", "earth", "water", "hot", "dry", "cold", "wet", "ignite", "snuff", "embiggen", "twist", "shorten", "stretch", "fiddle", "destroy", "imbue", "galvanize", "enchant", "free", "limited", "range", "of", "towards", "inside", "sphere", "cube", "self", "other", "ball", "mental", "physical", "grow", "shrink", "demon", "elemental", "spirit", "animal", "creature", "beast", "humanoid", "undead", "fresh", "stale", "phnglui", "mglwnafh", "cthulhu", "rlyeh", "wgahnagl", "fhtagn", "baguette", + "the", + "elder", + "scrolls", + "klaatu", + "berata", + "niktu", + "xyzzy", + "bless", + "curse", + "light", + "darkness", + "fire", + "air", + "earth", + "water", + "hot", + "dry", + "cold", + "wet", + "ignite", + "snuff", + "embiggen", + "twist", + "shorten", + "stretch", + "fiddle", + "destroy", + "imbue", + "galvanize", + "enchant", + "free", + "limited", + "range", + "of", + "towards", + "inside", + "sphere", + "cube", + "self", + "other", + "ball", + "mental", + "physical", + "grow", + "shrink", + "demon", + "elemental", + "spirit", + "animal", + "creature", + "beast", + "humanoid", + "undead", + "fresh", + "stale", + "phnglui", + "mglwnafh", + "cthulhu", + "rlyeh", + "wgahnagl", + "fhtagn", + "baguette", ]; const GREY: u32 = 0xFF40_4040; fn argb(c: i32) -> u32 { let c = c as u32; - rgba((c >> 16 & 255) as u8, (c >> 8 & 255) as u8, (c & 255) as u8, (c >> 24 & 255) as u8) + rgba( + (c >> 16 & 255) as u8, + (c >> 8 & 255) as u8, + (c & 255) as u8, + (c >> 24 & 255) as u8, + ) } impl Game<'_> { @@ -167,14 +235,20 @@ impl Game<'_> { &self.res.stations } fn translate(&self, key: &str, fallback: &str) -> String { - self.data().enchantments.translate(key).unwrap_or(fallback).to_owned() + self.data() + .enchantments + .translate(key) + .unwrap_or(fallback) + .to_owned() } fn brewing_open(&self) -> bool { matches!(self.container_kind(), Some(BlockEntity::Brewing(_))) } /// Opens a workstation menu for the block; false when it is not one. pub(super) fn open_station(&mut self, pos: [i32; 3], name: &str) -> bool { - let Some(kind) = Kind::from_block(name) else { return false }; + let Some(kind) = Kind::from_block(name) else { + return false; + }; if self.level.xp_seed == 0 { self.level.xp_seed = self.world.random.next_int(); } @@ -184,7 +258,9 @@ impl Game<'_> { } /// `AbstractContainerMenu.clearContainer`: inputs go back to the player. pub(super) fn close_station(&mut self) { - let Some(station) = self.station.take() else { return }; + let Some(station) = self.station.take() else { + return; + }; for stack in station.inputs.into_iter().flatten() { self.give_or_drop(stack); } @@ -204,7 +280,15 @@ impl Game<'_> { } pub(super) fn station_slot_position(&self, i: usize) -> Option<(f32, f32)> { if self.brewing_open() && (300..305).contains(&i) { - return Some([(56.0, 51.0), (79.0, 58.0), (102.0, 51.0), (79.0, 17.0), (17.0, 17.0)][i - 300]); + return Some( + [ + (56.0, 51.0), + (79.0, 58.0), + (102.0, 51.0), + (79.0, 17.0), + (17.0, 17.0), + ][i - 300], + ); } let s = self.station.as_ref()?; if s.kind == Kind::Merchant && i < 36 { @@ -232,41 +316,79 @@ impl Game<'_> { stations::bookshelf_offsets() .into_iter() .filter(|o| { - is([pos[0] + o[0], pos[1] + o[1], pos[2] + o[2]], "minecraft:enchantment_power_provider") - && is([pos[0] + o[0] / 2, pos[1] + o[1], pos[2] + o[2] / 2], "minecraft:enchantment_power_transmitter") + is( + [pos[0] + o[0], pos[1] + o[1], pos[2] + o[2]], + "minecraft:enchantment_power_provider", + ) && is( + [pos[0] + o[0] / 2, pos[1] + o[1], pos[2] + o[2] / 2], + "minecraft:enchantment_power_transmitter", + ) }) .count() as i32 } /// The anvil name the menu works with (`AnvilScreen.onNameChanged`). fn anvil_item_name(&self, s: &Station) -> String { match &s.inputs[0] { - Some(input) if input.custom_name().is_none() && s.name == self.res.names.item(&input.item) => String::new(), + Some(input) + if input.custom_name().is_none() && s.name == self.res.names.item(&input.item) => + { + String::new() + } Some(_) => s.name.clone(), None => String::new(), } } /// `slotsChanged` / `createResult` for the open station. pub(super) fn station_changed(&mut self) { - let Some(mut s) = self.station.take() else { return }; + let Some(mut s) = self.station.take() else { + return; + }; let creative = self.creative; let data = &self.res.stations; let items = &self.res.items; match s.kind { Kind::Enchanting => { s.bookcases = self.count_bookshelves(s.pos); - s.offers = stations::enchant_offers(&data.enchantments, items, self.level.xp_seed, s.bookcases, s.inputs[0].as_ref()); + s.offers = stations::enchant_offers( + &data.enchantments, + items, + self.level.xp_seed, + s.bookcases, + s.inputs[0].as_ref(), + ); } Kind::Anvil => { let name = self.anvil_item_name(&s); - let hover = s.inputs[0].as_ref().map(|i| stations::hover_name(&|id| self.res.names.item(id), i)).unwrap_or_default(); - s.anvil = stations::anvil_result(&data.enchantments, items, s.inputs[0].as_ref(), s.inputs[1].as_ref(), Some(&name), &hover, creative); + let hover = s.inputs[0] + .as_ref() + .map(|i| stations::hover_name(&|id| self.res.names.item(id), i)) + .unwrap_or_default(); + s.anvil = stations::anvil_result( + &data.enchantments, + items, + s.inputs[0].as_ref(), + s.inputs[1].as_ref(), + Some(&name), + &hover, + creative, + ); s.result = s.anvil.result.clone(); } Kind::Grindstone => { - s.result = stations::grindstone_result(&data.enchantments, items, s.inputs[0].as_ref(), s.inputs[1].as_ref()); + s.result = stations::grindstone_result( + &data.enchantments, + items, + s.inputs[0].as_ref(), + s.inputs[1].as_ref(), + ); } Kind::Smithing => { - s.result = data.recipes.smithing_result(&data.enchantments, s.inputs[0].as_ref(), s.inputs[1].as_ref(), s.inputs[2].as_ref()); + s.result = data.recipes.smithing_result( + &data.enchantments, + s.inputs[0].as_ref(), + s.inputs[1].as_ref(), + s.inputs[2].as_ref(), + ); } Kind::Merchant => super::trading::update(&mut s, items), Kind::Stonecutter => { @@ -276,12 +398,22 @@ impl Game<'_> { s.selected = None; s.start = 0; s.recipes = match &s.inputs[0] { - Some(input) => data.recipes.stonecutting.iter().enumerate().filter(|(_, r)| r.input.test(input)).map(|(i, _)| i).collect(), + Some(input) => data + .recipes + .stonecutting + .iter() + .enumerate() + .filter(|(_, r)| r.input.test(input)) + .map(|(i, _)| i) + .collect(), None => Vec::new(), }; } s.result = match (s.selected, &s.inputs[0]) { - (Some(i), Some(_)) => s.recipes.get(i).map(|&r| data.recipes.stonecutting[r].result.clone()), + (Some(i), Some(_)) => s + .recipes + .get(i) + .map(|&r| data.recipes.stonecutting[r].result.clone()), _ => None, }; } @@ -298,10 +430,18 @@ impl Game<'_> { return match slot - 300 { 0..=2 => (data.brewing.is_bottle(stack), 1), 3 => (data.brewing.is_reagent(stack), 64), - _ => (self.res.items.get(&stack.item).is_some_and(|i| i.brewing_fuel.is_some()), 64), + _ => ( + self.res + .items + .get(&stack.item) + .is_some_and(|i| i.brewing_fuel.is_some()), + 64, + ), }; } - let Some(s) = self.station.as_ref() else { return (true, 64) }; + let Some(s) = self.station.as_ref() else { + return (true, 64); + }; if slot < 36 { return (true, 64); } @@ -326,14 +466,20 @@ impl Game<'_> { (None, Some(mut s)) => { let take = if right { s.count.div_ceil(2) } else { s.count }; s.count -= take; - let taken = ItemStack { count: take, ..s.clone() }; + let taken = ItemStack { + count: take, + ..s.clone() + }; ((s.count > 0).then_some(s), Some(taken)) } (Some(mut c), None) => { let (ok, cap) = self.slot_rules(slot, &c); if ok { let n = if right { 1 } else { c.count }.min(cap.min(self.max_stack(&c))); - let placed = ItemStack { count: n, ..c.clone() }; + let placed = ItemStack { + count: n, + ..c.clone() + }; c.count -= n; (Some(placed), (c.count > 0).then_some(c)) } else { @@ -365,7 +511,11 @@ impl Game<'_> { } /// `moveItemStackTo` over `targets` (menu order), merging first, then empty slots. fn move_to(&mut self, stack: &mut ItemStack, targets: &[usize], reverse: bool) -> bool { - let order: Vec = if reverse { targets.iter().rev().copied().collect() } else { targets.to_vec() }; + let order: Vec = if reverse { + targets.iter().rev().copied().collect() + } else { + targets.to_vec() + }; let start = stack.count; if self.max_stack(stack) > 1 { for &t in &order { @@ -390,7 +540,10 @@ impl Game<'_> { let (ok, cap) = self.slot_rules(t, stack); if self.slot_mut(t).is_none() && (t < 36 || ok) { let n = cap.min(self.max_stack(stack)).min(stack.count); - *self.slot_mut(t) = Some(ItemStack { count: n, ..stack.clone() }); + *self.slot_mut(t) = Some(ItemStack { + count: n, + ..stack.clone() + }); stack.count -= n; } } @@ -402,15 +555,24 @@ impl Game<'_> { } /// `quickMoveStack` for one slot; returns whether anything moved. fn quick_move(&mut self, slot: usize) -> bool { - let Some(mut stack) = self.slot_mut(slot).take() else { return false }; + let Some(mut stack) = self.slot_mut(slot).take() else { + return false; + }; let player = Self::player_slots(); let moved = if (300..305).contains(&slot) || slot >= INPUT { self.move_to(&mut stack, &player, true) } else if self.brewing_open() { // BrewingStandMenu.quickMoveStack: fuel, ingredient, bottles, then the other half. let data = self.data(); - let fuel = self.res.items.get(&stack.item).is_some_and(|i| i.brewing_fuel.is_some()); - let (reagent, bottle) = (data.brewing.is_reagent(&stack), data.brewing.is_bottle(&stack)); + let fuel = self + .res + .items + .get(&stack.item) + .is_some_and(|i| i.brewing_fuel.is_some()); + let (reagent, bottle) = ( + data.brewing.is_reagent(&stack), + data.brewing.is_bottle(&stack), + ); let mut moved = false; if fuel { moved = self.move_to(&mut stack, &[304], false); @@ -422,7 +584,11 @@ impl Game<'_> { moved = self.move_to(&mut stack, &[300, 301, 302], false); } if !moved { - let other: Vec = if slot < 9 { (9..36).collect() } else { (0..9).collect() }; + let other: Vec = if slot < 9 { + (9..36).collect() + } else { + (0..9).collect() + }; moved = self.move_to(&mut stack, &other, false); } moved @@ -434,14 +600,20 @@ impl Game<'_> { if &*stack.item == "minecraft:lapis_lazuli" { moved = self.move_to(&mut stack, &[INPUT + 1], true); } else if self.station_slot_mut(INPUT).is_none() { - let one = ItemStack { count: 1, ..stack.clone() }; + let one = ItemStack { + count: 1, + ..stack.clone() + }; *self.station_slot_mut(INPUT) = Some(one); stack.count -= 1; moved = true; } } Some(Kind::Grindstone) => { - let both = self.station.as_ref().is_some_and(|s| s.inputs.iter().all(Option::is_some)); + let both = self + .station + .as_ref() + .is_some_and(|s| s.inputs.iter().all(Option::is_some)); if !both { moved = self.move_to(&mut stack, &[INPUT, INPUT + 1], false); } @@ -455,7 +627,11 @@ impl Game<'_> { None => {} } if !moved { - let other: Vec = if slot < 9 { (9..36).collect() } else { (0..9).collect() }; + let other: Vec = if slot < 9 { + (9..36).collect() + } else { + (0..9).collect() + }; moved = self.move_to(&mut stack, &other, false); } moved @@ -466,7 +642,11 @@ impl Game<'_> { moved } fn play_at(&mut self, sound: &str, pos: [i32; 3], volume: f32, pitch: f32) { - let at = [f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, f64::from(pos[2]) + 0.5]; + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; self.audio.play(sound, Some(at), volume, pitch); } fn give_or_drop(&mut self, stack: ItemStack) { @@ -488,15 +668,21 @@ impl Game<'_> { } /// Whether the result slot may be taken (`mayPickup`). fn may_take_result(&self) -> bool { - let Some(s) = self.station.as_ref() else { return false }; + let Some(s) = self.station.as_ref() else { + return false; + }; match s.kind { - Kind::Anvil => (self.creative || self.experience.level >= s.anvil.cost) && s.anvil.cost > 0, + Kind::Anvil => { + (self.creative || self.experience.level >= s.anvil.cost) && s.anvil.cost > 0 + } _ => true, } } /// The result slot's `onTake`. fn take_result(&mut self) { - let Some(mut s) = self.station.take() else { return }; + let Some(mut s) = self.station.take() else { + return; + }; let pos = s.pos; match s.kind { Kind::Anvil => { @@ -551,9 +737,21 @@ impl Game<'_> { Kind::Grindstone => { let (a, b) = (s.inputs[0].take(), s.inputs[1].take()); let mut random = LegacyRandom::new(self.world.random.next_long()); - let xp = stations::grindstone_experience(&self.res.stations.enchantments, &mut random, a.as_ref(), b.as_ref()); + let xp = stations::grindstone_experience( + &self.res.stations.enchantments, + &mut random, + a.as_ref(), + b.as_ref(), + ); if xp > 0 { - self.spawn_orbs([f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, f64::from(pos[2]) + 0.5], xp); + self.spawn_orbs( + [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ], + xp, + ); } let pitch = self.world.random.next_float() * 0.1 + 0.9; self.play_at("minecraft:block.grindstone.use", pos, 1.0, pitch); @@ -590,7 +788,9 @@ impl Game<'_> { } fn click_result(&mut self, shift: bool) { loop { - let Some(result) = self.station.as_ref().and_then(|s| s.result.clone()) else { return }; + let Some(result) = self.station.as_ref().and_then(|s| s.result.clone()) else { + return; + }; if !self.may_take_result() { return; } @@ -607,7 +807,13 @@ impl Game<'_> { } else { match &mut self.carried { None => self.carried = Some(result.clone()), - Some(c) if c.same_item_same_components(&result) && c.count + result.count <= self.res.items.get(&c.item).map_or(64, |i| i.max_stack) => c.count += result.count, + Some(c) + if c.same_item_same_components(&result) + && c.count + result.count + <= self.res.items.get(&c.item).map_or(64, |i| i.max_stack) => + { + c.count += result.count + } _ => return, } } @@ -615,7 +821,12 @@ impl Game<'_> { s.result = None; } self.take_result(); - let again = shift && self.station.as_ref().and_then(|s| s.result.as_ref()).is_some_and(|r| r.item == result.item); + let again = shift + && self + .station + .as_ref() + .and_then(|s| s.result.as_ref()) + .is_some_and(|r| r.item == result.item); if !again { return; } @@ -623,18 +834,34 @@ impl Game<'_> { } /// `EnchantmentMenu.clickMenuButton`. fn click_enchant(&mut self, button: usize) { - let Some(s) = self.station.as_ref() else { return }; + let Some(s) = self.station.as_ref() else { + return; + }; let cost = s.offers.costs[button]; let lapis_needed = button as u32 + 1; - let Some(item) = s.inputs[0].clone() else { return }; + let Some(item) = s.inputs[0].clone() else { + return; + }; let lapis = s.inputs[1].as_ref().map_or(0, |l| l.count); if lapis < lapis_needed && !self.creative { return; } - if cost <= 0 || (self.experience.level < lapis_needed as i32 || self.experience.level < cost) && !self.creative { + if cost <= 0 + || (self.experience.level < lapis_needed as i32 || self.experience.level < cost) + && !self.creative + { return; } - let Some(enchanted) = stations::apply_enchantment(&self.res.stations.enchantments, &self.res.items, self.level.xp_seed, button, cost, &item) else { return }; + let Some(enchanted) = stations::apply_enchantment( + &self.res.stations.enchantments, + &self.res.items, + self.level.xp_seed, + button, + cost, + &item, + ) else { + return; + }; let pos = s.pos; // Player.onEnchantmentPerformed self.give_levels(-(lapis_needed as i32)); @@ -659,11 +886,18 @@ impl Game<'_> { if self.station.is_none() && !self.brewing_open() { return false; } - let Some(size) = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]) else { return true }; + let Some(size) = self + .renderer + .as_ref() + .map(|r| [r.config.width, r.config.height]) + else { + return true; + }; let batch = HudBatch::new(size); let (ox, oy) = self.inventory_origin(&batch); let local = (self.cursor.0 - ox, self.cursor.1 - oy); - let shift = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft) || self.keys.contains(&winit::keyboard::KeyCode::ShiftRight); + let shift = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft) + || self.keys.contains(&winit::keyboard::KeyCode::ShiftRight); if let Some(kind) = self.station.as_ref().map(|s| s.kind) { if kind == Kind::Merchant && !right && self.merchant_click(local) { return true; @@ -689,7 +923,12 @@ impl Game<'_> { if let Some(st) = self.station.as_mut() { st.selected = Some(index); } - self.audio.play("minecraft:ui.stonecutter.select_recipe", None, 1.0, 1.0); + self.audio.play( + "minecraft:ui.stonecutter.select_recipe", + None, + 1.0, + 1.0, + ); self.station_changed(); } return true; @@ -697,7 +936,9 @@ impl Game<'_> { } } } - let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return true }; + let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { + return true; + }; if slot == RESULT { self.click_result(shift); return true; @@ -717,17 +958,24 @@ impl Game<'_> { } /// Recompute after slot changes; the anvil box follows its input item. fn station_after_input(&mut self) { - let Some(s) = self.station.as_mut() else { return }; + let Some(s) = self.station.as_mut() else { + return; + }; if s.kind == Kind::Anvil && s.inputs[0] != s.anvil_last { // AnvilScreen.slotChanged: the box shows the new input's name. s.anvil_last = s.inputs[0].clone(); - s.name = s.inputs[0].as_ref().map(|i| stations::hover_name(&|id| self.res.names.item(id), i)).unwrap_or_default(); + s.name = s.inputs[0] + .as_ref() + .map(|i| stations::hover_name(&|id| self.res.names.item(id), i)) + .unwrap_or_default(); } self.station_changed(); } pub(super) fn station_scroll(&mut self, d: f32) { self.merchant_scroll(d); - let Some(s) = self.station.as_mut() else { return }; + let Some(s) = self.station.as_mut() else { + return; + }; if s.kind != Kind::Stonecutter || s.recipes.len() <= 12 { return; } @@ -737,10 +985,16 @@ impl Game<'_> { } /// Whether keyboard text goes to the anvil rename box. pub(super) fn station_typing(&self) -> bool { - self.screen == Screen::Inventory && self.station.as_ref().is_some_and(|s| s.kind == Kind::Anvil && s.inputs[0].is_some()) + self.screen == Screen::Inventory + && self + .station + .as_ref() + .is_some_and(|s| s.kind == Kind::Anvil && s.inputs[0].is_some()) } pub(super) fn station_text(&mut self, text: Option<&str>, backspace: bool) { - let Some(s) = self.station.as_mut() else { return }; + let Some(s) = self.station.as_mut() else { + return; + }; if backspace { s.name.pop(); } else if let Some(t) = text { @@ -755,7 +1009,14 @@ impl Game<'_> { // ---------------------------------------------------------------- drawing - fn part(batch: &mut HudBatch, atlas: &horizon_client::hud::HudAtlas, name: &str, src: (f32, f32), size: (f32, f32), dst: (f32, f32)) { + fn part( + batch: &mut HudBatch, + atlas: &horizon_client::hud::HudAtlas, + name: &str, + src: (f32, f32), + size: (f32, f32), + dst: (f32, f32), + ) { if let Some(mut r) = atlas.sprites.get(name).copied() { let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32); r.u0 += src.0 * du; @@ -773,7 +1034,10 @@ impl Game<'_> { return; }; let cell = sheet.w / 16; - let (px, py) = ((sheet.u0 * atlas.width as f32) as u32, (sheet.v0 * atlas.height as f32) as u32); + let (px, py) = ( + (sheet.u0 * atlas.width as f32) as u32, + (sheet.v0 * atlas.height as f32) as u32, + ); let mut cursor = x; for ch in text.chars() { let advance = if ch == ' ' { @@ -787,7 +1051,9 @@ impl Game<'_> { let (cx, cy) = (px + col * cell, py + row * cell); let mut used = 0; for dx in (0..cell).rev() { - if (0..cell).any(|dy| atlas.pixels[(((cy + dy) * atlas.width + cx + dx) * 4 + 3) as usize] != 0) { + if (0..cell).any(|dy| { + atlas.pixels[(((cy + dy) * atlas.width + cx + dx) * 4 + 3) as usize] != 0 + }) { used = dx + 1; break; } @@ -815,7 +1081,11 @@ impl Game<'_> { } /// Draws the open station or brewing stand screen; false when none is open. pub(super) fn draw_station(&mut self, batch: &mut HudBatch) -> bool { - if self.station.as_ref().is_some_and(|s| s.kind == Kind::Merchant) { + if self + .station + .as_ref() + .is_some_and(|s| s.kind == Kind::Merchant) + { return self.draw_merchant(batch); } let brewing = self.brewing_open(); @@ -827,43 +1097,109 @@ impl Game<'_> { let mut tooltip: Option> = None; { let atlas = &self.res.atlas; - batch.fill(atlas, 0.0, 0.0, batch.width, batch.height, rgba(16, 16, 16, 160)); + batch.fill( + atlas, + 0.0, + 0.0, + batch.width, + batch.height, + rgba(16, 16, 16, 160), + ); } let inventory_label = self.translate("container.inventory", "Inventory"); if brewing { - let Some(BlockEntity::Brewing(b)) = self.container_kind() else { return true }; - let (fuel, total_fuel, brew, total_brew) = (b.fuel, b.total_fuel, b.brew_time, b.total_brew_time); + let Some(BlockEntity::Brewing(b)) = self.container_kind() else { + return true; + }; + let (fuel, total_fuel, brew, total_brew) = + (b.fuel, b.total_fuel, b.brew_time, b.total_brew_time); let atlas = &self.res.atlas; - Self::part(batch, atlas, "gui/container/brewing_stand", (0.0, 0.0), (176.0, 166.0), (ox, oy)); - let fuel_len = if total_fuel > 0 { ((18 * fuel + total_fuel - 1) / total_fuel).clamp(0, 18) } else { 0 }; + Self::part( + batch, + atlas, + "gui/container/brewing_stand", + (0.0, 0.0), + (176.0, 166.0), + (ox, oy), + ); + let fuel_len = if total_fuel > 0 { + ((18 * fuel + total_fuel - 1) / total_fuel).clamp(0, 18) + } else { + 0 + }; if fuel_len > 0 { - Self::part(batch, atlas, "gui/sprites/container/brewing_stand/fuel_length", (0.0, 0.0), (fuel_len as f32, 4.0), (ox + 60.0, oy + 44.0)); + Self::part( + batch, + atlas, + "gui/sprites/container/brewing_stand/fuel_length", + (0.0, 0.0), + (fuel_len as f32, 4.0), + (ox + 60.0, oy + 44.0), + ); } if brew > 0 && total_brew > 0 { let len = (28.0 * (1.0 - brew as f32 / total_brew as f32)) as i32; if len > 0 { - Self::part(batch, atlas, "gui/sprites/container/brewing_stand/brew_progress", (0.0, 0.0), (9.0, len as f32), (ox + 97.0, oy + 16.0)); + Self::part( + batch, + atlas, + "gui/sprites/container/brewing_stand/brew_progress", + (0.0, 0.0), + (9.0, len as f32), + (ox + 97.0, oy + 16.0), + ); } let bubble = [29, 24, 20, 16, 11, 6, 0][(brew / 2 % 7) as usize] as f32; if bubble > 0.0 { - Self::part(batch, atlas, "gui/sprites/container/brewing_stand/bubbles", (0.0, 29.0 - bubble), (12.0, bubble), (ox + 63.0, oy + 14.0 + 29.0 - bubble)); + Self::part( + batch, + atlas, + "gui/sprites/container/brewing_stand/bubbles", + (0.0, 29.0 - bubble), + (12.0, bubble), + (ox + 63.0, oy + 14.0 + 29.0 - bubble), + ); } } let title = self.translate("container.brewing", "Brewing Stand"); let tw = HudBatch::text_width(atlas, &title); - batch.text(atlas, &title, ox + (176.0 - tw) / 2.0, oy + 6.0, GREY, false); + batch.text( + atlas, + &title, + ox + (176.0 - tw) / 2.0, + oy + 6.0, + GREY, + false, + ); batch.text(atlas, &inventory_label, ox + 8.0, oy + 72.0, GREY, false); // Empty-slot icons. - for (i, icon) in [(300, "potion"), (301, "potion"), (302, "potion"), (304, "brewing_fuel")] { + for (i, icon) in [ + (300, "potion"), + (301, "potion"), + (302, "potion"), + (304, "brewing_fuel"), + ] { if self.slot_mut(i).is_none() { let (sx, sy) = self.station_slot_position(i).unwrap_or_default(); - batch.sprite(&self.res.atlas, &format!("gui/sprites/container/slot/{icon}"), ox + sx, oy + sy); + batch.sprite( + &self.res.atlas, + &format!("gui/sprites/container/slot/{icon}"), + ox + sx, + oy + sy, + ); } } } else if let Some(kind) = self.station.as_ref().map(|s| s.kind) { let title = self.translate(kind.title_key(), ""); let atlas = &self.res.atlas; - Self::part(batch, atlas, kind.texture(), (0.0, 0.0), (176.0, 166.0), (ox, oy)); + Self::part( + batch, + atlas, + kind.texture(), + (0.0, 0.0), + (176.0, 166.0), + (ox, oy), + ); let (tx, ty) = kind.title_pos(); batch.text(atlas, &title, ox + tx, oy + ty, GREY, false); batch.text(atlas, &inventory_label, ox + 8.0, oy + 72.0, GREY, false); @@ -872,7 +1208,12 @@ impl Game<'_> { match kind { Kind::Enchanting => { if s.inputs[1].is_none() { - batch.sprite(atlas, "gui/sprites/container/slot/lapis_lazuli", ox + 35.0, oy + 47.0); + batch.sprite( + atlas, + "gui/sprites/container/slot/lapis_lazuli", + ox + 35.0, + oy + 47.0, + ); } let mut names = LegacyRandom::new(i64::from(self.level.xp_seed)); let gold = s.inputs[1].as_ref().map_or(0, |l| l.count as i32); @@ -882,51 +1223,156 @@ impl Game<'_> { let (bx, by, bw, bh) = enchant_button(i); let cost = offers.costs[i]; if cost == 0 { - batch.sprite_scaled(atlas, "gui/sprites/container/enchanting_table/enchantment_slot_disabled", ox + bx, oy + by, bw, bh, u32::MAX); + batch.sprite_scaled( + atlas, + "gui/sprites/container/enchanting_table/enchantment_slot_disabled", + ox + bx, + oy + by, + bw, + bh, + u32::MAX, + ); continue; } let cost_text = cost.to_string(); let text_width = 86.0 - HudBatch::text_width(atlas, &cost_text); let count = names.next_int_bound(2).unwrap_or(0) + 3; - let words: Vec<&str> = (0..count).map(|_| WORDS[names.next_int_bound(WORDS.len() as i32).unwrap_or(0) as usize]).collect(); + let words: Vec<&str> = (0..count) + .map(|_| { + WORDS + [names.next_int_bound(WORDS.len() as i32).unwrap_or(0) as usize] + }) + .collect(); let message = words.join(" "); let disabled = (gold < i as i32 + 1 || level < cost) && !self.creative; let col: i32 = if disabled { - batch.sprite_scaled(atlas, "gui/sprites/container/enchanting_table/enchantment_slot_disabled", ox + bx, oy + by, bw, bh, u32::MAX); - batch.sprite(atlas, &format!("gui/sprites/container/enchanting_table/level_{}_disabled", i + 1), ox + bx + 1.0, oy + by + 1.0); + batch.sprite_scaled( + atlas, + "gui/sprites/container/enchanting_table/enchantment_slot_disabled", + ox + bx, + oy + by, + bw, + bh, + u32::MAX, + ); + batch.sprite( + atlas, + &format!( + "gui/sprites/container/enchanting_table/level_{}_disabled", + i + 1 + ), + ox + bx + 1.0, + oy + by + 1.0, + ); let c = ((-9937334i32) & 16711422) >> 1; let msg_color = argb(c | 0xFF00_0000u32 as i32); - self.galactic_deferred(batch, &message, ox + bx + 20.0, oy + by + 2.0, text_width, msg_color); + self.galactic_deferred( + batch, + &message, + ox + bx + 20.0, + oy + by + 2.0, + text_width, + msg_color, + ); -12550384 } else { let hover = inside(local, bx, by, bw, bh); - let sprite = if hover { "enchantment_slot_highlighted" } else { "enchantment_slot" }; - batch.sprite_scaled(atlas, &format!("gui/sprites/container/enchanting_table/{sprite}"), ox + bx, oy + by, bw, bh, u32::MAX); - batch.sprite(atlas, &format!("gui/sprites/container/enchanting_table/level_{}", i + 1), ox + bx + 1.0, oy + by + 1.0); + let sprite = if hover { + "enchantment_slot_highlighted" + } else { + "enchantment_slot" + }; + batch.sprite_scaled( + atlas, + &format!("gui/sprites/container/enchanting_table/{sprite}"), + ox + bx, + oy + by, + bw, + bh, + u32::MAX, + ); + batch.sprite( + atlas, + &format!("gui/sprites/container/enchanting_table/level_{}", i + 1), + ox + bx + 1.0, + oy + by + 1.0, + ); let msg_color = if hover { -128 } else { -9937334 }; - self.galactic_deferred(batch, &message, ox + bx + 20.0, oy + by + 2.0, text_width, argb(msg_color)); + self.galactic_deferred( + batch, + &message, + ox + bx + 20.0, + oy + by + 2.0, + text_width, + argb(msg_color), + ); -8323296 }; let atlas = &self.res.atlas; let cw = HudBatch::text_width(atlas, &cost_text); - batch.text(atlas, &cost_text, ox + bx + 20.0 + 86.0 - cw, oy + by + 9.0, argb(col), true); + batch.text( + atlas, + &cost_text, + ox + bx + 20.0 + 86.0 - cw, + oy + by + 9.0, + argb(col), + true, + ); // Tooltip with the clue (EnchantmentScreen.extractRenderState). if inside(local, bx, by, bw, 17.0) && let Some((id, l)) = &offers.clues[i] { let e = &self.res.stations.enchantments; let (name, _) = e.full_name(id, *l); - let clue = self.translate("container.enchant.clue", "%s . . . ?").replace("%s", &name); + let clue = self + .translate("container.enchant.clue", "%s . . . ?") + .replace("%s", &name); let mut lines = vec![(clue, u32::MAX)]; if !self.creative { lines.push((String::new(), u32::MAX)); if level < cost { - lines.push((self.translate("container.enchant.level.requirement", "Level Requirement: %s").replace("%s", &cost.to_string()), rgba(255, 85, 85, 255))); + lines.push(( + self.translate( + "container.enchant.level.requirement", + "Level Requirement: %s", + ) + .replace("%s", &cost.to_string()), + rgba(255, 85, 85, 255), + )); } else { let n = i + 1; - let lapis = if n == 1 { self.translate("container.enchant.lapis.one", "1 Lapis Lazuli") } else { self.translate("container.enchant.lapis.many", "%s Lapis Lazuli").replace("%s", &n.to_string()) }; - lines.push((lapis, if gold >= n as i32 { rgba(170, 170, 170, 255) } else { rgba(255, 85, 85, 255) })); - let levels = if n == 1 { self.translate("container.enchant.level.one", "1 Enchantment Level") } else { self.translate("container.enchant.level.many", "%s Enchantment Levels").replace("%s", &n.to_string()) }; + let lapis = if n == 1 { + self.translate( + "container.enchant.lapis.one", + "1 Lapis Lazuli", + ) + } else { + self.translate( + "container.enchant.lapis.many", + "%s Lapis Lazuli", + ) + .replace("%s", &n.to_string()) + }; + lines.push(( + lapis, + if gold >= n as i32 { + rgba(170, 170, 170, 255) + } else { + rgba(255, 85, 85, 255) + }, + )); + let levels = if n == 1 { + self.translate( + "container.enchant.level.one", + "1 Enchantment Level", + ) + } else { + self.translate( + "container.enchant.level.many", + "%s Enchantment Levels", + ) + .replace("%s", &n.to_string()) + }; lines.push((levels, rgba(170, 170, 170, 255))); } } @@ -935,14 +1381,42 @@ impl Game<'_> { } } Kind::Anvil => { - let field = if s.inputs[0].is_some() { "text_field" } else { "text_field_disabled" }; - batch.sprite_scaled(atlas, &format!("gui/sprites/container/anvil/{field}"), ox + 59.0, oy + 20.0, 110.0, 16.0, u32::MAX); + let field = if s.inputs[0].is_some() { + "text_field" + } else { + "text_field_disabled" + }; + batch.sprite_scaled( + atlas, + &format!("gui/sprites/container/anvil/{field}"), + ox + 59.0, + oy + 20.0, + 110.0, + 16.0, + u32::MAX, + ); if has_input && s.result.is_none() { - batch.sprite(atlas, "gui/sprites/container/anvil/error", ox + 99.0, oy + 45.0); + batch.sprite( + atlas, + "gui/sprites/container/anvil/error", + ox + 99.0, + oy + 45.0, + ); } if s.inputs[0].is_some() { - let blink = if (self.ticks / 6).is_multiple_of(2) { "_" } else { "" }; - batch.text(atlas, &format!("{}{blink}", s.name), ox + 62.0, oy + 24.0, u32::MAX, true); + let blink = if (self.ticks / 6).is_multiple_of(2) { + "_" + } else { + "" + }; + batch.text( + atlas, + &format!("{}{blink}", s.name), + ox + 62.0, + oy + 24.0, + u32::MAX, + true, + ); } let cost = s.anvil.cost; if cost > 0 { @@ -956,20 +1430,35 @@ impl Game<'_> { if !self.may_take_result() { color = argb(-40864); } - Some(self.translate("container.repair.cost", "Enchantment Cost: %1$s").replace("%1$s", &cost.to_string())) + Some( + self.translate("container.repair.cost", "Enchantment Cost: %1$s") + .replace("%1$s", &cost.to_string()), + ) }; if let Some(line) = line { let atlas = &self.res.atlas; let tw = HudBatch::text_width(atlas, &line); let tx = 176.0 - 8.0 - tw - 2.0; - batch.fill(atlas, ox + tx - 2.0, oy + 67.0, 176.0 - 8.0 - (tx - 2.0), 12.0, argb(1325400064)); + batch.fill( + atlas, + ox + tx - 2.0, + oy + 67.0, + 176.0 - 8.0 - (tx - 2.0), + 12.0, + argb(1325400064), + ); batch.text(atlas, &line, ox + tx, oy + 69.0, color, true); } } } Kind::Grindstone => { if has_input && s.result.is_none() { - batch.sprite(atlas, "gui/sprites/container/grindstone/error", ox + 92.0, oy + 31.0); + batch.sprite( + atlas, + "gui/sprites/container/grindstone/error", + ox + 92.0, + oy + 31.0, + ); } } Kind::Smithing => { @@ -977,13 +1466,29 @@ impl Game<'_> { for (i, icon) in icons.iter().enumerate() { if s.inputs[i].is_none() && !icon.is_empty() { let (sx, sy) = kind.input_pos(i); - batch.sprite(atlas, &format!("gui/sprites/container/slot/{icon}"), ox + sx, oy + sy); + batch.sprite( + atlas, + &format!("gui/sprites/container/slot/{icon}"), + ox + sx, + oy + sy, + ); } } if s.inputs.iter().all(Option::is_some) && s.result.is_none() { - batch.sprite(atlas, "gui/sprites/container/smithing/error", ox + 65.0, oy + 46.0); + batch.sprite( + atlas, + "gui/sprites/container/smithing/error", + ox + 65.0, + oy + 46.0, + ); if inside(local, 65.0, 46.0, 28.0, 21.0) { - tooltip = Some(vec![(self.translate("container.upgrade.error_tooltip", "Item can't be upgraded this way"), u32::MAX)]); + tooltip = Some(vec![( + self.translate( + "container.upgrade.error_tooltip", + "Item can't be upgraded this way", + ), + u32::MAX, + )]); } } } @@ -992,19 +1497,62 @@ impl Game<'_> { let display = s.inputs[0].is_some() && !s.recipes.is_empty(); let active = display && s.recipes.len() > 12; let rows = s.recipes.len().div_ceil(4).saturating_sub(3).max(1); - let offs = if active { (s.start / 4) as f32 / rows as f32 } else { 0.0 }; - let scroller = if active { "scroller" } else { "scroller_disabled" }; - batch.sprite(atlas, &format!("gui/sprites/container/stonecutter/{scroller}"), ox + 119.0, oy + 15.0 + (41.0 * offs).floor()); + let offs = if active { + (s.start / 4) as f32 / rows as f32 + } else { + 0.0 + }; + let scroller = if active { + "scroller" + } else { + "scroller_disabled" + }; + batch.sprite( + atlas, + &format!("gui/sprites/container/stonecutter/{scroller}"), + ox + 119.0, + oy + 15.0 + (41.0 * offs).floor(), + ); if display { let (start, selected) = (s.start, s.selected); // graphics.item: the icon only, without the count. - let shown: Vec<(usize, ItemStack)> = (start..(start + 12).min(s.recipes.len())).map(|i| (i, ItemStack { count: 1, ..self.res.stations.recipes.stonecutting[s.recipes[i]].result.clone() })).collect(); + let shown: Vec<(usize, ItemStack)> = (start + ..(start + 12).min(s.recipes.len())) + .map(|i| { + ( + i, + ItemStack { + count: 1, + ..self.res.stations.recipes.stonecutting[s.recipes[i]] + .result + .clone() + }, + ) + }) + .collect(); for (index, result) in shown { let p = index - start; - let (x, y) = (52.0 + (p % 4) as f32 * 16.0, 14.0 + (p / 4) as f32 * 18.0 + 2.0); + let (x, y) = ( + 52.0 + (p % 4) as f32 * 16.0, + 14.0 + (p / 4) as f32 * 18.0 + 2.0, + ); let hover = inside(local, x, y, 16.0, 18.0); - let sprite = if Some(index) == selected { "recipe_selected" } else if hover { "recipe_highlighted" } else { "recipe" }; - batch.sprite_scaled(&self.res.atlas, &format!("gui/sprites/container/stonecutter/{sprite}"), ox + x, oy + y - 1.0, 16.0, 18.0, u32::MAX); + let sprite = if Some(index) == selected { + "recipe_selected" + } else if hover { + "recipe_highlighted" + } else { + "recipe" + }; + batch.sprite_scaled( + &self.res.atlas, + &format!("gui/sprites/container/stonecutter/{sprite}"), + ox + x, + oy + y - 1.0, + 16.0, + 18.0, + u32::MAX, + ); self.draw_item(batch, &result, ox + x, oy + y); if hover { tooltip = Some(self.stack_tooltip(&result)); @@ -1015,7 +1563,9 @@ impl Game<'_> { } } for i in self.station_slots().unwrap_or_default() { - let Some((sx, sy)) = self.slot_position_any(i) else { continue }; + let Some((sx, sy)) = self.slot_position_any(i) else { + continue; + }; let stack = self.slot_mut(i).clone(); if let Some(stack) = stack { self.draw_item(batch, &stack, ox + sx, oy + sy); @@ -1023,7 +1573,14 @@ impl Game<'_> { } if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); - batch.fill(&self.res.atlas, ox + sx, oy + sy, 16.0, 16.0, rgba(255, 255, 255, 128)); + batch.fill( + &self.res.atlas, + ox + sx, + oy + sy, + 16.0, + 16.0, + rgba(255, 255, 255, 128), + ); if self.carried.is_none() && tooltip.is_none() && let Some(stack) = self.slot_mut(slot).clone() @@ -1038,11 +1595,20 @@ impl Game<'_> { } true } - fn galactic_deferred(&self, batch: &mut HudBatch, text: &str, x: f32, y: f32, max: f32, color: u32) { + fn galactic_deferred( + &self, + batch: &mut HudBatch, + text: &str, + x: f32, + y: f32, + max: f32, + color: u32, + ) { self.galactic(batch, text, x, y, max, color); } fn slot_position_any(&self, i: usize) -> Option<(f32, f32)> { - self.station_slot_position(i).or_else(|| (i < 36).then(|| self.slot_position(i))) + self.station_slot_position(i) + .or_else(|| (i < 36).then(|| self.slot_position(i))) } // ---------------------------------------------------------------- tooltips @@ -1068,9 +1634,13 @@ impl Game<'_> { }; let name = if let Some(n) = stack.custom_name() { n.to_owned() - } else if stack.data().and_then(|d| d.potion.as_ref()).is_some() || stack.item.ends_with("potion") || &*stack.item == "minecraft:tipped_arrow" { + } else if stack.data().and_then(|d| d.potion.as_ref()).is_some() + || stack.item.ends_with("potion") + || &*stack.item == "minecraft:tipped_arrow" + { let key = brewing::potion_name_key(&stack.item, stack.potion()); - e.translate(&key).map_or_else(|| self.res.names.item(&stack.item), str::to_owned) + e.translate(&key) + .map_or_else(|| self.res.names.item(&stack.item), str::to_owned) } else { self.res.names.item(&stack.item) }; @@ -1081,7 +1651,9 @@ impl Game<'_> { "minecraft:tipped_arrow" => 0.125, _ => 1.0, }; - for (line, cat) in brewing::tooltip(stack.potion(), scale, &|k| e.translate(k).map(str::to_owned)) { + for (line, cat) in brewing::tooltip(stack.potion(), scale, &|k| { + e.translate(k).map(str::to_owned) + }) { let c = match cat { brewing::Category::Beneficial => rgba(85, 85, 255, 255), brewing::Category::Harmful => rgba(255, 85, 85, 255), @@ -1091,22 +1663,49 @@ impl Game<'_> { } } if let Some((material, pattern)) = stack.data().and_then(|d| d.trim.clone()) { - lines.push((e.translate("item.minecraft.smithing_template.upgrade").unwrap_or("Upgrade:").to_owned(), rgba(170, 170, 170, 255))); + lines.push(( + e.translate("item.minecraft.smithing_template.upgrade") + .unwrap_or("Upgrade:") + .to_owned(), + rgba(170, 170, 170, 255), + )); let short = |s: &str| s.trim_start_matches("minecraft:").to_owned(); - let p = e.translate(&format!("trim_pattern.minecraft.{}", short(&pattern))).map_or_else(|| short(&pattern), str::to_owned); - let m = e.translate(&format!("trim_material.minecraft.{}", short(&material))).map_or_else(|| short(&material), str::to_owned); + let p = e + .translate(&format!("trim_pattern.minecraft.{}", short(&pattern))) + .map_or_else(|| short(&pattern), str::to_owned); + let m = e + .translate(&format!("trim_material.minecraft.{}", short(&material))) + .map_or_else(|| short(&material), str::to_owned); lines.push((format!(" {p}"), rgba(170, 170, 170, 255))); lines.push((format!(" {m}"), rgba(170, 170, 170, 255))); } - for (text, curse) in e.tooltip(stack.stored_enchantments()).into_iter().chain(e.tooltip(stack.enchantments())) { - lines.push((text, if curse { rgba(255, 85, 85, 255) } else { rgba(170, 170, 170, 255) })); + for (text, curse) in e + .tooltip(stack.stored_enchantments()) + .into_iter() + .chain(e.tooltip(stack.enchantments())) + { + lines.push(( + text, + if curse { + rgba(255, 85, 85, 255) + } else { + rgba(170, 170, 170, 255) + }, + )); } if let Some(info) = self.res.items.get(&stack.item) && info.max_damage > 0 && stack.damage > 0 && self.options_advanced_tooltips() { - lines.push((format!("Durability: {} / {}", info.max_damage - stack.damage, info.max_damage), u32::MAX)); + lines.push(( + format!( + "Durability: {} / {}", + info.max_damage - stack.damage, + info.max_damage + ), + u32::MAX, + )); } lines } @@ -1114,7 +1713,9 @@ impl Game<'_> { pub(super) fn station_info(&self) -> serde_json::Value { let Some(s) = self.station.as_ref() else { return match self.container_kind() { - Some(BlockEntity::Brewing(b)) => serde_json::json!({ "brew_time": b.brew_time, "fuel": b.fuel }), + Some(BlockEntity::Brewing(b)) => { + serde_json::json!({ "brew_time": b.brew_time, "fuel": b.fuel }) + } _ => serde_json::Value::Null, }; }; @@ -1133,13 +1734,26 @@ impl Game<'_> { false } /// `TooltipRenderUtil`: dark box with the purple border, first line spaced. - pub(super) fn draw_tooltip_lines(&self, batch: &mut HudBatch, lines: &[(String, u32)], x: f32, y: f32) { + pub(super) fn draw_tooltip_lines( + &self, + batch: &mut HudBatch, + lines: &[(String, u32)], + x: f32, + y: f32, + ) { if lines.is_empty() { return; } let atlas = &self.res.atlas; - let w = lines.iter().map(|(t, _)| HudBatch::text_width(atlas, t)).fold(0.0, f32::max); - let h = if lines.len() == 1 { 8.0 } else { 8.0 + 2.0 + (lines.len() - 1) as f32 * 10.0 }; + let w = lines + .iter() + .map(|(t, _)| HudBatch::text_width(atlas, t)) + .fold(0.0, f32::max); + let h = if lines.len() == 1 { + 8.0 + } else { + 8.0 + 2.0 + (lines.len() - 1) as f32 * 10.0 + }; let mut x = x + 12.0; let mut y = y - 12.0; if x + w > batch.width - 4.0 { @@ -1150,12 +1764,40 @@ impl Game<'_> { } y = y.max(4.0); batch.fill(atlas, x - 3.0, y - 4.0, w + 6.0, 1.0, rgba(16, 0, 16, 240)); - batch.fill(atlas, x - 3.0, y + h + 3.0, w + 6.0, 1.0, rgba(16, 0, 16, 240)); - batch.fill(atlas, x - 4.0, y - 3.0, w + 8.0, h + 6.0, rgba(16, 0, 16, 240)); + batch.fill( + atlas, + x - 3.0, + y + h + 3.0, + w + 6.0, + 1.0, + rgba(16, 0, 16, 240), + ); + batch.fill( + atlas, + x - 4.0, + y - 3.0, + w + 8.0, + h + 6.0, + rgba(16, 0, 16, 240), + ); batch.fill(atlas, x - 3.0, y - 3.0, w + 6.0, 1.0, rgba(80, 0, 255, 80)); - batch.fill(atlas, x - 3.0, y + h + 2.0, w + 6.0, 1.0, rgba(40, 0, 127, 80)); + batch.fill( + atlas, + x - 3.0, + y + h + 2.0, + w + 6.0, + 1.0, + rgba(40, 0, 127, 80), + ); batch.fill(atlas, x - 3.0, y - 2.0, 1.0, h + 4.0, rgba(60, 0, 190, 80)); - batch.fill(atlas, x + w + 2.0, y - 2.0, 1.0, h + 4.0, rgba(60, 0, 190, 80)); + batch.fill( + atlas, + x + w + 2.0, + y - 2.0, + 1.0, + h + 4.0, + rgba(60, 0, 190, 80), + ); let mut ty = y; for (i, (text, color)) in lines.iter().enumerate() { batch.text(atlas, text, x, ty, *color, true); @@ -1167,8 +1809,14 @@ impl Game<'_> { if self.carried.is_some() { return; } - let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) else { return }; - let stack = if slot == 200 { self.craft_result() } else { self.slot_mut(slot).clone() }; + let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) else { + return; + }; + let stack = if slot == 200 { + self.craft_result() + } else { + self.slot_mut(slot).clone() + }; if let Some(stack) = stack { let lines = self.stack_tooltip(&stack); self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1); @@ -1176,7 +1824,13 @@ impl Game<'_> { } /// 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) { + 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"), @@ -1186,7 +1840,20 @@ impl Game<'_> { }; 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, + 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. @@ -1202,11 +1869,18 @@ impl Game<'_> { 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) + 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 }; + 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); @@ -1214,15 +1888,31 @@ impl Game<'_> { 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)]; + 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) }); + 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), + 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 => {} } } @@ -1234,7 +1924,11 @@ impl Game<'_> { let mut changes = Vec::new(); for (pos, entity) in self.world.block_entities.iter_mut() { if let BlockEntity::Brewing(b) = entity { - let out = b.tick(&self.res.stations.brewing, &self.res.items, &self.res.providers); + let out = b.tick( + &self.res.stations.brewing, + &self.res.items, + &self.res.providers, + ); if out != brewing::BrewTick::default() { changes.push((*pos, out)); } @@ -1254,7 +1948,8 @@ impl Game<'_> { && AsRef::::as_ref(&s.name) == "minecraft:brewing_stand" { for (i, has) in bottles.iter().enumerate() { - s.properties.insert(format!("has_bottle_{i}"), has.to_string()); + s.properties + .insert(format!("has_bottle_{i}"), has.to_string()); } if let Ok(id) = self.res.assets.registry.resolve(&s) { self.world.set(x, y, z, id)?; diff --git a/crates/horizon-client/src/game/trading.rs b/crates/horizon-client/src/game/trading.rs index a2eb6e261..3b8383424 100644 --- a/crates/horizon-client/src/game/trading.rs +++ b/crates/horizon-client/src/game/trading.rs @@ -35,15 +35,28 @@ pub(super) struct MerchantState { pub(super) fn inventory_slot(i: usize) -> (f32, f32) { match i { 0..9 => (108.0 + SHIFT + i as f32 * 18.0, 142.0), - _ => (108.0 + SHIFT + ((i - 9) % 9) as f32 * 18.0, 84.0 + ((i - 9) / 9) as f32 * 18.0), + _ => ( + 108.0 + SHIFT + ((i - 9) % 9) as f32 * 18.0, + 84.0 + ((i - 9) / 9) as f32 * 18.0, + ), } } /// `MerchantContainer.updateSellItem`. pub(super) fn update(s: &mut Station, items: &horizon_client::items::Items) { let Some(m) = s.merchant.as_mut() else { return }; - let (active, result) = merchant::sell_item(&m.offers, items, s.inputs[0].as_ref(), s.inputs[1].as_ref(), Some(m.shop_item)); + let (active, result) = merchant::sell_item( + &m.offers, + items, + s.inputs[0].as_ref(), + s.inputs[1].as_ref(), + Some(m.shop_item), + ); m.active = active; - m.future_xp = if result.is_some() { active.map_or(0, |i| m.offers[i].xp) } else { 0 }; + m.future_xp = if result.is_some() { + active.map_or(0, |i| m.offers[i].xp) + } else { + 0 + }; s.result = result; } @@ -51,9 +64,20 @@ impl Game<'_> { /// Offers a villager of `profession` gets on reaching `level`. fn new_offers(&mut self, profession: &str, variant: &str, level: i32) -> Vec { let set = merchant::Trades::set_for(profession, level); - let sequence = format!("minecraft:trade_set/{}", set.trim_start_matches("minecraft:")); - let random = self.potions.trade_randoms.entry(sequence.clone()).or_insert_with(|| merchant::sequence_random(self.level.seed, &sequence)); - let ctx = TradeContext { items: &self.res.items, enchantments: &self.res.stations.enchantments, variant }; + let sequence = format!( + "minecraft:trade_set/{}", + set.trim_start_matches("minecraft:") + ); + let random = self + .potions + .trade_randoms + .entry(sequence.clone()) + .or_insert_with(|| merchant::sequence_random(self.level.seed, &sequence)); + let ctx = TradeContext { + items: &self.res.items, + enchantments: &self.res.stations.enchantments, + variant, + }; self.res.stations.trades.offers_from_set(&ctx, &set, random) } /// Opens a merchant menu for a villager (or a generated one for tests). @@ -97,10 +121,15 @@ impl Game<'_> { let mut pop = 3 + self.world.random.next_int_bound(4).unwrap_or(0); m.xp += offer.xp; let level_up = merchant::can_level_up(m.level) && m.xp >= merchant::max_xp(m.level); - let at = self.player.as_ref().map(|p| [p.position.x, p.position.y + 0.5, p.position.z]); - self.audio.play("minecraft:entity.villager.yes", at, 1.0, 1.0); + let at = self + .player + .as_ref() + .map(|p| [p.position.x, p.position.y + 0.5, p.position.z]); + self.audio + .play("minecraft:entity.villager.yes", at, 1.0, 1.0); if level_up { - let (profession, variant, level) = (m.profession.clone(), m.variant.clone(), m.level + 1); + let (profession, variant, level) = + (m.profession.clone(), m.variant.clone(), m.level + 1); m.level = level; let more = self.new_offers(&profession, &variant, level); if let Some(m) = s.merchant.as_mut() { @@ -116,7 +145,9 @@ impl Game<'_> { } /// `MerchantMenu.tryMoveItems`: return payment, then fill it for the selected offer. fn try_move_items(&mut self, index: usize) { - let Some(s) = self.station.as_mut() else { return }; + let Some(s) = self.station.as_mut() else { + return; + }; let returned: Vec = s.inputs.iter_mut().filter_map(Option::take).collect(); for stack in returned { if let Some(rest) = self.give(stack) @@ -125,15 +156,28 @@ impl Game<'_> { self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40); } } - let Some(offer) = self.station.as_ref().and_then(|s| s.merchant.as_ref()).and_then(|m| m.offers.get(index)).cloned() else { return }; + let Some(offer) = self + .station + .as_ref() + .and_then(|s| s.merchant.as_ref()) + .and_then(|m| m.offers.get(index)) + .cloned() + else { + return; + }; let wants = [Some(offer.cost_a(&self.res.items)), offer.cost_b()]; for (slot, want) in wants.into_iter().enumerate() { let Some(want) = want else { continue }; let max = self.res.items.get(&want.item).map_or(64, |i| i.max_stack); let mut gathered: Option = None; for i in (9..36).chain(0..9) { - let Some(s) = self.inventory[i].as_mut() else { continue }; - if !s.same_item_same_components(&ItemStack { count: s.count, ..want.clone() }) { + let Some(s) = self.inventory[i].as_mut() else { + continue; + }; + if !s.same_item_same_components(&ItemStack { + count: s.count, + ..want.clone() + }) { continue; } let have = gathered.as_ref().map_or(0, |g| g.count); @@ -142,7 +186,10 @@ impl Game<'_> { break; } s.count -= n; - let taken = ItemStack { count: n, ..s.clone() }; + let taken = ItemStack { + count: n, + ..s.clone() + }; if s.count == 0 { self.inventory[i] = None; } @@ -158,16 +205,24 @@ impl Game<'_> { } /// Clicks on the offer list; true when one was hit. pub(super) fn merchant_click(&mut self, local: (f32, f32)) -> bool { - let Some(m) = self.station.as_ref().and_then(|s| s.merchant.as_ref()) else { return false }; + let Some(m) = self.station.as_ref().and_then(|s| s.merchant.as_ref()) else { + return false; + }; for i in 0..7 { let (x, y) = (5.0 + SHIFT, 18.0 + 20.0 * i as f32); - if local.0 >= x && local.0 < x + 88.0 && local.1 >= y && local.1 < y + 20.0 && i + m.scroll < m.offers.len() { + if local.0 >= x + && local.0 < x + 88.0 + && local.1 >= y + && local.1 < y + 20.0 + && i + m.scroll < m.offers.len() + { let index = i + m.scroll; if let Some(m) = self.station.as_mut().and_then(|s| s.merchant.as_mut()) { m.shop_item = index; m.focused = Some(i); } - self.audio.play("minecraft:ui.button.click", None, 0.25, 1.0); + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); self.try_move_items(index); self.station_changed(); return true; @@ -176,7 +231,9 @@ impl Game<'_> { false } pub(super) fn merchant_scroll(&mut self, d: f32) { - let Some(m) = self.station.as_mut().and_then(|s| s.merchant.as_mut()) else { return }; + let Some(m) = self.station.as_mut().and_then(|s| s.merchant.as_mut()) else { + return; + }; if m.offers.len() > 7 { let max = m.offers.len() - 7; m.scroll = (m.scroll as i32 - d.signum() as i32).clamp(0, max as i32) as usize; @@ -186,12 +243,29 @@ impl Game<'_> { pub(super) fn draw_merchant(&mut self, batch: &mut HudBatch) -> bool { let (ox, oy) = self.inventory_origin(batch); let local = (self.cursor.0 - ox, self.cursor.1 - oy); - let Some(m) = self.station.as_ref().and_then(|s| s.merchant.as_ref()) else { return false }; - let (profession, level, xp, scroll, shop, future, focused) = (m.profession.clone(), m.level, m.xp, m.scroll, m.shop_item, m.future_xp, m.focused); + let Some(m) = self.station.as_ref().and_then(|s| s.merchant.as_ref()) else { + return false; + }; + let (profession, level, xp, scroll, shop, future, focused) = ( + m.profession.clone(), + m.level, + m.xp, + m.scroll, + m.shop_item, + m.future_xp, + m.focused, + ); let offers = m.offers.clone(); let costs: Vec = offers.iter().map(|o| o.cost_a(&self.res.items)).collect(); let atlas = &self.res.atlas; - batch.fill(atlas, 0.0, 0.0, batch.width, batch.height, rgba(16, 16, 16, 160)); + batch.fill( + atlas, + 0.0, + 0.0, + batch.width, + batch.height, + rgba(16, 16, 16, 160), + ); if let Some(mut r) = atlas.sprites.get("gui/container/villager").copied() { let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32); r.u1 = r.u0 + 276.0 * du; @@ -200,28 +274,74 @@ impl Game<'_> { } let e = &self.res.stations.enchantments; let tr = |k: &str, f: &str| e.translate(k).unwrap_or(f).to_owned(); - let name = tr(&format!("entity.minecraft.villager.{profession}"), &profession); - let title = tr("merchant.title", "%s - %s").replacen("%s", &name, 1).replacen("%s", &tr(&format!("merchant.level.{level}"), ""), 1); + let name = tr( + &format!("entity.minecraft.villager.{profession}"), + &profession, + ); + let title = tr("merchant.title", "%s - %s") + .replacen("%s", &name, 1) + .replacen("%s", &tr(&format!("merchant.level.{level}"), ""), 1); let tw = HudBatch::text_width(atlas, &title); - batch.text(atlas, &title, ox + SHIFT + (49.0 + 138.0 - (tw / 2.0).floor()), oy + 6.0, GREY, false); + batch.text( + atlas, + &title, + ox + SHIFT + (49.0 + 138.0 - (tw / 2.0).floor()), + oy + 6.0, + GREY, + false, + ); let trades = tr("merchant.trades", "Trades"); let tw = HudBatch::text_width(atlas, &trades); - batch.text(atlas, &trades, ox + SHIFT + 5.0 - (tw / 2.0).floor() + 48.0, oy + 6.0, GREY, false); - batch.text(atlas, &tr("container.inventory", "Inventory"), ox + SHIFT + 107.0, oy + 72.0, GREY, false); + batch.text( + atlas, + &trades, + ox + SHIFT + 5.0 - (tw / 2.0).floor() + 48.0, + oy + 6.0, + GREY, + false, + ); + batch.text( + atlas, + &tr("container.inventory", "Inventory"), + ox + SHIFT + 107.0, + oy + 72.0, + GREY, + false, + ); if offers.get(shop).is_some_and(MerchantOffer::out_of_stock) { - batch.sprite(atlas, "gui/sprites/container/villager/out_of_stock", ox + SHIFT + 182.0, oy + 35.0); + batch.sprite( + atlas, + "gui/sprites/container/villager/out_of_stock", + ox + SHIFT + 182.0, + oy + 35.0, + ); } // Experience bar (levels 1-4). if level < 5 { - batch.sprite(atlas, "gui/sprites/container/villager/experience_bar_background", ox + SHIFT + 136.0, oy + 16.0); + batch.sprite( + atlas, + "gui/sprites/container/villager/experience_bar_background", + ox + SHIFT + 136.0, + oy + 16.0, + ); let min = merchant::min_xp(level); if xp >= min && merchant::can_level_up(level) { let mult = 102.0 / (merchant::max_xp(level) - min) as f32; let w = ((mult * (xp - min) as f32).floor()).min(102.0); - batch.sprite_part(atlas, "gui/sprites/container/villager/experience_bar_current", ox + SHIFT + 136.0, oy + 16.0, w / 102.0); + batch.sprite_part( + atlas, + "gui/sprites/container/villager/experience_bar_current", + ox + SHIFT + 136.0, + oy + 16.0, + w / 102.0, + ); if future > 0 { let fw = (future as f32 * mult).floor().min(102.0 - w); - if let Some(mut r) = atlas.sprites.get("gui/sprites/container/villager/experience_bar_result").copied() { + if let Some(mut r) = atlas + .sprites + .get("gui/sprites/container/villager/experience_bar_result") + .copied() + { let du = (r.u1 - r.u0) / r.w as f32; r.u0 += w * du; r.u1 = r.u0 + fw * du; @@ -239,16 +359,33 @@ impl Game<'_> { if scroll as i32 == steps - 1 { y = 113; } - batch.sprite(atlas, "gui/sprites/container/villager/scroller", ox + SHIFT + 94.0, oy + 18.0 + y as f32); + batch.sprite( + atlas, + "gui/sprites/container/villager/scroller", + ox + SHIFT + 94.0, + oy + 18.0 + y as f32, + ); } else { - batch.sprite(atlas, "gui/sprites/container/villager/scroller_disabled", ox + SHIFT + 94.0, oy + 18.0); + batch.sprite( + atlas, + "gui/sprites/container/villager/scroller_disabled", + ox + SHIFT + 94.0, + oy + 18.0, + ); } // Offer buttons. let mut tooltip: Option = None; for (row, (index, offer)) in offers.iter().enumerate().skip(scroll).take(7).enumerate() { let (bx, by) = (ox + SHIFT + 5.0, oy + 18.0 + 20.0 * row as f32); - let hover = local.0 >= 5.0 + SHIFT && local.0 < 93.0 + SHIFT && local.1 >= 18.0 + 20.0 * row as f32 && local.1 < 38.0 + 20.0 * row as f32; - let sprite = if hover || focused == Some(row) { "gui/sprites/widget/button_highlighted" } else { "gui/sprites/widget/button" }; + let hover = local.0 >= 5.0 + SHIFT + && local.0 < 93.0 + SHIFT + && local.1 >= 18.0 + 20.0 * row as f32 + && local.1 < 38.0 + 20.0 * row as f32; + let sprite = if hover || focused == Some(row) { + "gui/sprites/widget/button_highlighted" + } else { + "gui/sprites/widget/button" + }; batch.sprite_scaled(&self.res.atlas, sprite, bx, by, 88.0, 20.0, u32::MAX); let y = oy + 16.0 + 1.0 + 20.0 * row as f32 + 2.0; let base = offer.base_cost_a.stack.clone(); @@ -258,19 +395,55 @@ impl Game<'_> { self.draw_item(batch, &cost_a, x, y); } else { // Discounted: the base price struck through, then the new price. - self.draw_item(batch, &ItemStack { count: 1, ..cost_a.clone() }, x, y); + self.draw_item( + batch, + &ItemStack { + count: 1, + ..cost_a.clone() + }, + x, + y, + ); let atlas = &self.res.atlas; let t = base.count.to_string(); - batch.text(atlas, &t, x + 17.0 - HudBatch::text_width(atlas, &t), y + 9.0, u32::MAX, true); + batch.text( + atlas, + &t, + x + 17.0 - HudBatch::text_width(atlas, &t), + y + 9.0, + u32::MAX, + true, + ); let t = cost_a.count.to_string(); - batch.text(atlas, &t, x + 14.0 + 17.0 - HudBatch::text_width(atlas, &t), y + 9.0, u32::MAX, true); - batch.sprite(atlas, "gui/sprites/container/villager/discount_strikethrough", x + 7.0, y + 12.0); + batch.text( + atlas, + &t, + x + 14.0 + 17.0 - HudBatch::text_width(atlas, &t), + y + 9.0, + u32::MAX, + true, + ); + batch.sprite( + atlas, + "gui/sprites/container/villager/discount_strikethrough", + x + 7.0, + y + 12.0, + ); } if let Some(b) = offer.cost_b() { self.draw_item(batch, &b, ox + SHIFT + 40.0, y); } - let arrow = if offer.out_of_stock() { "trade_arrow_out_of_stock" } else { "trade_arrow" }; - batch.sprite(&self.res.atlas, &format!("gui/sprites/container/villager/{arrow}"), ox + SHIFT + 60.0, y + 3.0); + let arrow = if offer.out_of_stock() { + "trade_arrow_out_of_stock" + } else { + "trade_arrow" + }; + batch.sprite( + &self.res.atlas, + &format!("gui/sprites/container/villager/{arrow}"), + ox + SHIFT + 60.0, + y + 3.0, + ); self.draw_item(batch, &offer.result, ox + SHIFT + 73.0, y); if hover && self.carried.is_none() { let rel = local.0 - (5.0 + SHIFT); @@ -295,7 +468,14 @@ impl Game<'_> { } if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); - batch.fill(&self.res.atlas, ox + sx, oy + sy, 16.0, 16.0, rgba(255, 255, 255, 128)); + batch.fill( + &self.res.atlas, + ox + sx, + oy + sy, + 16.0, + 16.0, + rgba(255, 255, 255, 128), + ); if self.carried.is_none() && tooltip.is_none() { tooltip = self.slot_mut(slot).clone(); } diff --git a/crates/horizon-client/src/gamerules.rs b/crates/horizon-client/src/gamerules.rs index 08862b1f9..92815e908 100644 --- a/crates/horizon-client/src/gamerules.rs +++ b/crates/horizon-client/src/gamerules.rs @@ -29,10 +29,22 @@ pub struct Rule { pub max: i32, } const fn b(name: &'static str, category: &'static str, default: bool) -> Rule { - Rule { name, category, default: Value::Bool(default), min: 0, max: 0 } + Rule { + name, + category, + default: Value::Bool(default), + min: 0, + max: 0, + } } const fn i(name: &'static str, category: &'static str, default: i32, min: i32, max: i32) -> Rule { - Rule { name, category, default: Value::Int(default), min, max } + Rule { + name, + category, + default: Value::Int(default), + min, + max, + } } /// Every rule available without experimental features, in registration order. pub const RULES: &[Rule] = &[ @@ -49,7 +61,13 @@ pub const RULES: &[Rule] = &[ b("entity_drops", "drops", true), b("fall_damage", "player", true), b("fire_damage", "player", true), - i("fire_spread_radius_around_player", "updates", 128, -1, i32::MAX), + i( + "fire_spread_radius_around_player", + "updates", + 128, + -1, + i32::MAX, + ), b("forgive_dead_players", "mobs", true), b("freeze_damage", "player", true), b("global_sound_events", "misc", true), @@ -69,8 +87,20 @@ pub const RULES: &[Rule] = &[ b("mob_griefing", "mobs", true), b("natural_health_regeneration", "player", true), b("player_movement_check", "player", true), - i("players_nether_portal_creative_delay", "player", 0, 0, i32::MAX), - i("players_nether_portal_default_delay", "player", 80, 0, i32::MAX), + i( + "players_nether_portal_creative_delay", + "player", + 0, + 0, + i32::MAX, + ), + i( + "players_nether_portal_default_delay", + "player", + 80, + 0, + i32::MAX, + ), i("players_sleeping_percentage", "player", 100, 0, i32::MAX), b("projectiles_can_break_blocks", "drops", true), b("pvp", "player", true), @@ -144,14 +174,25 @@ impl GameRules { Value::Bool(b) => Tag::Byte(i8::from(b)), Value::Int(i) => Tag::Int(i), }; - (horizon_world::nbt::JavaString::from(format!("minecraft:{}", r.name).as_str()), tag) + ( + horizon_world::nbt::JavaString::from(format!("minecraft:{}", r.name).as_str()), + tag, + ) }) .collect(); - NamedTag { name: "".into(), tag: Tag::compound([("data", Tag::compound(data)), ("DataVersion", Tag::Int(DATA_VERSION))]) } + NamedTag { + name: "".into(), + tag: Tag::compound([ + ("data", Tag::compound(data)), + ("DataVersion", Tag::Int(DATA_VERSION)), + ]), + } } pub fn from_nbt(root: &Tag) -> Self { let mut rules = Self::default(); - let Some(data) = root.get("data") else { return rules }; + let Some(data) = root.get("data") else { + return rules; + }; for r in RULES { let key = format!("minecraft:{}", r.name); let value = data.get(&key).or_else(|| data.get(r.name)); @@ -168,8 +209,12 @@ impl GameRules { rules } pub fn load(world: &Path) -> Self { - let Ok(bytes) = fs::read(world.join("data/minecraft/game_rules.dat")) else { return Self::default() }; - let Ok(raw) = Compression::Gzip.decode(&bytes, 16 << 20) else { return Self::default() }; + let Ok(bytes) = fs::read(world.join("data/minecraft/game_rules.dat")) else { + return Self::default(); + }; + let Ok(raw) = Compression::Gzip.decode(&bytes, 16 << 20) else { + return Self::default(); + }; match nbt::read_named(&raw, Limits::default()) { Ok((root, _)) => Self::from_nbt(&root.tag), Err(_) => Self::default(), @@ -178,8 +223,12 @@ impl GameRules { pub fn save(&self, world: &Path) -> crate::Result<()> { let dir = world.join("data/minecraft"); fs::create_dir_all(&dir)?; - let bytes = nbt::write_named(&self.to_nbt(), Limits::default()).map_err(|e| e.to_string())?; - fs::write(dir.join("game_rules.dat"), Compression::Gzip.encode(&bytes)?)?; + let bytes = + nbt::write_named(&self.to_nbt(), Limits::default()).map_err(|e| e.to_string())?; + fs::write( + dir.join("game_rules.dat"), + Compression::Gzip.encode(&bytes)?, + )?; Ok(()) } } diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index b006baf92..f2666f6ca 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -133,7 +133,8 @@ fn mip_chain(pixels: &[u8], size: u32, layers: u32) -> (Vec, u32) { let levels = size.trailing_zeros() + 1; let mut out = Vec::new(); for layer in 0..layers as usize { - let base = &pixels[layer * (size * size * 4) as usize..(layer + 1) * (size * size * 4) as usize]; + let base = + &pixels[layer * (size * size * 4) as usize..(layer + 1) * (size * size * 4) as usize]; let mut level = base.to_vec(); let mut s = size as usize; out.extend_from_slice(&level); @@ -155,7 +156,11 @@ fn mip_chain(pixels: &[u8], size: u32, layers: u32) -> (Vec, u32) { } let o = &mut next[(y * n + x) * 4..][..4]; for c in 0..3 { - o[c] = if weight > 0 { (acc[c] / weight) as u8 } else { 0 }; + o[c] = if weight > 0 { + (acc[c] / weight) as u8 + } else { + 0 + }; } o[3] = (acc[3] / 4) as u8; } @@ -263,7 +268,11 @@ impl Renderer { multisampled: false, }, ), - entry(1 + 1, vf, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering)), + entry( + 1 + 1, + vf, + wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + ), entry( 3, vf, @@ -273,7 +282,11 @@ impl Renderer { multisampled: false, }, ), - entry(4, vf, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering)), + entry( + 4, + vf, + wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + ), ], }); let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { @@ -281,7 +294,8 @@ impl Renderer { bind_group_layouts: &[Some(&bindings)], ..Default::default() }); - let vertex_attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4]; + let vertex_attributes = + wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4]; let instance_attributes = wgpu::vertex_attr_array![5=>Float32x4]; let terrain_buffers = [ Some(wgpu::VertexBufferLayout { @@ -374,8 +388,28 @@ impl Renderer { true, Some(alpha_blend), ); - let sky = pipeline("Sky", "vs_sky", "fs_sky", &[], tri, None, false, false, None); - let dark_disc = pipeline("Dark disc", "vs_sky", "fs_dark_disc", &[], tri, None, false, false, Some(alpha_blend)); + let sky = pipeline( + "Sky", + "vs_sky", + "fs_sky", + &[], + tri, + None, + false, + false, + None, + ); + let dark_disc = pipeline( + "Dark disc", + "vs_sky", + "fs_dark_disc", + &[], + tri, + None, + false, + false, + Some(alpha_blend), + ); let lines = pipeline( "Block outline", "vs_line", @@ -537,7 +571,11 @@ impl Renderer { multisampled: false, }, ), - entry(2, vf, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering)), + entry( + 2, + vf, + wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + ), entry( 3, vf, @@ -547,7 +585,11 @@ impl Renderer { multisampled: false, }, ), - entry(4, vf, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering)), + entry( + 4, + vf, + wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + ), ], }); let atlas_sampler = device.create_sampler(&wgpu::SamplerDescriptor { @@ -670,7 +712,8 @@ impl Renderer { label: Some("Horizon screen effects"), source: wgpu::ShaderSource::Wgsl(include_str!("screen.wgsl").into()), }); - let screen_attributes = wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Float32x4,3=>Float32x4]; + let screen_attributes = + wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Float32x4,3=>Float32x4]; let screen_vertex = [Some(wgpu::VertexBufferLayout { array_stride: std::mem::size_of::() as u64, step_mode: wgpu::VertexStepMode::Vertex, @@ -688,37 +731,42 @@ impl Renderer { operation: wgpu::BlendOperation::Add, }, }; - let screen_pipelines = [("fs_screen", alpha_blend), ("fs_vignette", vignette_blend)].map(|(entry, blend)| { - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("Screen effects"), - layout: Some(&entity_layout), - vertex: wgpu::VertexState { - module: &screen_shader, - entry_point: Some("vs_screen"), - compilation_options: Default::default(), - buffers: &screen_vertex, - }, - primitive: wgpu::PrimitiveState { cull_mode: None, ..Default::default() }, - depth_stencil: None, - multisample: Default::default(), - fragment: Some(wgpu::FragmentState { - module: &screen_shader, - entry_point: Some(entry), - compilation_options: Default::default(), - targets: &[Some(wgpu::ColorTargetState { - format: config.format.remove_srgb_suffix(), - blend: Some(blend), - write_mask: wgpu::ColorWrites::ALL, - })], - }), - multiview_mask: None, - cache: None, - }) - }); + let screen_pipelines = + [("fs_screen", alpha_blend), ("fs_vignette", vignette_blend)].map(|(entry, blend)| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Screen effects"), + layout: Some(&entity_layout), + vertex: wgpu::VertexState { + module: &screen_shader, + entry_point: Some("vs_screen"), + compilation_options: Default::default(), + buffers: &screen_vertex, + }, + primitive: wgpu::PrimitiveState { + cull_mode: None, + ..Default::default() + }, + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &screen_shader, + entry_point: Some(entry), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: config.format.remove_srgb_suffix(), + blend: Some(blend), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }) + }); let screen_capacity = 64; let screen_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("Screen effect vertices"), - size: screen_capacity * std::mem::size_of::() as u64, + size: screen_capacity + * std::mem::size_of::() as u64, usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); @@ -820,7 +868,11 @@ impl Renderer { /// VSync on: tear-free presentation (Mailbox, else Fifo); off: Immediate when available. pub fn set_vsync(&mut self, vsync: bool) { let has = |m| self.present_modes.contains(&m); - let mode = match (vsync, has(wgpu::PresentMode::Mailbox), has(wgpu::PresentMode::Immediate)) { + let mode = match ( + vsync, + has(wgpu::PresentMode::Mailbox), + has(wgpu::PresentMode::Immediate), + ) { (true, true, _) => wgpu::PresentMode::Mailbox, (true, false, _) => wgpu::PresentMode::Fifo, (false, _, true) => wgpu::PresentMode::Immediate, @@ -899,7 +951,14 @@ impl Renderer { /// SectionOcclusionGraph: breadth-first from the camera section through /// faces its VisGraph connects, never stepping back towards the camera. fn update_reachable(&mut self, from: SectionKey, radius: i32) { - const STEPS: [(i32, i32, i32); 6] = [(0, -1, 0), (0, 1, 0), (0, 0, -1), (0, 0, 1), (-1, 0, 0), (1, 0, 0)]; + const STEPS: [(i32, i32, i32); 6] = [ + (0, -1, 0), + (0, 1, 0), + (0, 0, -1), + (0, 0, 1), + (-1, 0, 0), + (1, 0, 0), + ]; let opposite = |d: usize| d ^ 1; self.reachable.clear(); let mut queue = std::collections::VecDeque::new(); @@ -908,7 +967,11 @@ impl Renderer { self.reachable.insert(from); let sections = (crate::chunk::HEIGHT / 16) as i32; while let Some((key, entered, travelled)) = queue.pop_front() { - let vis = self.visibility.get(&key).copied().unwrap_or(crate::mesher::ALL_VISIBLE); + let vis = self + .visibility + .get(&key) + .copied() + .unwrap_or(crate::mesher::ALL_VISIBLE); for (d, step) in STEPS.iter().enumerate() { if travelled & (1 << opposite(d)) != 0 { continue; @@ -919,7 +982,11 @@ impl Renderer { continue; } let next = (key.0 + step.0, key.1 + step.1, key.2 + step.2); - if next.1 < -1 || next.1 > sections || (next.0 - from.0).abs() > radius || (next.2 - from.2).abs() > radius { + if next.1 < -1 + || next.1 > sections + || (next.0 - from.0).abs() > radius + || (next.2 - from.2).abs() > radius + { continue; } if self.reachable.insert(next) { @@ -940,13 +1007,19 @@ impl Renderer { let aspect = self.config.width as f32 / self.config.height.max(1) as f32; let (yaw, pitch) = (frame.yaw.to_radians(), frame.pitch.to_radians()); // Minecraft yaw: 0 = +Z (south), 90 = -X (west); pitch positive looks down. - let forward = Vec3::new(-yaw.sin() * pitch.cos(), -pitch.sin(), yaw.cos() * pitch.cos()); + let forward = Vec3::new( + -yaw.sin() * pitch.cos(), + -pitch.sin(), + 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()) + * Mat4::from_rotation_x( + ((f - 0.2).cos() * bob).abs().mul_add(5.0, 0.0).to_radians(), + ) }); Mat4::perspective_rh(frame.fov_degrees.to_radians(), aspect, 0.05, far) * bob @@ -1068,22 +1141,44 @@ impl Renderer { let view_proj = self.view_projection(frame); let aspect = self.config.width as f32 / self.config.height.max(1) as f32; let (yaw, pitch) = (frame.yaw.to_radians(), frame.pitch.to_radians()); - let forward = Vec3::new(-yaw.sin() * pitch.cos(), -pitch.sin(), yaw.cos() * pitch.cos()); + let forward = Vec3::new( + -yaw.sin() * pitch.cos(), + -pitch.sin(), + yaw.cos() * pitch.cos(), + ); let view = Mat4::look_to_rh(Vec3::ZERO, forward, Vec3::Y); let sun_angle = frame.sky.sun_angle.to_radians(); // Celestial bodies rotate around the X axis; angle 0 = noon. let sun = Vec3::new(0.0, sun_angle.cos(), -sun_angle.sin()); let (fog_color, fog) = if let Some(f) = frame.fog { - (f.color, [f.environmental_start, f.environmental_end, f.render_distance_start, f.render_distance_end]) + ( + f.color, + [ + f.environmental_start, + f.environmental_end, + f.render_distance_start, + f.render_distance_end, + ], + ) } else if frame.underwater { ( - [frame.water_fog[0], frame.water_fog[1], frame.water_fog[2], 1.0], + [ + frame.water_fog[0], + frame.water_fog[1], + frame.water_fog[2], + 1.0, + ], [-8.0, 96.0, -8.0, 96.0], ) } else { let d = frame.distance; ( - [frame.sky.fog_color[0], frame.sky.fog_color[1], frame.sky.fog_color[2], 1.0], + [ + frame.sky.fog_color[0], + frame.sky.fog_color[1], + frame.sky.fog_color[2], + 1.0, + ], // FogRenderer: render-distance fog starts at max(d - 16, 0)... d. { let (start, end) = frame.environment_fog.unwrap_or((f32::MAX, f32::MAX)); @@ -1095,7 +1190,12 @@ impl Renderer { view_proj: view_proj.to_cols_array_2d(), fog_color, fog, - sky_color: [frame.sky.sky_color[0], frame.sky.sky_color[1], frame.sky.sky_color[2], 1.0], + sky_color: [ + frame.sky.sky_color[0], + frame.sky.sky_color[1], + frame.sky.sky_color[2], + 1.0, + ], misc: [ 1.0 - frame.sky.sky_light_factor, frame.game_time, @@ -1155,7 +1255,11 @@ impl Renderer { }) { return None; } - Some(((sx, sy, sz), center.length_squared(), origin.as_vec3().to_array())) + Some(( + (sx, sy, sz), + center.length_squared(), + origin.as_vec3().to_array(), + )) }) .collect(); visible.sort_by(|a, b| a.1.total_cmp(&b.1)); @@ -1196,7 +1300,18 @@ impl Renderer { ] }; let edges = [ - (0, 1), (2, 3), (4, 5), (6, 7), (0, 2), (1, 3), (4, 6), (5, 7), (0, 4), (1, 5), (2, 6), (3, 7), + (0, 1), + (2, 3), + (4, 5), + (6, 7), + (0, 2), + (1, 3), + (4, 6), + (5, 7), + (0, 4), + (1, 5), + (2, 6), + (3, 7), ]; let lines: Vec<[f32; 3]> = edges.iter().flat_map(|&(a, b)| [c(a), c(b)]).collect(); self.queue @@ -1239,10 +1354,12 @@ impl Renderer { self.index_quads = (entity_quads + hand_quads).next_power_of_two(); self.indices = Self::quad_indices(&self.device, self.index_quads); } - let view_target = surface_frame.texture.create_view(&wgpu::TextureViewDescriptor { - format: Some(self.config.format.remove_srgb_suffix()), - ..Default::default() - }); + let view_target = surface_frame + .texture + .create_view(&wgpu::TextureViewDescriptor { + format: Some(self.config.format.remove_srgb_suffix()), + ..Default::default() + }); let mut encoder = self .device .create_command_encoder(&wgpu::CommandEncoderDescriptor { @@ -1254,16 +1371,18 @@ impl Renderer { resolve_target: None, depth_slice: None, ops: wgpu::Operations { - load: wgpu::LoadOp::Clear(if frame.title || (frame.end_sky && !frame.underwater) { - wgpu::Color::BLACK - } else { - wgpu::Color { - r: f64::from(fog_color[0]), - g: f64::from(fog_color[1]), - b: f64::from(fog_color[2]), - a: 1.0, - } - }), + load: wgpu::LoadOp::Clear( + if frame.title || (frame.end_sky && !frame.underwater) { + wgpu::Color::BLACK + } else { + wgpu::Color { + r: f64::from(fog_color[0]), + g: f64::from(fog_color[1]), + b: f64::from(fog_color[2]), + a: 1.0, + } + }, + ), store: wgpu::StoreOp::Store, }, })]; @@ -1375,22 +1494,28 @@ impl Renderer { pass.draw_indexed(0..hand_quads * 6, (entity_quads * 4) as i32, 0..1); } if !frame.screen.is_empty() { - let vertices: Vec = frame.screen.iter().flat_map(|q| q.vertices).collect(); + let vertices: Vec = + frame.screen.iter().flat_map(|q| q.vertices).collect(); if vertices.len() as u64 > self.screen_capacity { self.screen_capacity = (vertices.len() as u64).next_power_of_two(); self.screen_buffer = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("Screen effect vertices"), - size: self.screen_capacity * std::mem::size_of::() as u64, + size: self.screen_capacity + * std::mem::size_of::() as u64, usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); } - self.queue.write_buffer(&self.screen_buffer, 0, bytemuck::cast_slice(&vertices)); + self.queue + .write_buffer(&self.screen_buffer, 0, bytemuck::cast_slice(&vertices)); let attachments = [Some(wgpu::RenderPassColorAttachment { view: &view_target, resolve_target: None, depth_slice: None, - ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store }, + ops: wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + }, })]; let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("Screen effects"), @@ -1417,10 +1542,16 @@ impl Renderer { frame.hud, [self.config.width, self.config.height], ); - let readback = self.screenshot.take().map(|path| (path, self.copy_frame(&mut encoder, &surface_frame.texture))); + let readback = self + .screenshot + .take() + .map(|path| (path, self.copy_frame(&mut encoder, &surface_frame.texture))); self.queue.submit([encoder.finish()]); if let Some((path, buffer)) = readback { - self.screenshot_result = Some(self.write_screenshot(&path, &buffer).map_err(|e| e.to_string())); + self.screenshot_result = Some( + self.write_screenshot(&path, &buffer) + .map_err(|e| e.to_string()), + ); } self.window.pre_present_notify(); self.queue.present(surface_frame); @@ -1435,7 +1566,11 @@ impl Renderer { fn padded_row(&self) -> u32 { (self.config.width * 4).next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) } - fn copy_frame(&self, encoder: &mut wgpu::CommandEncoder, texture: &wgpu::Texture) -> wgpu::Buffer { + fn copy_frame( + &self, + encoder: &mut wgpu::CommandEncoder, + texture: &wgpu::Texture, + ) -> wgpu::Buffer { let buffer = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("Horizon screenshot"), size: u64::from(self.padded_row()) * u64::from(self.config.height), @@ -1452,7 +1587,11 @@ impl Renderer { rows_per_image: None, }, }, - wgpu::Extent3d { width: self.config.width, height: self.config.height, depth_or_array_layers: 1 }, + wgpu::Extent3d { + width: self.config.width, + height: self.config.height, + depth_or_array_layers: 1, + }, ); buffer } @@ -1464,22 +1603,41 @@ impl Renderer { buffer.map_async(wgpu::MapMode::Read, .., move |r| { let _ = sender.send(r); }); - self.device.poll(wgpu::PollType::wait_indefinitely()).map_err(|e| e.to_string())?; - receiver.recv().map_err(|e| e.to_string())?.map_err(|e| e.to_string())?; - let (width, height, row) = (self.config.width, self.config.height, self.padded_row() as usize); - let bgra = matches!(self.config.format.remove_srgb_suffix(), wgpu::TextureFormat::Bgra8Unorm); + self.device + .poll(wgpu::PollType::wait_indefinitely()) + .map_err(|e| e.to_string())?; + receiver + .recv() + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + let (width, height, row) = ( + self.config.width, + self.config.height, + self.padded_row() as usize, + ); + let bgra = matches!( + self.config.format.remove_srgb_suffix(), + wgpu::TextureFormat::Bgra8Unorm + ); let mut pixels = Vec::with_capacity((width * height * 4) as usize); { let data = buffer.get_mapped_range(..).map_err(|e| e.to_string())?; for y in 0..height as usize { - for px in data[y * row..y * row + width as usize * 4].as_chunks::<4>().0 { + for px in data[y * row..y * row + width as usize * 4] + .as_chunks::<4>() + .0 + { let (r, b) = if bgra { (px[2], px[0]) } else { (px[0], px[2]) }; pixels.extend_from_slice(&[r, px[1], b, 255]); } } } buffer.unmap(); - let mut encoder = png::Encoder::new(std::io::BufWriter::new(std::fs::File::create(path)?), width, height); + let mut encoder = png::Encoder::new( + std::io::BufWriter::new(std::fs::File::create(path)?), + width, + height, + ); encoder.set_color(png::ColorType::Rgba); encoder.set_depth(png::BitDepth::Eight); encoder.write_header()?.write_image_data(&pixels)?; diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index e4bf7b96b..6941a9222 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -316,7 +316,9 @@ impl ServerDamageEnvironment for Environment<'_> { Ok(self.status.resistance.is_some()) } fn resistance_amplifier(&mut self) -> io::Result { - self.status.resistance.ok_or_else(|| io::Error::other("no resistance effect")) + self.status + .resistance + .ok_or_else(|| io::Error::other("no resistance effect")) } fn award_resisted(&mut self, value: i32) -> io::Result<()> { self.stat("resisted", value) diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 7c9574bc1..1be29902f 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -48,7 +48,9 @@ pub fn decode(path: &Path) -> Result<(u32, u32, Vec)> { Ok((info.width, info.height, rgba)) } fn walk(dir: &Path, out: &mut Vec) { - let Ok(entries) = fs::read_dir(dir) else { return }; + let Ok(entries) = fs::read_dir(dir) else { + return; + }; for entry in entries.flatten() { let path = entry.path(); if path.is_dir() { @@ -78,7 +80,9 @@ impl HudAtlas { walk(&textures.join("mob_effect"), &mut files); files.retain(|p| { let s = p.to_string_lossy(); - (!s.contains("title/background") || s.contains("panorama_")) && !s.contains("realms") && !s.contains("presets") + (!s.contains("title/background") || s.contains("panorama_")) + && !s.contains("realms") + && !s.contains("presets") }); let decode_one = |path: &PathBuf| -> Option<(String, u32, u32, Vec)> { let name = path @@ -114,9 +118,14 @@ impl HudAtlas { let mut images: Vec<_> = std::thread::scope(|scope| { let handles: Vec<_> = files .chunks(chunk) - .map(|part| scope.spawn(move || part.iter().filter_map(decode_one).collect::>())) + .map(|part| { + scope.spawn(move || part.iter().filter_map(decode_one).collect::>()) + }) .collect(); - handles.into_iter().flat_map(|h| h.join().unwrap_or_default()).collect() + handles + .into_iter() + .flat_map(|h| h.join().unwrap_or_default()) + .collect() }); images.push(("horizon/white".into(), 4, 4, vec![255; 64])); images.sort_by(|a, b| b.2.cmp(&a.2).then(b.1.cmp(&a.1))); @@ -156,7 +165,14 @@ impl HudAtlas { ); } let white = sprites["horizon/white"]; - let font = crate::font::Font::load(root, &sprites, &pixels, (width, height), (glyph_region, height - glyph_region), white); + let font = crate::font::Font::load( + root, + &sprites, + &pixels, + (width, height), + (glyph_region, height - glyph_region), + white, + ); Ok(Self { pixels, width, @@ -194,7 +210,10 @@ impl HudBatch { pub fn new(window: [u32; 2]) -> Self { let limit = GUI_SCALE.load(std::sync::atomic::Ordering::Relaxed); let mut scale = 1; - while (limit == 0 || scale < limit) && window[0] / (scale + 1) >= 320 && window[1] / (scale + 1) >= 240 { + while (limit == 0 || scale < limit) + && window[0] / (scale + 1) >= 320 + && window[1] / (scale + 1) >= 240 + { scale += 1; } Self { @@ -226,7 +245,16 @@ impl HudBatch { self.rect_uv(x, y, r.w as f32, r.h as f32, r, u32::MAX); } } - pub fn sprite_scaled(&mut self, atlas: &HudAtlas, name: &str, x: f32, y: f32, w: f32, h: f32, color: u32) { + pub fn sprite_scaled( + &mut self, + atlas: &HudAtlas, + name: &str, + x: f32, + y: f32, + w: f32, + h: f32, + color: u32, + ) { if let Some(r) = atlas.sprites.get(name).copied() { self.rect_uv(x, y, w, h, r, color); } @@ -252,23 +280,55 @@ impl HudBatch { atlas.font.width(text) } /// Draw plain text (legacy `§` codes are honoured); returns the advance. - pub fn text(&mut self, atlas: &HudAtlas, text: &str, x: f32, y: f32, color: u32, shadow: bool) -> f32 { - let t = if text.contains('§') { crate::text::Text::legacy(text) } else { crate::text::Text::literal(text) }; + pub fn text( + &mut self, + atlas: &HudAtlas, + text: &str, + x: f32, + y: f32, + color: u32, + shadow: bool, + ) -> f32 { + let t = if text.contains('§') { + crate::text::Text::legacy(text) + } else { + crate::text::Text::literal(text) + }; self.text_styled(atlas, &t, x, y, color, shadow) } /// Font.drawInternal: styled glyphs, shadows first, with bold, italic, /// underline and strikethrough. `color` is the default colour and alpha. - pub fn text_styled(&mut self, atlas: &HudAtlas, text: &crate::text::Text, x: f32, y: f32, color: u32, shadow: bool) -> f32 { + pub fn text_styled( + &mut self, + atlas: &HudAtlas, + text: &crate::text::Text, + x: f32, + y: f32, + color: u32, + shadow: bool, + ) -> f32 { let font = &atlas.font; let alpha = (color >> 24) as u8; let mut glyphs = Vec::new(); let mut cursor = x; for (i, (ch, style)) in text.chars().enumerate() { let g = font.glyph(ch); - let c = style.color.map_or(color, |rgb| rgba((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8, alpha)); + let c = style.color.map_or(color, |rgb| { + rgba((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8, alpha) + }); let bold = style.is_bold(); let advance = g.advance + if bold { g.offset } else { 0.0 }; - glyphs.push((cursor, g, c, bold, style.is_italic(), style.underlined == Some(true), style.strikethrough == Some(true), i == 0, advance)); + glyphs.push(( + cursor, + g, + c, + bold, + style.is_italic(), + style.underlined == Some(true), + style.strikethrough == Some(true), + i == 0, + advance, + )); cursor += advance; } self.patches.extend(font.take_patches()); @@ -278,7 +338,15 @@ impl HudBatch { for &(gx, g, c, bold, italic, underline, strike, first, advance) in &glyphs { let (dx, col) = if is_shadow { let b = c.to_le_bytes(); - (g.offset, rgba((f32::from(b[0]) * 0.25) as u8, (f32::from(b[1]) * 0.25) as u8, (f32::from(b[2]) * 0.25) as u8, b[3])) + ( + g.offset, + rgba( + (f32::from(b[0]) * 0.25) as u8, + (f32::from(b[1]) * 0.25) as u8, + (f32::from(b[2]) * 0.25) as u8, + b[3], + ), + ) } else { (0.0, c) }; @@ -287,7 +355,12 @@ impl HudBatch { let thick = if bold { 0.1 } else { 0.0 }; let draw = |batch: &mut Self, ox: f32| match g.rect { Some(r) => { - let (x0, x1, y0, y1) = (px + ox + g.left, px + ox + g.right, py + g.top, py + g.bottom); + let (x0, x1, y0, y1) = ( + px + ox + g.left, + px + ox + g.right, + py + g.top, + py + g.bottom, + ); batch.quad( [ [x0 + shear(g.top) - thick, y0 - thick], @@ -302,7 +375,12 @@ impl HudBatch { None if g.right > 0.0 => { // SpecialGlyphs.MISSING: a 5x8 outline. let (bx, by) = (px + ox, py); - for (fx, fy, fw, fh) in [(0.0, 0.0, 5.0, 1.0), (0.0, 7.0, 5.0, 1.0), (0.0, 1.0, 1.0, 6.0), (4.0, 1.0, 1.0, 6.0)] { + for (fx, fy, fw, fh) in [ + (0.0, 0.0, 5.0, 1.0), + (0.0, 7.0, 5.0, 1.0), + (0.0, 1.0, 1.0, 6.0), + (4.0, 1.0, 1.0, 6.0), + ] { batch.rect_uv(bx + fx, by + fy, fw, fh, white, col); } } @@ -470,10 +548,27 @@ impl HudRenderer { if let Some(texture) = &self.atlas_texture { for p in &batch.patches { queue.write_texture( - wgpu::TexelCopyTextureInfo { texture, mip_level: 0, origin: wgpu::Origin3d { x: p.x, y: p.y, z: 0 }, aspect: wgpu::TextureAspect::All }, + wgpu::TexelCopyTextureInfo { + texture, + mip_level: 0, + origin: wgpu::Origin3d { + x: p.x, + y: p.y, + z: 0, + }, + aspect: wgpu::TextureAspect::All, + }, &p.rgba, - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(p.width * 4), rows_per_image: None }, - wgpu::Extent3d { width: p.width, height: p.height, depth_or_array_layers: 1 }, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(p.width * 4), + rows_per_image: None, + }, + wgpu::Extent3d { + width: p.width, + height: p.height, + depth_or_array_layers: 1, + }, ); } } diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index 7eb995762..c95b33eac 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -31,7 +31,12 @@ impl StackData { impl ItemStack { pub fn new(item: &str, count: u32) -> Self { - Self { item: Arc::from(item), count, damage: 0, extra: None } + Self { + item: Arc::from(item), + count, + damage: 0, + extra: None, + } } pub fn data(&self) -> Option<&StackData> { self.extra.as_deref() @@ -53,11 +58,18 @@ impl ItemStack { } /// `EnchantmentHelper.getItemEnchantmentLevel` (0 when absent). pub fn enchantment_level(&self, id: &str) -> u32 { - self.enchantments().iter().find(|(e, _)| &**e == id).map_or(0, |(_, l)| *l) + self.enchantments() + .iter() + .find(|(e, _)| &**e == id) + .map_or(0, |(_, l)| *l) } /// The component an anvil/grindstone works on: stored for books. pub fn crafting_enchantments(&self) -> &[(Arc, u32)] { - if &*self.item == "minecraft:enchanted_book" { self.stored_enchantments() } else { self.enchantments() } + if &*self.item == "minecraft:enchanted_book" { + self.stored_enchantments() + } else { + self.enchantments() + } } pub fn set_crafting_enchantments(&mut self, levels: Levels) { if &*self.item == "minecraft:enchanted_book" { @@ -71,7 +83,11 @@ impl ItemStack { pub fn enchant(&mut self, id: &str, level: u32) { let book = &*self.item == "minecraft:enchanted_book"; let data = self.data_mut(); - let list = if book { &mut data.stored_enchantments } else { &mut data.enchantments }; + let list = if book { + &mut data.stored_enchantments + } else { + &mut data.enchantments + }; upgrade(list, id, level); } pub fn has_any_enchantments(&self) -> bool { @@ -96,7 +112,11 @@ impl ItemStack { } /// `ItemStack.transmuteCopy`: another item keeping every component. pub fn transmute(&self, item: &str, count: u32) -> Self { - let mut stack = Self { item: Arc::from(item), count, ..self.clone() }; + let mut stack = Self { + item: Arc::from(item), + count, + ..self.clone() + }; stack.tidy(); stack } @@ -142,12 +162,29 @@ fn string(t: &Tag) -> Option { } } fn read_levels(t: Option<&Tag>) -> Levels { - let Some(Tag::Compound(map)) = t else { return Vec::new() }; + let Some(Tag::Compound(map)) = t else { + return Vec::new(); + }; // Pre-1.21.5 worlds wrap the map in {levels: {...}}. if let Some(Tag::Compound(inner)) = map.get(&JavaString::from("levels")) { - return inner.iter().filter_map(|(k, v)| Some((Arc::from(k.to_string_lossy().as_str()), int(v)?.clamp(1, 255) as u32))).collect(); + return inner + .iter() + .filter_map(|(k, v)| { + Some(( + Arc::from(k.to_string_lossy().as_str()), + int(v)?.clamp(1, 255) as u32, + )) + }) + .collect(); } - map.iter().filter_map(|(k, v)| Some((Arc::from(k.to_string_lossy().as_str()), int(v)?.clamp(1, 255) as u32))).collect() + map.iter() + .filter_map(|(k, v)| { + Some(( + Arc::from(k.to_string_lossy().as_str()), + int(v)?.clamp(1, 255) as u32, + )) + }) + .collect() } /// A text component as stored by vanilla: a plain string or `{"text": ...}`. fn read_text(t: &Tag) -> Option { @@ -173,7 +210,10 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { entries.push(("minecraft:enchantments", levels_tag(&d.enchantments))); } if !d.stored_enchantments.is_empty() { - entries.push(("minecraft:stored_enchantments", levels_tag(&d.stored_enchantments))); + entries.push(( + "minecraft:stored_enchantments", + levels_tag(&d.stored_enchantments), + )); } if d.repair_cost > 0 { entries.push(("minecraft:repair_cost", Tag::Int(d.repair_cost as i32))); @@ -182,12 +222,18 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { entries.push(("minecraft:custom_name", Tag::String(name.as_str().into()))); } if let Some(potion) = &d.potion { - entries.push(("minecraft:potion_contents", Tag::compound([("potion", Tag::String((&**potion).into()))]))); + entries.push(( + "minecraft:potion_contents", + Tag::compound([("potion", Tag::String((&**potion).into()))]), + )); } if let Some((material, pattern)) = &d.trim { entries.push(( "minecraft:trim", - Tag::compound([("material", Tag::String((&**material).into())), ("pattern", Tag::String((&**pattern).into()))]), + Tag::compound([ + ("material", Tag::String((&**material).into())), + ("pattern", Tag::String((&**pattern).into())), + ]), )); } } @@ -195,21 +241,33 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { } /// Damage and extra components from a stack's `components` compound. pub fn decode_components(components: Option<&Tag>) -> (u32, Option>) { - let Some(c) = components else { return (0, None) }; + let Some(c) = components else { + return (0, None); + }; let damage = c.get("minecraft:damage").and_then(int).unwrap_or(0).max(0) as u32; let potion = match c.get("minecraft:potion_contents") { Some(Tag::String(s)) => Some(Arc::from(s.to_string_lossy().as_str())), - Some(t) => t.get("potion").and_then(string).map(|s| Arc::from(s.as_str())), + Some(t) => t + .get("potion") + .and_then(string) + .map(|s| Arc::from(s.as_str())), None => None, }; let data = StackData { enchantments: read_levels(c.get("minecraft:enchantments")), stored_enchantments: read_levels(c.get("minecraft:stored_enchantments")), - repair_cost: c.get("minecraft:repair_cost").and_then(int).unwrap_or(0).max(0) as u32, + repair_cost: c + .get("minecraft:repair_cost") + .and_then(int) + .unwrap_or(0) + .max(0) as u32, custom_name: c.get("minecraft:custom_name").and_then(read_text), potion, trim: c.get("minecraft:trim").and_then(|t| { - Some((Arc::from(t.get("material").and_then(string)?.as_str()), Arc::from(t.get("pattern").and_then(string)?.as_str()))) + Some(( + Arc::from(t.get("material").and_then(string)?.as_str()), + Arc::from(t.get("pattern").and_then(string)?.as_str()), + )) }), }; (damage, (!data.is_empty()).then(|| Box::new(data))) @@ -230,7 +288,11 @@ mod tests { let tag = encode_components(&stack).expect("components"); let (damage, extra) = decode_components(Some(&tag)); assert_eq!(damage, 12); - let back = ItemStack { damage, extra, ..ItemStack::new("minecraft:diamond_sword", 1) }; + let back = ItemStack { + damage, + extra, + ..ItemStack::new("minecraft:diamond_sword", 1) + }; assert_eq!(back.enchantment_level("minecraft:sharpness"), 3); assert_eq!(back.enchantment_level("minecraft:unbreaking"), 2); assert_eq!(back.repair_cost(), 3); @@ -253,7 +315,11 @@ mod tests { book.enchant("minecraft:mending", 1); assert!(book.enchantments().is_empty()); assert_eq!(book.stored_enchantments().len(), 1); - upgrade(&mut book.data_mut().stored_enchantments, "minecraft:mending", 1); + upgrade( + &mut book.data_mut().stored_enchantments, + "minecraft:mending", + 1, + ); assert_eq!(book.crafting_enchantments()[0].1, 1); let book = ItemStack::new("minecraft:book", 1).transmute("minecraft:enchanted_book", 1); assert!(book.extra.is_none()); diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index b59fcb819..1f76fe295 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -69,7 +69,10 @@ pub(crate) fn load_tags(root: &Path, kind: &str) -> Result Result>, out: &mut HashSet, depth: u32) { + fn resolve( + name: &str, + raw: &HashMap>, + out: &mut HashSet, + depth: u32, + ) { if depth > 32 { return; } @@ -115,7 +123,9 @@ impl Items { for (i, s) in facts.states.iter().enumerate() { let default = registry.default_state(&s.name); if default == Some(BlockStateId(i as u32)) && &*s.item != "minecraft:air" { - block_for_item.entry(&s.item).or_insert(BlockStateId(i as u32)); + block_for_item + .entry(&s.item) + .or_insert(BlockStateId(i as u32)); } } let mut items = HashMap::new(); @@ -129,7 +139,10 @@ impl Items { .map(|r| ToolRule { blocks: match &r["blocks"] { Value::String(s) => vec![s.clone()], - Value::Array(a) => a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect(), + Value::Array(a) => a + .iter() + .filter_map(|v| v.as_str().map(str::to_owned)) + .collect(), _ => vec![], }, speed: r["speed"].as_f64().map(|v| v as f32), @@ -141,7 +154,10 @@ impl Items { .as_array() .into_iter() .flatten() - .filter(|m| m["type"].as_str() == Some(kind) && m["operation"].as_str() == Some("add_value")) + .filter(|m| { + m["type"].as_str() == Some(kind) + && m["operation"].as_str() == Some("add_value") + }) .filter_map(|m| m["amount"].as_f64()) .sum::() as f32 }; @@ -163,8 +179,13 @@ impl Items { .as_f64() .unwrap_or(1.0) as f32, food, - model: c["minecraft:item_model"].as_str().unwrap_or(name).to_owned(), - equip_slot: c["minecraft:equippable"]["slot"].as_str().map(str::to_owned), + model: c["minecraft:item_model"] + .as_str() + .unwrap_or(name) + .to_owned(), + equip_slot: c["minecraft:equippable"]["slot"] + .as_str() + .map(str::to_owned), modifiers: c["minecraft:attribute_modifiers"] .as_array() .into_iter() @@ -179,9 +200,17 @@ impl Items { )) }) .collect(), - fuel: c.get("minecraft:cooking_fuel").map(|f| (f["burn_time"].clone(), f["speed_multiplier"].clone())), - brewing_fuel: c.get("minecraft:brewing_fuel").map(|f| (f["uses"].clone(), f["speed_multiplier"].clone())), - remainder: c["minecraft:use_remainder"]["id"].as_str().or(c["minecraft:crafting_remainder"]["id"].as_str()).or(c["minecraft:crafting_remainder"].as_str()).map(str::to_owned), + fuel: c + .get("minecraft:cooking_fuel") + .map(|f| (f["burn_time"].clone(), f["speed_multiplier"].clone())), + brewing_fuel: c + .get("minecraft:brewing_fuel") + .map(|f| (f["uses"].clone(), f["speed_multiplier"].clone())), + remainder: c["minecraft:use_remainder"]["id"] + .as_str() + .or(c["minecraft:crafting_remainder"]["id"].as_str()) + .or(c["minecraft:crafting_remainder"].as_str()) + .map(str::to_owned), attack_damage: modifier("minecraft:attack_damage"), attack_speed: modifier("minecraft:attack_speed"), }, @@ -197,8 +226,15 @@ impl Items { if p.is_dir() { walk_loot(&p, base, loot)?; } else if p.extension().is_some_and(|e| e == "json") { - let id = p.strip_prefix(base)?.with_extension("").to_string_lossy().replace('\\', "/"); - loot.insert(format!("minecraft:{id}"), serde_json::from_slice(&fs::read(&p)?)?); + let id = p + .strip_prefix(base)? + .with_extension("") + .to_string_lossy() + .replace('\\', "/"); + loot.insert( + format!("minecraft:{id}"), + serde_json::from_slice(&fs::read(&p)?)?, + ); } } Ok(()) @@ -218,12 +254,24 @@ impl Items { } /// Only the block and item tags, for tools that need tag membership. pub fn tags_only(root: &Path) -> Result { - Ok(Self { items: HashMap::new(), order: Vec::new(), block_tags: load_tags(root, "block")?, item_tags: load_tags(root, "item")?, loot: HashMap::new() }) + Ok(Self { + items: HashMap::new(), + order: Vec::new(), + block_tags: load_tags(root, "block")?, + item_tags: load_tags(root, "item")?, + loot: HashMap::new(), + }) } /// An item table with only tags, for unit tests of item rules. #[cfg(test)] pub fn for_tests(item_tags: HashMap>) -> Self { - Self { items: HashMap::new(), order: Vec::new(), block_tags: HashMap::new(), item_tags, loot: HashMap::new() } + Self { + items: HashMap::new(), + order: Vec::new(), + block_tags: HashMap::new(), + item_tags, + loot: HashMap::new(), + } } fn block_matches(&self, spec: &str, block: &str) -> bool { match spec.strip_prefix('#') { @@ -289,13 +337,33 @@ impl Items { } /// Evaluate an entity's loot table (`minecraft:entities/`). /// Evaluate any loot table by id (e.g. `minecraft:gameplay/chicken_lay`). - pub fn loot_table(&self, id: &str, killed_by_player: bool, held: Option<&ItemStack>, random: &mut LegacyRandom) -> Vec { - let Some(table) = self.loot.get(id) else { return vec![] }; + pub fn loot_table( + &self, + id: &str, + killed_by_player: bool, + held: Option<&ItemStack>, + random: &mut LegacyRandom, + ) -> Vec { + let Some(table) = self.loot.get(id) else { + return vec![]; + }; let empty = BTreeMap::new(); - let ctx = LootContext { items: self, block: "", properties: &empty, held, killed_by_player }; + let ctx = LootContext { + items: self, + block: "", + properties: &empty, + held, + killed_by_player, + }; ctx.evaluate(table, random) } - pub fn entity_drops(&self, entity: &str, killed_by_player: bool, held: Option<&ItemStack>, random: &mut LegacyRandom) -> Vec { + pub fn entity_drops( + &self, + entity: &str, + killed_by_player: bool, + held: Option<&ItemStack>, + random: &mut LegacyRandom, + ) -> Vec { let name = entity.trim_start_matches("minecraft:"); let Some(table) = self.loot.get(&format!("minecraft:entities/{name}")) else { return vec![]; @@ -322,7 +390,11 @@ impl LootContext<'_> { let rolls = ctx.number(&pool["rolls"], random).max(0.0) as u32; for _ in 0..rolls { let mut produced = Vec::new(); - ctx.choose(pool["entries"].as_array().map_or(&[][..], Vec::as_slice), random, &mut produced); + ctx.choose( + pool["entries"].as_array().map_or(&[][..], Vec::as_slice), + random, + &mut produced, + ); for mut stack in produced { ctx.modifiers(&pool["modifier"], &mut stack, random); ctx.modifiers(&table["modifier"], &mut stack, random); @@ -350,8 +422,14 @@ impl LootContext<'_> { fn number(&self, v: &Value, random: &mut LegacyRandom) -> f32 { match v { Value::Number(n) => n.as_f64().unwrap_or(0.0) as f32, - Value::Object(o) => match o.get("type").and_then(Value::as_str).unwrap_or("minecraft:uniform") { - "minecraft:constant" => o.get("value").and_then(Value::as_f64).unwrap_or(0.0) as f32, + Value::Object(o) => match o + .get("type") + .and_then(Value::as_str) + .unwrap_or("minecraft:uniform") + { + "minecraft:constant" => { + o.get("value").and_then(Value::as_f64).unwrap_or(0.0) as f32 + } "minecraft:uniform" => { let min = self.number(o.get("min").unwrap_or(&Value::Null), random); let max = self.number(o.get("max").unwrap_or(&Value::Null), random); @@ -374,7 +452,10 @@ impl LootContext<'_> { } fn int_number(&self, v: &Value, random: &mut LegacyRandom) -> i32 { if let Value::Object(o) = v - && o.get("type").and_then(Value::as_str).unwrap_or("minecraft:uniform") == "minecraft:uniform" + && o.get("type") + .and_then(Value::as_str) + .unwrap_or("minecraft:uniform") + == "minecraft:uniform" { let min = self.int_number(o.get("min").unwrap_or(&Value::Null), random); let max = self.int_number(o.get("max").unwrap_or(&Value::Null), random); @@ -397,14 +478,26 @@ impl LootContext<'_> { "minecraft:tool/can_silk_touch" => self.enchantment_level("minecraft:silk_touch") > 0, "minecraft:tool/can_shear" => self.held.is_some_and(|h| &*h.item == "minecraft:shears"), "minecraft:inverted" => !self.condition(&c["term"], random), - "minecraft:any_of" => c["terms"].as_array().into_iter().flatten().any(|t| self.condition(t, random)), - "minecraft:all_of" => c["terms"].as_array().into_iter().flatten().all(|t| self.condition(t, random)), + "minecraft:any_of" => c["terms"] + .as_array() + .into_iter() + .flatten() + .any(|t| self.condition(t, random)), + "minecraft:all_of" => c["terms"] + .as_array() + .into_iter() + .flatten() + .all(|t| self.condition(t, random)), "minecraft:random_chance" => random.next_float() < self.number(&c["chance"], random), "minecraft:table_bonus" => { // BonusLevelTableCondition: chances[min(level, len - 1)]. - let level = self.enchantment_level(c["enchantment"].as_str().unwrap_or("")) as usize; + let level = + self.enchantment_level(c["enchantment"].as_str().unwrap_or("")) as usize; let chances = c["chances"].as_array().map_or(&[][..], Vec::as_slice); - let chance = chances.get(level.min(chances.len().saturating_sub(1))).and_then(Value::as_f64).unwrap_or(0.0) as f32; + let chance = chances + .get(level.min(chances.len().saturating_sub(1))) + .and_then(Value::as_f64) + .unwrap_or(0.0) as f32; random.next_float() < chance } "minecraft:match_block" | "minecraft:block_state_property" => { @@ -413,41 +506,63 @@ impl LootContext<'_> { None => true, }; blocks_ok - && c["state"].as_object().into_iter().flatten().chain(c["properties"].as_object().into_iter().flatten()).all(|(k, v)| { - let have = self.properties.get(k).map(String::as_str); - match v { - Value::String(s) => have == Some(s.as_str()), - Value::Object(r) => { - let have: i64 = have.and_then(|h| h.parse().ok()).unwrap_or(0); - r.get("min").and_then(Value::as_i64).is_none_or(|m| have >= m) - && r.get("max").and_then(Value::as_i64).is_none_or(|m| have <= m) + && c["state"] + .as_object() + .into_iter() + .flatten() + .chain(c["properties"].as_object().into_iter().flatten()) + .all(|(k, v)| { + let have = self.properties.get(k).map(String::as_str); + match v { + Value::String(s) => have == Some(s.as_str()), + Value::Object(r) => { + let have: i64 = have.and_then(|h| h.parse().ok()).unwrap_or(0); + r.get("min") + .and_then(Value::as_i64) + .is_none_or(|m| have >= m) + && r.get("max") + .and_then(Value::as_i64) + .is_none_or(|m| have <= m) + } + _ => true, } - _ => true, - } - }) + }) } "minecraft:match_tool" => { let items = &c["predicate"]["items"]; let items_ok = match (self.held, items) { (_, Value::Null) => self.held.is_some(), (Some(h), Value::String(s)) => match s.strip_prefix('#') { - Some(tag) => self.items.item_tags.get(tag).is_some_and(|t| t.contains(&*h.item)), + Some(tag) => self + .items + .item_tags + .get(tag) + .is_some_and(|t| t.contains(&*h.item)), None => **s == *h.item, }, _ => false, }; // ItemPredicate "minecraft:enchantments": each entry needs a level in range. - let enchants_ok = c["predicate"]["predicates"]["minecraft:enchantments"].as_array().into_iter().flatten().all(|e| { - let level = self.enchantment_level(e["enchantments"].as_str().unwrap_or("")); - let min = e["levels"]["min"].as_u64().unwrap_or(1) as u32; - let max = e["levels"]["max"].as_u64().map_or(u32::MAX, |m| m as u32); - level >= min.max(1) && level <= max - }); + let enchants_ok = c["predicate"]["predicates"]["minecraft:enchantments"] + .as_array() + .into_iter() + .flatten() + .all(|e| { + let level = + self.enchantment_level(e["enchantments"].as_str().unwrap_or("")); + let min = e["levels"]["min"].as_u64().unwrap_or(1) as u32; + let max = e["levels"]["max"].as_u64().map_or(u32::MAX, |m| m as u32); + level >= min.max(1) && level <= max + }); items_ok && enchants_ok } "minecraft:killed_by_player" => self.killed_by_player, "minecraft:random_chance_with_enchanted_bonus" => { - let level = if self.killed_by_player && self.block.is_empty() { self.enchantment_level(c["enchantment"].as_str().unwrap_or("")) } else { 0 }; + let level = if self.killed_by_player && self.block.is_empty() { + self.enchantment_level(c["enchantment"].as_str().unwrap_or("")) + } else { + 0 + }; let chance = if level > 0 { crate::enchant::level_value(&c["enchanted_chance"], level) } else { @@ -474,7 +589,12 @@ impl LootContext<'_> { .all(|c| self.condition(c, random)) } /// Expand entries; returns whether an entry succeeded (for alternatives). - fn expand(&self, e: &Value, random: &mut LegacyRandom, out: &mut Vec<(i32, ItemStack, Value)>) -> bool { + fn expand( + &self, + e: &Value, + random: &mut LegacyRandom, + out: &mut Vec<(i32, ItemStack, Value)>, + ) -> bool { if !self.conditions(e, random) { return false; } @@ -515,7 +635,16 @@ impl LootContext<'_> { true } "minecraft:empty" => { - out.push((e["weight"].as_i64().unwrap_or(1) as i32, ItemStack { item: Arc::from("minecraft:air"), count: 0, damage: 0, extra: None }, Value::Null)); + out.push(( + e["weight"].as_i64().unwrap_or(1) as i32, + ItemStack { + item: Arc::from("minecraft:air"), + count: 0, + damage: 0, + extra: None, + }, + Value::Null, + )); true } _ => false, @@ -561,11 +690,16 @@ impl LootContext<'_> { match f["type"].as_str().or(f["function"].as_str()).unwrap_or("") { "minecraft:set_count" => { let n = self.int_number(&f["count"], random); - let base = if f["add"].as_bool() == Some(true) { stack.count as i32 } else { 0 }; + let base = if f["add"].as_bool() == Some(true) { + stack.count as i32 + } else { + 0 + }; stack.count = (base + n).max(0) as u32; } "minecraft:apply_bonus" => { - let level = self.enchantment_level(f["enchantment"].as_str().unwrap_or("")) as i32; + let level = + self.enchantment_level(f["enchantment"].as_str().unwrap_or("")) as i32; let count = stack.count as i32; let params = &f["parameters"]; stack.count = match f["formula"].as_str().unwrap_or("") { @@ -578,7 +712,10 @@ impl LootContext<'_> { count + random.next_int_bound(multiplier * level + 1).unwrap_or(0) } "minecraft:binomial_with_bonus_count" => { - let (extra, p) = (params["extra"].as_i64().unwrap_or(0) as i32, params["probability"].as_f64().unwrap_or(0.0) as f32); + let (extra, p) = ( + params["extra"].as_i64().unwrap_or(0) as i32, + params["probability"].as_f64().unwrap_or(0.0) as f32, + ); let mut n = count; for _ in 0..level + extra { if random.next_float() < p { @@ -622,8 +759,19 @@ mod tests { use super::*; use serde_json::json; - fn ctx<'a>(items: &'a Items, held: Option<&'a ItemStack>, props: &'a BTreeMap, block: &'a str) -> LootContext<'a> { - LootContext { items, block, properties: props, held, killed_by_player: block.is_empty() } + fn ctx<'a>( + items: &'a Items, + held: Option<&'a ItemStack>, + props: &'a BTreeMap, + block: &'a str, + ) -> LootContext<'a> { + LootContext { + items, + block, + properties: props, + held, + killed_by_player: block.is_empty(), + } } #[test] @@ -637,16 +785,26 @@ mod tests { {"type":"minecraft:item","name":"minecraft:diamond","modifier":[{"type":"minecraft:apply_bonus","enchantment":"minecraft:fortune","formula":"minecraft:ore_drops"}]}]}]}]}); let mut random = LegacyRandom::new(7); let n = 20000; - let total: u32 = (0..n).map(|_| ctx(&items, Some(&pick), &props, "minecraft:diamond_ore").evaluate(&ore, &mut random).iter().map(|s| s.count).sum::()).sum(); + let total: u32 = (0..n) + .map(|_| { + ctx(&items, Some(&pick), &props, "minecraft:diamond_ore") + .evaluate(&ore, &mut random) + .iter() + .map(|s| s.count) + .sum::() + }) + .sum(); // Fortune III ore drops average (1 + 1 + 2 + 3 + 4) / 5 = 2.2 diamonds. let mean = f64::from(total) / f64::from(n); assert!((mean - 2.2).abs() < 0.05, "{mean}"); let mut silk = ItemStack::new("minecraft:diamond_pickaxe", 1); silk.enchant("minecraft:silk_touch", 1); - let drops = ctx(&items, Some(&silk), &props, "minecraft:diamond_ore").evaluate(&ore, &mut random); + let drops = + ctx(&items, Some(&silk), &props, "minecraft:diamond_ore").evaluate(&ore, &mut random); assert_eq!(&*drops[0].item, "minecraft:diamond_ore"); let plain = ItemStack::new("minecraft:diamond_pickaxe", 1); - let drops = ctx(&items, Some(&plain), &props, "minecraft:diamond_ore").evaluate(&ore, &mut random); + let drops = + ctx(&items, Some(&plain), &props, "minecraft:diamond_ore").evaluate(&ore, &mut random); assert_eq!((&*drops[0].item, drops[0].count), ("minecraft:diamond", 1)); // Looting III adds level x uniform(0, 1) on player kills. let flesh = json!({"pools":[{"rolls":1,"entries":[{"type":"minecraft:item","name":"minecraft:rotten_flesh","modifier":[ @@ -654,12 +812,37 @@ mod tests { {"type":"minecraft:enchanted_count_increase","count":{"type":"minecraft:uniform","min":0.0,"max":1.0},"enchantment":"minecraft:looting"}]}]}]}); let mut sword = ItemStack::new("minecraft:iron_sword", 1); sword.enchant("minecraft:looting", 3); - let looted: u32 = (0..n).map(|_| ctx(&items, Some(&sword), &props, "").evaluate(&flesh, &mut random).iter().map(|s| s.count).sum::()).sum(); - let base: u32 = (0..n).map(|_| ctx(&items, None, &props, "").evaluate(&flesh, &mut random).iter().map(|s| s.count).sum::()).sum(); + let looted: u32 = (0..n) + .map(|_| { + ctx(&items, Some(&sword), &props, "") + .evaluate(&flesh, &mut random) + .iter() + .map(|s| s.count) + .sum::() + }) + .sum(); + let base: u32 = (0..n) + .map(|_| { + ctx(&items, None, &props, "") + .evaluate(&flesh, &mut random) + .iter() + .map(|s| s.count) + .sum::() + }) + .sum(); assert!(f64::from(looted) / f64::from(n) > f64::from(base) / f64::from(n) + 1.0); // Table bonus uses the chance for the tool's level. let leaves = json!({"pools":[{"rolls":1,"conditions":[{"type":"minecraft:table_bonus","enchantment":"minecraft:fortune","chances":[0.0,0.0,0.0,1.0]}],"entries":[{"type":"minecraft:item","name":"minecraft:apple"}]}]}); - assert_eq!(ctx(&items, Some(&pick), &props, "minecraft:oak_leaves").evaluate(&leaves, &mut random).len(), 1); - assert!(ctx(&items, Some(&plain), &props, "minecraft:oak_leaves").evaluate(&leaves, &mut random).is_empty()); + assert_eq!( + ctx(&items, Some(&pick), &props, "minecraft:oak_leaves") + .evaluate(&leaves, &mut random) + .len(), + 1 + ); + assert!( + ctx(&items, Some(&plain), &props, "minecraft:oak_leaves") + .evaluate(&leaves, &mut random) + .is_empty() + ); } } diff --git a/crates/horizon-client/src/keybinds.rs b/crates/horizon-client/src/keybinds.rs index 0d608e2ef..a62323409 100644 --- a/crates/horizon-client/src/keybinds.rs +++ b/crates/horizon-client/src/keybinds.rs @@ -26,7 +26,11 @@ pub const MAPPINGS: &[(&str, &str, &str)] = &[ ("key.friends", "key.keyboard.o", "multiplayer"), ("key.socialInteractions", "key.keyboard.p", "multiplayer"), ("key.toggleGui", "key.keyboard.f1", "misc"), - ("key.toggleSpectatorShaderEffects", "key.keyboard.f4", "misc"), + ( + "key.toggleSpectatorShaderEffects", + "key.keyboard.f4", + "misc", + ), ("key.screenshot", "key.keyboard.f2", "misc"), ("key.togglePerspective", "key.keyboard.f5", "misc"), ("key.smoothCamera", "key.keyboard.unknown", "misc"), @@ -50,7 +54,16 @@ pub const MAPPINGS: &[(&str, &str, &str)] = &[ ("key.hotbar.9", "key.keyboard.9", "inventory"), ]; /// KeyMapping.Category sort order. -pub const CATEGORIES: [&str; 8] = ["movement", "misc", "multiplayer", "gameplay", "inventory", "creative", "spectator", "debug"]; +pub const CATEGORIES: [&str; 8] = [ + "movement", + "misc", + "multiplayer", + "gameplay", + "inventory", + "creative", + "spectator", + "debug", +]; /// InputConstants key names <-> winit physical keys. const KEYS: &[(&str, KeyCode)] = &[ @@ -228,15 +241,25 @@ pub struct KeyBinds { } impl Default for KeyBinds { fn default() -> Self { - Self { keys: MAPPINGS.iter().map(|(n, d, _)| (*n, (*d).to_owned())).collect() } + Self { + keys: MAPPINGS + .iter() + .map(|(n, d, _)| (*n, (*d).to_owned())) + .collect(), + } } } impl KeyBinds { pub fn get(&self, name: &str) -> &str { - self.keys.get(name).map_or("key.keyboard.unknown", String::as_str) + self.keys + .get(name) + .map_or("key.keyboard.unknown", String::as_str) } pub fn default_of(name: &str) -> &'static str { - MAPPINGS.iter().find(|m| m.0 == name).map_or("key.keyboard.unknown", |m| m.1) + MAPPINGS + .iter() + .find(|m| m.0 == name) + .map_or("key.keyboard.unknown", |m| m.1) } pub fn is_default(&self, name: &str) -> bool { self.get(name) == Self::default_of(name) @@ -256,7 +279,10 @@ impl KeyBinds { } } pub fn saved(&self) -> Vec<(&'static str, String)> { - MAPPINGS.iter().map(|(n, _, _)| (*n, self.get(n).to_owned())).collect() + MAPPINGS + .iter() + .map(|(n, _, _)| (*n, self.get(n).to_owned())) + .collect() } pub fn reset_all(&mut self) { *self = Self::default(); @@ -269,7 +295,9 @@ impl KeyBinds { } MAPPINGS .iter() - .filter(|(n, _, _)| *n != name && self.get(n) == key && (!self.is_default(n) || !self.is_default(name))) + .filter(|(n, _, _)| { + *n != name && self.get(n) == key && (!self.is_default(n) || !self.is_default(name)) + }) .map(|(n, _, _)| *n) .collect() } @@ -282,7 +310,9 @@ impl KeyBinds { /// player's bindings. `None` means the key now does nothing; mouse /// mappings bound to keys come back as `Err(button)`. pub fn translate(&self, key: KeyCode) -> Option> { - let Some(name) = key_name(key) else { return Some(Ok(key)) }; + let Some(name) = key_name(key) else { + return Some(Ok(key)); + }; if let Some(mapping) = self.mapping_for(name) { let default = Self::default_of(mapping); if let Some(code) = key_code(default) { @@ -291,7 +321,10 @@ impl KeyBinds { return mouse_button(default).map(Err); } // An unbound key whose default meaning was moved elsewhere is inert. - if MAPPINGS.iter().any(|(n, d, _)| *d == name && !self.is_default(n)) { + if MAPPINGS + .iter() + .any(|(n, d, _)| *d == name && !self.is_default(n)) + { return None; } Some(Ok(key)) @@ -306,7 +339,10 @@ impl KeyBinds { } return key_code(default).map(Ok); } - if MAPPINGS.iter().any(|(n, d, _)| *d == name && !self.is_default(n)) { + if MAPPINGS + .iter() + .any(|(n, d, _)| *d == name && !self.is_default(n)) + { return None; } Some(Err(button)) diff --git a/crates/horizon-client/src/lang.rs b/crates/horizon-client/src/lang.rs index a8a86b523..037baf621 100644 --- a/crates/horizon-client/src/lang.rs +++ b/crates/horizon-client/src/lang.rs @@ -41,7 +41,10 @@ impl ResourceSource for std::path::PathBuf { impl Language { pub fn from_map(code: &str, map: HashMap) -> Self { - Self { code: code.to_owned(), map } + Self { + code: code.to_owned(), + map, + } } /// ClientLanguage.loadFrom: en_us first, then the selected language, each /// from every source in priority order (later sources override). @@ -53,13 +56,18 @@ impl Language { } for c in codes { for source in sources { - let Some(bytes) = source.read(&format!("assets/minecraft/lang/{c}.json")) else { continue }; + let Some(bytes) = source.read(&format!("assets/minecraft/lang/{c}.json")) else { + continue; + }; if let Ok(entries) = serde_json::from_slice::>(&bytes) { map.extend(entries); } } } - Self { code: code.to_owned(), map } + Self { + code: code.to_owned(), + map, + } } pub fn get(&self, key: &str) -> Option<&str> { self.map.get(key).map(String::as_str) @@ -77,12 +85,21 @@ pub fn available(sources: &[&dyn ResourceSource]) -> Vec { let mut found: BTreeMap = BTreeMap::new(); found.insert( DEFAULT.into(), - LanguageInfo { code: DEFAULT.into(), name: "English".into(), region: "US".into(), bidirectional: false }, + LanguageInfo { + code: DEFAULT.into(), + name: "English".into(), + region: "US".into(), + bidirectional: false, + }, ); for source in sources { for path in ["assets/pack.mcmeta", "pack.mcmeta"] { - let Some(bytes) = source.read(path) else { continue }; - let Ok(value) = serde_json::from_slice::(&bytes) else { continue }; + let Some(bytes) = source.read(path) else { + continue; + }; + let Ok(value) = serde_json::from_slice::(&bytes) else { + continue; + }; for (code, info) in value["language"].as_object().into_iter().flatten() { // Only languages whose file exists somewhere are selectable. let file = format!("assets/minecraft/lang/{code}.json"); @@ -115,11 +132,15 @@ pub fn code() -> String { } /// Language.getOrDefault: the translation, or the key itself. pub fn get(key: &str) -> String { - current().and_then(|l| l.get(key).map(str::to_owned)).unwrap_or_else(|| key.to_owned()) + current() + .and_then(|l| l.get(key).map(str::to_owned)) + .unwrap_or_else(|| key.to_owned()) } /// The translation, or `fallback` when the key is missing. pub fn get_or(key: &str, fallback: &str) -> String { - current().and_then(|l| l.get(key).map(str::to_owned)).unwrap_or_else(|| fallback.to_owned()) + current() + .and_then(|l| l.get(key).map(str::to_owned)) + .unwrap_or_else(|| fallback.to_owned()) } pub fn has(key: &str) -> bool { current().is_some_and(|l| l.get(key).is_some()) @@ -145,14 +166,20 @@ mod tests { ("assets/minecraft/lang/fr_fr.json".into(), br#"{"a":"Pomme"}"#.to_vec()), ("assets/pack.mcmeta".into(), r#"{"language":{"fr_fr":{"name":"Français","region":"France"},"de_de":{"name":"Deutsch","region":"Deutschland"}}}"#.as_bytes().to_vec()), ])); - let pack = Mem(HashMap::from([("assets/minecraft/lang/fr_fr.json".into(), br#"{"b":"Banane"}"#.to_vec())])); + let pack = Mem(HashMap::from([( + "assets/minecraft/lang/fr_fr.json".into(), + br#"{"b":"Banane"}"#.to_vec(), + )])); let sources: [&dyn ResourceSource; 2] = [&base, &pack]; let fr = Language::load(&sources, "fr_fr"); assert_eq!(fr.get("a"), Some("Pomme")); assert_eq!(fr.get("b"), Some("Banane")); let langs = available(&sources); // de_de has no file, so only English and French are offered. - assert_eq!(langs.iter().map(|l| l.code.as_str()).collect::>(), ["en_us", "fr_fr"]); + assert_eq!( + langs.iter().map(|l| l.code.as_str()).collect::>(), + ["en_us", "fr_fr"] + ); assert_eq!(langs[1].label(), "Français (France)"); } } diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index d8367363e..2d521f35b 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -10,23 +10,23 @@ pub mod biome; pub mod block_entity_render; pub mod blocks; pub mod brewing; -pub mod chunk; pub mod chat; +pub mod chunk; pub mod clock; +pub mod collisions; pub mod command; pub mod containers; pub mod control; pub mod crafting; -pub mod enchant; pub mod creative; -pub mod collisions; pub mod effects; +pub mod enchant; pub mod entities; pub mod entity_nbt; pub mod environment; +pub mod fog; pub mod font; pub mod gamerules; -pub mod fog; pub mod gfx; pub mod health; pub mod hud; @@ -35,16 +35,16 @@ pub mod input; pub mod item_data; pub mod items; pub mod keybinds; -pub mod lang; pub mod landing; +pub mod lang; pub mod light; pub mod merchant; pub mod mesher; -pub mod music; pub mod mobs; pub mod models; pub mod motion; pub mod multiplayer; +pub mod music; pub mod net; pub mod options_ui; pub mod packs; diff --git a/crates/horizon-client/src/light.rs b/crates/horizon-client/src/light.rs index 0dc8071b3..930a26610 100644 --- a/crates/horizon-client/src/light.rs +++ b/crates/horizon-client/src/light.rs @@ -69,7 +69,12 @@ impl LightTables { collision::CachedCollisionRegistry, nbt::{self, Limits}, }; - let data = nbt::read_named(&std::fs::read(root.join("occlusion.nbt"))?, Limits::default())?.0.tag; + let data = nbt::read_named( + &std::fs::read(root.join("occlusion.nbt"))?, + Limits::default(), + )? + .0 + .tag; let occlusion = CachedCollisionRegistry::from_nbt(&data, registry)?; let mut tables = Self::new(facts); let block = VoxelShape::block(); @@ -82,7 +87,9 @@ impl LightTables { if !state.can_occlude || !state.shape_occlusion { continue; } - let Some(shape) = occlusion.cached_shape(BlockStateId(id as u32))? else { continue }; + let Some(shape) = occlusion.cached_shape(BlockStateId(id as u32))? else { + continue; + }; if shape.is_empty() { continue; } @@ -102,7 +109,12 @@ impl LightTables { let key: Vec = face .boxes() .iter() - .flat_map(|b| b.min_position().components().into_iter().chain(b.max_position().components())) + .flat_map(|b| { + b.min_position() + .components() + .into_iter() + .chain(b.max_position().components()) + }) .map(f64::to_bits) .collect(); *by_geometry.entry(key).or_insert_with(|| { @@ -162,16 +174,28 @@ impl LightTables { /// Whether a state change can change light (`hasDifferentLightProperties`). pub fn differs(&self, old: u16, new: u16) -> bool { let (a, b) = (&self.cells[old as usize], &self.cells[new as usize]); - old != new && (a.dampening != b.dampening || a.emission != b.emission || a.shaped || b.shaped) + old != new + && (a.dampening != b.dampening || a.emission != b.emission || a.shaped || b.shaped) } } // Direction index order matches `Direction` (down, up, north, south, west, east); // `d ^ 1` is the opposite direction. -const OFFSETS: [(i32, i32, i32); 6] = [(0, -1, 0), (0, 1, 0), (0, 0, -1), (0, 0, 1), (-1, 0, 0), (1, 0, 0)]; +const OFFSETS: [(i32, i32, i32); 6] = [ + (0, -1, 0), + (0, 1, 0), + (0, 0, -1), + (0, 0, 1), + (-1, 0, 0), + (1, 0, 0), +]; /// `region[dz][dx]` holds the chunks around the centre (index 1,1). /// `sky` is false in dimensions without skylight (the Nether). -pub fn light_chunk(region: &[[Option<&Chunk>; 3]; 3], tables: &LightTables, sky_light: bool) -> Vec> { +pub fn light_chunk( + region: &[[Option<&Chunk>; 3]; 3], + tables: &LightTables, + sky_light: bool, +) -> Vec> { let center = region[1][1].expect("centre chunk"); // Highest occupied section in the region bounds the work. let mut top_section = 0; @@ -224,7 +248,12 @@ pub fn light_chunk(region: &[[Option<&Chunk>; 3]; 3], tables: &LightTables, sky_ // The top layer (above the occupied range) is always open sky. let mut y = h as i32 - 1; sky[at(x, y as usize, z)] = 15; - while y > 0 && !tables.edge_occluded(states[at(x, y as usize, z)] as usize, states[at(x, y as usize - 1, z)] as usize) { + while y > 0 + && !tables.edge_occluded( + states[at(x, y as usize, z)] as usize, + states[at(x, y as usize - 1, z)] as usize, + ) + { y -= 1; sky[at(x, y as usize, z)] = 15; } @@ -238,7 +267,12 @@ pub fn light_chunk(region: &[[Option<&Chunk>; 3]; 3], tables: &LightTables, sky_ } let own = lowest[z * W + x]; let mut deepest = own; - for (nx, nz) in [(x.wrapping_sub(1), z), (x + 1, z), (x, z.wrapping_sub(1)), (x, z + 1)] { + for (nx, nz) in [ + (x.wrapping_sub(1), z), + (x + 1, z), + (x, z.wrapping_sub(1)), + (x, z + 1), + ] { if nx < W && nz < W && present(nx, nz) { deepest = deepest.max(lowest[nz * W + nx]); } @@ -266,7 +300,8 @@ pub fn light_chunk(region: &[[Option<&Chunk>; 3]; 3], tables: &LightTables, sky_ let from = states[p] as usize; for (d, (ox, oy, oz)) in OFFSETS.iter().enumerate() { let (nx, ny, nz) = (x as i32 + ox, y as i32 + oy, z as i32 + oz); - if nx < 0 || nz < 0 || ny < 0 || nx >= W as i32 || nz >= W as i32 || ny >= h as i32 { + if nx < 0 || nz < 0 || ny < 0 || nx >= W as i32 || nz >= W as i32 || ny >= h as i32 + { continue; } let (nx, ny, nz) = (nx as usize, ny as usize, nz as usize); @@ -316,7 +351,6 @@ pub fn light_chunk(region: &[[Option<&Chunk>; 3]; 3], tables: &LightTables, sky_ sections } - /// Resident chunks the incremental relighter reads and writes. pub trait LightWorld { fn state(&self, x: i32, y: i32, z: i32) -> Option; @@ -329,16 +363,22 @@ impl LightWorld for HashMap<(i32, i32), Arc> { if !(MIN_Y..MIN_Y + HEIGHT).contains(&y) { return None; } - self.get(&(x >> 4, z >> 4)).filter(|c| c.lit).map(|c| c.get(x & 15, y, z & 15)) + self.get(&(x >> 4, z >> 4)) + .filter(|c| c.lit) + .map(|c| c.get(x & 15, y, z & 15)) } fn light(&self, x: i32, y: i32, z: i32) -> Option { if !(MIN_Y..MIN_Y + HEIGHT).contains(&y) { return None; } - self.get(&(x >> 4, z >> 4)).filter(|c| c.lit).map(|c| c.light(x & 15, y, z & 15)) + self.get(&(x >> 4, z >> 4)) + .filter(|c| c.lit) + .map(|c| c.light(x & 15, y, z & 15)) } fn set_light(&mut self, x: i32, y: i32, z: i32, packed: u8) { - let Some(chunk) = self.get_mut(&(x >> 4, z >> 4)) else { return }; + let Some(chunk) = self.get_mut(&(x >> 4, z >> 4)) else { + return; + }; let s = ((y - MIN_Y) >> 4) as usize; let i = index(x, y, z); if chunk.sections[s].light(i) == packed { @@ -355,20 +395,32 @@ impl LightWorld for HashMap<(i32, i32), Arc> { } type Pos = (i32, i32, i32); fn level(world: &impl LightWorld, sky: bool, p: Pos) -> Option { - world.light(p.0, p.1, p.2).map(|v| if sky { v >> 4 } else { v & 15 }) + world + .light(p.0, p.1, p.2) + .map(|v| if sky { v >> 4 } else { v & 15 }) } fn set_level(world: &mut impl LightWorld, sky: bool, p: Pos, value: u8) { - let Some(old) = world.light(p.0, p.1, p.2) else { return }; - let packed = if sky { (old & 0x0F) | value << 4 } else { (old & 0xF0) | value }; + let Some(old) = world.light(p.0, p.1, p.2) else { + return; + }; + let packed = if sky { + (old & 0x0F) | value << 4 + } else { + (old & 0xF0) | value + }; world.set_light(p.0, p.1, p.2, packed); } /// `ChunkSkyLightSources`: the Y of the upper block of the highest occluded /// edge in the column (every block at or above it is a sky source). pub fn lowest_sky_source(world: &impl LightWorld, tables: &LightTables, x: i32, z: i32) -> i32 { let mut y = MIN_Y + HEIGHT - 1; - let Some(mut top) = world.state(x, y, z) else { return MIN_Y }; + let Some(mut top) = world.state(x, y, z) else { + return MIN_Y; + }; while y > MIN_Y { - let Some(bottom) = world.state(x, y - 1, z) else { break }; + let Some(bottom) = world.state(x, y - 1, z) else { + break; + }; if tables.edge_occluded(top as usize, bottom as usize) { return y; } @@ -383,9 +435,22 @@ pub fn lowest_sky_source(world: &impl LightWorld, tables: &LightTables, x: i32, /// from the brighter boundary (increase pass). Returns every position whose /// stored light changed, for remeshing. `force` clears around each position /// as if it had been fully lit, for light computed from outdated blocks. -pub fn relight(world: &mut impl LightWorld, tables: &LightTables, sky_light: bool, positions: &[Pos], force: bool) -> Vec { +pub fn relight( + world: &mut impl LightWorld, + tables: &LightTables, + sky_light: bool, + positions: &[Pos], + force: bool, +) -> Vec { let mut changed = Vec::new(); - relight_layer(world, tables, false, positions.to_vec(), force, &mut changed); + relight_layer( + world, + tables, + false, + positions.to_vec(), + force, + &mut changed, + ); if sky_light { let mut seeds = positions.to_vec(); let mut columns: HashMap<(i32, i32), i32> = HashMap::new(); @@ -414,12 +479,21 @@ pub fn relight(world: &mut impl LightWorld, tables: &LightTables, sky_light: boo changed.dedup(); changed } -fn relight_layer(world: &mut impl LightWorld, tables: &LightTables, sky: bool, seeds: Vec, force: bool, changed: &mut Vec) { +fn relight_layer( + world: &mut impl LightWorld, + tables: &LightTables, + sky: bool, + seeds: Vec, + force: bool, + changed: &mut Vec, +) { let mut decrease: VecDeque<(Pos, u8)> = VecDeque::new(); let mut cleared: Vec = Vec::new(); let mut increase: VecDeque = VecDeque::new(); for p in seeds { - let Some(old) = level(world, sky, p) else { continue }; + let Some(old) = level(world, sky, p) else { + continue; + }; if old > 0 { set_level(world, sky, p, 0); changed.push(p); @@ -430,7 +504,9 @@ fn relight_layer(world: &mut impl LightWorld, tables: &LightTables, sky: bool, s while let Some((p, from)) = decrease.pop_front() { for (ox, oy, oz) in OFFSETS { let q = (p.0 + ox, p.1 + oy, p.2 + oz); - let Some(l) = level(world, sky, q) else { continue }; + let Some(l) = level(world, sky, q) else { + continue; + }; if l == 0 { continue; } @@ -450,10 +526,14 @@ fn relight_layer(world: &mut impl LightWorld, tables: &LightTables, sky: bool, s let mut sources: HashMap<(i32, i32), i32> = HashMap::new(); for p in cleared { let seed = if sky { - let lowest = *sources.entry((p.0, p.2)).or_insert_with(|| lowest_sky_source(world, tables, p.0, p.2)); + let lowest = *sources + .entry((p.0, p.2)) + .or_insert_with(|| lowest_sky_source(world, tables, p.0, p.2)); if p.1 >= lowest { 15 } else { 0 } } else { - world.state(p.0, p.1, p.2).map_or(0, |s| tables.cells[s as usize].emission) + world + .state(p.0, p.1, p.2) + .map_or(0, |s| tables.cells[s as usize].emission) }; if seed > level(world, sky, p).unwrap_or(15) { set_level(world, sky, p, seed); @@ -462,15 +542,23 @@ fn relight_layer(world: &mut impl LightWorld, tables: &LightTables, sky: bool, s } } while let Some(p) = increase.pop_front() { - let Some(l) = level(world, sky, p) else { continue }; + let Some(l) = level(world, sky, p) else { + continue; + }; if l <= 1 { continue; } - let Some(from) = world.state(p.0, p.1, p.2) else { continue }; + let Some(from) = world.state(p.0, p.1, p.2) else { + continue; + }; for (d, (ox, oy, oz)) in OFFSETS.iter().enumerate() { let q = (p.0 + ox, p.1 + oy, p.2 + oz); - let Some(to) = world.state(q.0, q.1, q.2) else { continue }; - let Some(ql) = level(world, sky, q) else { continue }; + let Some(to) = world.state(q.0, q.1, q.2) else { + continue; + }; + let Some(ql) = level(world, sky, q) else { + continue; + }; let next = l.saturating_sub(tables.cells[to as usize].dampening.max(1)); if next > ql && !tables.blocked(from as usize, to as usize, d) { set_level(world, sky, q, next); @@ -529,8 +617,9 @@ mod tests { let lit: Vec<_> = chunks .keys() .map(|&(x, z)| { - let region: [[Option<&Chunk>; 3]; 3] = - std::array::from_fn(|dz| std::array::from_fn(|dx| chunks.get(&(x + dx as i32 - 1, z + dz as i32 - 1)))); + let region: [[Option<&Chunk>; 3]; 3] = std::array::from_fn(|dz| { + std::array::from_fn(|dx| chunks.get(&(x + dx as i32 - 1, z + dz as i32 - 1))) + }); let mut c = chunks[&(x, z)].clone(); c.sections = light_chunk(®ion, &tables(), true); c.lit = true; @@ -570,7 +659,11 @@ mod tests { } } }); - assert_eq!(sky(&w, 8, 3, 8), 15, "slab cell is lit through its open top"); + assert_eq!( + sky(&w, 8, 3, 8), + 15, + "slab cell is lit through its open top" + ); // Without the shape test the room would be lit (slabs have no dampening). assert_eq!(sky(&w, 8, 2, 8), 0, "the full bottom face stops sky light"); } @@ -579,17 +672,28 @@ mod tests { let mut w = world(|c| { c.set(8, 0, 8, TORCH); }); - let edits = [((8, 0, 8), AIR), ((9, 1, 8), STONE), ((3, 2, 3), TORCH), ((8, 5, 8), SLAB), ((8, -1, 8), AIR)]; + let edits = [ + ((8, 0, 8), AIR), + ((9, 1, 8), STONE), + ((3, 2, 3), TORCH), + ((8, 5, 8), SLAB), + ((8, -1, 8), AIR), + ]; for ((x, y, z), state) in edits { Arc::make_mut(w.get_mut(&(0, 0)).unwrap()).set(x, y, z, state); relight(&mut w, &tables(), true, &[(x, y, z)], false); } - let region: [[Option<&Chunk>; 3]; 3] = - std::array::from_fn(|dz| std::array::from_fn(|dx| w.get(&(dx as i32 - 1, dz as i32 - 1)).map(|c| &**c))); + let region: [[Option<&Chunk>; 3]; 3] = std::array::from_fn(|dz| { + std::array::from_fn(|dx| w.get(&(dx as i32 - 1, dz as i32 - 1)).map(|c| &**c)) + }); let full = light_chunk(®ion, &tables(), true); for (si, s) in full.iter().enumerate() { for i in 0..4096 { - assert_eq!(s.light(i), w[&(0, 0)].sections[si].light(i), "section {si} index {i}"); + assert_eq!( + s.light(i), + w[&(0, 0)].sections[si].light(i), + "section {si} index {i}" + ); } } } diff --git a/crates/horizon-client/src/merchant.rs b/crates/horizon-client/src/merchant.rs index d8fa86a07..6ee8ef983 100644 --- a/crates/horizon-client/src/merchant.rs +++ b/crates/horizon-client/src/merchant.rs @@ -17,14 +17,34 @@ pub fn can_level_up(level: i32) -> bool { (1..5).contains(&level) } pub fn min_xp(level: i32) -> i32 { - if can_level_up(level) { LEVEL_XP[level as usize - 1] } else { 0 } + if can_level_up(level) { + LEVEL_XP[level as usize - 1] + } else { + 0 + } } pub fn max_xp(level: i32) -> i32 { - if can_level_up(level) { LEVEL_XP[level as usize] } else { 0 } + if can_level_up(level) { + LEVEL_XP[level as usize] + } else { + 0 + } } /// The professions with trades, as in `VillagerProfession`. pub const PROFESSIONS: &[&str] = &[ - "armorer", "butcher", "cartographer", "cleric", "farmer", "fisherman", "fletcher", "leatherworker", "librarian", "mason", "shepherd", "toolsmith", "weaponsmith", + "armorer", + "butcher", + "cartographer", + "cleric", + "farmer", + "fisherman", + "fletcher", + "leatherworker", + "librarian", + "mason", + "shepherd", + "toolsmith", + "weaponsmith", ]; /// An `ItemCost`: item and count (component predicates are not used by the @@ -58,11 +78,16 @@ impl MerchantOffer { /// `getModifiedCostCount` for cost A. pub fn cost_a_count(&self, items: &Items) -> u32 { let base = self.base_cost_a.stack.count as i32; - let demand_diff = ((base as f32 * self.demand as f32 * self.price_multiplier).floor() as i32).max(0); - (base + demand_diff + self.special_price_diff).clamp(1, Self::max_stack(items, &self.base_cost_a.stack) as i32) as u32 + let demand_diff = + ((base as f32 * self.demand as f32 * self.price_multiplier).floor() as i32).max(0); + (base + demand_diff + self.special_price_diff) + .clamp(1, Self::max_stack(items, &self.base_cost_a.stack) as i32) as u32 } pub fn cost_a(&self, items: &Items) -> ItemStack { - ItemStack { count: self.cost_a_count(items), ..self.base_cost_a.stack.clone() } + ItemStack { + count: self.cost_a_count(items), + ..self.base_cost_a.stack.clone() + } } pub fn cost_b(&self) -> Option { self.cost_b.as_ref().map(|c| c.stack.clone()) @@ -75,7 +100,12 @@ impl MerchantOffer { self.demand = self.demand + self.uses - (self.max_uses - self.uses); } /// `satisfiedBy(buyA, buyB)`. - pub fn satisfied_by(&self, items: &Items, a: Option<&ItemStack>, b: Option<&ItemStack>) -> bool { + pub fn satisfied_by( + &self, + items: &Items, + a: Option<&ItemStack>, + b: Option<&ItemStack>, + ) -> bool { let Some(a) = a else { return false }; if !self.base_cost_a.test(a) || a.count < self.cost_a_count(items) { return false; @@ -87,7 +117,12 @@ impl MerchantOffer { } } /// `MerchantOffer.take`: consume the payment; false when not satisfied. - pub fn take(&self, items: &Items, a: &mut Option, b: &mut Option) -> bool { + pub fn take( + &self, + items: &Items, + a: &mut Option, + b: &mut Option, + ) -> bool { if !self.satisfied_by(items, a.as_ref(), b.as_ref()) { return false; } @@ -108,7 +143,13 @@ impl MerchantOffer { } } /// `MerchantOffers.getRecipeFor`: the hinted offer if it fits, else the first that does. -pub fn recipe_for(offers: &[MerchantOffer], items: &Items, a: Option<&ItemStack>, b: Option<&ItemStack>, hint: Option) -> Option { +pub fn recipe_for( + offers: &[MerchantOffer], + items: &Items, + a: Option<&ItemStack>, + b: Option<&ItemStack>, + hint: Option, +) -> Option { if let Some(h) = hint && offers.get(h).is_some_and(|o| o.satisfied_by(items, a, b)) { @@ -117,7 +158,13 @@ pub fn recipe_for(offers: &[MerchantOffer], items: &Items, a: Option<&ItemStack> offers.iter().position(|o| o.satisfied_by(items, a, b)) } /// `MerchantContainer.updateSellItem`: (active offer, result). -pub fn sell_item(offers: &[MerchantOffer], items: &Items, a: Option<&ItemStack>, b: Option<&ItemStack>, hint: Option) -> (Option, Option) { +pub fn sell_item( + offers: &[MerchantOffer], + items: &Items, + a: Option<&ItemStack>, + b: Option<&ItemStack>, + hint: Option, +) -> (Option, Option) { let (a, b) = if a.is_none() { (b, None) } else { (a, b) }; if a.is_none() { return (None, None); @@ -152,7 +199,9 @@ pub struct Trades { pub sets: HashMap, } fn walk(dir: &Path, base: &Path, out: &mut HashMap) { - let Ok(entries) = fs::read_dir(dir) else { return }; + let Ok(entries) = fs::read_dir(dir) else { + return; + }; for e in entries.flatten() { let p = e.path(); if p.is_dir() { @@ -162,7 +211,13 @@ fn walk(dir: &Path, base: &Path, out: &mut HashMap) { && let Ok(bytes) = fs::read(&p) && let Ok(v) = serde_json::from_slice(&bytes) { - out.insert(format!("minecraft:{}", rel.with_extension("").to_string_lossy().replace('\\', "/")), v); + out.insert( + format!( + "minecraft:{}", + rel.with_extension("").to_string_lossy().replace('\\', "/") + ), + v, + ); } } } @@ -170,14 +225,37 @@ impl Trades { pub fn load(root: &Path) -> Self { let data = root.join("data/minecraft"); let (mut trades, mut raw_tags, mut sets) = (HashMap::new(), HashMap::new(), HashMap::new()); - walk(&data.join("villager_trade"), &data.join("villager_trade"), &mut trades); - walk(&data.join("tags/villager_trade"), &data.join("tags/villager_trade"), &mut raw_tags); + walk( + &data.join("villager_trade"), + &data.join("villager_trade"), + &mut trades, + ); + walk( + &data.join("tags/villager_trade"), + &data.join("tags/villager_trade"), + &mut raw_tags, + ); walk(&data.join("trade_set"), &data.join("trade_set"), &mut sets); let raw: HashMap> = raw_tags .into_iter() - .map(|(k, v)| (k, v["values"].as_array().into_iter().flatten().filter_map(|e| e.as_str().map(str::to_owned)).collect())) + .map(|(k, v)| { + ( + k, + v["values"] + .as_array() + .into_iter() + .flatten() + .filter_map(|e| e.as_str().map(str::to_owned)) + .collect(), + ) + }) .collect(); - fn expand(name: &str, raw: &HashMap>, out: &mut Vec, depth: u32) { + fn expand( + name: &str, + raw: &HashMap>, + out: &mut Vec, + depth: u32, + ) { for v in raw.get(name).into_iter().flatten() { match v.strip_prefix('#') { Some(t) if depth < 16 => expand(t, raw, out, depth + 1), @@ -199,7 +277,10 @@ impl Trades { } /// `VillagerProfession.getTrades(level)`. pub fn set_for(profession: &str, level: i32) -> String { - format!("minecraft:{}/level_{level}", profession.trim_start_matches("minecraft:")) + format!( + "minecraft:{}/level_{level}", + profession.trim_start_matches("minecraft:") + ) } fn trade_list(&self, spec: &Value) -> Vec { match spec { @@ -207,21 +288,39 @@ impl Trades { Some(tag) => self.tags.get(tag).cloned().unwrap_or_default(), None => vec![s.clone()], }, - Value::Array(a) => a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect(), + Value::Array(a) => a + .iter() + .filter_map(|v| v.as_str().map(str::to_owned)) + .collect(), _ => vec![], } } /// `AbstractVillager.addOffersFromTradeSet`. - pub fn offers_from_set(&self, ctx: &TradeContext<'_>, set_id: &str, random: &mut R) -> Vec { - let Some(set) = self.sets.get(set_id) else { return vec![] }; + pub fn offers_from_set( + &self, + ctx: &TradeContext<'_>, + set_id: &str, + random: &mut R, + ) -> Vec { + let Some(set) = self.sets.get(set_id) else { + return vec![]; + }; let mut potential = self.trade_list(&set["trades"]); let amount = int_provider(&set["amount"], random); let duplicates = set["allow_duplicates"].as_bool().unwrap_or(false); let mut out = Vec::new(); while (out.len() as i32) < amount && !potential.is_empty() { let roll = random.next_int_bound(potential.len() as i32).unwrap_or(0) as usize; - let id = if duplicates { potential[roll].clone() } else { potential.remove(roll) }; - match self.trades.get(&id).and_then(|t| offer_from(ctx, t, random)) { + let id = if duplicates { + potential[roll].clone() + } else { + potential.remove(roll) + }; + match self + .trades + .get(&id) + .and_then(|t| offer_from(ctx, t, random)) + { Some(o) => out.push(o), None if duplicates => { potential.remove(roll); @@ -244,8 +343,15 @@ fn int_provider(v: &Value, random: &mut R) -> i32 { Value::Number(n) => n.as_i64().unwrap_or(0) as i32, Value::Object(o) => match o.get("type").and_then(Value::as_str).unwrap_or("") { "minecraft:uniform" => { - let (min, max) = (o["min"].as_i64().unwrap_or(0) as i32, o["max"].as_i64().unwrap_or(0) as i32); - if min >= max { min } else { min + random.next_int_bound(max - min + 1).unwrap_or(0) } + let (min, max) = ( + o["min"].as_i64().unwrap_or(0) as i32, + o["max"].as_i64().unwrap_or(0) as i32, + ); + if min >= max { + min + } else { + min + random.next_int_bound(max - min + 1).unwrap_or(0) + } } "minecraft:constant" => o["value"].as_i64().unwrap_or(0) as i32, _ => o.get("value").and_then(Value::as_i64).unwrap_or(0) as i32, @@ -257,7 +363,9 @@ fn cost(items: &Items, v: &Value, additional: i32) -> ItemCost { let id = v["id"].as_str().unwrap_or("minecraft:air"); let max = items.get(id).map_or(64, |i| i.max_stack) as i32; let count = (v["count"].as_i64().unwrap_or(1) as i32 + additional).clamp(0, max); - ItemCost { stack: ItemStack::new(id, count as u32) } + ItemCost { + stack: ItemStack::new(id, count as u32), + } } fn variant_ok(pred: &Value, variant: &str) -> bool { match &pred["predicate"]["minecraft:predicates"]["minecraft:villager/variant"] { @@ -267,14 +375,21 @@ fn variant_ok(pred: &Value, variant: &str) -> bool { } } /// `VillagerTrade.getOffer`. -pub fn offer_from(ctx: &TradeContext<'_>, t: &Value, random: &mut R) -> Option { +pub fn offer_from( + ctx: &TradeContext<'_>, + t: &Value, + random: &mut R, +) -> Option { if let Some(p) = t.get("merchant_predicate") && !variant_ok(p, ctx.variant) { return None; } let gives = &t["gives"]; - let mut result = ItemStack::new(gives["id"].as_str()?, gives["count"].as_u64().unwrap_or(1) as u32); + let mut result = ItemStack::new( + gives["id"].as_str()?, + gives["count"].as_u64().unwrap_or(1) as u32, + ); let mut additional = 0; let modifiers: Vec<&Value> = match &t["given_item_modifier"] { Value::Array(a) => a.iter().collect(), @@ -287,7 +402,10 @@ pub fn offer_from(ctx: &TradeContext<'_>, t: &Value, random: &m additional += extra; } if let Some(Value::String(tag)) = t.get("double_trade_price_enchantments") - && result.stored_enchantments().iter().any(|(e, _)| ctx.enchantments.in_tag(tag, e)) + && result + .stored_enchantments() + .iter() + .any(|(e, _)| ctx.enchantments.in_tag(tag, e)) { additional *= 2; } @@ -313,7 +431,12 @@ pub fn offer_from(ctx: &TradeContext<'_>, t: &Value, random: &m }) } /// The loot functions trades use; None discards the offer. -fn apply_modifier(ctx: &TradeContext<'_>, m: &Value, stack: ItemStack, random: &mut R) -> Option<(ItemStack, i32)> { +fn apply_modifier( + ctx: &TradeContext<'_>, + m: &Value, + stack: ItemStack, + random: &mut R, +) -> Option<(ItemStack, i32)> { let e = ctx.enchantments; let pool = |options: &Value| -> Vec> { match options { @@ -328,26 +451,53 @@ fn apply_modifier(ctx: &TradeContext<'_>, m: &Value, stack: Ite let levels = int_provider(&m["levels"], random); // EnchantmentHelper.enchantItem on the loot context's random. let chosen = e.select(ctx.items, random, &stack.item, levels, &pool(&m["options"])); - let mut out = if &*stack.item == "minecraft:book" { ItemStack::new("minecraft:enchanted_book", stack.count) } else { stack }; + let mut out = if &*stack.item == "minecraft:book" { + ItemStack::new("minecraft:enchanted_book", stack.count) + } else { + stack + }; for (id, l) in chosen { out.enchant(&id, l); } - let extra = if m["include_additional_cost_component"].as_bool().unwrap_or(false) && levels > 0 { levels } else { 0 }; + let extra = if m["include_additional_cost_component"] + .as_bool() + .unwrap_or(false) + && levels > 0 + { + levels + } else { + 0 + }; Some((out, extra)) } "minecraft:enchant_randomly" => { let book = &*stack.item == "minecraft:book"; let only_compatible = m["only_compatible"].as_bool().unwrap_or(true); - let options: Vec> = pool(&m["options"]).into_iter().filter(|id| book || !only_compatible || e.can_enchant(ctx.items, id, &stack.item)).collect(); + let options: Vec> = pool(&m["options"]) + .into_iter() + .filter(|id| book || !only_compatible || e.can_enchant(ctx.items, id, &stack.item)) + .collect(); if options.is_empty() { return Some((stack, 0)); } - let id = options[random.next_int_bound(options.len() as i32).unwrap_or(0) as usize].clone(); + let id = + options[random.next_int_bound(options.len() as i32).unwrap_or(0) as usize].clone(); let max = e.get(&id).map_or(1, |d| d.max_level) as i32; - let level = if max <= 1 { 1 } else { 1 + random.next_int_bound(max).unwrap_or(0) }; - let mut out = if book { ItemStack::new("minecraft:enchanted_book", 1) } else { stack }; + let level = if max <= 1 { + 1 + } else { + 1 + random.next_int_bound(max).unwrap_or(0) + }; + let mut out = if book { + ItemStack::new("minecraft:enchanted_book", 1) + } else { + stack + }; out.enchant(&id, level as u32); - let extra = if m["include_additional_cost_component"].as_bool().unwrap_or(false) { + let extra = if m["include_additional_cost_component"] + .as_bool() + .unwrap_or(false) + { 2 + random.next_int_bound(5 + level * 10).unwrap_or(0) + 3 * level } else { 0 @@ -357,8 +507,14 @@ fn apply_modifier(ctx: &TradeContext<'_>, m: &Value, stack: Ite "minecraft:filtered" => { let filter = &m["item_filter"]; let item_ok = filter["items"].as_str().is_none_or(|i| i == &*stack.item); - let needs = |key: &str, have: bool| filter["predicates"][key].as_array().is_none_or(|_| have); - let ok = item_ok && needs("minecraft:enchantments", !stack.enchantments().is_empty()) && needs("minecraft:stored_enchantments", !stack.stored_enchantments().is_empty()); + let needs = + |key: &str, have: bool| filter["predicates"][key].as_array().is_none_or(|_| have); + let ok = item_ok + && needs("minecraft:enchantments", !stack.enchantments().is_empty()) + && needs( + "minecraft:stored_enchantments", + !stack.stored_enchantments().is_empty(), + ); if ok { Some((stack, 0)) } else if m["on_fail"]["type"] == "minecraft:discard" { @@ -367,7 +523,10 @@ fn apply_modifier(ctx: &TradeContext<'_>, m: &Value, stack: Ite Some((stack, 0)) } } - "minecraft:set_potion" => Some((stack.with_potion(m["id"].as_str().unwrap_or("minecraft:water")), 0)), + "minecraft:set_potion" => Some(( + stack.with_potion(m["id"].as_str().unwrap_or("minecraft:water")), + 0, + )), "minecraft:discard" => None, // Dyes, stew effects, random potions and exploration maps keep the plain item. _ => Some((stack, 0)), @@ -384,8 +543,12 @@ mod tests { } fn offer(cost: u32, b: Option) -> MerchantOffer { MerchantOffer { - base_cost_a: ItemCost { stack: ItemStack::new("minecraft:emerald", cost) }, - cost_b: b.map(|n| ItemCost { stack: ItemStack::new("minecraft:book", n) }), + base_cost_a: ItemCost { + stack: ItemStack::new("minecraft:emerald", cost), + }, + cost_b: b.map(|n| ItemCost { + stack: ItemStack::new("minecraft:book", n), + }), result: ItemStack::new("minecraft:iron_boots", 1), uses: 0, max_uses: 12, @@ -417,17 +580,42 @@ mod tests { let offers = vec![offer(5, None), offer(1, Some(1))]; let mut a = Some(ItemStack::new("minecraft:emerald", 6)); let mut b = None; - assert_eq!(sell_item(&offers, &items, a.as_ref(), b.as_ref(), None).0, Some(0)); + assert_eq!( + sell_item(&offers, &items, a.as_ref(), b.as_ref(), None).0, + Some(0) + ); assert!(offers[0].take(&items, &mut a, &mut b)); assert_eq!(a.as_ref().unwrap().count, 1); // Payment in the second slot only still matches (A and B swap). let book = Some(ItemStack::new("minecraft:book", 1)); - let (i, r) = sell_item(&offers, &items, None, Some(&ItemStack::new("minecraft:emerald", 5)), None); - assert_eq!((i, r.map(|r| r.item)), (Some(0), Some(Arc::from("minecraft:iron_boots")))); - assert_eq!(sell_item(&offers, &items, a.as_ref(), book.as_ref(), Some(1)).0, Some(1)); + let (i, r) = sell_item( + &offers, + &items, + None, + Some(&ItemStack::new("minecraft:emerald", 5)), + None, + ); + assert_eq!( + (i, r.map(|r| r.item)), + (Some(0), Some(Arc::from("minecraft:iron_boots"))) + ); + assert_eq!( + sell_item(&offers, &items, a.as_ref(), book.as_ref(), Some(1)).0, + Some(1) + ); let mut out = offers[0].clone(); out.uses = 12; - assert_eq!(sell_item(&[out], &items, Some(&ItemStack::new("minecraft:emerald", 5)), None, None).1, None); + assert_eq!( + sell_item( + &[out], + &items, + Some(&ItemStack::new("minecraft:emerald", 5)), + None, + None + ) + .1, + None + ); } #[test] @@ -452,15 +640,33 @@ mod tests { trades.insert("minecraft:t/helmet".into(), json!({"gives":{"id":"minecraft:iron_helmet"},"max_uses":12,"reputation_discount":0.2,"wants":{"count":5,"id":"minecraft:emerald"}})); trades.insert("minecraft:t/desert".into(), json!({"gives":{"id":"minecraft:sand"},"wants":{"id":"minecraft:emerald"},"merchant_predicate":{"entity":"this","predicate":{"minecraft:predicates":{"minecraft:villager/variant":"minecraft:desert"}},"type":"minecraft:entity_properties"}})); let mut tags = HashMap::new(); - tags.insert("minecraft:t/level_1".into(), vec!["minecraft:t/boots".into(), "minecraft:t/helmet".into(), "minecraft:t/desert".into()]); + tags.insert( + "minecraft:t/level_1".into(), + vec![ + "minecraft:t/boots".into(), + "minecraft:t/helmet".into(), + "minecraft:t/desert".into(), + ], + ); let mut sets = HashMap::new(); - sets.insert("minecraft:t/level_1".into(), json!({"amount": 5, "trades": "#minecraft:t/level_1"})); + sets.insert( + "minecraft:t/level_1".into(), + json!({"amount": 5, "trades": "#minecraft:t/level_1"}), + ); let t = Trades { trades, tags, sets }; - let ctx = TradeContext { items: &items, enchantments: &e, variant: "minecraft:plains" }; + let ctx = TradeContext { + items: &items, + enchantments: &e, + variant: "minecraft:plains", + }; let offers = t.offers_from_set(&ctx, "minecraft:t/level_1", &mut sequence_random(1, "x")); // The desert-only trade is skipped for a plains villager; no duplicates. assert_eq!(offers.len(), 2); assert_ne!(offers[0].result.item, offers[1].result.item); - assert!(offers.iter().all(|o| o.max_uses == 12 && (o.price_multiplier - 0.2).abs() < 1e-6)); + assert!( + offers + .iter() + .all(|o| o.max_uses == 12 && (o.price_multiplier - 0.2).abs() < 1e-6) + ); } } diff --git a/crates/horizon-client/src/mesher.rs b/crates/horizon-client/src/mesher.rs index 4480f246e..368c92518 100644 --- a/crates/horizon-client/src/mesher.rs +++ b/crates/horizon-client/src/mesher.rs @@ -45,7 +45,12 @@ pub struct SectionMesh { } impl Default for SectionMesh { fn default() -> Self { - Self { solid: Vec::new(), translucent: Vec::new(), visibility: ALL_VISIBLE, block_entities: Vec::new() } + Self { + solid: Vec::new(), + translucent: Vec::new(), + visibility: ALL_VISIBLE, + block_entities: Vec::new(), + } } } pub const ALL_VISIBLE: u64 = (1 << 36) - 1; @@ -56,7 +61,11 @@ fn visibility(pad: &Padded, info: &[Info]) -> u64 { let opaque = |x: i32, y: i32, z: i32| info[pad.blocks[pi(x, y, z)] as usize].solid; let mut stack = Vec::new(); for start in 0..4096usize { - let (x, y, z) = ((start & 15) as i32, (start >> 8) as i32, ((start >> 4) & 15) as i32); + let (x, y, z) = ( + (start & 15) as i32, + (start >> 8) as i32, + ((start >> 4) & 15) as i32, + ); if seen[start] || opaque(x, y, z) { continue; } @@ -65,13 +74,32 @@ fn visibility(pad: &Padded, info: &[Info]) -> u64 { stack.push(start); while let Some(c) = stack.pop() { let (x, y, z) = ((c & 15) as i32, (c >> 8) as i32, ((c >> 4) & 15) as i32); - if y == 0 { faces |= 1 << 0; } - if y == 15 { faces |= 1 << 1; } - if z == 0 { faces |= 1 << 2; } - if z == 15 { faces |= 1 << 3; } - if x == 0 { faces |= 1 << 4; } - if x == 15 { faces |= 1 << 5; } - for (dx, dy, dz) in [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)] { + if y == 0 { + faces |= 1 << 0; + } + if y == 15 { + faces |= 1 << 1; + } + if z == 0 { + faces |= 1 << 2; + } + if z == 15 { + faces |= 1 << 3; + } + if x == 0 { + faces |= 1 << 4; + } + if x == 15 { + faces |= 1 << 5; + } + for (dx, dy, dz) in [ + (1, 0, 0), + (-1, 0, 0), + (0, 1, 0), + (0, -1, 0), + (0, 0, 1), + (0, 0, -1), + ] { let (nx, ny, nz) = (x + dx, y + dy, z + dz); if !(0..16).contains(&nx) || !(0..16).contains(&ny) || !(0..16).contains(&nz) { continue; @@ -460,7 +488,10 @@ impl Mesher<'_> { } let state = &info[id as usize]; if state.block_entity { - out.block_entities.push(([center.x * 16 + x, base_y + y, center.z * 16 + z], u32::from(id))); + out.block_entities.push(( + [center.x * 16 + x, base_y + y, center.z * 16 + z], + u32::from(id), + )); } if state.solid && Direction::ALL.iter().all(|d| { @@ -479,7 +510,10 @@ impl Mesher<'_> { continue; } let world = BlockPos::new(center.x * 16 + x, base_y + y, center.z * 16 + z); - let Ok(models) = self.assets.model_catalog.collect(BlockStateId(id.into()), world) + let Ok(models) = self + .assets + .model_catalog + .collect(BlockStateId(id.into()), world) else { continue; }; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index a02fc467b..a8fea8b4d 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -8,8 +8,8 @@ pub mod ai; pub mod anim; pub mod aquatic; -pub mod data; pub mod control; +pub mod data; pub mod farm; pub mod goals; pub mod hostile; @@ -18,8 +18,8 @@ pub mod living; pub mod nav; pub mod path; pub mod render; -pub mod species; pub mod spawning; +pub mod species; pub mod undead; mod world; @@ -47,7 +47,12 @@ pub struct Part { } impl Part { fn parse(name: &str, v: &Value) -> Self { - let pose: Vec = v["pose"].as_array().into_iter().flatten().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect(); + let pose: Vec = v["pose"] + .as_array() + .into_iter() + .flatten() + .map(|x| x.as_f64().unwrap_or(0.0) as f32) + .collect(); let mut p = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0]; for (i, x) in pose.iter().enumerate().take(9) { p[i] = *x; @@ -61,11 +66,18 @@ impl Part { .as_array()? .iter() .map(|vx| { - let a: Vec = vx.as_array().into_iter().flatten().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect(); + let a: Vec = vx + .as_array() + .into_iter() + .flatten() + .map(|x| x.as_f64().unwrap_or(0.0) as f32) + .collect(); [a[0], a[1], a[2], a[3], a[4]] }) .collect(); - (verts.len() == 4).then(|| Polygon { vertices: [verts[0], verts[1], verts[2], verts[3]] }) + (verts.len() == 4).then(|| Polygon { + vertices: [verts[0], verts[1], verts[2], verts[3]], + }) }) .collect(); let mut children: Vec = v["children"] @@ -75,7 +87,12 @@ impl Part { .map(|(k, c)| Part::parse(k, c)) .collect(); children.sort_by(|a, b| a.name.cmp(&b.name)); - Self { name: name.to_owned(), pose: p, polygons, children } + Self { + name: name.to_owned(), + pose: p, + polygons, + children, + } } } /// Kept for callers of the earlier simple AI; species now select behaviour. @@ -178,7 +195,12 @@ impl MobTypes { let models: Value = serde_json::from_slice(&fs::read(root.join("entity-models.json"))?)?; let item_tags = crate::items::load_tags(root, "item").unwrap_or_default(); let tag = |name: &str| -> Arc<[String]> { - let mut v: Vec = item_tags.get(&format!("minecraft:{name}")).into_iter().flatten().cloned().collect(); + let mut v: Vec = item_tags + .get(&format!("minecraft:{name}")) + .into_iter() + .flatten() + .cloned() + .collect(); v.sort(); v.into() }; @@ -190,14 +212,19 @@ impl MobTypes { continue; } let model_key = format!("minecraft:{}", def.model); - let Some(model) = models.get(&model_key) else { continue }; + let Some(model) = models.get(&model_key) else { + continue; + }; let attr = |k: &str| t["attributes"][format!("minecraft:{k}")].as_f64(); let mut layers = HashMap::new(); if let Some(all) = models.as_object() { for prefix in def.layer_prefixes() { let start = format!("minecraft:{prefix}#"); for (k, v) in all.iter().filter(|(k, _)| k.starts_with(&start)) { - layers.insert(k.trim_start_matches("minecraft:").to_owned(), Arc::new(Part::parse("root", v))); + layers.insert( + k.trim_start_matches("minecraft:").to_owned(), + Arc::new(Part::parse("root", v)), + ); } } } @@ -241,8 +268,15 @@ impl MobTypes { anim: def.anim, sounds: def.sounds, step_sound: def.step_sound, - food: def.food_tag().map(tag).unwrap_or_else(|| Arc::from(Vec::new())), - tempt: def.tempt_tag().or(def.food_tag()).map(tag).unwrap_or_else(|| Arc::from(Vec::new())), + food: def + .food_tag() + .map(tag) + .unwrap_or_else(|| Arc::from(Vec::new())), + tempt: def + .tempt_tag() + .or(def.food_tag()) + .map(tag) + .unwrap_or_else(|| Arc::from(Vec::new())), category, id, }, @@ -285,30 +319,63 @@ pub struct Damage { } impl Damage { pub fn fall() -> Self { - Self { kind: DamageKind::Fall, attacker: None, from: None } + Self { + kind: DamageKind::Fall, + attacker: None, + from: None, + } } pub fn of(kind: DamageKind) -> Self { - Self { kind, attacker: None, from: None } + Self { + kind, + attacker: None, + from: None, + } } pub fn player(from: [f64; 3]) -> Self { - Self { kind: DamageKind::PlayerAttack, attacker: Some(Who::Player), from: Some(from) } + Self { + kind: DamageKind::PlayerAttack, + attacker: Some(Who::Player), + from: Some(from), + } } pub fn mob(id: u32, from: [f64; 3]) -> Self { - Self { kind: DamageKind::MobAttack, attacker: Some(Who::Mob(id)), from: Some(from) } + Self { + kind: DamageKind::MobAttack, + attacker: Some(Who::Mob(id)), + from: Some(from), + } } /// DamageTypeTags.PANIC_CAUSES pub fn causes_panic(&self) -> bool { - !matches!(self.kind, DamageKind::Fall | DamageKind::Drown | DamageKind::Generic | DamageKind::InWall) + !matches!( + self.kind, + DamageKind::Fall | DamageKind::Drown | DamageKind::Generic | DamageKind::InWall + ) } /// DamageTypeTags.BYPASSES_ARMOR pub fn bypasses_armor(&self) -> bool { - matches!(self.kind, DamageKind::Fall | DamageKind::OnFire | DamageKind::Drown | DamageKind::Magic | DamageKind::InWall | DamageKind::Generic) + matches!( + self.kind, + DamageKind::Fall + | DamageKind::OnFire + | DamageKind::Drown + | DamageKind::Magic + | DamageKind::InWall + | DamageKind::Generic + ) } pub fn is_fire(&self) -> bool { - matches!(self.kind, DamageKind::OnFire | DamageKind::InFire | DamageKind::Lava | DamageKind::Fireball) + matches!( + self.kind, + DamageKind::OnFire | DamageKind::InFire | DamageKind::Lava | DamageKind::Fireball + ) } pub fn is_projectile(&self) -> bool { - matches!(self.kind, DamageKind::Arrow | DamageKind::Thrown | DamageKind::Fireball) + matches!( + self.kind, + DamageKind::Arrow | DamageKind::Thrown | DamageKind::Fireball + ) } } /// Per-mob attribute base values (the type's defaults unless changed). @@ -422,31 +489,76 @@ pub enum MobEvent { Shoot([f64; 3], [f64; 3]), Explode([f64; 3], f32), /// Melee or ranged damage to another mob. - AttackMob { target: u32, amount: f32, source: Damage }, + AttackMob { + target: u32, + amount: f32, + source: Damage, + }, /// Set another mob's attack target (HurtByTargetGoal alerts). - SetTarget { mob: u32, target: Who }, + SetTarget { + mob: u32, + target: Who, + }, Projectile(crate::projectiles::Projectile), /// Spawn a new mob (breeding, slime splitting, chicken eggs...). Spawn(Box), /// Spawn a mob by type id at a position (conversions, splits). - SpawnKind { kind: String, at: [f64; 3], setup: SpawnSetup }, - DropItem { item: Arc, count: u32, at: [f64; 3] }, - SetBlock { pos: [i32; 3], state: horizon_world::registry::BlockStateId }, + SpawnKind { + kind: String, + at: [f64; 3], + setup: SpawnSetup, + }, + DropItem { + item: Arc, + count: u32, + at: [f64; 3], + }, + SetBlock { + pos: [i32; 3], + state: horizon_world::registry::BlockStateId, + }, /// Destroy a block, dropping nothing (sheep eating grass becomes dirt via SetBlock). - BreakBlock { pos: [i32; 3], drop: bool }, - Particles { kind: &'static str, at: [f64; 3], count: u32 }, - Experience { at: [f64; 3], amount: u32 }, + BreakBlock { + pos: [i32; 3], + drop: bool, + }, + Particles { + kind: &'static str, + at: [f64; 3], + count: u32, + }, + Experience { + at: [f64; 3], + amount: u32, + }, /// Apply an effect to the player (witch potions, bee stings, cave spider poison). - EffectPlayer { effect: &'static str, ticks: i32, amplifier: i32 }, + EffectPlayer { + effect: &'static str, + ticks: i32, + amplifier: i32, + }, /// Set an entity on fire. - Ignite { target: Who, seconds: i32 }, + Ignite { + target: Who, + seconds: i32, + }, /// Two animals bred: the game spawns the baby and resets the partner. - Breed { parent: u32, partner: u32 }, + Breed { + parent: u32, + partner: u32, + }, /// Replace a block by name (sheep turning grass to dirt), optionally with /// the destroy effect. - SetBlockName { pos: [i32; 3], name: &'static str, effect: bool }, + SetBlockName { + pos: [i32; 3], + name: &'static str, + effect: bool, + }, /// Drop the loot of a gift table (chicken eggs, armadillo scutes). - GiftLoot { table: &'static str, at: [f64; 3] }, + GiftLoot { + table: &'static str, + at: [f64; 3], + }, } /// How a spawned-by-kind mob should be set up. #[derive(Clone, Debug, Default)] @@ -508,7 +620,11 @@ pub struct MobWorld<'a> { } impl Mob { pub fn new(id: u32, kind: Arc, position: Vec3, yaw: f32) -> Self { - let mut random = LegacyRandom::new(i64::from(id).wrapping_mul(0x5DEE_CE66D) ^ (position.x.to_bits() as i64) ^ (position.z.to_bits() as i64).rotate_left(17)); + let mut random = LegacyRandom::new( + i64::from(id).wrapping_mul(0x5DEE_CE66D) + ^ (position.x.to_bits() as i64) + ^ (position.z.to_bits() as i64).rotate_left(17), + ); let _ = random.next_int(); let mut mob = Self { id, @@ -551,7 +667,12 @@ impl Mob { last_damage: None, removed: false, anim: anim::AnimState::default(), - attrs: Attrs { speed: kind.speed, attack_damage: kind.attack_damage, max_health: kind.max_health, follow_range: kind.follow_range }, + attrs: Attrs { + speed: kind.speed, + attack_damage: kind.attack_damage, + max_health: kind.max_health, + follow_range: kind.follow_range, + }, kind, }; ai::register(&mut mob); @@ -561,7 +682,11 @@ impl Mob { let w = f64::from(self.width()) / 2.0; Aabb::new( Vec3::new(self.position.x - w, self.position.y, self.position.z - w), - Vec3::new(self.position.x + w, self.position.y + f64::from(self.height()), self.position.z + w), + Vec3::new( + self.position.x + w, + self.position.y + f64::from(self.height()), + self.position.z + w, + ), ) } pub fn alive(&self) -> bool { @@ -574,7 +699,12 @@ impl Mob { self.kind.species } /// The player hit this mob (melee): LivingEntity.hurt with knockback. - pub fn hurt(&mut self, amount: f32, from: Option<[f64; 3]>, _random: &mut LegacyRandom) -> bool { + pub fn hurt( + &mut self, + amount: f32, + from: Option<[f64; 3]>, + _random: &mut LegacyRandom, + ) -> bool { let source = match from { Some(f) => Damage::player(f), None => Damage::of(DamageKind::Generic), @@ -650,20 +780,35 @@ impl Mob { let (kx, kz) = (xd / len * power, zd / len * power); self.velocity = Vec3::new( self.velocity.x / 2.0 - kx, - if self.on_ground { (self.velocity.y / 2.0 + power).min(0.4) } else { self.velocity.y }, + if self.on_ground { + (self.velocity.y / 2.0 + power).min(0.4) + } else { + self.velocity.y + }, self.velocity.z / 2.0 - kz, ); } /// One game tick. Returns false once the mob should be removed. - pub fn tick(&mut self, w: &MobWorld, _random: &mut LegacyRandom, events: &mut Vec) -> bool { + pub fn tick( + &mut self, + w: &MobWorld, + _random: &mut LegacyRandom, + events: &mut Vec, + ) -> bool { ai::tick(self, w, events) } pub fn distance_to(&self, p: [f64; 3]) -> f64 { - let d = [p[0] - self.position.x, p[1] - self.position.y, p[2] - self.position.z]; + let d = [ + p[0] - self.position.x, + p[1] - self.position.y, + p[2] - self.position.z, + ]; (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() } pub fn distance_sqr(&self, p: Vec3) -> f64 { - (p.x - self.position.x).powi(2) + (p.y - self.position.y).powi(2) + (p.z - self.position.z).powi(2) + (p.x - self.position.x).powi(2) + + (p.y - self.position.y).powi(2) + + (p.z - self.position.z).powi(2) } /// Movement speed attribute bonus (baby zombies, sprinting modifiers). /// MOVEMENT_SPEED including effects (speed +20%/level, slowness -15%/level). @@ -693,7 +838,11 @@ impl Mob { ai::speed_bonus(self) } pub fn center(&self) -> [f64; 3] { - [self.position.x, self.position.y + f64::from(self.height()) / 2.0, self.position.z] + [ + self.position.x, + self.position.y + f64::from(self.height()) / 2.0, + self.position.z, + ] } pub fn sound(&self, event: &'static str, events: &mut Vec) { let at = [self.position.x, self.eye_y(), self.position.z]; @@ -701,36 +850,69 @@ impl Mob { } /// 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.random.next_float() - self.random.next_float()) * 0.2 + + if self.is_baby() { 1.5 } else { 1.0 }; let at = [self.position.x, self.eye_y(), self.position.z]; events.push(MobEvent::Sound(event, at, ai::sound_volume(self), pitch)); } } /// Model geometry for a mob, posed for its animation state, as camera-relative /// vertices textured from the shared atlas. -pub fn render(mob: &Mob, alpha: f32, camera: glam::DVec3, uv: [f32; 4], light: u32, out: &mut Vec) { +pub fn render( + mob: &Mob, + alpha: f32, + camera: glam::DVec3, + uv: [f32; 4], + light: u32, + out: &mut Vec, +) { render::render_single(mob, alpha, camera, uv, light, out); } /// Load one baked model layer from `entity-models.json` (e.g. `minecraft:chest#main`). pub fn load_model(root: &Path, key: &str) -> Option { - let models: Value = serde_json::from_slice(&fs::read(root.join("entity-models.json")).ok()?).ok()?; + let models: Value = + serde_json::from_slice(&fs::read(root.join("entity-models.json")).ok()?).ok()?; models.get(key).map(|m| Part::parse("root", m)) } /// ModelPart.render: translate, rotate ZYX, scale, then children. -pub fn render_model(part: &Part, base: glam::Mat4, pose_for: &dyn Fn(&Part) -> [f32; 9], uv: [f32; 4], light: u32, overlay: u32, out: &mut Vec) { +pub fn render_model( + part: &Part, + base: glam::Mat4, + pose_for: &dyn Fn(&Part) -> [f32; 9], + uv: [f32; 4], + light: u32, + overlay: u32, + out: &mut Vec, +) { visit(part, base, pose_for, uv, light, overlay, out); - fn visit(part: &Part, parent: glam::Mat4, pose_for: &dyn Fn(&Part) -> [f32; 9], uv: [f32; 4], light: u32, overlay: u32, out: &mut Vec) { + fn visit( + part: &Part, + parent: glam::Mat4, + pose_for: &dyn Fn(&Part) -> [f32; 9], + uv: [f32; 4], + light: u32, + overlay: u32, + out: &mut Vec, + ) { let p = pose_for(part); let m = parent * glam::Mat4::from_translation(glam::Vec3::new(p[0], p[1], p[2]) / 16.0) - * glam::Mat4::from_quat(glam::Quat::from_euler(glam::EulerRot::ZYX, p[5], p[4], p[3])) + * glam::Mat4::from_quat(glam::Quat::from_euler( + glam::EulerRot::ZYX, + p[5], + p[4], + p[3], + )) * glam::Mat4::from_scale(glam::Vec3::new(p[6], p[7], p[8])); for poly in &part.polygons { for v in poly.vertices { let pos = m.transform_point3(glam::Vec3::new(v[0], v[1], v[2]) / 16.0); out.push(Vertex { pos: pos.to_array(), - uv: [uv[0] + (uv[2] - uv[0]) * v[3], uv[1] + (uv[3] - uv[1]) * v[4]], + uv: [ + uv[0] + (uv[2] - uv[0]) * v[3], + uv[1] + (uv[3] - uv[1]) * v[4], + ], layer: overlay, color: 0xFFFF_FFFF, light, diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 00739f766..70d566d6b 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -70,9 +70,22 @@ pub fn family(s: Species) -> Family { use Species as S; match s { S::Pig | S::Cow | S::Mooshroom | S::Sheep | S::Chicken => Family::Farm, - S::Zombie | S::Husk | S::Drowned | S::ZombieVillager | S::Skeleton | S::Stray | S::Bogged | S::WitherSkeleton => Family::Undead, + S::Zombie + | S::Husk + | S::Drowned + | S::ZombieVillager + | S::Skeleton + | S::Stray + | S::Bogged + | S::WitherSkeleton => Family::Undead, S::Creeper | S::Spider | S::CaveSpider => Family::Hostile, - S::Squid | S::GlowSquid | S::Cod | S::Salmon | S::TropicalFish | S::Pufferfish | S::Dolphin => Family::Aquatic, + S::Squid + | S::GlowSquid + | S::Cod + | S::Salmon + | S::TropicalFish + | S::Pufferfish + | S::Dolphin => Family::Aquatic, _ => Family::Generic, } } @@ -590,13 +603,17 @@ fn tick_effects(m: &mut Mob) { for (effect, ticks, amp) in &mut effects { let interval = |base: i32| (base >> (*amp).max(0)).max(1); match *effect { - "minecraft:poison" if *ticks % interval(25) == 0 && !m.kind.flags.undead && m.health > 1.0 => { + "minecraft:poison" + if *ticks % interval(25) == 0 && !m.kind.flags.undead && m.health > 1.0 => + { m.damage(1.0, Damage::of(DamageKind::Magic)); } "minecraft:wither" if *ticks % interval(40) == 0 => { m.damage(1.0, Damage::of(DamageKind::Magic)); } - "minecraft:regeneration" if *ticks % interval(50) == 0 && !m.kind.flags.undead && m.alive() => { + "minecraft:regeneration" + if *ticks % interval(50) == 0 && !m.kind.flags.undead && m.alive() => + { m.health = (m.health + 1.0).min(m.attrs.max_health); } _ => {} diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index 3f23d6ff4..ad0889f81 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -325,7 +325,9 @@ pub fn setup( ) { let _ = w_anims; match m.kind.anim { - Anim::Squid | Anim::Fish | Anim::Pufferfish | Anim::Dolphin => super::aquatic::anim(m, s, p), + Anim::Squid | Anim::Fish | Anim::Pufferfish | Anim::Dolphin => { + super::aquatic::anim(m, s, p) + } Anim::Quadruped | Anim::PolarBear | Anim::Panda | Anim::Goat => quadruped(p, s), Anim::Sheep => { quadruped(p, s); diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index 2b753d912..64b68c139 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -55,7 +55,13 @@ pub fn register(m: &mut Mob) { g.add(5, LookAtPlayer::new(6.0)); g.add(6, MeleeAttack::new(1.2, true)); m.ai.targets.add(1, HurtByTarget::new().alert()); - m.ai.mov.kind = MoveKind::SmoothSwimming { max_turn_x: 85.0, max_turn_y: 10.0, in_water: 0.02, outside: 0.1, gravity: true }; + m.ai.mov.kind = MoveKind::SmoothSwimming { + max_turn_x: 85.0, + max_turn_y: 10.0, + in_water: 0.02, + outside: 0.1, + gravity: true, + }; m.ai.look.kind = super::control::LookKind::SmoothSwimming(10.0); m.ai.nav.kind = NavKind::Water { breach: true }; m.air = 4800; @@ -106,7 +112,11 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { // AbstractFish.aiStep flops on land (applied before travel next tick). if !m.fluids.in_water && m.on_ground && m.vertical_collision_below { let (a, b) = (m.random.next_float(), m.random.next_float()); - m.velocity = Vec3::new(m.velocity.x + f64::from((a * 2.0 - 1.0) * 0.05), m.velocity.y + 0.4, m.velocity.z + f64::from((b * 2.0 - 1.0) * 0.05)); + m.velocity = Vec3::new( + m.velocity.x + f64::from((a * 2.0 - 1.0) * 0.05), + m.velocity.y + 0.4, + m.velocity.z + f64::from((b * 2.0 - 1.0) * 0.05), + ); m.on_ground = false; let flop = match m.species() { S::Cod => "entity.cod.flop", @@ -121,12 +131,21 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { if let Some(p) = &w.player && p.alive && !p.creative - && m.bounds().inflate(Vec3::new(0.3, 0.3, 0.3)).intersects(p.bounds) + && m.bounds() + .inflate(Vec3::new(0.3, 0.3, 0.3)) + .intersects(p.bounds) && m.ai.no_action_time % 10 == 0 { let amount = 1.0 + m.extra.size as f32; - events.push(MobEvent::AttackPlayer(amount, [m.position.x, m.position.y, m.position.z])); - events.push(MobEvent::EffectPlayer { effect: "minecraft:poison", ticks: 60 * m.extra.size, amplifier: 0 }); + events.push(MobEvent::AttackPlayer( + amount, + [m.position.x, m.position.y, m.position.z], + )); + events.push(MobEvent::EffectPlayer { + effect: "minecraft:poison", + ticks: 60 * m.extra.size, + amplifier: 0, + }); m.sound("entity.puffer_fish.sting", events); } } @@ -142,7 +161,11 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } if m.on_ground { let (a, b) = (m.random.next_float(), m.random.next_float()); - m.velocity = Vec3::new(m.velocity.x + f64::from((a * 2.0 - 1.0) * 0.2), m.velocity.y + 0.5, m.velocity.z + f64::from((b * 2.0 - 1.0) * 0.2)); + m.velocity = Vec3::new( + m.velocity.x + f64::from((a * 2.0 - 1.0) * 0.2), + m.velocity.y + 0.5, + m.velocity.z + f64::from((b * 2.0 - 1.0) * 0.2), + ); m.yaw = m.random.next_float() * 360.0; m.on_ground = false; } @@ -208,7 +231,11 @@ pub fn travel(m: &mut Mob, w: &MobWorld, input: Vec3, events: &mut Vec } // AbstractFish.travelInWater / Dolphin.travelInWater. S::Cod | S::Salmon | S::TropicalFish | S::Pufferfish | S::Dolphin if m.fluids.in_water => { - let speed = if m.species() == S::Dolphin { m.ai.speed } else { 0.01 }; + let speed = if m.species() == S::Dolphin { + m.ai.speed + } else { + 0.01 + }; m.move_relative(speed, input); m.do_move(w, events); m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9); @@ -222,7 +249,10 @@ pub fn travel(m: &mut Mob, w: &MobWorld, input: Vec3, events: &mut Vec } /// FishMoveControl.tick (fish use it instead of the default move control). pub fn fish_move_control(m: &mut Mob) { - if !matches!(m.species(), Species::Cod | Species::Salmon | Species::TropicalFish | Species::Pufferfish) { + if !matches!( + m.species(), + Species::Cod | Species::Salmon | Species::TropicalFish | Species::Pufferfish + ) { return; } if m.fluids.eye_in_water { @@ -261,10 +291,21 @@ impl Goal for SquidRandomMovement { fn tick(&mut self, m: &mut Mob, _: &mut Cx) { if m.ai.no_action_time > 100 { m.extra.vector = [0.0; 3]; - } else if m.random.next_int_bound(super::goals::reduced(50)).unwrap_or(1) == 0 || !m.fluids.in_water || m.extra.vector == [0.0; 3] { + } else if m + .random + .next_int_bound(super::goals::reduced(50)) + .unwrap_or(1) + == 0 + || !m.fluids.in_water + || m.extra.vector == [0.0; 3] + { let angle = m.random.next_float() * PI * 2.0; let y = -0.1 + m.random.next_float() * 0.2; - m.extra.vector = [f64::from(angle.cos() * 0.2), f64::from(y), f64::from(angle.sin() * 0.2)]; + m.extra.vector = [ + f64::from(angle.cos() * 0.2), + f64::from(y), + f64::from(angle.sin() * 0.2), + ]; } } } @@ -279,7 +320,9 @@ impl Goal for SquidFlee { 0 } fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - let Some(by) = m.ai.last_hurt_by.and_then(|w| cx.w.target_info(w)) else { return false }; + let Some(by) = m.ai.last_hurt_by.and_then(|w| cx.w.target_info(w)) else { + return false; + }; m.fluids.in_water && m.distance_sqr(by.position) < 100.0 } fn start(&mut self, _: &mut Mob, _: &mut Cx) { @@ -290,9 +333,19 @@ impl Goal for SquidFlee { } fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { self.ticks += 1; - let Some(by) = m.ai.last_hurt_by.and_then(|w| cx.w.target_info(w)) else { return }; - let mut f = [m.position.x - by.position.x, m.position.y - by.position.y, m.position.z - by.position.z]; - let at = [(m.position.x + f[0]).floor() as i32, (m.position.y + f[1]).floor() as i32, (m.position.z + f[2]).floor() as i32]; + let Some(by) = m.ai.last_hurt_by.and_then(|w| cx.w.target_info(w)) else { + return; + }; + let mut f = [ + m.position.x - by.position.x, + m.position.y - by.position.y, + m.position.z - by.position.z, + ]; + let at = [ + (m.position.x + f[0]).floor() as i32, + (m.position.y + f[1]).floor() as i32, + (m.position.z + f[2]).floor() as i32, + ]; let air = cx.w.facts.is_air(cx.w.world.block(at[0], at[1], at[2])); if cx.w.fluid(at[0], at[1], at[2]) == Fluid::Water || air { let length = (f[0] * f[0] + f[1] * f[1] + f[2] * f[2]).sqrt(); @@ -322,10 +375,26 @@ impl Goal for PufferfishPuff { } fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { let area = m.bounds().inflate(Vec3::new(2.0, 2.0, 2.0)); - let player = cx.w.player.as_ref().is_some_and(|p| p.alive && !p.creative && area.intersects(p.bounds)); + let player = + cx.w.player + .as_ref() + .is_some_and(|p| p.alive && !p.creative && area.intersects(p.bounds)); // TARGETING_CONDITIONS: not other fish (not_scary_for_pufferfish) and alive. let mob = cx.w.others.iter().any(|s| { - s.id != m.id && s.alive && !matches!(s.species, Species::Cod | Species::Salmon | Species::TropicalFish | Species::Pufferfish | Species::Squid | Species::GlowSquid | Species::Dolphin | Species::Axolotl) && area.intersects(s.bounds) + s.id != m.id + && s.alive + && !matches!( + s.species, + Species::Cod + | Species::Salmon + | Species::TropicalFish + | Species::Pufferfish + | Species::Squid + | Species::GlowSquid + | Species::Dolphin + | Species::Axolotl + ) + && area.intersects(s.bounds) }); player || mob } @@ -342,13 +411,37 @@ pub fn finalize(m: &mut Mob) { if m.species() == Species::TropicalFish { // TropicalFish.COMMON_VARIANTS: (pattern index, base colour, pattern colour). const COMMON: [(u8, u8, u8); 22] = [ - (7, 1, 7), (6, 7, 7), (6, 7, 11), (11, 0, 7), (1, 11, 7), (0, 1, 0), (5, 6, 3), (9, 10, 4), (11, 0, 14), (5, 0, 4), (8, 0, 7), - (11, 0, 1), (3, 9, 6), (4, 5, 3), (10, 14, 0), (2, 7, 14), (9, 14, 0), (6, 0, 4), (0, 14, 0), (1, 7, 0), (3, 9, 4), (6, 4, 4), + (7, 1, 7), + (6, 7, 7), + (6, 7, 11), + (11, 0, 7), + (1, 11, 7), + (0, 1, 0), + (5, 6, 3), + (9, 10, 4), + (11, 0, 14), + (5, 0, 4), + (8, 0, 7), + (11, 0, 1), + (3, 9, 6), + (4, 5, 3), + (10, 14, 0), + (2, 7, 14), + (9, 14, 0), + (6, 0, 4), + (0, 14, 0), + (1, 7, 0), + (3, 9, 4), + (6, 4, 4), ]; let (p, b, c) = if m.random.next_float() < 0.9 { COMMON[m.random.next_int_bound(COMMON.len() as i32).unwrap_or(0) as usize] } else { - (m.random.next_int_bound(12).unwrap_or(0) as u8, m.random.next_int_bound(16).unwrap_or(0) as u8, m.random.next_int_bound(16).unwrap_or(0) as u8) + ( + m.random.next_int_bound(12).unwrap_or(0) as u8, + m.random.next_int_bound(16).unwrap_or(0) as u8, + m.random.next_int_bound(16).unwrap_or(0) as u8, + ) }; m.extra.variant = p; m.extra.variant2 = b; @@ -369,7 +462,11 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { S::Cod => p.yrot("tail_fin", -amp * 0.45 * (0.6 * s.age).sin()), S::TropicalFish => p.yrot("tail", -amp * 0.45 * (0.6 * s.age).sin()), S::Salmon => { - let (a, k) = if m.fluids.in_water { (1.0, 1.0) } else { (1.3, 1.7) }; + let (a, k) = if m.fluids.in_water { + (1.0, 1.0) + } else { + (1.3, 1.7) + }; p.yrot("body_back", -a * 0.25 * (k * 0.6 * s.age).sin()); } S::Pufferfish => { @@ -405,23 +502,42 @@ pub fn rotations(m: &Mob, alpha: f32, body: f32) -> Option { let x = m.anim.lerp(X_BODY_ROT, alpha); let z = m.anim.lerp(Z_BODY_ROT, alpha); Some( - glam::Mat4::from_translation(glam::Vec3::new(0.0, if baby { 0.25 } else { 0.5 }, 0.0)) - * glam::Mat4::from_rotation_y((180.0 - body).to_radians()) + glam::Mat4::from_translation(glam::Vec3::new( + 0.0, + if baby { 0.25 } else { 0.5 }, + 0.0, + )) * glam::Mat4::from_rotation_y((180.0 - body).to_radians()) * glam::Mat4::from_rotation_x(x.to_radians()) * glam::Mat4::from_rotation_y(z.to_radians()) - * glam::Mat4::from_translation(glam::Vec3::new(0.0, if baby { -0.6 } else { -1.2 }, 0.0)), + * glam::Mat4::from_translation(glam::Vec3::new( + 0.0, + if baby { -0.6 } else { -1.2 }, + 0.0, + )), ) } S::Cod | S::Salmon | S::TropicalFish => { - let (a, k) = if m.species() == S::Salmon && !m.fluids.in_water { (1.3, 1.7) } else { (1.0, 1.0) }; - let mut t = glam::Mat4::from_rotation_y((180.0 - body).to_radians()) * glam::Mat4::from_rotation_y((a * 4.3 * (k * 0.6 * age).sin()).to_radians()); + let (a, k) = if m.species() == S::Salmon && !m.fluids.in_water { + (1.3, 1.7) + } else { + (1.0, 1.0) + }; + let mut t = glam::Mat4::from_rotation_y((180.0 - body).to_radians()) + * glam::Mat4::from_rotation_y((a * 4.3 * (k * 0.6 * age).sin()).to_radians()); if !m.fluids.in_water { - let off = if m.species() == S::Cod { glam::Vec3::new(0.1, 0.1, -0.1) } else { glam::Vec3::new(0.2, 0.1, 0.0) }; + let off = if m.species() == S::Cod { + glam::Vec3::new(0.1, 0.1, -0.1) + } else { + glam::Vec3::new(0.2, 0.1, 0.0) + }; t *= glam::Mat4::from_translation(off) * glam::Mat4::from_rotation_z(PI / 2.0); } Some(t) } - S::Pufferfish => Some(glam::Mat4::from_translation(glam::Vec3::new(0.0, (age * 0.05).cos() * 0.08, 0.0)) * glam::Mat4::from_rotation_y((180.0 - body).to_radians())), + S::Pufferfish => Some( + glam::Mat4::from_translation(glam::Vec3::new(0.0, (age * 0.05).cos() * 0.08, 0.0)) + * glam::Mat4::from_rotation_y((180.0 - body).to_radians()), + ), _ => None, } } diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index c030ecd87..021de51c5 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -559,7 +559,10 @@ impl Stroll { } /// RandomSwimmingGoal(speed, interval) pub fn swimming(speed: f64, interval: i32) -> Self { - Self { swim: true, ..Self::new(speed).interval(interval) } + Self { + swim: true, + ..Self::new(speed).interval(interval) + } } } impl Goal for Stroll { @@ -591,7 +594,11 @@ impl Goal for Stroll { let mut p = m.default_random_pos(cx.w, 10, 7); let mut count = 0; while let Some(q) = p { - let s = cx.w.world.block(q[0].floor() as i32, q[1].floor() as i32, q[2].floor() as i32); + let s = cx.w.world.block( + q[0].floor() as i32, + q[1].floor() as i32, + q[2].floor() as i32, + ); if cx.w.data.state(s).flags & super::data::WATER != 0 || count >= 10 { break; } @@ -1662,18 +1669,28 @@ impl Goal for EatBlock { pub struct BreathAir; impl BreathAir { fn find_air(m: &mut Mob, cx: &mut Cx) { - let (x, y, z) = (m.position.x.floor() as i32, m.position.y.floor() as i32, m.position.z.floor() as i32); + let (x, y, z) = ( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); let mut dest = None; for yy in y..=y + 8 { let s = cx.w.world.block(x, yy, z); let f = cx.w.facts.get(s); - if (f.fluid == crate::blocks::Fluid::None || &*f.name == "minecraft:bubble_column") && cx.w.data.state(s).flags & super::data::LAND != 0 { + if (f.fluid == crate::blocks::Fluid::None || &*f.name == "minecraft:bubble_column") + && cx.w.data.state(s).flags & super::data::LAND != 0 + { dest = Some([x, yy, z]); break; } } let d = dest.unwrap_or([x, (m.position.y + 8.0).floor() as i32, z]); - m.nav_move_to(cx.w, [f64::from(d[0]), f64::from(d[1] + 1), f64::from(d[2])], 1.0); + m.nav_move_to( + cx.w, + [f64::from(d[0]), f64::from(d[1] + 1), f64::from(d[2])], + 1.0, + ); } } impl Goal for BreathAir { @@ -1693,7 +1710,11 @@ impl Goal for BreathAir { } fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { Self::find_air(m, cx); - let input = Vec3::new(f64::from(m.ai.xxa), f64::from(m.ai.yya), f64::from(m.ai.zza)); + let input = Vec3::new( + f64::from(m.ai.xxa), + f64::from(m.ai.yya), + f64::from(m.ai.zza), + ); m.move_relative(0.02, input); let mut ev = Vec::new(); m.do_move(cx.w, &mut ev); @@ -1714,9 +1735,17 @@ impl Goal for TryFindWater { if !m.on_ground || m.fluids.in_water { return false; } - let (bx, by, bz) = (m.position.x.floor() as i32, m.position.y.floor() as i32, m.position.z.floor() as i32); + let (bx, by, bz) = ( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); for _ in 0..10 { - let p = [bx + m.random.next_int_bound(20).unwrap_or(0) - 10, by + 2 - m.random.next_int_bound(8).unwrap_or(0), bz + m.random.next_int_bound(20).unwrap_or(0) - 10]; + let p = [ + bx + m.random.next_int_bound(20).unwrap_or(0) - 10, + by + 2 - m.random.next_int_bound(8).unwrap_or(0), + bz + m.random.next_int_bound(20).unwrap_or(0) - 10, + ]; if cx.w.fluid(p[0], p[1], p[2]) == crate::blocks::Fluid::Water { self.wanted = [f64::from(p[0]), f64::from(p[1]), f64::from(p[2])]; return true; diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 45c1f4406..b9d4b7aef 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -193,9 +193,18 @@ pub fn body(m: &Mob) -> (String, String) { "entity/strider/strider" }), ), - S::Squid => (baby_or(m, "squid#main", "squid_baby#main"), b("entity/squid/squid")), - S::GlowSquid => (baby_or(m, "glow_squid#main", "glow_squid_baby#main"), b("entity/squid/glow_squid")), - S::Dolphin => (baby_or(m, "dolphin#main", "dolphin_baby#main"), b("entity/dolphin/dolphin")), + S::Squid => ( + baby_or(m, "squid#main", "squid_baby#main"), + b("entity/squid/squid"), + ), + S::GlowSquid => ( + baby_or(m, "glow_squid#main", "glow_squid_baby#main"), + b("entity/squid/glow_squid"), + ), + S::Dolphin => ( + baby_or(m, "dolphin#main", "dolphin_baby#main"), + b("entity/dolphin/dolphin"), + ), S::Pufferfish => { let model = match m.extra.size { 0 => "pufferfish_small#main", @@ -206,9 +215,15 @@ pub fn body(m: &Mob) -> (String, String) { } S::TropicalFish => { if m.extra.variant < 6 { - ("tropical_fish_small#main".into(), "entity/fish/tropical_a".into()) + ( + "tropical_fish_small#main".into(), + "entity/fish/tropical_a".into(), + ) } else { - ("tropical_fish_large#main".into(), "entity/fish/tropical_b".into()) + ( + "tropical_fish_large#main".into(), + "entity/fish/tropical_b".into(), + ) } } _ => (m.kind.model_key(), m.kind.texture.clone()), @@ -321,8 +336,18 @@ pub fn layers(m: &Mob) -> Vec { S::Creeper if m.extra.charged => {} S::TropicalFish => { // TropicalFishPatternLayer: the pattern tinted with the pattern colour. - let (model, letter, n) = if m.extra.variant < 6 { ("tropical_fish_small#pattern", "a", m.extra.variant + 1) } else { ("tropical_fish_large#pattern", "b", m.extra.variant - 5) }; - push(&mut v, model, &format!("entity/fish/tropical_{letter}_pattern_{n}"), abgr(DYE[m.extra.variant3 as usize & 15]), false); + let (model, letter, n) = if m.extra.variant < 6 { + ("tropical_fish_small#pattern", "a", m.extra.variant + 1) + } else { + ("tropical_fish_large#pattern", "b", m.extra.variant - 5) + }; + push( + &mut v, + model, + &format!("entity/fish/tropical_{letter}_pattern_{n}"), + abgr(DYE[m.extra.variant3 as usize & 15]), + false, + ); } S::Villager | S::ZombieVillager => { let base = if m.species() == S::Villager { @@ -539,19 +564,32 @@ pub fn render_single( } /// The transform of a named part (ModelPart.translateAndRotate down the tree). -pub fn part_matrix(part: &Part, parent: glam::Mat4, poses: &Poses, name: &str, x_offset: f32) -> Option { +pub fn part_matrix( + part: &Part, + parent: glam::Mat4, + poses: &Poses, + name: &str, + x_offset: f32, +) -> Option { let mut p = poses.pose(part); if part.name == name { p[0] += x_offset; } let m = parent * glam::Mat4::from_translation(glam::Vec3::new(p[0], p[1], p[2]) / 16.0) - * glam::Mat4::from_quat(glam::Quat::from_euler(glam::EulerRot::ZYX, p[5], p[4], p[3])) + * glam::Mat4::from_quat(glam::Quat::from_euler( + glam::EulerRot::ZYX, + p[5], + p[4], + p[3], + )) * glam::Mat4::from_scale(glam::Vec3::new(p[6], p[7], p[8])); if part.name == name { return Some(m); } - part.children.iter().find_map(|c| part_matrix(c, m, poses, name, x_offset)) + part.children + .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]) { @@ -560,9 +598,26 @@ fn item_display(item: &str) -> ([f32; 3], [f32; 3], [f32; 3]) { ([-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" { + } 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)) { + } 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]) @@ -573,7 +628,13 @@ 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 }; + 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 { @@ -582,23 +643,59 @@ fn item_sprite(m: &Mob, item: &str) -> String { format!("item/{name}") } /// 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) { - let skeleton = matches!(m.species(), Species::Skeleton | Species::Stray | Species::Bogged | Species::WitherSkeleton); +fn held_items( + m: &Mob, + model: &Part, + base: glam::Mat4, + poses: &Poses, + atlas: Atlas, + light: u32, + out: &mut Vec, +) { + let skeleton = matches!( + m.species(), + Species::Skeleton | Species::Stray | Species::Bogged | Species::WitherSkeleton + ); for (item, left) in [(&m.extra.main_hand, false), (&m.extra.off_hand, true)] { let Some(item) = item else { continue }; let arm = if left { "left_arm" } else { "right_arm" }; - let offset = if skeleton { if left { -1.0 } else { 1.0 } } else { 0.0 }; - let Some(mut t) = part_matrix(model, base, poses, arm, offset) else { continue }; - let Some(uv) = atlas(&item_sprite(m, item)) else { continue }; + let offset = if skeleton { + if left { -1.0 } else { 1.0 } + } else { + 0.0 + }; + let Some(mut t) = part_matrix(model, base, poses, arm, offset) else { + continue; + }; + let Some(uv) = atlas(&item_sprite(m, item)) else { + continue; + }; let baby = m.is_baby(); - let (ox, oy, oz) = if baby { (0.0, 1.0, -4.5) } else { (1.0, 2.0, -10.0) }; + let (ox, oy, oz) = if baby { + (0.0, 1.0, -4.5) + } else { + (1.0, 2.0, -10.0) + }; t *= glam::Mat4::from_rotation_x((-90.0f32).to_radians()) * glam::Mat4::from_rotation_y(PI); - t *= glam::Mat4::from_translation(glam::Vec3::new(if left { -ox } else { ox } / 16.0, oy / 16.0, oz / 16.0)); + t *= glam::Mat4::from_translation(glam::Vec3::new( + if left { -ox } else { ox } / 16.0, + oy / 16.0, + oz / 16.0, + )); // 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]) }; + 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_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)); draw_item_plane(t, uv, light, out); @@ -610,13 +707,29 @@ pub fn draw_item_plane(t: glam::Mat4, uv: [f32; 4], light: u32, out: &mut Vec 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" + (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, diff --git a/crates/horizon-client/src/models/cube.rs b/crates/horizon-client/src/models/cube.rs index fddce73dd..f186008f9 100644 --- a/crates/horizon-client/src/models/cube.rs +++ b/crates/horizon-client/src/models/cube.rs @@ -27,7 +27,11 @@ pub fn cube_styles(faces: &[BakedFace]) -> Option<[CubeStyle; 6]> { } let mut styles = [None; 6]; for face in faces { - if !face.opaque || face.translucent || face.quad.tint_index != -1 || face.quad.light_emission != 0 { + if !face.opaque + || face.translucent + || face.quad.tint_index != -1 + || face.quad.light_emission != 0 + { return None; } let q = &face.quad; diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 948dbf49d..4d8c9f94b 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -234,11 +234,22 @@ impl PlayerMotion { } /// Add (or remove) a transient attribute modifier, e.g. from equipment /// (`LivingEntity.collectEquipmentChanges` applying item modifiers). - pub fn set_modifier(&mut self, attribute: &str, id: &str, amount: f64, operation: &str, present: bool) -> Result<()> { + pub fn set_modifier( + &mut self, + attribute: &str, + id: &str, + amount: f64, + operation: &str, + present: bool, + ) -> Result<()> { let Some(key) = self.attributes.key(attribute) else { return Ok(()); }; - let Some(handle) = self.attributes.get_instance(Some(key)).map_err(attribute_error)? else { + let Some(handle) = self + .attributes + .get_instance(Some(key)) + .map_err(attribute_error)? + else { return Ok(()); }; let operation = match operation { @@ -976,7 +987,10 @@ impl LivingMotionWorld for MotionWorld<'_, '_, '_> { Ok(self.player.status.jump_boost.is_some()) } fn jump_boost_amplifier(&mut self) -> Result { - self.player.status.jump_boost.ok_or_else(|| "absent jump boost".into()) + self.player + .status + .jump_boost + .ok_or_else(|| "absent jump boost".into()) } fn sprinting(&mut self) -> Result { Ok(self.player.sprinting) diff --git a/crates/horizon-client/src/multiplayer.rs b/crates/horizon-client/src/multiplayer.rs index 5072f616f..8e2ef5c64 100644 --- a/crates/horizon-client/src/multiplayer.rs +++ b/crates/horizon-client/src/multiplayer.rs @@ -15,18 +15,36 @@ use std::{ #[derive(Clone, Debug)] pub enum Ping { Pinging, - Ok { motd: String, players: String, ms: u128, version: String }, + Ok { + motd: String, + players: String, + ms: u128, + version: String, + }, Failed(String), } type Pings = Arc>>; #[derive(Clone, Debug)] pub enum Screen { - List { servers: Vec, selected: Option, pings: Pings }, + List { + servers: Vec, + selected: Option, + pings: Pings, + }, /// Add (index None) or edit a server entry. - Edit { index: Option, name: String, address: String, focus: u8 }, - Direct { address: String }, - Disconnected { reason: String }, + Edit { + index: Option, + name: String, + address: String, + focus: u8, + }, + Direct { + address: String, + }, + Disconnected { + reason: String, + }, } /// What a click asks the title screen to do. pub enum Outcome { @@ -38,26 +56,39 @@ pub enum Outcome { pub type ButtonSpec = (f32, f32, f32, String, bool, u8); pub fn servers_file(saves: &Path) -> PathBuf { - saves.parent().map_or_else(|| PathBuf::from("servers.dat"), |p| p.join("servers.dat")) + saves + .parent() + .map_or_else(|| PathBuf::from("servers.dat"), |p| p.join("servers.dat")) } fn ping_all(servers: &[ServerEntry], pings: &Pings) { for s in servers { let address = s.ip.clone(); pings.lock().unwrap().insert(address.clone(), Ping::Pinging); let pings = pings.clone(); - let _ = std::thread::Builder::new().name("horizon-ping".into()).spawn(move || { - let result = match crate::net::ping(&address, Duration::from_secs(5)) { - Ok((json, ms)) => { - let lang = Default::default(); - let motd = crate::net::json_text(&json["description"], &lang); - let players = format!("{}/{}", json["players"]["online"].as_i64().unwrap_or(0), json["players"]["max"].as_i64().unwrap_or(0)); - let version = json["version"]["name"].as_str().unwrap_or("?").to_owned(); - Ping::Ok { motd, players, ms, version } - } - Err(e) => Ping::Failed(e), - }; - pings.lock().unwrap().insert(address, result); - }); + let _ = std::thread::Builder::new() + .name("horizon-ping".into()) + .spawn(move || { + let result = match crate::net::ping(&address, Duration::from_secs(5)) { + Ok((json, ms)) => { + let lang = Default::default(); + let motd = crate::net::json_text(&json["description"], &lang); + let players = format!( + "{}/{}", + json["players"]["online"].as_i64().unwrap_or(0), + json["players"]["max"].as_i64().unwrap_or(0) + ); + let version = json["version"]["name"].as_str().unwrap_or("?").to_owned(); + Ping::Ok { + motd, + players, + ms, + version, + } + } + Err(e) => Ping::Failed(e), + }; + pings.lock().unwrap().insert(address, result); + }); } } @@ -66,39 +97,152 @@ impl Screen { let servers = servers::load(&servers_file(saves)); let pings: Pings = Arc::default(); ping_all(&servers, &pings); - Self::List { servers, selected: None, pings } + Self::List { + servers, + selected: None, + pings, + } } pub fn buttons(&self, w: f32, h: f32) -> Vec { - let b = |x: f32, y: f32, bw: f32, label: &str, enabled: bool, id: u8| (x, y, bw, label.to_owned(), enabled, id); + let b = |x: f32, y: f32, bw: f32, label: &str, enabled: bool, id: u8| { + (x, y, bw, label.to_owned(), enabled, id) + }; match self { // JoinMultiplayerScreen's two button rows. Self::List { selected, .. } => vec![ - b(w / 2.0 - 154.0, h - 52.0, 100.0, "Join Server", selected.is_some(), 40), - b(w / 2.0 - 50.0, h - 52.0, 100.0, "Direct Connection", true, 41), + b( + w / 2.0 - 154.0, + h - 52.0, + 100.0, + "Join Server", + selected.is_some(), + 40, + ), + b( + w / 2.0 - 50.0, + h - 52.0, + 100.0, + "Direct Connection", + true, + 41, + ), b(w / 2.0 + 54.0, h - 52.0, 100.0, "Add Server", true, 42), - b(w / 2.0 - 154.0, h - 28.0, 74.0, "Edit", selected.is_some(), 43), - b(w / 2.0 - 76.0, h - 28.0, 74.0, "Delete", selected.is_some(), 44), + b( + w / 2.0 - 154.0, + h - 28.0, + 74.0, + "Edit", + selected.is_some(), + 43, + ), + b( + w / 2.0 - 76.0, + h - 28.0, + 74.0, + "Delete", + selected.is_some(), + 44, + ), b(w / 2.0 + 2.0, h - 28.0, 74.0, "Refresh", true, 45), b(w / 2.0 + 80.0, h - 28.0, 74.0, "Back", true, 46), ], Self::Edit { address, .. } => vec![ - b(w / 2.0 - 100.0, h / 4.0 + 96.0 + 18.0, 200.0, "Done", servers::parse_address(address).is_some(), 50), - b(w / 2.0 - 100.0, h / 4.0 + 120.0 + 18.0, 200.0, "Cancel", true, 51), + b( + w / 2.0 - 100.0, + h / 4.0 + 96.0 + 18.0, + 200.0, + "Done", + servers::parse_address(address).is_some(), + 50, + ), + b( + w / 2.0 - 100.0, + h / 4.0 + 120.0 + 18.0, + 200.0, + "Cancel", + true, + 51, + ), ], Self::Direct { address } => vec![ - b(w / 2.0 - 100.0, h / 4.0 + 96.0 + 12.0, 200.0, "Join Server", servers::parse_address(address).is_some(), 52), - b(w / 2.0 - 100.0, h / 4.0 + 120.0 + 12.0, 200.0, "Cancel", true, 53), + b( + w / 2.0 - 100.0, + h / 4.0 + 96.0 + 12.0, + 200.0, + "Join Server", + servers::parse_address(address).is_some(), + 52, + ), + b( + w / 2.0 - 100.0, + h / 4.0 + 120.0 + 12.0, + 200.0, + "Cancel", + true, + 53, + ), ], - Self::Disconnected { .. } => vec![b(w / 2.0 - 100.0, h / 2.0 + 30.0, 200.0, "Back to Server List", true, 54)], + Self::Disconnected { .. } => vec![b( + w / 2.0 - 100.0, + h / 2.0 + 30.0, + 200.0, + "Back to Server List", + true, + 54, + )], } } - fn field(atlas: &HudAtlas, batch: &mut HudBatch, label: &str, value: &str, y: f32, focused: bool, blink: bool) { + fn field( + atlas: &HudAtlas, + batch: &mut HudBatch, + label: &str, + value: &str, + y: f32, + focused: bool, + blink: bool, + ) { let w = batch.width; - batch.text(atlas, label, w / 2.0 - 100.0, y, rgba(160, 160, 160, 255), true); - batch.fill(atlas, w / 2.0 - 100.0, y + 11.0, 200.0, 20.0, if focused { u32::MAX } else { rgba(160, 160, 160, 255) }); - batch.fill(atlas, w / 2.0 - 99.0, y + 12.0, 198.0, 18.0, rgba(0, 0, 0, 255)); - let shown = if focused && blink { format!("{value}_") } else { value.to_owned() }; - batch.text(atlas, &shown, w / 2.0 - 96.0, y + 17.0, rgba(224, 224, 224, 255), true); + batch.text( + atlas, + label, + w / 2.0 - 100.0, + y, + rgba(160, 160, 160, 255), + true, + ); + batch.fill( + atlas, + w / 2.0 - 100.0, + y + 11.0, + 200.0, + 20.0, + if focused { + u32::MAX + } else { + rgba(160, 160, 160, 255) + }, + ); + batch.fill( + atlas, + w / 2.0 - 99.0, + y + 12.0, + 198.0, + 18.0, + rgba(0, 0, 0, 255), + ); + let shown = if focused && blink { + format!("{value}_") + } else { + value.to_owned() + }; + batch.text( + atlas, + &shown, + w / 2.0 - 96.0, + y + 17.0, + rgba(224, 224, 224, 255), + true, + ); } pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, blink: bool) { let (w, h) = (batch.width, batch.height); @@ -108,7 +252,11 @@ impl Screen { batch.text(atlas, text, (w - tw) / 2.0, y, color, true); }; match self { - Self::List { servers, selected, pings } => { + Self::List { + servers, + selected, + pings, + } => { centered(batch, "Play Multiplayer", 8.0, u32::MAX); batch.fill(atlas, 0.0, 32.0, w, h - 32.0 - 64.0, rgba(0, 0, 0, 100)); let pings = pings.lock().unwrap(); @@ -119,60 +267,174 @@ impl Screen { } let x = w / 2.0 - 152.0; if *selected == Some(i) { - batch.fill(atlas, x - 2.0, y - 2.0, 306.0, 36.0, rgba(128, 128, 128, 255)); + batch.fill( + atlas, + x - 2.0, + y - 2.0, + 306.0, + 36.0, + rgba(128, 128, 128, 255), + ); batch.fill(atlas, x - 1.0, y - 1.0, 304.0, 34.0, rgba(0, 0, 0, 255)); } batch.sprite_scaled(atlas, "misc/unknown_server", x, y, 32.0, 32.0, u32::MAX); batch.text(atlas, &server.name, x + 35.0, y + 1.0, u32::MAX, false); let (line, right, color) = match pings.get(&server.ip) { - Some(Ping::Ok { motd, players, ms, .. }) => (motd.lines().next().unwrap_or("").to_owned(), format!("{players} {ms} ms"), rgba(128, 128, 128, 255)), - Some(Ping::Failed(_)) => ("Can't connect to server".to_owned(), String::new(), rgba(170, 0, 0, 255)), - _ => ("Pinging...".to_owned(), String::new(), rgba(128, 128, 128, 255)), + Some(Ping::Ok { + motd, players, ms, .. + }) => ( + motd.lines().next().unwrap_or("").to_owned(), + format!("{players} {ms} ms"), + rgba(128, 128, 128, 255), + ), + Some(Ping::Failed(_)) => ( + "Can't connect to server".to_owned(), + String::new(), + rgba(170, 0, 0, 255), + ), + _ => ( + "Pinging...".to_owned(), + String::new(), + rgba(128, 128, 128, 255), + ), }; batch.text(atlas, &line, x + 35.0, y + 12.0, color, false); - batch.text(atlas, &server.ip, x + 35.0, y + 22.0, rgba(96, 96, 96, 255), false); + batch.text( + atlas, + &server.ip, + x + 35.0, + y + 22.0, + rgba(96, 96, 96, 255), + false, + ); if !right.is_empty() { let tw = HudBatch::text_width(atlas, &right); - batch.text(atlas, &right, x + 300.0 - tw, y + 1.0, rgba(128, 128, 128, 255), false); + batch.text( + atlas, + &right, + x + 300.0 - tw, + y + 1.0, + rgba(128, 128, 128, 255), + false, + ); } } if servers.is_empty() { - centered(batch, "No servers yet: add one or use Direct Connection", h / 2.0 - 20.0, rgba(160, 160, 160, 255)); + centered( + batch, + "No servers yet: add one or use Direct Connection", + h / 2.0 - 20.0, + rgba(160, 160, 160, 255), + ); } } - Self::Edit { index, name, address, focus } => { - centered(batch, if index.is_some() { "Edit Server Info" } else { "Add Server" }, 17.0, u32::MAX); + Self::Edit { + index, + name, + address, + focus, + } => { + centered( + batch, + if index.is_some() { + "Edit Server Info" + } else { + "Add Server" + }, + 17.0, + u32::MAX, + ); Self::field(atlas, batch, "Server Name", name, 53.0, *focus == 0, blink); - Self::field(atlas, batch, "Server Address", address, 94.0, *focus == 1, blink); + Self::field( + atlas, + batch, + "Server Address", + address, + 94.0, + *focus == 1, + blink, + ); } Self::Direct { address } => { centered(batch, "Direct Connection", 20.0, u32::MAX); - Self::field(atlas, batch, "Server Address", address, 100.0 - 11.0, true, blink); + Self::field( + atlas, + batch, + "Server Address", + address, + 100.0 - 11.0, + true, + blink, + ); } Self::Disconnected { reason } => { - centered(batch, "Connection Lost", h / 2.0 - 40.0, rgba(170, 170, 170, 255)); + centered( + batch, + "Connection Lost", + h / 2.0 - 40.0, + rgba(170, 170, 170, 255), + ); for (i, line) in wrap(reason, 300.0, atlas).iter().enumerate() { centered(batch, line, h / 2.0 - 16.0 + i as f32 * 9.0, u32::MAX); } } } } - pub fn click(&mut self, id: Option, x: f32, y: f32, size: (f32, f32), saves: &Path) -> Outcome { + pub fn click( + &mut self, + id: Option, + x: f32, + y: f32, + size: (f32, f32), + saves: &Path, + ) -> Outcome { let (w, h) = size; match (&mut *self, id) { - (Self::List { servers, selected, .. }, Some(40)) => { + ( + Self::List { + servers, selected, .. + }, + Some(40), + ) => { if let Some(s) = selected.and_then(|i| servers.get(i)) { return Outcome::Connect(s.ip.clone()); } } - (Self::List { .. }, Some(41)) => *self = Self::Direct { address: String::new() }, - (Self::List { .. }, Some(42)) => *self = Self::Edit { index: None, name: "Minecraft Server".into(), address: String::new(), focus: 1 }, - (Self::List { servers, selected, .. }, Some(43)) => { - if let Some((i, s)) = selected.and_then(|i| servers.get(i).map(|s| (i, s.clone()))) { - *self = Self::Edit { index: Some(i), name: s.name, address: s.ip, focus: 0 }; + (Self::List { .. }, Some(41)) => { + *self = Self::Direct { + address: String::new(), } } - (Self::List { servers, selected, .. }, Some(44)) => { + (Self::List { .. }, Some(42)) => { + *self = Self::Edit { + index: None, + name: "Minecraft Server".into(), + address: String::new(), + focus: 1, + } + } + ( + Self::List { + servers, selected, .. + }, + Some(43), + ) => { + if let Some((i, s)) = selected.and_then(|i| servers.get(i).map(|s| (i, s.clone()))) + { + *self = Self::Edit { + index: Some(i), + name: s.name, + address: s.ip, + focus: 0, + }; + } + } + ( + Self::List { + servers, selected, .. + }, + Some(44), + ) => { if let Some(i) = selected.take() && i < servers.len() { @@ -182,9 +444,18 @@ impl Screen { } (Self::List { .. }, Some(45)) => *self = Self::list(saves), (Self::List { .. }, Some(46)) => return Outcome::Back, - (Self::List { servers, selected, .. }, None) => { + ( + Self::List { + servers, selected, .. + }, + None, + ) => { let index = ((y - 36.0) / 36.0).floor(); - if y >= 36.0 && y < h - 64.0 && (x - w / 2.0).abs() < 154.0 && (index as usize) < servers.len() { + if y >= 36.0 + && y < h - 64.0 + && (x - w / 2.0).abs() < 154.0 + && (index as usize) < servers.len() + { let index = index as usize; if *selected == Some(index) { return Outcome::Connect(servers[index].ip.clone()); @@ -192,7 +463,15 @@ impl Screen { *selected = Some(index); } } - (Self::Edit { index, name, address, .. }, Some(50)) => { + ( + Self::Edit { + index, + name, + address, + .. + }, + Some(50), + ) => { let mut list = servers::load(&servers_file(saves)); let entry = ServerEntry::new(name.trim(), address.trim()); match index.and_then(|i| list.get_mut(i)) { @@ -205,8 +484,13 @@ impl Screen { let _ = servers::save(&servers_file(saves), &list); *self = Self::list(saves); } - (Self::Edit { .. } | Self::Direct { .. } | Self::Disconnected { .. }, Some(51 | 53 | 54)) => *self = Self::list(saves), - (Self::Direct { address }, Some(52)) => return Outcome::Connect(address.trim().to_owned()), + ( + Self::Edit { .. } | Self::Direct { .. } | Self::Disconnected { .. }, + Some(51 | 53 | 54), + ) => *self = Self::list(saves), + (Self::Direct { address }, Some(52)) => { + return Outcome::Connect(address.trim().to_owned()); + } (Self::Edit { focus, .. }, None) => { for (i, fy) in [(0u8, 53.0 + 11.0), (1, 94.0 + 11.0)] { if y >= fy && y < fy + 20.0 && (x - w / 2.0).abs() < 100.0 { @@ -220,7 +504,12 @@ impl Screen { } fn focused_field(&mut self) -> Option<&mut String> { match self { - Self::Edit { name, address, focus, .. } => Some(if *focus == 0 { name } else { address }), + Self::Edit { + name, + address, + focus, + .. + } => Some(if *focus == 0 { name } else { address }), Self::Direct { address } => Some(address), _ => None, } @@ -262,7 +551,11 @@ pub fn wrap(text: &str, width: f32, atlas: &HudAtlas) -> Vec { for paragraph in text.lines() { let mut line = String::new(); for word in paragraph.split(' ') { - let candidate = if line.is_empty() { word.to_owned() } else { format!("{line} {word}") }; + let candidate = if line.is_empty() { + word.to_owned() + } else { + format!("{line} {word}") + }; if HudBatch::text_width(atlas, &candidate) > width && !line.is_empty() { lines.push(std::mem::take(&mut line)); line = word.to_owned(); diff --git a/crates/horizon-client/src/music.rs b/crates/horizon-client/src/music.rs index 5dfec1571..ebc86ac44 100644 --- a/crates/horizon-client/src/music.rs +++ b/crates/horizon-client/src/music.rs @@ -16,7 +16,12 @@ pub struct Music { } impl Music { fn new(sound: &str, min_delay: i32, max_delay: i32, replace_current_music: bool) -> Self { - Self { sound: sound.to_owned(), min_delay, max_delay, replace_current_music } + Self { + sound: sound.to_owned(), + min_delay, + max_delay, + replace_current_music, + } } /// `Musics.MENU`. pub fn menu() -> Self { @@ -34,7 +39,12 @@ impl Music { fn parse(v: &Value) -> Option { let sound = v["sound"].as_str()?; let int = |k: &str| v[k].as_i64().unwrap_or(0) as i32; - Some(Self::new(sound, int("min_delay"), int("max_delay"), v["replace_current_music"].as_bool().unwrap_or(false))) + Some(Self::new( + sound, + int("min_delay"), + int("max_delay"), + v["replace_current_music"].as_bool().unwrap_or(false), + )) } } /// `BackgroundMusic`: the attribute value. @@ -74,7 +84,9 @@ impl Layer { let music = &attributes["minecraft:audio/background_music"]; Self { music: (!music.is_null()).then(|| BackgroundMusic::parse(music)), - volume: attributes["minecraft:audio/music_volume"].as_f64().map(|v| v.clamp(0.0, 1.0) as f32), + volume: attributes["minecraft:audio/music_volume"] + .as_f64() + .map(|v| v.clamp(0.0, 1.0) as f32), } } } @@ -87,7 +99,9 @@ pub struct MusicTables { impl MusicTables { pub fn load(root: &Path) -> Self { let read = |dir: &str| -> HashMap { - let Ok(entries) = fs::read_dir(root.join("data/minecraft").join(dir)) else { return HashMap::new() }; + let Ok(entries) = fs::read_dir(root.join("data/minecraft").join(dir)) else { + return HashMap::new(); + }; entries .flatten() .filter_map(|e| { @@ -98,7 +112,10 @@ impl MusicTables { }) .collect() }; - Self { dimensions: read("dimension_type"), biomes: read("worldgen/biome") } + Self { + dimensions: read("dimension_type"), + biomes: read("worldgen/biome"), + } } /// `EnvironmentAttributes.BACKGROUND_MUSIC` at a position. pub fn background(&self, dimension: &str, biome: &str) -> BackgroundMusic { @@ -141,7 +158,9 @@ impl MusicFrequency { } } fn next_song_delay(self, music: Option<&Music>, random: &mut LegacyRandom) -> i32 { - let Some(music) = music else { return self.max_frequency() }; + let Some(music) = music else { + return self.max_frequency(); + }; if self == Self::Constant { return 100; } @@ -152,7 +171,11 @@ impl MusicFrequency { } /// `Mth.nextInt(random, min, max)`: inclusive. fn next_int(random: &mut LegacyRandom, min: i32, max: i32) -> i32 { - if min >= max { min } else { random.next_int_bound(max - min + 1).unwrap_or(0) + min } + if min >= max { + min + } else { + 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 { @@ -189,7 +212,9 @@ pub struct MusicManager { 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); + let seed = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos() as i64); Self::new(seed) } } @@ -208,7 +233,13 @@ impl MusicManager { } /// `MusicManager.tick` with the situational music and music volume; /// `loading` holds back a new track (`LevelLoadingScreen`). - pub fn tick(&mut self, music: Option<&Music>, volume: f32, loading: bool, out: &mut impl MusicOutput) { + pub fn tick( + &mut self, + music: Option<&Music>, + volume: f32, + loading: bool, + out: &mut impl MusicOutput, + ) { if self.current.is_some() && self.current_gain != volume && !self.fade(volume, music, out) { return; } @@ -223,7 +254,9 @@ impl MusicManager { } if !out.is_active() { self.current = None; - let delay = self.frequency.next_song_delay(Some(music), &mut self.random); + let delay = self + .frequency + .next_song_delay(Some(music), &mut self.random); self.next_song_delay = self.next_song_delay.min(delay); } } @@ -248,10 +281,18 @@ impl MusicManager { if self.current.take().is_some() { out.stop(); } - self.next_song_delay = self.frequency.next_song_delay(situational, &mut self.random) + 100; + self.next_song_delay = self + .frequency + .next_song_delay(situational, &mut self.random) + + 100; } /// `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>, + out: &mut impl MusicOutput, + ) -> bool { if self.current.is_none() { return false; } diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs index 551fdac41..94bc7c701 100644 --- a/crates/horizon-client/src/net.rs +++ b/crates/horizon-client/src/net.rs @@ -27,7 +27,11 @@ pub enum Event { /// Progress text for the connecting screen. Status(String), /// Configuration finished: the play state begins with these registries. - Joined { registries: Arc, uuid: u128, name: String }, + Joined { + registries: Arc, + uuid: u128, + name: String, + }, Packet(Box), /// A packet that failed to decode (skipped, like vanilla's skippable packets). DecodeError(String), @@ -57,7 +61,15 @@ impl Session { let thread = std::thread::Builder::new() .name("horizon-net".into()) .spawn(move || { - let reason = match run(&address_owned, &name_owned, view_distance, &lang, &send, &thread_writer, &thread_counters) { + let reason = match run( + &address_owned, + &name_owned, + view_distance, + &lang, + &send, + &thread_writer, + &thread_counters, + ) { Ok(reason) => reason, Err(e) => e, }; @@ -68,7 +80,15 @@ impl Session { }) .ok(); let debug = std::env::var_os("HORIZON_NET_DEBUG").is_some(); - Self { events, writer, thread, address: address.to_owned(), name: name.to_owned(), counters, debug } + Self { + events, + writer, + thread, + address: address.to_owned(), + name: name.to_owned(), + counters, + debug, + } } /// Everything received since the last poll. pub fn poll(&self) -> Vec { @@ -76,7 +96,14 @@ impl Session { } /// Send a play packet; silently dropped once the connection is gone. pub fn send(&self, packet: play::Serverbound) { - if self.debug && !matches!(packet, play::Serverbound::ClientTickEnd(_) | play::Serverbound::MovePlayerPos(_) | play::Serverbound::MovePlayerPosRot(_)) { + if self.debug + && !matches!( + packet, + play::Serverbound::ClientTickEnd(_) + | play::Serverbound::MovePlayerPos(_) + | play::Serverbound::MovePlayerPosRot(_) + ) + { eprintln!("[net] -> {packet:?}"); } if let Some(w) = self.writer.lock().unwrap().as_mut() @@ -114,57 +141,106 @@ fn run( shared_writer: &Mutex>, shared_counters: &Mutex>>, ) -> Result { - let (host, port) = parse_address(address).ok_or_else(|| format!("Invalid server address: {address}"))?; + let (host, port) = + parse_address(address).ok_or_else(|| format!("Invalid server address: {address}"))?; status(send, "Connecting to the server..."); - let mut c = Connection::connect(&host, port, Duration::from_secs(10)).map_err(|e| e.to_string())?; + let mut c = + Connection::connect(&host, port, Duration::from_secs(10)).map_err(|e| e.to_string())?; *shared_counters.lock().unwrap() = Some(c.reader.counters.clone()); let e = |e: horizon_protocol::Error| e.to_string(); c.send( - &handshake::Serverbound::Intention(handshake::Intention { protocol: PROTOCOL_VERSION, host: host.clone(), port, intent: handshake::LOGIN }) - .encode(), + &handshake::Serverbound::Intention(handshake::Intention { + protocol: PROTOCOL_VERSION, + host: host.clone(), + port, + intent: handshake::LOGIN, + }) + .encode(), ) .map_err(e)?; status(send, "Logging in..."); let uuid = offline_uuid(name); - c.send(&login::Serverbound::Hello(login::ServerHello { name: name.to_owned(), uuid }).encode()).map_err(e)?; + c.send( + &login::Serverbound::Hello(login::ServerHello { + name: name.to_owned(), + uuid, + }) + .encode(), + ) + .map_err(e)?; let profile = loop { let (id, payload) = c.recv().map_err(e)?; match login::Clientbound::decode(id, &payload).map_err(e)? { login::Clientbound::Compression(p) => c.set_compression(p.threshold), login::Clientbound::LoginFinished(p) => { - c.send(&login::Serverbound::LoginAcknowledged(Empty).encode()).map_err(e)?; + c.send(&login::Serverbound::LoginAcknowledged(Empty).encode()) + .map_err(e)?; break p.profile; } login::Clientbound::Disconnect(p) => { - let reason = serde_json::from_str::(&p.reason_json).map(|v| json_text(&v, lang)).unwrap_or(p.reason_json); + let reason = serde_json::from_str::(&p.reason_json) + .map(|v| json_text(&v, lang)) + .unwrap_or(p.reason_json); return Err(reason); } login::Clientbound::Hello(_) => { return Err("This server is in online mode. Horizon only joins offline-mode servers (online-mode=false).".into()); } login::Clientbound::CustomQuery(q) => { - c.send(&login::Serverbound::CustomQueryAnswer(login::CustomQueryAnswer { transaction: q.transaction, payload: None }).encode()) - .map_err(e)?; + c.send( + &login::Serverbound::CustomQueryAnswer(login::CustomQueryAnswer { + transaction: q.transaction, + payload: None, + }) + .encode(), + ) + .map_err(e)?; } login::Clientbound::CookieRequest(q) => { - c.send(&login::Serverbound::CookieResponse(login::CookieResponse { key: q.key, payload: None }).encode()).map_err(e)?; + c.send( + &login::Serverbound::CookieResponse(login::CookieResponse { + key: q.key, + payload: None, + }) + .encode(), + ) + .map_err(e)?; } login::Clientbound::Unknown(..) => {} } }; status(send, "Joining world..."); - c.send(&cfg::Serverbound::ClientInformation(cfg::ClientInformation::new(view_distance)).encode()).map_err(e)?; - c.send(&cfg::Serverbound::CustomPayload(cfg::CustomPayload { channel: "minecraft:brand".into(), data: brand() }).encode()).map_err(e)?; + c.send( + &cfg::Serverbound::ClientInformation(cfg::ClientInformation::new(view_distance)).encode(), + ) + .map_err(e)?; + c.send( + &cfg::Serverbound::CustomPayload(cfg::CustomPayload { + channel: "minecraft:brand".into(), + data: brand(), + }) + .encode(), + ) + .map_err(e)?; let (mut reader, writer) = c.split(); *shared_writer.lock().unwrap() = Some(writer); let registries = configure(&mut reader, shared_writer, lang)?; - let _ = send.send(Event::Joined { registries: Arc::new(registries), uuid: profile.uuid, name: profile.name }); + let _ = send.send(Event::Joined { + registries: Arc::new(registries), + uuid: profile.uuid, + name: profile.name, + }); loop { let (id, payload) = reader.recv().map_err(e)?; let packet = match play::Clientbound::decode(id, &payload) { Ok(p) => p, Err(err) => { - let name = horizon_protocol::ids::name(horizon_protocol::State::Play, horizon_protocol::Direction::Clientbound, id).unwrap_or("?"); + let name = horizon_protocol::ids::name( + horizon_protocol::State::Play, + horizon_protocol::Direction::Clientbound, + id, + ) + .unwrap_or("?"); let _ = send.send(Event::DecodeError(format!("{name}: {err}"))); continue; } @@ -180,7 +256,10 @@ fn run( play::Clientbound::BundleDelimiter(_) => {} play::Clientbound::ResourcePackPush(p) => { // Declined: Horizon has no server resource packs. - reply(play::Serverbound::ResourcePack(cfg::ResourcePackResponse { id: p.id, action: 1 })); + reply(play::Serverbound::ResourcePack(cfg::ResourcePackResponse { + id: p.id, + action: 1, + })); } play::Clientbound::StartConfiguration(_) => { reply(play::Serverbound::ConfigurationAcknowledged(Empty)); @@ -199,7 +278,11 @@ fn run( /// The configuration phase: registries, tags and known packs until the /// server finishes it (ClientConfigurationPacketListenerImpl). -fn configure(reader: &mut ConnReader, writer: &Mutex>, lang: &Language) -> Result { +fn configure( + reader: &mut ConnReader, + writer: &Mutex>, + lang: &Language, +) -> Result { let mut registries = Dynamic::default(); let reply = |p: cfg::Serverbound| -> Result<(), String> { match writer.lock().unwrap().as_mut() { @@ -213,11 +296,27 @@ fn configure(reader: &mut ConnReader, writer: &Mutex>, lang: cfg::Clientbound::KeepAlive(k) => reply(cfg::Serverbound::KeepAlive(k))?, cfg::Clientbound::Ping(p) => reply(cfg::Serverbound::Pong(p))?, // Know no packs: the server then sends every registry entry in full. - cfg::Clientbound::SelectKnownPacks(_) => reply(cfg::Serverbound::SelectKnownPacks(cfg::SelectKnownPacks { packs: vec![] }))?, + cfg::Clientbound::SelectKnownPacks(_) => { + reply(cfg::Serverbound::SelectKnownPacks(cfg::SelectKnownPacks { + packs: vec![], + }))? + } cfg::Clientbound::RegistryData(r) => registries.add(r), - cfg::Clientbound::CodeOfConduct(_) => reply(cfg::Serverbound::AcceptCodeOfConduct(Empty))?, - cfg::Clientbound::ResourcePackPush(p) => reply(cfg::Serverbound::ResourcePack(cfg::ResourcePackResponse { id: p.id, action: 1 }))?, - cfg::Clientbound::CookieRequest(q) => reply(cfg::Serverbound::CookieResponse(cfg::CookieResponse { key: q.key, payload: None }))?, + cfg::Clientbound::CodeOfConduct(_) => { + reply(cfg::Serverbound::AcceptCodeOfConduct(Empty))? + } + cfg::Clientbound::ResourcePackPush(p) => { + reply(cfg::Serverbound::ResourcePack(cfg::ResourcePackResponse { + id: p.id, + action: 1, + }))? + } + cfg::Clientbound::CookieRequest(q) => { + reply(cfg::Serverbound::CookieResponse(cfg::CookieResponse { + key: q.key, + payload: None, + }))? + } cfg::Clientbound::Disconnect(d) => return Err(plain(&d.reason, lang)), cfg::Clientbound::FinishConfiguration(_) => { reply(cfg::Serverbound::FinishConfiguration(Empty))?; @@ -244,8 +343,20 @@ pub fn json_text(v: &serde_json::Value, lang: &Language) -> String { let mut out = if let Some(t) = o.get("text").and_then(|t| t.as_str()) { t.to_owned() } else if let Some(key) = o.get("translate").and_then(|t| t.as_str()) { - let args: Vec = o.get("with").and_then(|w| w.as_array()).map(|a| a.iter().map(|e| json_text(e, lang)).collect()).unwrap_or_default(); - let pattern = lang.get(key).cloned().or_else(|| o.get("fallback").and_then(|f| f.as_str()).map(str::to_owned)).unwrap_or_else(|| key.to_owned()); + let args: Vec = o + .get("with") + .and_then(|w| w.as_array()) + .map(|a| a.iter().map(|e| json_text(e, lang)).collect()) + .unwrap_or_default(); + let pattern = lang + .get(key) + .cloned() + .or_else(|| { + o.get("fallback") + .and_then(|f| f.as_str()) + .map(str::to_owned) + }) + .unwrap_or_else(|| key.to_owned()); horizon_protocol::text::format_java(&pattern, &args) } else { String::new() @@ -275,21 +386,32 @@ pub fn ping(address: &str, timeout: Duration) -> Result<(serde_json::Value, u128 use horizon_protocol::packets::status; let (host, port) = parse_address(address).ok_or("Invalid address")?; let mut c = Connection::connect(&host, port, timeout).map_err(|e| e.to_string())?; - c.reader.set_read_timeout(Some(timeout)).map_err(|e| e.to_string())?; + c.reader + .set_read_timeout(Some(timeout)) + .map_err(|e| e.to_string())?; let e = |e: horizon_protocol::Error| e.to_string(); c.send( - &handshake::Serverbound::Intention(handshake::Intention { protocol: PROTOCOL_VERSION, host: host.clone(), port, intent: handshake::STATUS }) - .encode(), + &handshake::Serverbound::Intention(handshake::Intention { + protocol: PROTOCOL_VERSION, + host: host.clone(), + port, + intent: handshake::STATUS, + }) + .encode(), ) .map_err(e)?; - c.send(&status::Serverbound::StatusRequest(Empty).encode()).map_err(e)?; + c.send(&status::Serverbound::StatusRequest(Empty).encode()) + .map_err(e)?; let (id, payload) = c.recv().map_err(e)?; let json = match status::Clientbound::decode(id, &payload).map_err(e)? { - status::Clientbound::StatusResponse(s) => serde_json::from_str(&s.json).map_err(|e| e.to_string())?, + status::Clientbound::StatusResponse(s) => { + serde_json::from_str(&s.json).map_err(|e| e.to_string())? + } _ => return Err("unexpected status reply".into()), }; let start = std::time::Instant::now(); - c.send(&status::Serverbound::PingRequest(status::Ping { time: 1 }).encode()).map_err(e)?; + c.send(&status::Serverbound::PingRequest(status::Ping { time: 1 }).encode()) + .map_err(e)?; let _ = c.recv().map_err(e)?; Ok((json, start.elapsed().as_millis())) } diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index eee11d3a1..68a85998e 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -73,13 +73,22 @@ fn generic(caption: &str, value: Text) -> Text { Text::translate("options.generic_value", &[tr(caption), value]) } fn percent(caption: &str, value: f32) -> Text { - Text::translate("options.percent_value", &[tr(caption), Text::literal(((f64::from(value) * 100.0) as i32).to_string())]) + Text::translate( + "options.percent_value", + &[ + tr(caption), + Text::literal(((f64::from(value) * 100.0) as i32).to_string()), + ], + ) } fn on_off(v: bool) -> Text { tr(if v { "options.on" } else { "options.off" }) } fn chat_px(caption: &str, px: f32) -> Text { - Text::translate("options.pixel_value", &[tr(caption), Text::literal((px as i32).to_string())]) + Text::translate( + "options.pixel_value", + &[tr(caption), Text::literal((px as i32).to_string())], + ) } enum Kind { /// Slider position 0..1. @@ -150,7 +159,11 @@ impl Opt { Opt::SimulationDistance => unit(s.simulation_distance as f32, 5.0, 32.0), Opt::Sensitivity => Kind::Slider(s.sensitivity), Opt::WheelSensitivity => unit(s.mouse_wheel_sensitivity, 0.01, 10.0), - Opt::Volume(i) => Kind::Slider(if i == 0 { s.master_volume } else { s.volumes[i] }), + Opt::Volume(i) => Kind::Slider(if i == 0 { + s.master_volume + } else { + s.volumes[i] + }), Opt::GuiScale => unit(s.gui_scale as f32, 0.0, 6.0), Opt::Gamma => Kind::Slider(s.gamma), Opt::MaxFps => unit(s.max_fps as f32, 10.0, 260.0), @@ -182,7 +195,9 @@ impl Opt { v => generic(c, Text::literal(v.to_string())), }, Opt::RenderDistance => generic(c, Text::tr("options.chunks", &[&s.render_distance])), - Opt::SimulationDistance => generic(c, Text::tr("options.chunks", &[&s.simulation_distance])), + Opt::SimulationDistance => { + generic(c, Text::tr("options.chunks", &[&s.simulation_distance])) + } Opt::Sensitivity => { if s.sensitivity == 0.0 { generic(c, tr("options.sensitivity.min")) @@ -192,11 +207,22 @@ impl Opt { percent(c, 2.0 * s.sensitivity) } } - Opt::WheelSensitivity => generic(c, Text::literal(format!("{:.2}", s.mouse_wheel_sensitivity))), + Opt::WheelSensitivity => generic( + c, + Text::literal(format!("{:.2}", s.mouse_wheel_sensitivity)), + ), Opt::Volume(i) => { - let v = if i == 0 { s.master_volume } else { s.volumes[i] }; + let v = if i == 0 { + s.master_volume + } else { + s.volumes[i] + }; let caption = format!("soundCategory.{}", SOUND_SOURCES[i]); - if v == 0.0 { generic(&caption, tr("options.off")) } else { percent(&caption, v) } + if v == 0.0 { + generic(&caption, tr("options.off")) + } else { + percent(&caption, v) + } } Opt::GuiScale => { if s.gui_scale == 0 { @@ -220,7 +246,13 @@ impl Opt { } Opt::CloudRange => generic(c, Text::tr("options.chunks", &[&s.cloud_range])), Opt::EntityDistance => percent(c, s.entity_distance), - Opt::BiomeBlend => generic(c, tr(&format!("options.biomeBlendRadius.{}", s.biome_blend * 2 + 1))), + Opt::BiomeBlend => generic( + c, + tr(&format!( + "options.biomeBlendRadius.{}", + s.biome_blend * 2 + 1 + )), + ), Opt::Preset => generic(c, tr(&format!("options.graphics.{}", s.graphics_preset))), Opt::Mipmaps => { if s.mipmap_levels == 0 { @@ -234,7 +266,10 @@ impl Opt { if s.chunk_fade <= 0.0 { tr("options.chunkFade.none") } else { - Text::tr("options.chunkFade.seconds", &[&format!("{:.2}", s.chunk_fade)]) + Text::tr( + "options.chunkFade.seconds", + &[&format!("{:.2}", s.chunk_fade)], + ) } } Opt::MenuBlur => { @@ -255,7 +290,9 @@ impl Opt { } Opt::ChatWidth => chat_px(c, (s.chat_width * 280.0 + 40.0).floor()), Opt::ChatHeightFocused => chat_px(c, (s.chat_height_focused * 160.0 + 20.0).floor()), - Opt::ChatHeightUnfocused => chat_px(c, (s.chat_height_unfocused * 160.0 + 20.0).floor()), + Opt::ChatHeightUnfocused => { + chat_px(c, (s.chat_height_unfocused * 160.0 + 20.0).floor()) + } Opt::ChatLineSpacing => percent(c, s.chat_line_spacing), _ => generic(c, self.value_text(s)), } @@ -273,19 +310,47 @@ impl Opt { "fast" => "options.clouds.fast", _ => "options.clouds.fancy", }), - Opt::Particles => tr(["options.particles.all", "options.particles.decreased", "options.particles.minimal"][usize::from(s.particles.min(2))]), + Opt::Particles => tr([ + "options.particles.all", + "options.particles.decreased", + "options.particles.minimal", + ][usize::from(s.particles.min(2))]), Opt::EntityShadows => on_off(s.entity_shadows), Opt::Vignette => on_off(s.vignette), Opt::Autosave => on_off(s.autosave_indicator), Opt::CutoutLeaves => on_off(s.cutout_leaves), Opt::ImprovedTransparency => on_off(s.improved_transparency), - Opt::AttackIndicator => tr(["options.off", "options.attack.crosshair", "options.attack.hotbar"][usize::from(s.attack_indicator.min(2))]), - Opt::InactivityFps => tr(if s.inactivity_fps_limit == "minimized" { "options.inactivityFpsLimit.minimized" } else { "options.inactivityFpsLimit.afk" }), - Opt::ChunkBuilder => tr(["options.prioritizeChunkUpdates.none", "options.prioritizeChunkUpdates.byPlayer", "options.prioritizeChunkUpdates.nearby"][usize::from(s.prioritize_chunk_updates.min(2))]), - Opt::ToggleCrouch => tr(if s.toggle_crouch { "options.key.toggle" } else { "options.key.hold" }), - Opt::ToggleSprint => tr(if s.toggle_sprint { "options.key.toggle" } else { "options.key.hold" }), + Opt::AttackIndicator => tr([ + "options.off", + "options.attack.crosshair", + "options.attack.hotbar", + ][usize::from(s.attack_indicator.min(2))]), + Opt::InactivityFps => tr(if s.inactivity_fps_limit == "minimized" { + "options.inactivityFpsLimit.minimized" + } else { + "options.inactivityFpsLimit.afk" + }), + Opt::ChunkBuilder => tr([ + "options.prioritizeChunkUpdates.none", + "options.prioritizeChunkUpdates.byPlayer", + "options.prioritizeChunkUpdates.nearby", + ][usize::from(s.prioritize_chunk_updates.min(2))]), + Opt::ToggleCrouch => tr(if s.toggle_crouch { + "options.key.toggle" + } else { + "options.key.hold" + }), + Opt::ToggleSprint => tr(if s.toggle_sprint { + "options.key.toggle" + } else { + "options.key.hold" + }), Opt::AutoJump => on_off(s.auto_jump), - Opt::ChatVisibility => tr(["options.chat.visibility.full", "options.chat.visibility.system", "options.chat.visibility.hidden"][usize::from(s.chat_visibility.min(2))]), + Opt::ChatVisibility => tr([ + "options.chat.visibility.full", + "options.chat.visibility.system", + "options.chat.visibility.hidden", + ][usize::from(s.chat_visibility.min(2))]), Opt::ChatColors => on_off(s.chat_colors), Opt::ChatLinks => on_off(s.chat_links), Opt::AutoSuggestions => on_off(s.auto_suggestions), @@ -352,7 +417,13 @@ impl Opt { } /// Advance a cycle button (CycleButton.cycleValue). pub fn cycle(self, s: &mut Settings, back: bool) { - let next = |n: u8, count: u8| if back { (n + count - 1) % count } else { (n + 1) % count }; + let next = |n: u8, count: u8| { + if back { + (n + count - 1) % count + } else { + (n + 1) % count + } + }; match self { Opt::InvertY => s.invert_y = !s.invert_y, Opt::DiscreteScroll => s.discrete_scroll = !s.discrete_scroll, @@ -372,7 +443,13 @@ impl Opt { Opt::CutoutLeaves => s.cutout_leaves = !s.cutout_leaves, Opt::ImprovedTransparency => s.improved_transparency = !s.improved_transparency, Opt::AttackIndicator => s.attack_indicator = next(s.attack_indicator, 3), - Opt::InactivityFps => s.inactivity_fps_limit = if s.inactivity_fps_limit == "afk" { "minimized".into() } else { "afk".into() }, + Opt::InactivityFps => { + s.inactivity_fps_limit = if s.inactivity_fps_limit == "afk" { + "minimized".into() + } else { + "afk".into() + } + } Opt::ChunkBuilder => s.prioritize_chunk_updates = next(s.prioritize_chunk_updates, 3), Opt::ToggleCrouch => s.toggle_crouch = !s.toggle_crouch, Opt::ToggleSprint => s.toggle_sprint = !s.toggle_sprint, @@ -464,11 +541,32 @@ enum Act { OpenPackFolder, } enum WKind { - Button { label: Text, active: bool, act: Act }, - Slider { label: Text, value: f32, opt: Opt }, - Text { text: Text, color: u32, centered: bool }, - LanguageRow { label: Text, selected: bool, code: String }, - PackRow { pack: PackEntry, selected: bool, index: usize, count: usize }, + Button { + label: Text, + active: bool, + act: Act, + }, + Slider { + label: Text, + value: f32, + opt: Opt, + }, + Text { + text: Text, + color: u32, + centered: bool, + }, + LanguageRow { + label: Text, + selected: bool, + code: String, + }, + PackRow { + pack: PackEntry, + selected: bool, + index: usize, + count: usize, + }, } struct Widget { x: f32, @@ -530,7 +628,18 @@ impl Default for OptionsUi { } } fn button(x: f32, y: f32, w: f32, label: Text, act: Act) -> Widget { - Widget { x, y, w, h: 20.0, kind: WKind::Button { label, active: true, act }, list: false } + Widget { + x, + y, + w, + h: 20.0, + kind: WKind::Button { + label, + active: true, + act, + }, + list: false, + } } fn inactive(mut w: Widget) -> Widget { if let WKind::Button { active, .. } = &mut w.kind { @@ -540,7 +649,18 @@ fn inactive(mut w: Widget) -> Widget { } fn option_widget(s: &Settings, opt: Opt, x: f32, y: f32, w: f32) -> Widget { match opt.kind(s) { - Kind::Slider(v) => Widget { x, y, w, h: 20.0, kind: WKind::Slider { label: opt.label(s), value: v, opt }, list: false }, + Kind::Slider(v) => Widget { + x, + y, + w, + h: 20.0, + kind: WKind::Slider { + label: opt.label(s), + value: v, + opt, + }, + list: false, + }, Kind::Cycle => button(x, y, w, opt.label(s), Act::Cycle(opt)), } } @@ -552,7 +672,9 @@ enum Row { Buttons(Widget, Option), } fn pairs(opts: &[Opt]) -> Vec { - opts.chunks(2).map(|c| Row::Pair(c[0], c.get(1).copied())).collect() + opts.chunks(2) + .map(|c| Row::Pair(c[0], c.get(1).copied())) + .collect() } impl OptionsUi { pub fn page(&self) -> Page { @@ -601,7 +723,14 @@ impl OptionsUi { match self.page() { Page::Video => { let mut rows = vec![Row::Header("options.video.display.header")]; - rows.extend(pairs(&[Opt::MaxFps, Opt::Vsync, Opt::InactivityFps, Opt::GuiScale, Opt::Fullscreen, Opt::Gamma])); + rows.extend(pairs(&[ + Opt::MaxFps, + Opt::Vsync, + Opt::InactivityFps, + Opt::GuiScale, + Opt::Fullscreen, + Opt::Gamma, + ])); rows.push(Row::Header("options.video.quality.header")); rows.push(Row::Big(Opt::Preset)); rows.extend(pairs(&[ @@ -622,7 +751,12 @@ impl OptionsUi { Opt::WeatherRadius, ])); rows.push(Row::Header("options.video.preferences.header")); - rows.extend(pairs(&[Opt::Autosave, Opt::Vignette, Opt::AttackIndicator, Opt::ChunkFade])); + rows.extend(pairs(&[ + Opt::Autosave, + Opt::Vignette, + Opt::AttackIndicator, + Opt::ChunkFade, + ])); rows } Page::Sound => { @@ -633,13 +767,34 @@ impl OptionsUi { } Page::Controls => { let mut rows = vec![Row::Buttons( - button(0.0, 0.0, 150.0, tr("options.mouse_settings"), Act::Push(Page::Mouse)), - Some(button(0.0, 0.0, 150.0, tr("controls.keybinds"), Act::Push(Page::KeyBinds))), + button( + 0.0, + 0.0, + 150.0, + tr("options.mouse_settings"), + Act::Push(Page::Mouse), + ), + Some(button( + 0.0, + 0.0, + 150.0, + tr("controls.keybinds"), + Act::Push(Page::KeyBinds), + )), )]; - rows.extend(pairs(&[Opt::ToggleCrouch, Opt::ToggleSprint, Opt::AutoJump])); + rows.extend(pairs(&[ + Opt::ToggleCrouch, + Opt::ToggleSprint, + Opt::AutoJump, + ])); rows } - Page::Mouse => pairs(&[Opt::Sensitivity, Opt::WheelSensitivity, Opt::DiscreteScroll, Opt::InvertY]), + Page::Mouse => pairs(&[ + Opt::Sensitivity, + Opt::WheelSensitivity, + Opt::DiscreteScroll, + Opt::InvertY, + ]), Page::Chat => pairs(&[ Opt::ChatVisibility, Opt::ChatColors, @@ -673,7 +828,13 @@ impl OptionsUi { } } /// Build every widget of the current page. - fn layout(&mut self, s: &Settings, atlas: &HudAtlas, w: f32, h: f32) -> (Vec, f32, f32, f32) { + fn layout( + &mut self, + s: &Settings, + atlas: &HudAtlas, + w: f32, + h: f32, + ) -> (Vec, f32, f32, f32) { let mut out = Vec::new(); let page = self.page(); let cx = (w / 2.0).floor(); @@ -682,9 +843,26 @@ impl OptionsUi { let (mut top, mut bottom, mut content) = (33.0, h - 33.0, 0.0); match page { Page::Main => { - out.push(Widget { x: 0.0, y: 12.0, w, h: 9.0, kind: WKind::Text { text: tr("options.title"), color: u32::MAX, centered: true } , list: false }); + out.push(Widget { + x: 0.0, + y: 12.0, + w, + h: 9.0, + kind: WKind::Text { + text: tr("options.title"), + color: u32::MAX, + centered: true, + }, + list: false, + }); out.push(option_widget(s, Opt::Fov, cx - 154.0, 29.0, 150.0)); - out.push(inactive(button(cx + 4.0, 29.0, 150.0, tr("options.online"), Act::None))); + out.push(inactive(button( + cx + 4.0, + 29.0, + 150.0, + tr("options.online"), + Act::None, + ))); let entries = [ ("options.skinCustomisation", None), ("options.sounds", Some(Page::Sound)), @@ -709,12 +887,25 @@ impl OptionsUi { bottom = 0.0; } Page::KeyBinds => { - out.push(Widget { x: 0.0, y: 12.0, w, h: 9.0, kind: WKind::Text { text: tr(Self::title(page)), color: u32::MAX, centered: true } , list: false }); - let mut mappings: Vec<(&str, &str)> = MAPPINGS.iter().map(|(n, _, c)| (*n, *c)).collect(); + out.push(Widget { + x: 0.0, + y: 12.0, + w, + h: 9.0, + kind: WKind::Text { + text: tr(Self::title(page)), + color: u32::MAX, + centered: true, + }, + list: false, + }); + let mut mappings: Vec<(&str, &str)> = + MAPPINGS.iter().map(|(n, _, c)| (*n, *c)).collect(); mappings.sort_by(|a, b| { let ca = CATEGORIES.iter().position(|c| *c == a.1).unwrap_or(99); let cb = CATEGORIES.iter().position(|c| *c == b.1).unwrap_or(99); - ca.cmp(&cb).then_with(|| lang::get(a.0).cmp(&lang::get(b.0))) + ca.cmp(&cb) + .then_with(|| lang::get(a.0).cmp(&lang::get(b.0))) }); let row_left = cx - 170.0; let scrollbar_x = row_left + 340.0 + 6.0 + 2.0; @@ -724,44 +915,122 @@ impl OptionsUi { for (name, category) in mappings { if category != last_category { last_category = category; - let label = Text::translate(&format!("key.categories.{category}"), &[]).with_style(&Style { bold: Some(true), underlined: Some(true), ..Style::default() }); - out.push(Widget { x: 0.0, y: y + 7.0, w, h: 9.0, kind: WKind::Text { text: label, color: u32::MAX, centered: true } , list: false }); + let label = Text::translate(&format!("key.categories.{category}"), &[]) + .with_style(&Style { + bold: Some(true), + underlined: Some(true), + ..Style::default() + }); + out.push(Widget { + x: 0.0, + y: y + 7.0, + w, + h: 9.0, + kind: WKind::Text { + text: label, + color: u32::MAX, + centered: true, + }, + list: false, + }); y += 20.0; } - out.push(Widget { x: row_left + 2.0, y: y + 6.0, w: 200.0, h: 9.0, kind: WKind::Text { text: tr(name), color: u32::MAX, centered: false } , list: false }); + out.push(Widget { + x: row_left + 2.0, + y: y + 6.0, + w: 200.0, + h: 9.0, + kind: WKind::Text { + text: tr(name), + color: u32::MAX, + centered: false, + }, + list: false, + }); let key = s.keys.get(name).to_owned(); let mut message = keybinds::display_name(&key); let conflicts = s.keys.conflicts(name); if !conflicts.is_empty() { - message = Text::literal("[ ").append(message.with_color(text::WHITE)).append(" ]").with_color(text::YELLOW); + message = Text::literal("[ ") + .append(message.with_color(text::WHITE)) + .append(" ]") + .with_color(text::YELLOW); } if self.selected_key == Some(name) { - message = Text::literal("> ").append(message.with_style(&Style { color: Some(text::WHITE), underlined: Some(true), ..Style::default() })).append(" <").with_color(text::YELLOW); + message = Text::literal("> ") + .append(message.with_style(&Style { + color: Some(text::WHITE), + underlined: Some(true), + ..Style::default() + })) + .append(" <") + .with_color(text::YELLOW); } let reset_x = scrollbar_x - 50.0 - 10.0; let change_x = reset_x - 5.0 - 75.0; let name_static = MAPPINGS.iter().find(|m| m.0 == name).map_or("", |m| m.0); out.push(button(change_x, y, 75.0, message, Act::Key(name_static))); if !conflicts.is_empty() { - out.push(Widget { x: change_x - 6.0, y: y + 1.0, w: 3.0, h: 18.0, kind: WKind::Text { text: Text::empty(), color: rgba(255, 255, 0, 255), centered: false } , list: false }); + out.push(Widget { + x: change_x - 6.0, + y: y + 1.0, + w: 3.0, + h: 18.0, + kind: WKind::Text { + text: Text::empty(), + color: rgba(255, 255, 0, 255), + centered: false, + }, + list: false, + }); } - let reset = button(reset_x, y, 50.0, tr("controls.reset"), Act::ResetKey(name_static)); - out.push(if s.keys.is_default(name) { inactive(reset) } else { reset }); + let reset = button( + reset_x, + y, + 50.0, + tr("controls.reset"), + Act::ResetKey(name_static), + ); + out.push(if s.keys.is_default(name) { + inactive(reset) + } else { + reset + }); y += 20.0; } content = y + self.scroll - top + 2.0; out[list_start..].iter_mut().for_each(|w| w.list = true); - out.push(button(cx - 154.0, h - 27.0, 150.0, tr("controls.resetAll"), Act::ResetKeys)); + out.push(button( + cx - 154.0, + h - 27.0, + 150.0, + tr("controls.resetAll"), + Act::ResetKeys, + )); out.push(button(cx + 4.0, h - 27.0, 150.0, tr("gui.done"), Act::Done)); } Page::Language => { top = 36.0; bottom = h - 53.0; - out.push(Widget { x: 0.0, y: 4.0, w, h: 9.0, kind: WKind::Text { text: tr(Self::title(page)), color: u32::MAX, centered: true } , list: false }); + out.push(Widget { + x: 0.0, + y: 4.0, + w, + h: 9.0, + kind: WKind::Text { + text: tr(Self::title(page)), + color: u32::MAX, + centered: true, + }, + list: false, + }); self.language_search.x = cx - 100.0; self.language_search.y = 17.0; let query = self.language_search.value.to_lowercase(); - let current = self.language_choice.clone().unwrap_or_else(|| s.language.clone()); + let current = self + .language_choice + .clone() + .unwrap_or_else(|| s.language.clone()); if std::mem::take(&mut self.center_language) && let Some(i) = self.languages.iter().position(|l| l.code == current) { @@ -771,50 +1040,175 @@ impl OptionsUi { let list_start = out.len(); let mut y = top + 2.0 - self.scroll; for l in &self.languages { - if !query.is_empty() && !l.label().to_lowercase().contains(&query) && !l.code.contains(&query) { + if !query.is_empty() + && !l.label().to_lowercase().contains(&query) + && !l.code.contains(&query) + { continue; } - out.push(Widget { x: cx - 110.0, y, w: 220.0, h: 18.0, kind: WKind::LanguageRow { label: Text::literal(l.label()), selected: l.code == current, code: l.code.clone() } , list: false }); + out.push(Widget { + x: cx - 110.0, + y, + w: 220.0, + h: 18.0, + kind: WKind::LanguageRow { + label: Text::literal(l.label()), + selected: l.code == current, + code: l.code.clone(), + }, + list: false, + }); y += 18.0; } content = y + self.scroll - top + 2.0; out[list_start..].iter_mut().for_each(|w| w.list = true); - out.push(Widget { x: 0.0, y: h - 45.0, w, h: 9.0, kind: WKind::Text { text: tr("options.languageAccuracyWarning"), color: rgba(0xBA, 0xBA, 0xBA, 255), centered: true } , list: false }); - out.push(button(cx - 154.0, h - 28.0, 150.0, tr("options.font"), Act::Push(Page::Font))); + out.push(Widget { + x: 0.0, + y: h - 45.0, + w, + h: 9.0, + kind: WKind::Text { + text: tr("options.languageAccuracyWarning"), + color: rgba(0xBA, 0xBA, 0xBA, 255), + centered: true, + }, + list: false, + }); + out.push(button( + cx - 154.0, + h - 28.0, + 150.0, + tr("options.font"), + Act::Push(Page::Font), + )); out.push(button(cx + 4.0, h - 28.0, 150.0, tr("gui.done"), Act::Done)); } Page::Packs => { top = 47.0; bottom = h - 33.0; - out.push(Widget { x: 0.0, y: 8.0, w, h: 9.0, kind: WKind::Text { text: tr("resourcePack.title"), color: u32::MAX, centered: true } , list: false }); - out.push(Widget { x: 0.0, y: 20.0, w, h: 9.0, kind: WKind::Text { text: tr("pack.dropInfo").with_color(text::GRAY), color: u32::MAX, centered: true } , list: false }); + out.push(Widget { + x: 0.0, + y: 8.0, + w, + h: 9.0, + kind: WKind::Text { + text: tr("resourcePack.title"), + color: u32::MAX, + centered: true, + }, + list: false, + }); + out.push(Widget { + x: 0.0, + y: 20.0, + w, + h: 9.0, + kind: WKind::Text { + text: tr("pack.dropInfo").with_color(text::GRAY), + color: u32::MAX, + centered: true, + }, + list: false, + }); let lists = [(false, cx - 4.0 - 200.0), (true, cx + 4.0)]; let list_start = out.len(); for (selected, lx) in lists { - let entries = if selected { &self.selected } else { &self.available }; - let header = tr(if selected { "pack.selected.title" } else { "pack.available.title" }).with_style(&Style { bold: Some(true), underlined: Some(true), ..Style::default() }); - out.push(Widget { x: lx, y: top + 4.0, w: 200.0, h: 9.0, kind: WKind::Text { text: header, color: u32::MAX, centered: true } , list: false }); + let entries = if selected { + &self.selected + } else { + &self.available + }; + let header = tr(if selected { + "pack.selected.title" + } else { + "pack.available.title" + }) + .with_style(&Style { + bold: Some(true), + underlined: Some(true), + ..Style::default() + }); + out.push(Widget { + x: lx, + y: top + 4.0, + w: 200.0, + h: 9.0, + kind: WKind::Text { + text: header, + color: u32::MAX, + centered: true, + }, + list: false, + }); let mut y = top + 17.0 - self.scroll; for (i, p) in entries.iter().enumerate() { - out.push(Widget { x: lx, y, w: 200.0, h: 36.0, kind: WKind::PackRow { pack: p.clone(), selected, index: i, count: entries.len() } , list: false }); + out.push(Widget { + x: lx, + y, + w: 200.0, + h: 36.0, + kind: WKind::PackRow { + pack: p.clone(), + selected, + index: i, + count: entries.len(), + }, + list: false, + }); y += 36.0; } content = f32::max(content, y + self.scroll - top + 4.0); } out[list_start..].iter_mut().for_each(|w| w.list = true); - out.push(button(cx - 154.0, h - 27.0, 150.0, tr("pack.openFolder"), Act::OpenPackFolder)); + out.push(button( + cx - 154.0, + h - 27.0, + 150.0, + tr("pack.openFolder"), + Act::OpenPackFolder, + )); out.push(button(cx + 4.0, h - 27.0, 150.0, tr("gui.done"), Act::Done)); } _ => { - out.push(Widget { x: 0.0, y: 12.0, w, h: 9.0, kind: WKind::Text { text: tr(Self::title(page)), color: u32::MAX, centered: true } , list: false }); + out.push(Widget { + x: 0.0, + y: 12.0, + w, + h: 9.0, + kind: WKind::Text { + text: tr(Self::title(page)), + color: u32::MAX, + centered: true, + }, + list: false, + }); let list_start = out.len(); let mut y = top + 2.0 - self.scroll; for row in self.list_rows(s) { match row { Row::Header(key) => { - let padding = if y + self.scroll <= top + 2.0 { 0.0 } else { 18.0 }; - let label = tr(key).with_style(&Style { bold: Some(true), underlined: Some(true), ..Style::default() }); - out.push(Widget { x: 0.0, y: y + 2.0 + padding + 4.0, w, h: 9.0, kind: WKind::Text { text: label, color: u32::MAX, centered: true } , list: false }); + let padding = if y + self.scroll <= top + 2.0 { + 0.0 + } else { + 18.0 + }; + let label = tr(key).with_style(&Style { + bold: Some(true), + underlined: Some(true), + ..Style::default() + }); + out.push(Widget { + x: 0.0, + y: y + 2.0 + padding + 4.0, + w, + h: 9.0, + kind: WKind::Text { + text: label, + color: u32::MAX, + centered: true, + }, + list: false, + }); y += padding + 18.0; } Row::Big(opt) => { @@ -853,7 +1247,13 @@ impl OptionsUi { let max = (content - (bottom - top)).max(0.0); self.scroll = self.scroll.clamp(0.0, max); } - pub fn draw(&mut self, s: &Settings, batch: &mut HudBatch, atlas: &HudAtlas, cursor: (f32, f32)) { + pub fn draw( + &mut self, + s: &Settings, + batch: &mut HudBatch, + atlas: &HudAtlas, + cursor: (f32, f32), + ) { let (w, h) = (batch.width, batch.height); let (widgets, top, bottom, content) = self.layout(s, atlas, w, h); self.clamp_scroll(top, bottom, content); @@ -869,65 +1269,183 @@ impl OptionsUi { if !visible(wd) { continue; } - let hover = ui::hovered(cursor, wd.x, wd.y, wd.w, wd.h) && (!wd.list || cursor.1 >= top && cursor.1 < bottom); + let hover = ui::hovered(cursor, wd.x, wd.y, wd.w, wd.h) + && (!wd.list || cursor.1 >= top && cursor.1 < bottom); match &wd.kind { WKind::Button { label, active, act } => { ui::button(batch, atlas, wd.x, wd.y, wd.w, wd.h, label, *active, hover); if hover && let Act::Key(name) = act { let conflicts = s.keys.conflicts(name); if !conflicts.is_empty() { - let names = conflicts.iter().map(|c| lang::get(c)).collect::>().join(", "); - let full = Text::translate("controls.keybinds.duplicateKeybinds", &[Text::literal(names)]); - tooltip = Some(full.plain().split('\n').map(|l| Text::literal(l.to_owned())).collect::>()); + let names = conflicts + .iter() + .map(|c| lang::get(c)) + .collect::>() + .join(", "); + let full = Text::translate( + "controls.keybinds.duplicateKeybinds", + &[Text::literal(names)], + ); + tooltip = Some( + full.plain() + .split('\n') + .map(|l| Text::literal(l.to_owned())) + .collect::>(), + ); } } } WKind::Slider { label, value, opt } => { let dragging = self.dragging == Some(*opt); - ui::slider(batch, atlas, wd.x, wd.y, wd.w, label, *value, hover || dragging, true); + ui::slider( + batch, + atlas, + wd.x, + wd.y, + wd.w, + label, + *value, + hover || dragging, + true, + ); } - WKind::Text { text, color, centered } => { + WKind::Text { + text, + color, + centered, + } => { if text.is_empty() { batch.fill(atlas, wd.x, wd.y, wd.w, wd.h, *color); } else if *centered { let tw = atlas.font.width_text(text); - batch.text_styled(atlas, text, wd.x + ((wd.w - tw) / 2.0).floor(), wd.y, *color, true); + batch.text_styled( + atlas, + text, + wd.x + ((wd.w - tw) / 2.0).floor(), + wd.y, + *color, + true, + ); } else { batch.text_styled(atlas, text, wd.x, wd.y, *color, true); } } - WKind::LanguageRow { label, selected, .. } => { + WKind::LanguageRow { + label, selected, .. + } => { if *selected { batch.fill(atlas, wd.x, wd.y, wd.w, wd.h, u32::MAX); - batch.fill(atlas, wd.x + 1.0, wd.y + 1.0, wd.w - 2.0, wd.h - 2.0, rgba(0, 0, 0, 255)); + batch.fill( + atlas, + wd.x + 1.0, + wd.y + 1.0, + wd.w - 2.0, + wd.h - 2.0, + rgba(0, 0, 0, 255), + ); } let tw = atlas.font.width_text(label); - batch.text_styled(atlas, label, wd.x + ((wd.w - tw) / 2.0).floor(), wd.y + 2.0 + 7.0 - 4.0, u32::MAX, true); + batch.text_styled( + atlas, + label, + wd.x + ((wd.w - tw) / 2.0).floor(), + wd.y + 2.0 + 7.0 - 4.0, + u32::MAX, + true, + ); } - WKind::PackRow { pack, selected, index, count } => { + WKind::PackRow { + pack, + selected, + index, + count, + } => { if hover { batch.fill(atlas, wd.x, wd.y, wd.w, wd.h, rgba(255, 255, 255, 255)); - batch.fill(atlas, wd.x + 1.0, wd.y + 1.0, wd.w - 2.0, wd.h - 2.0, rgba(0, 0, 0, 255)); + batch.fill( + atlas, + wd.x + 1.0, + wd.y + 1.0, + wd.w - 2.0, + wd.h - 2.0, + rgba(0, 0, 0, 255), + ); } - batch.sprite_scaled(atlas, "misc/unknown_pack", wd.x + 2.0, wd.y + 2.0, 32.0, 32.0, u32::MAX); - let title_color = if pack.compatible { u32::MAX } else { rgba(255, 85, 85, 255) }; - batch.text_styled(atlas, &pack.title, wd.x + 36.0, wd.y + 3.0, title_color, true); - for (i, line) in atlas.font.split(&pack.description, 157.0).iter().take(2).enumerate() { - batch.text_styled(atlas, line, wd.x + 36.0, wd.y + 14.0 + i as f32 * 9.0, rgba(128, 128, 128, 255), true); + batch.sprite_scaled( + atlas, + "misc/unknown_pack", + wd.x + 2.0, + wd.y + 2.0, + 32.0, + 32.0, + u32::MAX, + ); + let title_color = if pack.compatible { + u32::MAX + } else { + rgba(255, 85, 85, 255) + }; + batch.text_styled( + atlas, + &pack.title, + wd.x + 36.0, + wd.y + 3.0, + title_color, + true, + ); + for (i, line) in atlas + .font + .split(&pack.description, 157.0) + .iter() + .take(2) + .enumerate() + { + batch.text_styled( + atlas, + line, + wd.x + 36.0, + wd.y + 14.0 + i as f32 * 9.0, + rgba(128, 128, 128, 255), + true, + ); } if hover && cursor.0 < wd.x + 34.0 { // TransferableSelectionList arrows over the icon. - batch.fill(atlas, wd.x + 2.0, wd.y + 2.0, 32.0, 32.0, rgba(160, 160, 160, 136)); + batch.fill( + atlas, + wd.x + 2.0, + wd.y + 2.0, + 32.0, + 32.0, + rgba(160, 160, 160, 136), + ); let sprite_dir = if *selected { "unselect" } else { "select" }; let left = cursor.0 < wd.x + 18.0; - let name = format!("gui/sprites/transferable_list/{sprite_dir}{}", if left || !*selected { "_highlighted" } else { "" }); + let name = format!( + "gui/sprites/transferable_list/{sprite_dir}{}", + if left || !*selected { + "_highlighted" + } else { + "" + } + ); batch.sprite(atlas, &name, wd.x + 2.0, wd.y + 2.0); if *selected { if *index > 0 { - batch.sprite(atlas, "gui/sprites/transferable_list/move_up", wd.x + 2.0, wd.y + 2.0); + batch.sprite( + atlas, + "gui/sprites/transferable_list/move_up", + wd.x + 2.0, + wd.y + 2.0, + ); } if index + 1 < *count { - batch.sprite(atlas, "gui/sprites/transferable_list/move_down", wd.x + 2.0, wd.y + 2.0); + batch.sprite( + atlas, + "gui/sprites/transferable_list/move_down", + wd.x + 2.0, + wd.y + 2.0, + ); } } } @@ -947,7 +1465,14 @@ impl OptionsUi { let mut search = self.language_search.clone(); search.draw(batch, atlas, None); if search.value.is_empty() { - batch.text_styled(atlas, &tr("gui.language.search").with_color(text::GRAY).italic(), search.text_x(), search.text_y(), u32::MAX, true); + batch.text_styled( + atlas, + &tr("gui.language.search").with_color(text::GRAY).italic(), + search.text_x(), + search.text_y(), + u32::MAX, + true, + ); } self.language_search = search; } @@ -956,12 +1481,23 @@ impl OptionsUi { } } /// Mouse press/drag. Returns events for the game. - pub fn click(&mut self, s: &mut Settings, atlas: &HudAtlas, x: f32, y: f32, size: (f32, f32), drag: bool, right: bool) -> Vec { + pub fn click( + &mut self, + s: &mut Settings, + atlas: &HudAtlas, + x: f32, + y: f32, + size: (f32, f32), + drag: bool, + right: bool, + ) -> Vec { let (widgets, top, bottom, _) = self.layout(s, atlas, size.0, size.1); let mut events = Vec::new(); if drag { if let Some(opt) = self.dragging - && let Some(wd) = widgets.iter().find(|wd| matches!(&wd.kind, WKind::Slider { opt: o, .. } if *o == opt)) + && let Some(wd) = widgets + .iter() + .find(|wd| matches!(&wd.kind, WKind::Slider { opt: o, .. } if *o == opt)) { opt.set_slider(s, ui::slider_value(wd.x, wd.w, x)); events.push(Event::Changed); @@ -970,7 +1506,11 @@ impl OptionsUi { } // Key Binds: a mouse button pressed while waiting binds it. if let Some(name) = self.selected_key.take() { - let button = if right { "key.mouse.right" } else { "key.mouse.left" }; + let button = if right { + "key.mouse.right" + } else { + "key.mouse.left" + }; s.keys.set(name, button); events.push(Event::Changed); return events; @@ -983,7 +1523,9 @@ impl OptionsUi { continue; } match wd.kind { - WKind::Button { active: true, act, .. } => match act { + WKind::Button { + active: true, act, .. + } => match act { Act::Push(p) => self.push(p), Act::Done => events.extend(self.back(s)), Act::Cycle(opt) => { @@ -1020,7 +1562,12 @@ impl OptionsUi { self.language_choice = Some(code); } } - WKind::PackRow { pack, selected, index, .. } => { + WKind::PackRow { + pack, + selected, + index, + .. + } => { if pack.required { continue; } @@ -1028,8 +1575,14 @@ impl OptionsUi { if selected && on_icon && x >= wd.x + 18.0 { // Right half of the icon: move up (top) or down (bottom). let up = y < wd.y + 18.0; - let target = if up { index.checked_sub(1) } else { Some(index + 1) }; - if let Some(t) = target.filter(|t| *t < self.selected.len() && !self.selected[*t].required) { + let target = if up { + index.checked_sub(1) + } else { + Some(index + 1) + }; + if let Some(t) = target + .filter(|t| *t < self.selected.len() && !self.selected[*t].required) + { self.selected.swap(index, t); self.packs_changed = true; } @@ -1072,7 +1625,8 @@ impl OptionsUi { } } Page::Packs if self.packs_changed => { - let mut ids: Vec = self.selected.iter().rev().map(|p| p.id.clone()).collect(); + let mut ids: Vec = + self.selected.iter().rev().map(|p| p.id.clone()).collect(); if !ids.contains(&"vanilla".to_owned()) { ids.insert(0, "vanilla".into()); } @@ -1096,11 +1650,22 @@ impl OptionsUi { } /// Keys while the options are open. Returns events; `handled` false lets /// Escape fall through. - pub fn key(&mut self, s: &mut Settings, key: winit::keyboard::KeyCode, text: Option<&str>) -> Vec { + pub fn key( + &mut self, + s: &mut Settings, + key: winit::keyboard::KeyCode, + text: Option<&str>, + ) -> Vec { use winit::keyboard::KeyCode as K; if let Some(name) = self.selected_key.take() { // KeyBindsScreen.keyPressed: Escape unbinds. - let value = if key == K::Escape { "key.keyboard.unknown".to_owned() } else { keybinds::key_name(key).unwrap_or("key.keyboard.unknown").to_owned() }; + let value = if key == K::Escape { + "key.keyboard.unknown".to_owned() + } else { + keybinds::key_name(key) + .unwrap_or("key.keyboard.unknown") + .to_owned() + }; s.keys.set(name, &value); return vec![Event::Changed]; } diff --git a/crates/horizon-client/src/packs.rs b/crates/horizon-client/src/packs.rs index 61a1e16f3..9e78a5f13 100644 --- a/crates/horizon-client/src/packs.rs +++ b/crates/horizon-client/src/packs.rs @@ -42,7 +42,11 @@ pub fn component(v: &serde_json::Value) -> Text { let mut t = if let Some(s) = o.get("text").and_then(|s| s.as_str()) { Text::legacy(s) } else if let Some(k) = o.get("translate").and_then(|s| s.as_str()) { - let args: Vec = o.get("with").and_then(|w| w.as_array()).map(|a| a.iter().map(component).collect()).unwrap_or_default(); + let args: Vec = o + .get("with") + .and_then(|w| w.as_array()) + .map(|a| a.iter().map(component).collect()) + .unwrap_or_default(); Text::translate(k, &args) } else { Text::empty() @@ -51,7 +55,10 @@ pub fn component(v: &serde_json::Value) -> Text { t.push(component(extra)); } if let Some(c) = o.get("color").and_then(|c| c.as_str()) { - let rgb = crate::text::named_color(c).or_else(|| c.strip_prefix('#').and_then(|h| u32::from_str_radix(h, 16).ok())); + let rgb = crate::text::named_color(c).or_else(|| { + c.strip_prefix('#') + .and_then(|h| u32::from_str_radix(h, 16).ok()) + }); if let Some(rgb) = rgb { t = t.with_color(rgb); } @@ -66,7 +73,10 @@ pub fn component(v: &serde_json::Value) -> Text { fn format_of(v: &serde_json::Value) -> Option<(i64, i64)> { match v { serde_json::Value::Number(n) => Some((n.as_i64()?, 0)), - serde_json::Value::Array(a) => Some((a.first()?.as_i64()?, a.get(1).and_then(|m| m.as_i64()).unwrap_or(0))), + serde_json::Value::Array(a) => Some(( + a.first()?.as_i64()?, + a.get(1).and_then(|m| m.as_i64()).unwrap_or(0), + )), _ => None, } } @@ -75,11 +85,18 @@ fn format_of(v: &serde_json::Value) -> Option<(i64, i64)> { pub fn compatible(meta: &serde_json::Value) -> bool { let pack = &meta["pack"]; let current = RESOURCE_FORMAT; - if let (Some(min), Some(max)) = (format_of(&pack["min_format"]), format_of(&pack["max_format"])) { - return min <= current && current <= (max.0, max.1.max(if max.1 == 0 { i64::MAX } else { max.1 })); + if let (Some(min), Some(max)) = ( + format_of(&pack["min_format"]), + format_of(&pack["max_format"]), + ) { + return min <= current + && current <= (max.0, max.1.max(if max.1 == 0 { i64::MAX } else { max.1 })); } if let Some(range) = pack["supported_formats"].as_array() - && let (Some(lo), Some(hi)) = (range.first().and_then(|v| v.as_i64()), range.get(1).and_then(|v| v.as_i64())) + && let (Some(lo), Some(hi)) = ( + range.first().and_then(|v| v.as_i64()), + range.get(1).and_then(|v| v.as_i64()), + ) { return lo <= current.0 && current.0 <= hi; } @@ -94,13 +111,22 @@ fn read_meta(source: &Source) -> Option { } fn pack(id: String, title: Text, source: Source) -> Option { let meta = read_meta(&source)?; - Some(Pack { id, title, description: component(&meta["pack"]["description"]), compatible: compatible(&meta), source }) + Some(Pack { + id, + title, + description: component(&meta["pack"]["description"]), + compatible: compatible(&meta), + source, + }) } /// Built-in and `resourcepacks/` packs (vanilla itself excluded), sorted like /// the pack screen (built-ins first, then by name). pub fn discover(resources: &Path, packs_dir: &Path) -> Vec { let mut out = Vec::new(); - for (id, key) in [("programmer_art", "resourcePack.programmer_art.name"), ("high_contrast", "resourcePack.high_contrast.name")] { + for (id, key) in [ + ("programmer_art", "resourcePack.programmer_art.name"), + ("high_contrast", "resourcePack.high_contrast.name"), + ] { let z = resources.join(format!("assets/minecraft/resourcepacks/{id}.zip")); if z.exists() && let Some(p) = pack(id.into(), Text::translate(key, &[]), Source::Zip(z)) @@ -136,7 +162,9 @@ fn pack_files(source: &Source) -> io::Result>> Source::Dir(d) => { let mut stack = vec![d.join("assets")]; while let Some(dir) = stack.pop() { - let Ok(entries) = fs::read_dir(&dir) else { continue }; + let Ok(entries) = fs::read_dir(&dir) else { + continue; + }; for e in entries.flatten() { let p = e.path(); if p.is_dir() { @@ -163,7 +191,11 @@ fn link(target: &Path, at: &Path) -> io::Result<()> { } #[cfg(not(unix))] fn link(target: &Path, at: &Path) -> io::Result<()> { - if target.is_dir() { Ok(()) } else { fs::copy(target, at).map(|_| ()) } + if target.is_dir() { + Ok(()) + } else { + fs::copy(target, at).map(|_| ()) + } } /// Build `out` as `vanilla` with the packs' files layered on top (packs in /// load order, last wins). Untouched directories are symlinks into vanilla. @@ -186,16 +218,48 @@ pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<( (1..parts.len()).map(move |n| parts[..n].join("/")) }) .collect(); - let zips: Vec> = packs.iter().map(|p| if let Source::Zip(z) = &p.source { Zip::open(z).ok() } else { None }).collect(); - fn mirror(rel: &str, vanilla: &Path, out: &Path, touched: &BTreeSet, files: &BTreeMap)>, zips: &[Option]) -> io::Result<()> { - let src = if rel.is_empty() { vanilla.to_path_buf() } else { vanilla.join(rel) }; - let dst = if rel.is_empty() { out.to_path_buf() } else { out.join(rel) }; + let zips: Vec> = packs + .iter() + .map(|p| { + if let Source::Zip(z) = &p.source { + Zip::open(z).ok() + } else { + None + } + }) + .collect(); + fn mirror( + rel: &str, + vanilla: &Path, + out: &Path, + touched: &BTreeSet, + files: &BTreeMap)>, + zips: &[Option], + ) -> io::Result<()> { + let src = if rel.is_empty() { + vanilla.to_path_buf() + } else { + vanilla.join(rel) + }; + let dst = if rel.is_empty() { + out.to_path_buf() + } else { + out.join(rel) + }; fs::create_dir_all(&dst)?; let mut names: BTreeSet = BTreeSet::new(); if let Ok(entries) = fs::read_dir(&src) { - names.extend(entries.flatten().map(|e| e.file_name().to_string_lossy().into_owned())); + names.extend( + entries + .flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()), + ); } - let prefix = if rel.is_empty() { String::new() } else { format!("{rel}/") }; + let prefix = if rel.is_empty() { + String::new() + } else { + format!("{rel}/") + }; for f in files.keys().filter_map(|f| f.strip_prefix(&prefix)) { names.insert(f.split('/').next().unwrap_or("").to_owned()); } @@ -223,15 +287,24 @@ pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<( } /// The packs to apply for an options.txt `resourcePacks` list (bottom first). pub fn enabled(all: &[Pack], ids: &[String]) -> Vec { - ids.iter().filter(|id| *id != "vanilla").filter_map(|id| all.iter().find(|p| &p.id == id).cloned()).collect() + ids.iter() + .filter(|id| *id != "vanilla") + .filter_map(|id| all.iter().find(|p| &p.id == id).cloned()) + .collect() } /// Resource root for a pack selection: vanilla itself when no pack is on. pub fn resource_root(vanilla: &Path, packs: &[Pack], cache: &Path) -> PathBuf { if packs.is_empty() { return vanilla.to_path_buf(); } - let key: String = packs.iter().map(|p| p.id.as_str()).collect::>().join("|"); - let hash = key.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3)); + let key: String = packs + .iter() + .map(|p| p.id.as_str()) + .collect::>() + .join("|"); + let hash = key.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| { + (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3) + }); let out = cache.join(format!("{hash:016x}")); match build_overlay(vanilla, packs, &out) { Ok(()) => out, @@ -248,12 +321,21 @@ mod tests { #[test] fn compatibility_ranges() { let v = |s: &str| serde_json::from_str::(s).unwrap(); - assert!(compatible(&v(r#"{"pack":{"min_format":97,"max_format":98}}"#))); - assert!(compatible(&v(r#"{"pack":{"min_format":[97,0],"max_format":[97,1]}}"#))); - assert!(!compatible(&v(r#"{"pack":{"min_format":[97,2],"max_format":99}}"#))); + assert!(compatible(&v( + r#"{"pack":{"min_format":97,"max_format":98}}"# + ))); + assert!(compatible(&v( + r#"{"pack":{"min_format":[97,0],"max_format":[97,1]}}"# + ))); + assert!(!compatible(&v( + r#"{"pack":{"min_format":[97,2],"max_format":99}}"# + ))); assert!(compatible(&v(r#"{"pack":{"pack_format":97}}"#))); assert!(!compatible(&v(r#"{"pack":{"pack_format":34}}"#))); - assert_eq!(component(&v(r#"["a",{"text":"b","color":"red"}]"#)).plain(), "ab"); + assert_eq!( + component(&v(r#"["a",{"text":"b","color":"red"}]"#)).plain(), + "ab" + ); } #[test] fn overlay_layers_packs_over_vanilla() { @@ -262,22 +344,47 @@ mod tests { let vanilla = base.join("vanilla"); fs::create_dir_all(vanilla.join("assets/minecraft/textures/block")).unwrap(); fs::create_dir_all(vanilla.join("assets/minecraft/lang")).unwrap(); - fs::write(vanilla.join("assets/minecraft/textures/block/stone.png"), b"vanilla").unwrap(); - fs::write(vanilla.join("assets/minecraft/textures/block/dirt.png"), b"vanilla dirt").unwrap(); + fs::write( + vanilla.join("assets/minecraft/textures/block/stone.png"), + b"vanilla", + ) + .unwrap(); + fs::write( + vanilla.join("assets/minecraft/textures/block/dirt.png"), + b"vanilla dirt", + ) + .unwrap(); fs::write(vanilla.join("assets/minecraft/lang/en_us.json"), b"{}").unwrap(); fs::write(vanilla.join("facts.json"), b"[]").unwrap(); let pack_dir = base.join("packs/Mine"); fs::create_dir_all(pack_dir.join("assets/minecraft/textures/block")).unwrap(); - fs::write(pack_dir.join("pack.mcmeta"), br#"{"pack":{"description":"mine","pack_format":97}}"#).unwrap(); - fs::write(pack_dir.join("assets/minecraft/textures/block/stone.png"), b"pack").unwrap(); + fs::write( + pack_dir.join("pack.mcmeta"), + br#"{"pack":{"description":"mine","pack_format":97}}"#, + ) + .unwrap(); + fs::write( + pack_dir.join("assets/minecraft/textures/block/stone.png"), + b"pack", + ) + .unwrap(); let packs = discover(&vanilla, &base.join("packs")); assert_eq!(packs.len(), 1); assert_eq!(packs[0].id, "file/Mine"); let out = base.join("overlay"); build_overlay(&vanilla, &packs, &out).unwrap(); - assert_eq!(fs::read(out.join("assets/minecraft/textures/block/stone.png")).unwrap(), b"pack"); - assert_eq!(fs::read(out.join("assets/minecraft/textures/block/dirt.png")).unwrap(), b"vanilla dirt"); - assert_eq!(fs::read(out.join("assets/minecraft/lang/en_us.json")).unwrap(), b"{}"); + assert_eq!( + fs::read(out.join("assets/minecraft/textures/block/stone.png")).unwrap(), + b"pack" + ); + assert_eq!( + fs::read(out.join("assets/minecraft/textures/block/dirt.png")).unwrap(), + b"vanilla dirt" + ); + assert_eq!( + fs::read(out.join("assets/minecraft/lang/en_us.json")).unwrap(), + b"{}" + ); assert_eq!(fs::read(out.join("facts.json")).unwrap(), b"[]"); let _ = fs::remove_dir_all(base); } diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 7a863b054..0b628f165 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -46,7 +46,8 @@ fn pack(indices: &[u16], bits: u32) -> Vec { let per_long = (64 / bits) as usize; let mut longs = vec![0i64; indices.len().div_ceil(per_long)]; for (i, &v) in indices.iter().enumerate() { - longs[i / per_long] |= (i64::from(v) & ((1i64 << bits) - 1)) << ((i % per_long) as u32 * bits); + longs[i / per_long] |= + (i64::from(v) & ((1i64 << bits) - 1)) << ((i % per_long) as u32 * bits); } longs } @@ -55,9 +56,9 @@ fn unpack(longs: &[i64], bits: u32, count: usize) -> Vec { let mask = (1u64 << bits) - 1; (0..count) .map(|i| { - longs - .get(i / per_long) - .map_or(0, |&l| ((l as u64 >> ((i % per_long) as u32 * bits)) & mask) as u16) + longs.get(i / per_long).map_or(0, |&l| { + ((l as u64 >> ((i % per_long) as u32 * bits)) & mask) as u16 + }) }) .collect() } @@ -107,14 +108,24 @@ fn compound_or_empty(tag: Option) -> Tag { /// `dimensions//` inside a world folder. pub fn dimension_dir(world: &Path, dimension: &str) -> PathBuf { - let (namespace, path) = dimension.split_once(':').unwrap_or(("minecraft", dimension)); + let (namespace, path) = dimension + .split_once(':') + .unwrap_or(("minecraft", dimension)); world.join("dimensions").join(namespace).join(path) } /// Move a world saved by an older Horizon build (pre-26.3 layout with a /// DataVersion that keeps vanilla from upgrading it) into the 26.3 layout. pub fn migrate_legacy(world: &Path) -> Result<()> { - for (old, dimension) in [("", "minecraft:overworld"), ("DIM-1", "minecraft:the_nether"), ("DIM1", "minecraft:the_end")] { - let from = if old.is_empty() { world.to_owned() } else { world.join(old) }; + for (old, dimension) in [ + ("", "minecraft:overworld"), + ("DIM-1", "minecraft:the_nether"), + ("DIM1", "minecraft:the_end"), + ] { + let from = if old.is_empty() { + world.to_owned() + } else { + world.join(old) + }; let to = dimension_dir(world, dimension); for folder in ["region", "entities", "poi"] { let (src, dst) = (from.join(folder), to.join(folder)); @@ -147,20 +158,29 @@ impl SaveTables { let mut block_names: Vec = Vec::new(); let mut default_state = Vec::with_capacity(registry.len()); for id in 0..registry.len() { - let state = registry.state(BlockStateId(id as u32)).expect("registry state"); + let state = registry + .state(BlockStateId(id as u32)) + .expect("registry state"); if block_names.last() != Some(&state.name) { block_names.push(state.name.clone()); } - default_state.push(registry.default_state(&state.name) == Some(BlockStateId(id as u32))); + default_state + .push(registry.default_state(&state.name) == Some(BlockStateId(id as u32))); } - let block_ids = block_names.iter().enumerate().map(|(i, n)| (n.clone(), i as u16)).collect(); + let block_ids = block_names + .iter() + .enumerate() + .map(|(i, n)| (n.clone(), i as u16)) + .collect(); Self { block_names, block_ids, default_state, block_entity: Vec::new(), heightmaps: assets.properties.clone(), - air: registry.default_state("minecraft:air").map_or(0, |s| s.0 as u16), + air: registry + .default_state("minecraft:air") + .map_or(0, |s| s.0 as u16), } } /// Which states carry a block entity (`BlockFacts`), to drop entries for @@ -205,12 +225,22 @@ fn tick_list(ticks: &[SavedTick], name: impl Fn(u32) -> Option) -> Tag { .collect(), ) } -fn read_ticks(tag: Option<&Tag>, chunk: (i32, i32), id: impl Fn(&str) -> Option) -> Vec { - let Some(Tag::List(list)) = tag else { return Vec::new() }; +fn read_ticks( + tag: Option<&Tag>, + chunk: (i32, i32), + id: impl Fn(&str) -> Option, +) -> Vec { + let Some(Tag::List(list)) = tag else { + return Vec::new(); + }; list.iter() .filter_map(|t| { let kind = id(&text(t.get("i"))?)?; - let pos = BlockPos::new(number(t.get("x"))? as i32, number(t.get("y"))? as i32, number(t.get("z"))? as i32); + let pos = BlockPos::new( + number(t.get("x"))? as i32, + number(t.get("y"))? as i32, + number(t.get("z"))? as i32, + ); // SavedTick.filterTickListForChunk if (pos.x >> 4, pos.z >> 4) != chunk { return None; @@ -250,7 +280,10 @@ fn fluid_id(name: &str) -> Option { } fn encode_item(stack: &crate::items::ItemStack) -> Vec<(&'static str, Tag)> { - let mut entries = vec![("id", string(&stack.item)), ("count", Tag::Int(stack.count as i32))]; + let mut entries = vec![ + ("id", string(&stack.item)), + ("count", Tag::Int(stack.count as i32)), + ]; if let Some(components) = crate::item_data::encode_components(stack) { entries.push(("components", components)); } @@ -265,9 +298,17 @@ pub fn item_from_nbt(tag: &Tag) -> Option { if id == "minecraft:air" { return None; } - let count = number(tag.get("count")).or_else(|| number(tag.get("Count"))).unwrap_or(1).max(1) as u32; + let count = number(tag.get("count")) + .or_else(|| number(tag.get("Count"))) + .unwrap_or(1) + .max(1) as u32; let (damage, extra) = crate::item_data::decode_components(tag.get("components")); - Some(crate::items::ItemStack { item: Arc::from(id.as_str()), count, damage, extra }) + Some(crate::items::ItemStack { + item: Arc::from(id.as_str()), + count, + damage, + extra, + }) } pub fn encode_items(slots: &[Option]) -> Tag { Tag::List( @@ -298,7 +339,10 @@ pub fn decode_items(tag: Option<&Tag>, size: usize) -> Vec String { match (e, block) { - (crate::containers::BlockEntity::Chest(_), "minecraft:trapped_chest" | "minecraft:barrel" | "minecraft:dropper") => block.to_owned(), + ( + crate::containers::BlockEntity::Chest(_), + "minecraft:trapped_chest" | "minecraft:barrel" | "minecraft:dropper", + ) => block.to_owned(), _ => e.id().to_owned(), } } @@ -356,7 +400,13 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers: } BlockEntity::Brewing(b) => { let items = decode_items(tag.get("Items"), 5); - b.items = [items[0].clone(), items[1].clone(), items[2].clone(), items[3].clone(), items[4].clone()]; + b.items = [ + items[0].clone(), + items[1].clone(), + items[2].clone(), + items[3].clone(), + items[4].clone(), + ]; b.brew_time = int("BrewTime").unwrap_or(0); b.total_brew_time = int("total_brew_time").unwrap_or(400); if b.brew_time > 0 { @@ -387,23 +437,43 @@ impl HeightmapChunk for HeightmapView<'_> { SECTIONS as i32 * 16 } fn highest_section_y(&self) -> i32 { - let top = self.chunk.sections.iter().rposition(|s| !s.is_uniform(self.tables.air)).unwrap_or(0); + let top = self + .chunk + .sections + .iter() + .rposition(|s| !s.is_uniform(self.tables.air)) + .unwrap_or(0); MIN_Y + top as i32 * 16 } fn block_state(&self, x: i32, y: i32, z: i32) -> Self::State { - self.tables.heightmaps.heightmap_state(self.chunk.block(x, y, z)) + self.tables + .heightmaps + .heightmap_state(self.chunk.block(x, y, z)) } } /// Heightmaps kept after world generation (`ChunkStatus.FULL.heightmapsAfter`). fn heightmaps(chunk: &Chunk, tables: &SaveTables) -> Tag { - let kinds = [HeightmapType::WorldSurface, HeightmapType::OceanFloor, HeightmapType::MotionBlocking, HeightmapType::MotionBlockingNoLeaves]; - let mut maps: Vec = kinds.iter().filter_map(|k| Heightmap::new(*k, MIN_Y, SECTIONS as i32 * 16).ok()).collect(); + let kinds = [ + HeightmapType::WorldSurface, + HeightmapType::OceanFloor, + HeightmapType::MotionBlocking, + HeightmapType::MotionBlockingNoLeaves, + ]; + let mut maps: Vec = kinds + .iter() + .filter_map(|k| Heightmap::new(*k, MIN_Y, SECTIONS as i32 * 16).ok()) + .collect(); let view = HeightmapView { chunk, tables }; let mut refs: Vec<&mut Heightmap> = maps.iter_mut().collect(); if Heightmap::prime(&view, &mut refs).is_err() { return Tag::Compound(Compound::new()); } - Tag::compound(maps.iter().map(|m| (m.kind().name(), Tag::LongArray(m.raw_data().iter().map(|&w| w as i64).collect())))) + Tag::compound(maps.iter().map(|m| { + ( + m.kind().name(), + Tag::LongArray(m.raw_data().iter().map(|&w| w as i64).collect()), + ) + })) } /// Vanilla light layer (nibbles, index y<<8|z<<4|x, low nibble first). fn nibbles(light: &Light, sky: bool) -> Vec { @@ -426,7 +496,13 @@ pub fn encode(chunk: &Chunk, registry: &BlockRegistry, biomes: &Biomes) -> Named } /// The chunk NBT vanilla's `SerializableChunkData.write` produces for a full /// chunk. `sky_light` is false in dimensions without skylight. -pub fn encode_with(chunk: &Chunk, registry: &BlockRegistry, biomes: &Biomes, tables: Option<&SaveTables>, sky_light: bool) -> NamedTag { +pub fn encode_with( + chunk: &Chunk, + registry: &BlockRegistry, + biomes: &Biomes, + tables: Option<&SaveTables>, + sky_light: bool, +) -> NamedTag { let mut sections = Vec::new(); let air = tables.map_or(0, |t| t.air); // Sky layers below the highest section with light other than 15 are @@ -462,7 +538,13 @@ pub fn encode_with(chunk: &Chunk, registry: &BlockRegistry, biomes: &Biomes, tab let state = registry.state(BlockStateId(u32::from(*id))); match state { // BlockState.CODEC: the block name for default states. - Some(s) if tables.is_some_and(|t| t.default_state.get(*id as usize) == Some(&true)) => string(&s.name), + Some(s) + if tables.is_some_and(|t| { + t.default_state.get(*id as usize) == Some(&true) + }) => + { + string(&s.name) + } Some(s) => s.to_nbt(), None => string("minecraft:air"), } @@ -471,7 +553,10 @@ pub fn encode_with(chunk: &Chunk, registry: &BlockRegistry, biomes: &Biomes, tab ), )]; if palette.len() > 1 { - states.push(("data", Tag::LongArray(pack(&indices, bits_for(palette.len(), 4))))); + states.push(( + "data", + Tag::LongArray(pack(&indices, bits_for(palette.len(), 4))), + )); } let quart: Vec = (0..64).map(|i| chunk.biomes[si * 64 + i]).collect(); let mut biome_palette: Vec = Vec::new(); @@ -487,10 +572,18 @@ pub fn encode_with(chunk: &Chunk, registry: &BlockRegistry, biomes: &Biomes, tab .collect(); let mut biome_tag = vec![( "palette", - Tag::List(biome_palette.iter().map(|b| string(&biomes.get(*b).name)).collect()), + Tag::List( + biome_palette + .iter() + .map(|b| string(&biomes.get(*b).name)) + .collect(), + ), )]; if biome_palette.len() > 1 { - biome_tag.push(("data", Tag::LongArray(pack(&biome_indices, bits_for(biome_palette.len(), 0))))); + biome_tag.push(( + "data", + Tag::LongArray(pack(&biome_indices, bits_for(biome_palette.len(), 0))), + )); } let mut entries = vec![ ("Y", Tag::Byte(y as i8)), @@ -514,20 +607,33 @@ pub fn encode_with(chunk: &Chunk, registry: &BlockRegistry, biomes: &Biomes, tab } let extras = chunk.saved.as_deref(); let block_name = |p: &(i32, i32, i32)| -> String { - registry.state(chunk.block(p.0 & 15, p.1, p.2 & 15)).map_or_else(String::new, |s| s.name.clone()) + registry + .state(chunk.block(p.0 & 15, p.1, p.2 & 15)) + .map_or_else(String::new, |s| s.name.clone()) }; - let mut block_entities: Vec = chunk.block_entities.iter().map(|(p, e)| encode_block_entity(*p, e, &block_name(p))).collect(); + let mut block_entities: Vec = chunk + .block_entities + .iter() + .map(|(p, e)| encode_block_entity(*p, e, &block_name(p))) + .collect(); if let Some(extras) = extras { for raw in &extras.block_entities { - let pos = (number(raw.get("x")).unwrap_or(0) as i32, number(raw.get("y")).unwrap_or(0) as i32, number(raw.get("z")).unwrap_or(0) as i32); + let pos = ( + number(raw.get("x")).unwrap_or(0) as i32, + number(raw.get("y")).unwrap_or(0) as i32, + number(raw.get("z")).unwrap_or(0) as i32, + ); let state = chunk.get(pos.0 & 15, pos.1, pos.2 & 15) as usize; - let still_there = tables.is_none_or(|t| t.block_entity.get(state).copied().unwrap_or(true)); + let still_there = + tables.is_none_or(|t| t.block_entity.get(state).copied().unwrap_or(true)); if still_there && !chunk.block_entities.iter().any(|(p, _)| *p == pos) { block_entities.push(raw.clone()); } } } - let mut root = extras.map(|e| Tag::Compound(e.root.clone())).unwrap_or_else(|| Tag::Compound(Compound::new())); + let mut root = extras + .map(|e| Tag::Compound(e.root.clone())) + .unwrap_or_else(|| Tag::Compound(Compound::new())); for (key, value) in [ ("DataVersion", Tag::Int(DATA_VERSION)), ("xPos", Tag::Int(chunk.x)), @@ -543,32 +649,64 @@ pub fn encode_with(chunk: &Chunk, registry: &BlockRegistry, biomes: &Biomes, tab } if let Some(Tag::Compound(map)) = Some(&mut root) { map.entry("InhabitedTime".into()).or_insert(Tag::Long(0)); - map.entry("structures".into()).or_insert_with(|| Tag::compound([("References", Tag::Compound(Compound::new())), ("starts", Tag::Compound(Compound::new()))])); - map.entry("PostProcessing".into()).or_insert_with(|| Tag::List(vec![Tag::List(Vec::new()); SECTIONS])); + map.entry("structures".into()).or_insert_with(|| { + Tag::compound([ + ("References", Tag::Compound(Compound::new())), + ("starts", Tag::Compound(Compound::new())), + ]) + }); + map.entry("PostProcessing".into()) + .or_insert_with(|| Tag::List(vec![Tag::List(Vec::new()); SECTIONS])); } if let Some(t) = tables { put(&mut root, "Heightmaps", heightmaps(chunk, t)); let names = |k: u32| t.block_names.get(k as usize).cloned(); - let (blocks, fluids) = extras.map_or((&[][..], &[][..]), |e| (&e.block_ticks[..], &e.fluid_ticks[..])); + let (blocks, fluids) = extras.map_or((&[][..], &[][..]), |e| { + (&e.block_ticks[..], &e.fluid_ticks[..]) + }); put(&mut root, "block_ticks", tick_list(blocks, names)); put(&mut root, "fluid_ticks", tick_list(fluids, fluid_name)); } - NamedTag { name: "".into(), tag: root } + NamedTag { + name: "".into(), + tag: root, + } } /// Root keys `encode_with` regenerates; everything else is kept as loaded. const GENERATED_KEYS: [&str; 14] = [ - "DataVersion", "xPos", "zPos", "yPos", "Status", "LastUpdate", "isLightOn", "sections", "block_entities", "Heightmaps", - "block_ticks", "fluid_ticks", "entities", "CarvingMask", + "DataVersion", + "xPos", + "zPos", + "yPos", + "Status", + "LastUpdate", + "isLightOn", + "sections", + "block_entities", + "Heightmaps", + "block_ticks", + "fluid_ticks", + "entities", + "CarvingMask", ]; pub fn decode(root: &NamedTag, registry: &BlockRegistry, biomes: &Biomes) -> Option { decode_with(root, registry, biomes, None) } /// Only full chunks load; partially generated ones (vanilla's world border /// of proto chunks) are generated again. -pub fn decode_with(root: &NamedTag, registry: &BlockRegistry, biomes: &Biomes, tables: Option<&SaveTables>) -> Option { +pub fn decode_with( + root: &NamedTag, + registry: &BlockRegistry, + biomes: &Biomes, + tables: Option<&SaveTables>, +) -> Option { let tag = &root.tag; - let Tag::Int(x) = tag.get("xPos")? else { return None }; - let Tag::Int(z) = tag.get("zPos")? else { return None }; + let Tag::Int(x) = tag.get("xPos")? else { + return None; + }; + let Tag::Int(z) = tag.get("zPos")? else { + return None; + }; if text(tag.get("Status")).is_some_and(|s| s != "minecraft:full" && s != "full") { return None; } @@ -576,9 +714,13 @@ pub fn decode_with(root: &NamedTag, registry: &BlockRegistry, biomes: &Biomes, t let air = registry.default_state("minecraft:air")?.0 as u16; let mut cache: HashMap = HashMap::new(); let mut biome_data = (*chunk.biomes).clone(); - let Some(Tag::List(sections)) = tag.get("sections") else { return Some(chunk) }; + let Some(Tag::List(sections)) = tag.get("sections") else { + return Some(chunk); + }; for section in sections { - let Some(y) = number(section.get("Y")) else { continue }; + let Some(y) = number(section.get("Y")) else { + continue; + }; let si = y as i32 - (MIN_Y >> 4); if !(0..SECTIONS as i32).contains(&si) { continue; @@ -590,7 +732,10 @@ pub fn decode_with(root: &NamedTag, registry: &BlockRegistry, biomes: &Biomes, t .iter() .map(|p| { let state = BlockState::from_nbt(p).ok(); - let key = state.as_ref().map(|s| format!("{}{:?}", s.name, s.properties)).unwrap_or_default(); + let key = state + .as_ref() + .map(|s| format!("{}{:?}", s.name, s.properties)) + .unwrap_or_default(); *cache.entry(key).or_insert_with(|| { state .and_then(|s| { @@ -633,7 +778,9 @@ pub fn decode_with(root: &NamedTag, registry: &BlockRegistry, biomes: &Biomes, t }) .collect(); let indices = match b.get("data") { - Some(Tag::LongArray(data)) if ids.len() > 1 => unpack(data, bits_for(ids.len(), 0), 64), + Some(Tag::LongArray(data)) if ids.len() > 1 => { + unpack(data, bits_for(ids.len(), 0), 64) + } _ => vec![0; 64], }; for (i, idx) in indices.iter().enumerate() { @@ -655,10 +802,16 @@ pub fn decode_with(root: &NamedTag, registry: &BlockRegistry, biomes: &Biomes, t } } if let Tag::Compound(map) = tag { - extras.root = map.iter().filter(|(k, _)| !GENERATED_KEYS.contains(&k.to_string_lossy().as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); + extras.root = map + .iter() + .filter(|(k, _)| !GENERATED_KEYS.contains(&k.to_string_lossy().as_str())) + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); } if let Some(t) = tables { - extras.block_ticks = read_ticks(tag.get("block_ticks"), (*x, *z), |n| t.block_ids.get(n).map(|&i| u32::from(i))); + extras.block_ticks = read_ticks(tag.get("block_ticks"), (*x, *z), |n| { + t.block_ids.get(n).map(|&i| u32::from(i)) + }); extras.fluid_ticks = read_ticks(tag.get("fluid_ticks"), (*x, *z), fluid_id); } chunk.saved = Some(Arc::new(extras)); @@ -693,12 +846,20 @@ impl SaveDir { } fn read_record(&self, folder: &str, x: i32, z: i32) -> Option { let key = (x >> 5, z >> 5); - let cache = if folder == "region" { &self.regions } else { &self.entity_regions }; + let cache = if folder == "region" { + &self.regions + } else { + &self.entity_regions + }; let region = { let mut regions = cache.lock().ok()?; regions .entry(key) - .or_insert_with(|| RegionFile::open(self.region_path(folder, key.0, key.1)).ok().map(|r| Arc::new(Mutex::new(r)))) + .or_insert_with(|| { + RegionFile::open(self.region_path(folder, key.0, key.1)) + .ok() + .map(|r| Arc::new(Mutex::new(r))) + }) .clone()? }; let record = region.lock().ok()?.read(ChunkPos::new(x, z)).ok()??; @@ -722,10 +883,18 @@ impl SaveDir { } /// Rewrite every region file in `folder` touched by `records`, keeping /// its other chunks. `None` deletes a chunk. - fn write_records(&self, folder: &str, records: Vec<((i32, i32), Option)>) -> Result<()> { - let mut by_region: BTreeMap<(i32, i32), Vec<((i32, i32), Option)>> = BTreeMap::new(); + fn write_records( + &self, + folder: &str, + records: Vec<((i32, i32), Option)>, + ) -> Result<()> { + let mut by_region: BTreeMap<(i32, i32), Vec<((i32, i32), Option)>> = + BTreeMap::new(); for (key, tag) in records { - by_region.entry((key.0 >> 5, key.1 >> 5)).or_default().push((key, tag)); + by_region + .entry((key.0 >> 5, key.1 >> 5)) + .or_default() + .push((key, tag)); } if by_region.is_empty() { return Ok(()); @@ -735,7 +904,11 @@ impl SaveDir { let timestamp = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_secs() as u32); - let cache = if folder == "region" { &self.regions } else { &self.entity_regions }; + let cache = if folder == "region" { + &self.regions + } else { + &self.entity_regions + }; for ((rx, rz), list) in by_region { let path = self.region_path(folder, rx, rz); let mut records: BTreeMap<(i32, i32), ChunkRecord> = BTreeMap::new(); @@ -750,7 +923,15 @@ impl SaveDir { for (key, tag) in list { match tag { Some(tag) => { - records.insert(key, ChunkRecord::from_nbt(&tag, Compression::Zlib, timestamp, Limits::default())?); + records.insert( + key, + ChunkRecord::from_nbt( + &tag, + Compression::Zlib, + timestamp, + Limits::default(), + )?, + ); } None => { records.remove(&key); @@ -769,17 +950,30 @@ impl SaveDir { writer.finish()?; fs::rename(&temporary, &path)?; } - cache.lock().map_err(|_| "region cache poisoned")?.remove(&(rx, rz)); + cache + .lock() + .map_err(|_| "region cache poisoned")? + .remove(&(rx, rz)); } let _ = fs::remove_dir(&staging); Ok(()) } /// Rewrite every region touched by `chunks`, keeping their other chunks. - pub fn save(&self, chunks: &[Arc], registry: &BlockRegistry, biomes: &Biomes) -> Result { + pub fn save( + &self, + chunks: &[Arc], + registry: &BlockRegistry, + biomes: &Biomes, + ) -> Result { let tables = self.tables.get().map(|t| &**t); let records = chunks .iter() - .map(|c| ((c.x, c.z), Some(encode_with(c, registry, biomes, tables, self.sky_light)))) + .map(|c| { + ( + (c.x, c.z), + Some(encode_with(c, registry, biomes, tables, self.sky_light)), + ) + }) .collect(); self.write_records("region", records)?; Ok(chunks.len()) @@ -817,9 +1011,19 @@ fn write_dat(path: &Path, tag: Tag) -> Result<()> { if let Some(dir) = path.parent() { fs::create_dir_all(dir)?; } - let bytes = nbt::write_named(&NamedTag { name: "".into(), tag }, Limits::default()).map_err(|e| e.to_string())?; + let bytes = nbt::write_named( + &NamedTag { + name: "".into(), + tag, + }, + Limits::default(), + ) + .map_err(|e| e.to_string())?; let compressed = Compression::Gzip.encode(&bytes)?; - let file = path.file_name().and_then(|n| n.to_str()).unwrap_or("data.dat"); + let file = path + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("data.dat"); let temporary = path.with_file_name(format!("{file}_new")); fs::write(&temporary, compressed)?; if path.exists() { @@ -834,17 +1038,32 @@ fn write_dat(path: &Path, tag: Tag) -> Result<()> { } /// `SavedDataStorage`: `{data: ..., DataVersion}` under `data/minecraft/`. fn saved_data_path(world: &Path, name: &str) -> PathBuf { - world.join("data").join("minecraft").join(format!("{name}.dat")) + world + .join("data") + .join("minecraft") + .join(format!("{name}.dat")) } fn read_saved_data(world: &Path, name: &str) -> Option { - read_dat(&saved_data_path(world, name))?.get("data").cloned() + read_dat(&saved_data_path(world, name))? + .get("data") + .cloned() } fn write_saved_data(world: &Path, name: &str, data: Tag) -> Result<()> { - write_dat(&saved_data_path(world, name), Tag::compound([("data", data), ("DataVersion", Tag::Int(DATA_VERSION))])) + write_dat( + &saved_data_path(world, name), + Tag::compound([("data", data), ("DataVersion", Tag::Int(DATA_VERSION))]), + ) } fn uuid_text(u: [i32; 4]) -> String { let hex: String = u.iter().map(|v| format!("{:08x}", *v as u32)).collect(); - format!("{}-{}-{}-{}-{}", &hex[0..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..32]) + format!( + "{}-{}-{}-{}-{}", + &hex[0..8], + &hex[8..12], + &hex[12..16], + &hex[16..20], + &hex[20..32] + ) } fn uuid_from_text(s: &str) -> Option<[i32; 4]> { let hex: String = s.chars().filter(|c| *c != '-').collect(); @@ -859,7 +1078,9 @@ fn uuid_from_text(s: &str) -> Option<[i32; 4]> { } /// A random (version 4) UUID as vanilla's four-int form. pub fn random_uuid() -> [i32; 4] { - let t = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos() as u64); + let t = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos() as u64); let mut s = t ^ (std::process::id() as u64).rotate_left(32) ^ 0x9E37_79B9_7F4A_7C15; let mut next = || { s ^= s << 13; @@ -903,29 +1124,78 @@ pub(crate) fn read_doubles(tag: Option<&Tag>) -> Option<[f64; N] /// Default game rules of a new 26.3 world (`data/minecraft/game_rules.dat`). const GAME_RULES: [(&str, i32); 58] = [ - ("spawn_wandering_traders", 1), ("block_drops", 1), ("reduced_debug_info", 0), ("show_death_messages", 1), - ("spawner_blocks_work", 1), ("spawn_monsters", 1), ("tnt_explodes", 1), ("player_movement_check", 1), - ("immediate_respawn", 0), ("block_explosion_drop_decay", 1), ("spread_vines", 1), ("max_entity_cramming", 24), - ("forgive_dead_players", 1), ("fall_damage", 1), ("send_command_feedback", 1), ("global_sound_events", 1), - ("elytra_movement_check", 1), ("fire_spread_radius_around_player", 128), ("freeze_damage", 1), - ("mob_explosion_drop_decay", 1), ("natural_health_regeneration", 1), ("players_nether_portal_default_delay", 80), - ("mob_drops", 1), ("log_admin_commands", 1), ("mob_griefing", 1), ("spawn_mobs", 1), ("pvp", 1), - ("spectators_generate_chunks", 1), ("max_command_sequence_length", 65536), ("players_nether_portal_creative_delay", 0), - ("players_sleeping_percentage", 100), ("advance_weather", 1), ("max_block_modifications", 32768), - ("max_command_forks", 65536), ("drowning_damage", 1), ("command_block_output", 1), ("locator_bar", 1), - ("show_advancement_messages", 1), ("respawn_radius", 10), ("raids", 1), ("spawn_phantoms", 1), - ("max_snow_accumulation_height", 1), ("limited_crafting", 0), ("allow_entering_nether_using_portals", 1), - ("lava_source_conversion", 0), ("tnt_explosion_drop_decay", 0), ("universal_anger", 0), ("keep_inventory", 0), - ("spawn_patrols", 1), ("random_tick_speed", 3), ("fire_damage", 1), ("entity_drops", 1), ("advance_time", 1), - ("command_blocks_work", 1), ("spawn_wardens", 1), ("water_source_conversion", 1), ("projectiles_can_break_blocks", 1), + ("spawn_wandering_traders", 1), + ("block_drops", 1), + ("reduced_debug_info", 0), + ("show_death_messages", 1), + ("spawner_blocks_work", 1), + ("spawn_monsters", 1), + ("tnt_explodes", 1), + ("player_movement_check", 1), + ("immediate_respawn", 0), + ("block_explosion_drop_decay", 1), + ("spread_vines", 1), + ("max_entity_cramming", 24), + ("forgive_dead_players", 1), + ("fall_damage", 1), + ("send_command_feedback", 1), + ("global_sound_events", 1), + ("elytra_movement_check", 1), + ("fire_spread_radius_around_player", 128), + ("freeze_damage", 1), + ("mob_explosion_drop_decay", 1), + ("natural_health_regeneration", 1), + ("players_nether_portal_default_delay", 80), + ("mob_drops", 1), + ("log_admin_commands", 1), + ("mob_griefing", 1), + ("spawn_mobs", 1), + ("pvp", 1), + ("spectators_generate_chunks", 1), + ("max_command_sequence_length", 65536), + ("players_nether_portal_creative_delay", 0), + ("players_sleeping_percentage", 100), + ("advance_weather", 1), + ("max_block_modifications", 32768), + ("max_command_forks", 65536), + ("drowning_damage", 1), + ("command_block_output", 1), + ("locator_bar", 1), + ("show_advancement_messages", 1), + ("respawn_radius", 10), + ("raids", 1), + ("spawn_phantoms", 1), + ("max_snow_accumulation_height", 1), + ("limited_crafting", 0), + ("allow_entering_nether_using_portals", 1), + ("lava_source_conversion", 0), + ("tnt_explosion_drop_decay", 0), + ("universal_anger", 0), + ("keep_inventory", 0), + ("spawn_patrols", 1), + ("random_tick_speed", 3), + ("fire_damage", 1), + ("entity_drops", 1), + ("advance_time", 1), + ("command_blocks_work", 1), + ("spawn_wardens", 1), + ("water_source_conversion", 1), + ("projectiles_can_break_blocks", 1), ("ender_pearls_vanish_on_death", 1), ]; /// Integer-valued rules; the others are booleans stored as bytes. const INT_RULES: [&str; 11] = [ - "max_snow_accumulation_height", "random_tick_speed", - "max_entity_cramming", "fire_spread_radius_around_player", "players_nether_portal_default_delay", - "max_command_sequence_length", "players_nether_portal_creative_delay", "players_sleeping_percentage", - "max_block_modifications", "max_command_forks", "respawn_radius", + "max_snow_accumulation_height", + "random_tick_speed", + "max_entity_cramming", + "fire_spread_radius_around_player", + "players_nether_portal_default_delay", + "max_command_sequence_length", + "players_nether_portal_creative_delay", + "players_sleeping_percentage", + "max_block_modifications", + "max_command_forks", + "respawn_radius", ]; /// World and player state stored in `level.dat`, the saved-data files and @@ -1001,13 +1271,22 @@ impl Level { // 26.3: spawn {pos: [I; x, y, z], dimension, yaw, pitch}; older: SpawnX/Y/Z. level.world_spawn = match data.get("spawn").and_then(|s| s.get("pos")) { Some(Tag::IntArray(p)) if p.len() == 3 => Some([p[0], p[1], p[2]]), - _ => data.get("SpawnX").map(|_| [n(data.get("SpawnX")) as i32, n(data.get("SpawnY")) as i32, n(data.get("SpawnZ")) as i32]), + _ => data.get("SpawnX").map(|_| { + [ + n(data.get("SpawnX")) as i32, + n(data.get("SpawnY")) as i32, + n(data.get("SpawnZ")) as i32, + ] + }), }; if let Some(d) = data.get("difficulty_settings") { level.difficulty = text(d.get("difficulty")).unwrap_or_else(|| "normal".into()); level.hardcore = n(d.get("hardcore")) != 0; } - let mut rules: BTreeMap = GAME_RULES.iter().map(|(k, v)| ((*k).to_owned(), *v)).collect(); + let mut rules: BTreeMap = GAME_RULES + .iter() + .map(|(k, v)| ((*k).to_owned(), *v)) + .collect(); let saved_rules = read_saved_data(dir, "game_rules"); if let Some(Tag::Compound(map)) = &saved_rules { for (k, v) in map { @@ -1026,11 +1305,20 @@ impl Level { .unwrap_or(0); // Day time: the overworld clock (26.3) or Data.DayTime. level.day_time = read_saved_data(dir, "world_clocks") - .and_then(|c| number(c.get("minecraft:overworld").and_then(|o| o.get("total_ticks")))) + .and_then(|c| { + number( + c.get("minecraft:overworld") + .and_then(|o| o.get("total_ticks")), + ) + }) .or_else(|| number(data.get("DayTime"))) .unwrap_or(level.time); let weather = read_saved_data(dir, "weather"); - let w = |new: &str, old: &str| number(weather.as_ref().and_then(|w| w.get(new))).or_else(|| number(data.get(old))).unwrap_or(0); + let w = |new: &str, old: &str| { + number(weather.as_ref().and_then(|w| w.get(new))) + .or_else(|| number(data.get(old))) + .unwrap_or(0) + }; let raining = w("raining", "raining") != 0; let thundering = w("thundering", "thundering") != 0; level.weather = crate::world::Weather { @@ -1060,7 +1348,9 @@ impl Level { }) .or_else(|| data.get("Player").cloned()); level.player_uuid = uuid_from_tag(player.as_ref().and_then(|p| p.get("UUID"))).or(uuid); - let spawn = level.world_spawn.map(|s| [f64::from(s[0]), f64::from(s[1]), f64::from(s[2])]); + let spawn = level + .world_spawn + .map(|s| [f64::from(s[0]), f64::from(s[1]), f64::from(s[2])]); level.spawn = spawn; if let Some(p) = &player { level.read_player(p); @@ -1116,7 +1406,13 @@ impl Level { } } if let Some(eq) = p.get("equipment") { - for (name, slot) in [("feet", 100u8), ("legs", 101), ("chest", 102), ("head", 103), ("offhand", 150)] { + for (name, slot) in [ + ("feet", 100u8), + ("legs", 101), + ("chest", 102), + ("head", 103), + ("offhand", 150), + ] { if let Some(stack) = eq.get(name).and_then(item_from_nbt) { inventory.retain(|(s, ..)| *s != slot); if let Some(extra) = &stack.extra { @@ -1135,7 +1431,13 @@ impl Level { .filter_map(|e| { let id = text(e.get("id"))?; let get = |k: &str| number(e.get(k)); - Some((id, get("duration").unwrap_or(0) as i32, get("amplifier").unwrap_or(0) as i32, get("ambient").unwrap_or(0) != 0, get("show_icon").is_none_or(|v| v != 0))) + Some(( + id, + get("duration").unwrap_or(0) as i32, + get("amplifier").unwrap_or(0) as i32, + get("ambient").unwrap_or(0) != 0, + get("show_icon").is_none_or(|v| v != 0), + )) }) .collect(), _ => Vec::new(), @@ -1154,7 +1456,12 @@ impl Level { let mut equipment = Vec::new(); for (slot, id, count, damage) in &self.inventory { let extra = self.inventory_components.get(slot).cloned(); - let stack = crate::items::ItemStack { item: Arc::from(id.as_str()), count: *count, damage: *damage, extra }; + let stack = crate::items::ItemStack { + item: Arc::from(id.as_str()), + count: *count, + damage: *damage, + extra, + }; match slot { 0..=35 => { let mut entries = vec![("Slot", Tag::Byte(*slot as i8))]; @@ -1171,7 +1478,11 @@ impl Level { } let creative = self.creative; let mut abilities = compound_or_empty(p.get("abilities").cloned()); - for (k, v) in [("invulnerable", creative), ("mayfly", creative), ("instabuild", creative)] { + for (k, v) in [ + ("invulnerable", creative), + ("mayfly", creative), + ("instabuild", creative), + ] { put(&mut abilities, k, Tag::Byte(i8::from(v))); } if !creative { @@ -1179,8 +1490,10 @@ impl Level { } if let Tag::Compound(map) = &mut abilities { map.entry("mayBuild".into()).or_insert(Tag::Byte(1)); - map.entry("flySpeed".into()).or_insert(Tag::Float(0.05f32.to_bits())); - map.entry("walkSpeed".into()).or_insert(Tag::Float(0.1f32.to_bits())); + map.entry("flySpeed".into()) + .or_insert(Tag::Float(0.05f32.to_bits())); + map.entry("walkSpeed".into()) + .or_insert(Tag::Float(0.1f32.to_bits())); map.entry("flying".into()).or_insert(Tag::Byte(0)); } let uuid = self.player_uuid.unwrap_or([0, 0, 0, 0]); @@ -1194,7 +1507,10 @@ impl Level { ("Health", Tag::Float(self.health.to_bits())), ("foodLevel", Tag::Int(self.food)), ("foodSaturationLevel", Tag::Float(self.saturation.to_bits())), - ("foodExhaustionLevel", Tag::Float(self.food_exhaustion.to_bits())), + ( + "foodExhaustionLevel", + Tag::Float(self.food_exhaustion.to_bits()), + ), ("foodTickTimer", Tag::Int(self.food_tick_timer)), ("XpLevel", Tag::Int(self.xp_level)), ("XpP", Tag::Float(self.xp_progress.to_bits())), @@ -1222,7 +1538,14 @@ impl Level { ("playerGameType", Tag::Int(i32::from(self.creative))), ("Inventory", Tag::List(inventory)), ("abilities", abilities), - ("Dimension", string(if self.dimension.is_empty() { "minecraft:overworld" } else { &self.dimension })), + ( + "Dimension", + string(if self.dimension.is_empty() { + "minecraft:overworld" + } else { + &self.dimension + }), + ), ]; if !equipment.is_empty() { entries.push(("equipment", Tag::compound(equipment))); @@ -1232,7 +1555,11 @@ impl Level { } // A respawn point other than the world spawn (a bed). if let Some(s) = self.spawn { - let block = [s[0].floor() as i32, s[1].floor() as i32, s[2].floor() as i32]; + let block = [ + s[0].floor() as i32, + s[1].floor() as i32, + s[2].floor() as i32, + ]; if Some(block) != self.world_spawn { entries.push(( "respawn", @@ -1249,7 +1576,20 @@ impl Level { put(&mut p, key, value); } if let Tag::Compound(map) = &mut p { - for (key, value) in [("Air", Tag::Short(300)), ("Fire", Tag::Short(-20)), ("Invulnerable", Tag::Byte(0)), ("PortalCooldown", Tag::Int(0)), ("Score", Tag::Int(0)), ("SleepTimer", Tag::Short(0)), ("XpSeed", Tag::Int(0)), ("seenCredits", Tag::Byte(0)), ("HurtTime", Tag::Short(0)), ("DeathTime", Tag::Short(0)), ("AbsorptionAmount", Tag::Float(0)), ("FallFlying", Tag::Byte(0))] { + for (key, value) in [ + ("Air", Tag::Short(300)), + ("Fire", Tag::Short(-20)), + ("Invulnerable", Tag::Byte(0)), + ("PortalCooldown", Tag::Int(0)), + ("Score", Tag::Int(0)), + ("SleepTimer", Tag::Short(0)), + ("XpSeed", Tag::Int(0)), + ("seenCredits", Tag::Byte(0)), + ("HurtTime", Tag::Short(0)), + ("DeathTime", Tag::Short(0)), + ("AbsorptionAmount", Tag::Float(0)), + ("FallFlying", Tag::Byte(0)), + ] { map.entry(key.into()).or_insert(value); } } @@ -1259,16 +1599,45 @@ impl Level { pub fn write(&mut self, dir: &Path) -> Result<()> { fs::create_dir_all(dir)?; let existing = read_dat(&dir.join("level.dat")).and_then(|r| r.get("Data").cloned()); - let legacy = existing.as_ref().is_some_and(|d| d.get("Player").is_some() || d.get("WorldGenSettings").is_some()); + let legacy = existing + .as_ref() + .is_some_and(|d| d.get("Player").is_some() || d.get("WorldGenSettings").is_some()); let mut data = compound_or_empty(existing); if let Tag::Compound(map) = &mut data { // Pre-26.3 keys now stored elsewhere (a legacy Horizon level.dat). for key in [ - "Player", "WorldGenSettings", "DayTime", "SpawnX", "SpawnY", "SpawnZ", "SpawnAngle", "clearWeatherTime", "rainTime", - "thunderTime", "raining", "thundering", "Difficulty", "hardcore", "GameRules", "DimensionData", "WanderingTraderSpawnChance", - "WanderingTraderSpawnDelay", "WanderingTraderId", "BorderCenterX", "BorderCenterZ", "BorderSize", "BorderSafeZone", - "BorderWarningBlocks", "BorderWarningTime", "BorderSizeLerpTime", "BorderSizeLerpTarget", "BorderDamagePerBlock", - "DifficultyLocked", "ScheduledEvents", "CustomBossEvents", "DragonFight", + "Player", + "WorldGenSettings", + "DayTime", + "SpawnX", + "SpawnY", + "SpawnZ", + "SpawnAngle", + "clearWeatherTime", + "rainTime", + "thunderTime", + "raining", + "thundering", + "Difficulty", + "hardcore", + "GameRules", + "DimensionData", + "WanderingTraderSpawnChance", + "WanderingTraderSpawnDelay", + "WanderingTraderId", + "BorderCenterX", + "BorderCenterZ", + "BorderSize", + "BorderSafeZone", + "BorderWarningBlocks", + "BorderWarningTime", + "BorderSizeLerpTime", + "BorderSizeLerpTarget", + "BorderDamagePerBlock", + "DifficultyLocked", + "ScheduledEvents", + "CustomBossEvents", + "DragonFight", ] { map.remove(&JavaString::from(key)); } @@ -1276,7 +1645,13 @@ impl Level { let uuid = *self.player_uuid.get_or_insert_with(random_uuid); // A new world's first spawn point is its world spawn. if self.world_spawn.is_none() { - self.world_spawn = self.spawn.map(|s| [s[0].floor() as i32, s[1].floor() as i32, s[2].floor() as i32]); + self.world_spawn = self.spawn.map(|s| { + [ + s[0].floor() as i32, + s[1].floor() as i32, + s[2].floor() as i32, + ] + }); } let spawn = self.world_spawn.unwrap_or([0, 64, 0]); let mut history: Vec = match data.get("version_history") { @@ -1294,12 +1669,26 @@ impl Level { brands.push(string("horizon")); } let mut difficulty = compound_or_empty(data.get("difficulty_settings").cloned()); - put(&mut difficulty, "difficulty", string(if self.difficulty.is_empty() { "normal" } else { &self.difficulty })); - put(&mut difficulty, "hardcore", Tag::Byte(i8::from(self.hardcore))); + put( + &mut difficulty, + "difficulty", + string(if self.difficulty.is_empty() { + "normal" + } else { + &self.difficulty + }), + ); + put( + &mut difficulty, + "hardcore", + Tag::Byte(i8::from(self.hardcore)), + ); if let Tag::Compound(map) = &mut difficulty { map.entry("locked".into()).or_insert(Tag::Byte(0)); } - let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as i64); for (key, value) in [ ("DataVersion", Tag::Int(DATA_VERSION)), ( @@ -1339,7 +1728,19 @@ impl Level { map.entry("DataPacks".into()).or_insert_with(|| { Tag::compound([ ("Enabled", Tag::List(vec![string("vanilla")])), - ("Disabled", Tag::List(["minecart_improvements", "redstone_experiments", "trade_rebalance"].iter().map(|s| string(s)).collect())), + ( + "Disabled", + Tag::List( + [ + "minecart_improvements", + "redstone_experiments", + "trade_rebalance", + ] + .iter() + .map(|s| string(s)) + .collect(), + ), + ), ]) }); } @@ -1361,17 +1762,30 @@ impl Level { put(&mut overworld, "total_ticks", Tag::Long(self.day_time)); put(&mut clocks, "minecraft:overworld", overworld); if let Tag::Compound(map) = &mut clocks { - map.entry("minecraft:the_end".into()).or_insert_with(|| Tag::compound([("total_ticks", Tag::Long(self.time))])); + map.entry("minecraft:the_end".into()) + .or_insert_with(|| Tag::compound([("total_ticks", Tag::Long(self.time))])); } write_saved_data(dir, "world_clocks", clocks)?; if legacy || !saved_data_path(dir, "world_gen_settings").exists() { let dimension = |kind: &str, settings: &str, source: Tag| { Tag::compound([ ("type", string(kind)), - ("generator", Tag::compound([("type", string("minecraft:noise")), ("settings", string(settings)), ("biome_source", source)])), + ( + "generator", + Tag::compound([ + ("type", string("minecraft:noise")), + ("settings", string(settings)), + ("biome_source", source), + ]), + ), + ]) + }; + let preset = |p: &str| { + Tag::compound([ + ("type", string("minecraft:multi_noise")), + ("preset", string(p)), ]) }; - let preset = |p: &str| Tag::compound([("type", string("minecraft:multi_noise")), ("preset", string(p))]); write_saved_data( dir, "world_gen_settings", @@ -1382,9 +1796,30 @@ impl Level { ( "dimensions", Tag::compound([ - ("minecraft:overworld", dimension("minecraft:overworld", "minecraft:overworld", preset("minecraft:overworld"))), - ("minecraft:the_nether", dimension("minecraft:the_nether", "minecraft:nether", preset("minecraft:nether"))), - ("minecraft:the_end", dimension("minecraft:the_end", "minecraft:end", Tag::compound([("type", string("minecraft:the_end"))]))), + ( + "minecraft:overworld", + dimension( + "minecraft:overworld", + "minecraft:overworld", + preset("minecraft:overworld"), + ), + ), + ( + "minecraft:the_nether", + dimension( + "minecraft:the_nether", + "minecraft:nether", + preset("minecraft:nether"), + ), + ), + ( + "minecraft:the_end", + dimension( + "minecraft:the_end", + "minecraft:end", + Tag::compound([("type", string("minecraft:the_end"))]), + ), + ), ]), ), ]), @@ -1395,12 +1830,21 @@ impl Level { let mut rules = Tag::Compound(Compound::new()); for (name, default) in GAME_RULES { let value = self.game_rules.get(name).copied().unwrap_or(default); - let tag = if INT_RULES.contains(&name) { Tag::Int(value) } else { Tag::Byte(i8::from(value != 0)) }; + let tag = if INT_RULES.contains(&name) { + Tag::Int(value) + } else { + Tag::Byte(i8::from(value != 0)) + }; put(&mut rules, &format!("minecraft:{name}"), tag); } write_saved_data(dir, "game_rules", rules)?; } - write_dat(&dir.join("players").join("data").join(format!("{}.dat", uuid_text(uuid))), self.player_tag())?; + write_dat( + &dir.join("players") + .join("data") + .join(format!("{}.dat", uuid_text(uuid))), + self.player_tag(), + )?; write_dat(&dir.join("level.dat"), Tag::compound([("Data", data)]))?; Ok(()) } @@ -1418,7 +1862,9 @@ impl ChunkGenerator for Persistent { self.inner.worker() } fn load(&self, x: i32, z: i32) -> Option { - self.save.tables.get_or_init(|| Arc::new(SaveTables::new(&self.registry))); + self.save + .tables + .get_or_init(|| Arc::new(SaveTables::new(&self.registry))); let mut chunk = self.save.load(x, z, self.registry.registry, &self.biomes)?; for s in &mut chunk.sections { Arc::make_mut(s).compact(); @@ -1448,7 +1894,10 @@ mod tests { fn uuid_text_round_trips() { let u = [-158327916, 1572358581, -2125825222, -487948715]; assert_eq!(uuid_from_text(&uuid_text(u)), Some(u)); - assert_eq!(uuid_text([0, 1, 2, 3]), "00000000-0000-0001-0000-000200000003"); + assert_eq!( + uuid_text([0, 1, 2, 3]), + "00000000-0000-0001-0000-000200000003" + ); let r = random_uuid(); assert_eq!((r[1] >> 12) & 0xF, 4, "version 4"); } @@ -1476,7 +1925,11 @@ mod tests { health: 17.0, food: 15, saturation: 2.5, - inventory: vec![(0, "minecraft:stone".into(), 12, 0), (5, "minecraft:iron_sword".into(), 1, 3), (103, "minecraft:iron_helmet".into(), 1, 0)], + inventory: vec![ + (0, "minecraft:stone".into(), 12, 0), + (5, "minecraft:iron_sword".into(), 1, 3), + (103, "minecraft:iron_helmet".into(), 1, 0), + ], xp_level: 3, xp_progress: 0.5, xp_total: 30, @@ -1499,8 +1952,18 @@ mod tests { assert_eq!((back.health, back.food, back.saturation), (17.0, 15, 2.5)); let mut inv = back.inventory.clone(); inv.sort(); - assert_eq!(inv, vec![(0, "minecraft:stone".into(), 12, 0), (5, "minecraft:iron_sword".into(), 1, 3), (103, "minecraft:iron_helmet".into(), 1, 0)]); - assert_eq!((back.xp_level, back.xp_progress, back.xp_total), (3, 0.5, 30)); + assert_eq!( + inv, + vec![ + (0, "minecraft:stone".into(), 12, 0), + (5, "minecraft:iron_sword".into(), 1, 3), + (103, "minecraft:iron_helmet".into(), 1, 0) + ] + ); + assert_eq!( + (back.xp_level, back.xp_progress, back.xp_total), + (3, 0.5, 30) + ); assert_eq!(back.dimension, "minecraft:the_nether"); assert_eq!(back.world_spawn, Some([8, 64, 8])); assert_eq!(back.spawn, Some([20.0, 70.0, 20.0])); @@ -1510,11 +1973,24 @@ mod tests { assert_eq!(back.game_rule("random_tick_speed"), 3); // Unknown player data survives another save. let mut extra = back.player_extra.clone().unwrap(); - put(&mut extra, "EnderItems", Tag::List(vec![Tag::compound([("Slot", Tag::Byte(0)), ("id", string("minecraft:diamond")), ("count", Tag::Int(2))])])); - let mut again = Level { player_extra: Some(extra), ..back }; + put( + &mut extra, + "EnderItems", + Tag::List(vec![Tag::compound([ + ("Slot", Tag::Byte(0)), + ("id", string("minecraft:diamond")), + ("count", Tag::Int(2)), + ])]), + ); + let mut again = Level { + player_extra: Some(extra), + ..back + }; again.write(&dir).unwrap(); let third = Level::read(&dir).unwrap(); - assert!(matches!(third.player_extra.as_ref().and_then(|p| p.get("EnderItems")), Some(Tag::List(l)) if l.len() == 1)); + assert!( + matches!(third.player_extra.as_ref().and_then(|p| p.get("EnderItems")), Some(Tag::List(l)) if l.len() == 1) + ); assert!(dir.join("data/minecraft/world_gen_settings.dat").exists()); let _ = fs::remove_dir_all(&dir); } diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index abb70419f..0ea0c7bdc 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -5,7 +5,10 @@ use crate::keybinds::KeyBinds; use std::{collections::BTreeMap, fs, path::Path}; /// SoundSource names in vanilla order. -pub const SOUND_SOURCES: [&str; 11] = ["master", "music", "record", "weather", "block", "hostile", "neutral", "player", "ambient", "voice", "ui"]; +pub const SOUND_SOURCES: [&str; 11] = [ + "master", "music", "record", "weather", "block", "hostile", "neutral", "player", "ambient", + "voice", "ui", +]; /// Per-source volumes for the mixer (soundCategory_* except master). static SOURCE_VOLUMES: std::sync::RwLock<[f32; 11]> = std::sync::RwLock::new([1.0; 11]); @@ -18,8 +21,30 @@ pub fn sound_source(event: &str) -> usize { let e = event.trim_start_matches("minecraft:"); let index = |name: &str| SOUND_SOURCES.iter().position(|n| *n == name).unwrap_or(0); const HOSTILE: [&str; 24] = [ - "zombie", "skeleton", "creeper", "spider", "cave_spider", "enderman", "witch", "slime", "magma_cube", "blaze", "ghast", "drowned", "husk", "stray", - "phantom", "pillager", "vindicator", "evoker", "ravager", "guardian", "elder_guardian", "silverfish", "zombified_piglin", "wither_skeleton", + "zombie", + "skeleton", + "creeper", + "spider", + "cave_spider", + "enderman", + "witch", + "slime", + "magma_cube", + "blaze", + "ghast", + "drowned", + "husk", + "stray", + "phantom", + "pillager", + "vindicator", + "evoker", + "ravager", + "guardian", + "elder_guardian", + "silverfish", + "zombified_piglin", + "wither_skeleton", ]; if e.starts_with("music_disc.") { index("record") @@ -33,11 +58,20 @@ pub fn sound_source(event: &str) -> usize { index("ambient") } else if e.starts_with("ui.") { index("ui") - } else if e.starts_with("entity.player.") || e.starts_with("item.") || e.starts_with("entity.item.") || e.starts_with("entity.experience_orb") || e.starts_with("entity.arrow") { + } else if e.starts_with("entity.player.") + || e.starts_with("item.") + || e.starts_with("entity.item.") + || e.starts_with("entity.experience_orb") + || e.starts_with("entity.arrow") + { index("player") } else if let Some(rest) = e.strip_prefix("entity.") { let mob = rest.split('.').next().unwrap_or(""); - if HOSTILE.contains(&mob) { index("hostile") } else { index("neutral") } + if HOSTILE.contains(&mob) { + index("hostile") + } else { + index("neutral") + } } else { index("master") } @@ -45,7 +79,11 @@ pub fn sound_source(event: &str) -> usize { /// Volume multiplier of an event's source (master applied separately). pub fn event_volume(event: &str) -> f32 { let i = sound_source(event); - if i == 0 { 1.0 } else { SOURCE_VOLUMES.read().unwrap_or_else(|e| e.into_inner())[i] } + if i == 0 { + 1.0 + } else { + SOURCE_VOLUMES.read().unwrap_or_else(|e| e.into_inner())[i] + } } #[derive(Clone, Debug)] @@ -189,20 +227,26 @@ impl Default for Settings { } } fn unquote(v: &str) -> &str { - v.strip_prefix('"').and_then(|v| v.strip_suffix('"')).unwrap_or(v) + v.strip_prefix('"') + .and_then(|v| v.strip_suffix('"')) + .unwrap_or(v) } fn parse_list(v: &str) -> Vec { serde_json::from_str::>(v).unwrap_or_default() } impl Settings { pub fn load(path: &Path) -> Self { - let Ok(text) = fs::read_to_string(path) else { return Self::default() }; + let Ok(text) = fs::read_to_string(path) else { + return Self::default(); + }; Self::parse(&text) } pub fn parse(text: &str) -> Self { let mut s = Self::default(); for line in text.lines() { - let Some((k, v)) = line.split_once(':') else { continue }; + let Some((k, v)) = line.split_once(':') else { + continue; + }; let f = |d: f32| v.parse::().unwrap_or(d); let b = |d: bool| match v { "true" => true, @@ -212,7 +256,11 @@ impl Settings { let i = |d: i32| v.parse::().unwrap_or(d); match k { "version" => {} - "fov" => s.fov = v.parse::().map_or(70.0, |f| (f * 40.0 + 70.0).round().clamp(30.0, 110.0)), + "fov" => { + s.fov = v + .parse::() + .map_or(70.0, |f| (f * 40.0 + 70.0).round().clamp(30.0, 110.0)) + } "renderDistance" => s.render_distance = i(12).clamp(2, 32), "simulationDistance" => s.simulation_distance = i(12).clamp(5, 32), "mouseSensitivity" => s.sensitivity = f(0.5).clamp(0.0, 1.0), @@ -239,7 +287,9 @@ impl Settings { "improvedTransparency" => s.improved_transparency = b(false), "attackIndicator" => s.attack_indicator = v.parse::().unwrap_or(1).min(2), "inactivityFpsLimit" => s.inactivity_fps_limit = unquote(v).to_owned(), - "prioritizeChunkUpdates" => s.prioritize_chunk_updates = v.parse::().unwrap_or(0).min(2), + "prioritizeChunkUpdates" => { + s.prioritize_chunk_updates = v.parse::().unwrap_or(0).min(2) + } "menuBackgroundBlurriness" => s.menu_blur = i(5).clamp(0, 10), "invertYMouse" => s.invert_y = b(false), "mouseWheelSensitivity" => s.mouse_wheel_sensitivity = f(1.0).clamp(0.01, 10.0), @@ -295,63 +345,123 @@ impl Settings { ("chunkSectionFadeInTime".into(), self.chunk_fade.to_string()), ("cutoutLeaves".into(), self.cutout_leaves.to_string()), ("enableVsync".into(), self.vsync.to_string()), - ("entityDistanceScaling".into(), self.entity_distance.to_string()), + ( + "entityDistanceScaling".into(), + self.entity_distance.to_string(), + ), ("entityShadows".into(), self.entity_shadows.to_string()), ("forceUnicodeFont".into(), self.force_unicode.to_string()), - ("japaneseGlyphVariants".into(), self.japanese_glyphs.to_string()), + ( + "japaneseGlyphVariants".into(), + self.japanese_glyphs.to_string(), + ), ("fov".into(), ((self.fov - 70.0) / 40.0).to_string()), - ("graphicsPreset".into(), format!("\"{}\"", self.graphics_preset)), - ("prioritizeChunkUpdates".into(), self.prioritize_chunk_updates.to_string()), + ( + "graphicsPreset".into(), + format!("\"{}\"", self.graphics_preset), + ), + ( + "prioritizeChunkUpdates".into(), + self.prioritize_chunk_updates.to_string(), + ), ("fullscreen".into(), self.fullscreen.to_string()), ("gamma".into(), self.gamma.to_string()), ("guiScale".into(), self.gui_scale.to_string()), ("maxFps".into(), self.max_fps.to_string()), - ("improvedTransparency".into(), self.improved_transparency.to_string()), - ("inactivityFpsLimit".into(), format!("\"{}\"", self.inactivity_fps_limit)), + ( + "improvedTransparency".into(), + self.improved_transparency.to_string(), + ), + ( + "inactivityFpsLimit".into(), + format!("\"{}\"", self.inactivity_fps_limit), + ), ("mipmapLevels".into(), self.mipmap_levels.to_string()), ("particles".into(), self.particles.to_string()), - ("reducedDebugInfo".into(), self.reduced_debug_info.to_string()), + ( + "reducedDebugInfo".into(), + self.reduced_debug_info.to_string(), + ), ("renderClouds".into(), format!("\"{}\"", self.clouds)), ("cloudRange".into(), self.cloud_range.to_string()), ("renderDistance".into(), self.render_distance.to_string()), - ("simulationDistance".into(), self.simulation_distance.to_string()), + ( + "simulationDistance".into(), + self.simulation_distance.to_string(), + ), ("vignette".into(), self.vignette.to_string()), ("weatherRadius".into(), self.weather_radius.to_string()), ("autoJump".into(), self.auto_jump.to_string()), ("autoSuggestions".into(), self.auto_suggestions.to_string()), ("chatColors".into(), self.chat_colors.to_string()), ("chatLinks".into(), self.chat_links.to_string()), - ("discrete_mouse_scroll".into(), self.discrete_scroll.to_string()), + ( + "discrete_mouse_scroll".into(), + self.discrete_scroll.to_string(), + ), ("invertYMouse".into(), self.invert_y.to_string()), ("bobView".into(), self.view_bobbing.to_string()), ("toggleCrouch".into(), self.toggle_crouch.to_string()), ("toggleSprint".into(), self.toggle_sprint.to_string()), ("mouseSensitivity".into(), self.sensitivity.to_string()), ("highContrast".into(), self.high_contrast.to_string()), - ("resourcePacks".into(), serde_json::to_string(&self.resource_packs).unwrap_or_else(|_| "[]".into())), + ( + "resourcePacks".into(), + serde_json::to_string(&self.resource_packs).unwrap_or_else(|_| "[]".into()), + ), ("lang".into(), self.language.clone()), ("chatVisibility".into(), self.chat_visibility.to_string()), ("chatOpacity".into(), self.chat_opacity.to_string()), ("chatLineSpacing".into(), self.chat_line_spacing.to_string()), - ("textBackgroundOpacity".into(), self.text_background_opacity.to_string()), - ("chatHeightFocused".into(), self.chat_height_focused.to_string()), - ("chatHeightUnfocused".into(), self.chat_height_unfocused.to_string()), + ( + "textBackgroundOpacity".into(), + self.text_background_opacity.to_string(), + ), + ( + "chatHeightFocused".into(), + self.chat_height_focused.to_string(), + ), + ( + "chatHeightUnfocused".into(), + self.chat_height_unfocused.to_string(), + ), ("chatScale".into(), self.chat_scale.to_string()), ("chatWidth".into(), self.chat_width.to_string()), - ("mainHand".into(), if self.main_hand_left { "\"left\"".into() } else { "\"right\"".into() }), + ( + "mainHand".into(), + if self.main_hand_left { + "\"left\"".into() + } else { + "\"right\"".into() + }, + ), ("attackIndicator".into(), self.attack_indicator.to_string()), - ("mouseWheelSensitivity".into(), self.mouse_wheel_sensitivity.to_string()), - ("showAutosaveIndicator".into(), self.autosave_indicator.to_string()), - ("menuBackgroundBlurriness".into(), self.menu_blur.to_string()), + ( + "mouseWheelSensitivity".into(), + self.mouse_wheel_sensitivity.to_string(), + ), + ( + "showAutosaveIndicator".into(), + self.autosave_indicator.to_string(), + ), + ( + "menuBackgroundBlurriness".into(), + self.menu_blur.to_string(), + ), ]; for (name, key) in self.keys.saved() { lines.push((format!("key_{name}"), key)); } for (i, source) in SOUND_SOURCES.iter().enumerate() { - let v = if i == 0 { self.master_volume } else { self.volumes[i] }; + let v = if i == 0 { + self.master_volume + } else { + self.volumes[i] + }; lines.push((format!("soundCategory_{source}"), v.to_string())); } - let known: std::collections::BTreeSet = lines.iter().map(|(k, _)| k.clone()).collect(); + let known: std::collections::BTreeSet = + lines.iter().map(|(k, _)| k.clone()).collect(); for (k, v) in &self.extra { if !known.contains(k) { lines.push((k.clone(), v.clone())); @@ -368,7 +478,16 @@ impl Settings { } /// Volume of a sound source (master excluded). pub fn volume(&self, source: &str) -> f32 { - SOUND_SOURCES.iter().position(|n| *n == source).map_or(1.0, |i| if i == 0 { self.master_volume } else { self.volumes[i] }) + SOUND_SOURCES + .iter() + .position(|n| *n == source) + .map_or(1.0, |i| { + if i == 0 { + self.master_volume + } else { + self.volumes[i] + } + }) } pub fn chat_options(&self) -> crate::chat::ChatOptions { crate::chat::ChatOptions { diff --git a/crates/horizon-client/src/shadows.rs b/crates/horizon-client/src/shadows.rs index e971687da..641f53642 100644 --- a/crates/horizon-client/src/shadows.rs +++ b/crates/horizon-client/src/shadows.rs @@ -13,17 +13,20 @@ pub fn shadow_params(entity: &str) -> (f32, f32) { "tadpole" => 0.14, "pufferfish" => 0.2, "slime" | "magma_cube" | "bat" => 0.25, - "chicken" | "cod" | "parrot" | "rabbit" | "frog" | "silverfish" | "endermite" | "vex" => 0.3, - "cat" | "ocelot" | "fox" | "bee" | "allay" | "salmon" => 0.4, - "zombie" | "husk" | "drowned" | "zombie_villager" | "zombified_piglin" | "skeleton" | "stray" | "wither_skeleton" | "bogged" - | "creeper" | "enderman" | "villager" | "wandering_trader" | "witch" | "pillager" | "vindicator" | "evoker" | "illusioner" - | "blaze" | "breeze" | "snow_golem" | "copper_golem" | "strider" | "wolf" | "axolotl" | "tnt" | "falling_block" | "end_crystal" => { - 0.5 + "chicken" | "cod" | "parrot" | "rabbit" | "frog" | "silverfish" | "endermite" | "vex" => { + 0.3 } + "cat" | "ocelot" | "fox" | "bee" | "allay" | "salmon" => 0.4, + "zombie" | "husk" | "drowned" | "zombie_villager" | "zombified_piglin" | "skeleton" + | "stray" | "wither_skeleton" | "bogged" | "creeper" | "enderman" | "villager" + | "wandering_trader" | "witch" | "pillager" | "vindicator" | "evoker" | "illusioner" + | "blaze" | "breeze" | "snow_golem" | "copper_golem" | "strider" | "wolf" | "axolotl" + | "tnt" | "falling_block" | "end_crystal" => 0.5, "cave_spider" => 0.56, "creaking" => 0.6, - "pig" | "cow" | "mooshroom" | "sheep" | "goat" | "llama" | "trader_llama" | "iron_golem" | "camel" | "camel_husk" | "squid" - | "glow_squid" | "dolphin" | "turtle" | "hoglin" | "zoglin" | "nautilus" | "zombie_nautilus" | "minecart" => 0.7, + "pig" | "cow" | "mooshroom" | "sheep" | "goat" | "llama" | "trader_llama" + | "iron_golem" | "camel" | "camel_husk" | "squid" | "glow_squid" | "dolphin" | "turtle" + | "hoglin" | "zoglin" | "nautilus" | "zombie_nautilus" | "minecart" => 0.7, "horse" | "donkey" | "mule" | "skeleton_horse" | "zombie_horse" | "phantom" => 0.75, "spider" | "boat" => 0.8, "polar_bear" | "panda" | "warden" => 0.9, @@ -32,7 +35,11 @@ pub fn shadow_params(entity: &str) -> (f32, f32) { "ghast" => 1.5, _ => 0.5, }; - let strength = if matches!(id, "item" | "experience_orb") { 0.75 } else { 1.0 }; + let strength = if matches!(id, "item" | "experience_orb") { + 0.75 + } else { + 1.0 + }; (radius, strength) } @@ -63,12 +70,17 @@ pub fn shadow( let (x0, x1) = ((pos.x - r).floor() as i32, (pos.x + r).floor() as i32); let (z0, z1) = ((pos.z - r).floor() as i32, (pos.z + r).floor() as i32); let depth = (pow / 0.5 - 1.0).min(radius); - let (y0, y1) = ((pos.y - f64::from(depth)).floor() as i32, pos.y.floor() as i32); + let (y0, y1) = ( + (pos.y - f64::from(depth)).floor() as i32, + pos.y.floor() as i32, + ); for z in z0..=z1 { for x in x0..=x1 { for y in y0..=y1 { let below = facts.get(world.block(x, y - 1, z)); - if below.render_shape == crate::blocks::RenderShape::Invisible || !below.full_collision { + if below.render_shape == crate::blocks::RenderShape::Invisible + || !below.full_collision + { continue; } let packed = world.light(x, y, z); @@ -77,7 +89,10 @@ pub fn shadow( continue; } let power_at_depth = pow - (pos.y - f64::from(y)) as f32 * 0.5; - let alpha = (power_at_depth * 0.5 * crate::screen_effects::lightmap_brightness(ambient_light, raw as u8)).clamp(0.0, 1.0); + let alpha = (power_at_depth + * 0.5 + * crate::screen_effects::lightmap_brightness(ambient_light, raw as u8)) + .clamp(0.0, 1.0); // The block top, clipped to the shadow square so the UVs stay inside the sprite. let (bx0, bx1) = (f64::from(x).max(pos.x - r), f64::from(x + 1).min(pos.x + r)); let (bz0, bz1) = (f64::from(z).max(pos.z - r), f64::from(z + 1).min(pos.z + r)); @@ -93,7 +108,10 @@ pub fn shadow( let p = DVec3::new(wx, top, wz) - camera; out.push(Vertex { pos: p.as_vec3().to_array(), - uv: [sprite.u0 + (sprite.u1 - sprite.u0) * u(wx), sprite.v0 + (sprite.v1 - sprite.v0) * v(wz)], + uv: [ + sprite.u0 + (sprite.u1 - sprite.u0) * u(wx), + sprite.v0 + (sprite.v1 - sprite.v0) * v(wz), + ], layer: 0, color, light: 240 | 240 << 8, diff --git a/crates/horizon-client/src/signs.rs b/crates/horizon-client/src/signs.rs index 2d40391f9..07217ed79 100644 --- a/crates/horizon-client/src/signs.rs +++ b/crates/horizon-client/src/signs.rs @@ -34,7 +34,11 @@ pub struct SignText { } impl Default for SignText { fn default() -> Self { - Self { lines: Default::default(), color: BLACK, glowing: false } + Self { + lines: Default::default(), + color: BLACK, + glowing: false, + } } } impl SignText { @@ -67,7 +71,11 @@ pub struct SignData { } impl SignData { pub fn id(&self) -> &'static str { - if self.hanging { "minecraft:hanging_sign" } else { "minecraft:sign" } + if self.hanging { + "minecraft:hanging_sign" + } else { + "minecraft:sign" + } } /// `SignBlockEntity.getMaxTextLineWidth`. pub fn max_line_width(&self) -> f32 { @@ -81,12 +89,27 @@ impl SignData { pub fn encode(&self) -> Vec<(&'static str, Tag)> { let side = |t: &SignText| { Tag::compound([ - ("messages", Tag::List(t.lines.iter().map(|l| Tag::String(l.as_str().into())).collect())), - ("color", Tag::String(DYE_TEXT[usize::from(t.color.min(15))].0.into())), + ( + "messages", + Tag::List( + t.lines + .iter() + .map(|l| Tag::String(l.as_str().into())) + .collect(), + ), + ), + ( + "color", + Tag::String(DYE_TEXT[usize::from(t.color.min(15))].0.into()), + ), ("has_glowing_text", Tag::Byte(i8::from(t.glowing))), ]) }; - vec![("front_text", side(&self.front)), ("back_text", side(&self.back)), ("is_waxed", Tag::Byte(i8::from(self.waxed)))] + vec![ + ("front_text", side(&self.front)), + ("back_text", side(&self.back)), + ("is_waxed", Tag::Byte(i8::from(self.waxed))), + ] } pub fn decode(&mut self, tag: &Tag) { let side = |t: Option<&Tag>| -> SignText { @@ -118,7 +141,9 @@ fn component_text(tag: &Tag) -> String { let s = s.to_string_lossy(); match serde_json::from_str::(&s) { Ok(serde_json::Value::String(text)) => text, - Ok(v) if v.get("text").is_some() => v["text"].as_str().unwrap_or_default().to_owned(), + Ok(v) if v.get("text").is_some() => { + v["text"].as_str().unwrap_or_default().to_owned() + } _ => s, } } @@ -156,7 +181,10 @@ mod tests { use super::*; #[test] fn round_trips_nbt() { - let mut data = SignData { hanging: false, ..SignData::default() }; + let mut data = SignData { + hanging: false, + ..SignData::default() + }; data.front.lines[0] = "Hello".into(); data.front.color = 14; data.back.glowing = true; @@ -173,7 +201,10 @@ mod tests { assert_eq!(sign_kind("minecraft:stone"), None); assert_eq!(wood_type("minecraft:dark_oak_wall_sign"), "dark_oak"); assert_eq!(SignText::default().dark_color(), 0); - let red = SignText { color: 14, ..SignText::default() }; + let red = SignText { + color: 14, + ..SignText::default() + }; assert_eq!(red.dark_color(), 0x660000); } } diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index 393e796e4..8fd6f85d7 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -54,7 +54,14 @@ pub struct EnchantOffers { pub clues: [Option<(Arc, u32)>; 3], } /// `EnchantmentMenu.getEnchantmentList`. -pub fn enchantment_list(e: &Enchantments, items: &Items, seed: i32, slot: usize, cost: i32, item: &str) -> Levels { +pub fn enchantment_list( + e: &Enchantments, + items: &Items, + seed: i32, + slot: usize, + cost: i32, + item: &str, +) -> Levels { let mut random = LegacyRandom::new(i64::from(seed.wrapping_add(slot as i32))); let pool = e.tag("minecraft:in_enchanting_table").to_vec(); let mut list = e.select(items, &mut random, item, cost, &pool); @@ -65,7 +72,13 @@ pub fn enchantment_list(e: &Enchantments, items: &Items, seed: i32, slot: usize, list } /// `EnchantmentMenu.slotsChanged` for an enchantable item. -pub fn enchant_offers(e: &Enchantments, items: &Items, seed: i32, bookcases: i32, stack: Option<&ItemStack>) -> EnchantOffers { +pub fn enchant_offers( + e: &Enchantments, + items: &Items, + seed: i32, + bookcases: i32, + stack: Option<&ItemStack>, +) -> EnchantOffers { let mut offers = EnchantOffers::default(); let Some(stack) = stack else { return offers }; // ItemStack.isEnchantable: enchantable component and no enchantments yet. @@ -98,12 +111,23 @@ pub fn enchant_offers(e: &Enchantments, items: &Items, seed: i32, bookcases: i32 offers } /// `EnchantmentMenu.clickMenuButton` result: the enchanted item, or None. -pub fn apply_enchantment(e: &Enchantments, items: &Items, seed: i32, slot: usize, cost: i32, stack: &ItemStack) -> Option { +pub fn apply_enchantment( + e: &Enchantments, + items: &Items, + seed: i32, + slot: usize, + cost: i32, + stack: &ItemStack, +) -> Option { let list = enchantment_list(e, items, seed, slot, cost, &stack.item); if list.is_empty() { return None; } - let mut out = if &*stack.item == "minecraft:book" { stack.transmute("minecraft:enchanted_book", stack.count) } else { stack.clone() }; + let mut out = if &*stack.item == "minecraft:book" { + stack.transmute("minecraft:enchanted_book", stack.count) + } else { + stack.clone() + }; for (id, level) in list { out.enchant(&id, level); } @@ -128,8 +152,14 @@ fn max_damage(items: &Items, stack: &ItemStack) -> i32 { items.get(&stack.item).map_or(0, |i| i.max_damage as i32) } /// `ItemStack.isValidRepairItem`. -pub fn is_valid_repair_item(e: &Enchantments, items: &Items, stack: &ItemStack, material: &ItemStack) -> bool { - e.props(&stack.item).is_some_and(|p| Enchantments::item_in(items, &p.repairable, &material.item)) +pub fn is_valid_repair_item( + e: &Enchantments, + items: &Items, + stack: &ItemStack, + material: &ItemStack, +) -> bool { + e.props(&stack.item) + .is_some_and(|p| Enchantments::item_in(items, &p.repairable, &material.item)) } /// `AnvilMenu.calculateIncreasedRepairCost`. pub fn increased_repair_cost(cost: u32) -> u32 { @@ -137,7 +167,9 @@ pub fn increased_repair_cost(cost: u32) -> u32 { } /// The display name the rename box starts with (`getHoverName`). pub fn hover_name(names: &dyn Fn(&str) -> String, stack: &ItemStack) -> String { - stack.custom_name().map_or_else(|| names(&stack.item), str::to_owned) + stack + .custom_name() + .map_or_else(|| names(&stack.item), str::to_owned) } /// `AnvilMenu.createResult`. `name` is the rename box text (None = untouched). pub fn anvil_result( @@ -156,7 +188,8 @@ pub fn anvil_result( let mut result = input.clone(); let mut enchantments: Levels = input.crafting_enchantments().to_vec(); let mut price: i64 = 0; - let tax: i64 = i64::from(input.repair_cost()) + i64::from(addition.map_or(0, ItemStack::repair_cost)); + let tax: i64 = + i64::from(input.repair_cost()) + i64::from(addition.map_or(0, ItemStack::repair_cost)); let mut repair_item_count_cost = 0; let mut naming_cost = 0; if let Some(addition) = addition { @@ -195,8 +228,15 @@ pub fn anvil_result( let mut any_compatible = false; let mut any_incompatible = false; for (id, level) in addition.crafting_enchantments() { - let current = enchantments.iter().find(|(x, _)| x == id).map_or(0, |(_, l)| *l); - let mut level = if current == *level { level + 1 } else { (*level).max(current) }; + let current = enchantments + .iter() + .find(|(x, _)| x == id) + .map_or(0, |(_, l)| *l); + let mut level = if current == *level { + level + 1 + } else { + (*level).max(current) + }; let Some(def) = e.get(id) else { continue }; let mut compatible = e.can_enchant(items, id, &input.item); if creative || &*input.item == "minecraft:enchanted_book" { @@ -245,7 +285,11 @@ pub fn anvil_result( } } } - let mut cost = if price <= 0 { 0 } else { (tax + price).clamp(0, i64::from(i32::MAX)) as i32 }; + let mut cost = if price <= 0 { + 0 + } else { + (tax + price).clamp(0, i64::from(i32::MAX)) as i32 + }; let mut out = (price > 0).then_some(result); let mut only_renaming = false; if naming_cost == price && naming_cost > 0 { @@ -258,7 +302,9 @@ pub fn anvil_result( out = None; } if let Some(r) = out.as_mut() { - let mut base = r.repair_cost().max(addition.map_or(0, ItemStack::repair_cost)); + let mut base = r + .repair_cost() + .max(addition.map_or(0, ItemStack::repair_cost)); if naming_cost != price || naming_cost == 0 { base = increased_repair_cost(base); } @@ -266,7 +312,12 @@ pub fn anvil_result( r.set_crafting_enchantments(enchantments); r.tidy(); } - AnvilResult { result: out, cost, repair_item_count_cost, only_renaming } + AnvilResult { + result: out, + cost, + repair_item_count_cost, + only_renaming, + } } // ---------------------------------------------------------------- grindstone @@ -276,7 +327,12 @@ pub fn grindstone_accepts(items: &Items, stack: &ItemStack) -> bool { is_damageable(items, stack) || stack.has_any_enchantments() } fn remove_non_curses(e: &Enchantments, mut item: ItemStack) -> ItemStack { - let kept: Levels = item.crafting_enchantments().iter().filter(|(id, _)| e.is_curse(id)).cloned().collect(); + let kept: Levels = item + .crafting_enchantments() + .iter() + .filter(|(id, _)| e.is_curse(id)) + .cloned() + .collect(); let n = kept.len(); item.set_crafting_enchantments(kept); if &*item.item == "minecraft:enchanted_book" && item.stored_enchantments().is_empty() { @@ -291,7 +347,12 @@ fn remove_non_curses(e: &Enchantments, mut item: ItemStack) -> ItemStack { item } /// `GrindstoneMenu.computeResult`. -pub fn grindstone_result(e: &Enchantments, items: &Items, input: Option<&ItemStack>, additional: Option<&ItemStack>) -> Option { +pub fn grindstone_result( + e: &Enchantments, + items: &Items, + input: Option<&ItemStack>, + additional: Option<&ItemStack>, +) -> Option { if input.is_none() && additional.is_none() { return None; } @@ -304,7 +365,9 @@ pub fn grindstone_result(e: &Enchantments, items: &Items, input: Option<&ItemSta return None; } let durability = max_damage(items, a).max(max_damage(items, b)); - let remaining = (max_damage(items, a) - a.damage as i32) + (max_damage(items, b) - b.damage as i32) + durability * 5 / 100; + let remaining = (max_damage(items, a) - a.damage as i32) + + (max_damage(items, b) - b.damage as i32) + + durability * 5 / 100; let mut count = 1; if !is_damageable(items, a) { let stack_max = items.get(&a.item).map_or(64, |i| i.max_stack); @@ -327,15 +390,26 @@ pub fn grindstone_result(e: &Enchantments, items: &Items, input: Option<&ItemSta out.set_crafting_enchantments(levels); Some(remove_non_curses(e, out)) } - (Some(s), None) | (None, Some(s)) => s.has_any_enchantments().then(|| remove_non_curses(e, s.clone())), + (Some(s), None) | (None, Some(s)) => s + .has_any_enchantments() + .then(|| remove_non_curses(e, s.clone())), (None, None) => None, } } /// Experience from the grindstone result slot's `getExperienceAmount`. -pub fn grindstone_experience(e: &Enchantments, random: &mut LegacyRandom, input: Option<&ItemStack>, additional: Option<&ItemStack>) -> u32 { +pub fn grindstone_experience( + e: &Enchantments, + random: &mut LegacyRandom, + input: Option<&ItemStack>, + additional: Option<&ItemStack>, +) -> u32 { let from = |s: Option<&ItemStack>| -> i32 { s.map_or(0, |s| { - s.crafting_enchantments().iter().filter(|(id, _)| !e.is_curse(id)).map(|(id, l)| e.get(id).map_or(0, |d| d.min_cost.calculate(*l))).sum() + s.crafting_enchantments() + .iter() + .filter(|(id, _)| !e.is_curse(id)) + .map(|(id, l)| e.get(id).map_or(0, |d| d.min_cost.calculate(*l))) + .sum() }) }; let amount = from(input) + from(additional); @@ -351,8 +425,18 @@ pub fn grindstone_experience(e: &Enchantments, random: &mut LegacyRandom, input: #[derive(Clone, Debug)] pub enum Smithing { - Transform { template: Ingredient, base: Ingredient, addition: Ingredient, result: String }, - Trim { template: Ingredient, base: Ingredient, addition: Ingredient, pattern: String }, + Transform { + template: Ingredient, + base: Ingredient, + addition: Ingredient, + result: String, + }, + Trim { + template: Ingredient, + base: Ingredient, + addition: Ingredient, + pattern: String, + }, } #[derive(Clone, Debug)] pub struct Stonecutting { @@ -371,7 +455,10 @@ fn ingredient(v: &Value, items: &Items) -> Ingredient { let mut set = HashSet::new(); for s in match v { Value::String(s) => vec![s.clone()], - Value::Array(a) => a.iter().filter_map(|x| x.as_str().map(str::to_owned)).collect(), + Value::Array(a) => a + .iter() + .filter_map(|x| x.as_str().map(str::to_owned)) + .collect(), _ => vec![], } { match s.strip_prefix('#') { @@ -385,20 +472,34 @@ fn ingredient(v: &Value, items: &Items) -> Ingredient { } impl StationRecipes { pub fn load(root: &Path, items: &Items) -> Self { - let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/recipe")).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "json")).collect(); + let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/recipe")) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e == "json")) + .collect(); files.sort(); let mut smithing = Vec::new(); let mut stonecutting = Vec::new(); for p in files { let Ok(bytes) = fs::read(&p) else { continue }; - let Ok(v) = serde_json::from_slice::(&bytes) else { continue }; - let id = format!("minecraft:{}", p.file_stem().and_then(|s| s.to_str()).unwrap_or("")); + let Ok(v) = serde_json::from_slice::(&bytes) else { + continue; + }; + let id = format!( + "minecraft:{}", + p.file_stem().and_then(|s| s.to_str()).unwrap_or("") + ); match v["type"].as_str().unwrap_or("") { "minecraft:smithing_transform" => smithing.push(Smithing::Transform { template: ingredient(&v["template"], items), base: ingredient(&v["base"], items), addition: ingredient(&v["addition"], items), - result: v["result"]["id"].as_str().unwrap_or("minecraft:air").to_owned(), + result: v["result"]["id"] + .as_str() + .unwrap_or("minecraft:air") + .to_owned(), }), "minecraft:smithing_trim" => smithing.push(Smithing::Trim { template: ingredient(&v["template"], items), @@ -409,32 +510,67 @@ impl StationRecipes { "minecraft:stonecutting" => stonecutting.push(Stonecutting { id, input: ingredient(&v["ingredient"], items), - result: ItemStack::new(v["result"]["id"].as_str().unwrap_or("minecraft:air"), v["result"]["count"].as_u64().unwrap_or(1) as u32), + result: ItemStack::new( + v["result"]["id"].as_str().unwrap_or("minecraft:air"), + v["result"]["count"].as_u64().unwrap_or(1) as u32, + ), }), _ => {} } } let mut trim_materials = Vec::new(); - let mut tm: Vec<_> = fs::read_dir(root.join("data/minecraft/trim_material")).into_iter().flatten().flatten().map(|e| e.path()).collect(); + let mut tm: Vec<_> = fs::read_dir(root.join("data/minecraft/trim_material")) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path()) + .collect(); tm.sort(); for p in tm { if let Ok(bytes) = fs::read(&p) && let Ok(v) = serde_json::from_slice::(&bytes) { - let id = format!("minecraft:{}", p.file_stem().and_then(|s| s.to_str()).unwrap_or("")); - trim_materials.push((id, v["description"]["translate"].as_str().unwrap_or("").to_owned())); + let id = format!( + "minecraft:{}", + p.file_stem().and_then(|s| s.to_str()).unwrap_or("") + ); + trim_materials.push(( + id, + v["description"]["translate"] + .as_str() + .unwrap_or("") + .to_owned(), + )); } } - Self { smithing, stonecutting, trim_materials } + Self { + smithing, + stonecutting, + trim_materials, + } } /// Recipes whose input accepts `stack`, in display order. pub fn stonecutter(&self, stack: &ItemStack) -> Vec<&Stonecutting> { - self.stonecutting.iter().filter(|r| r.input.test(stack)).collect() + self.stonecutting + .iter() + .filter(|r| r.input.test(stack)) + .collect() } fn slot_ok(&self, slot: usize, stack: &ItemStack) -> bool { self.smithing.iter().any(|r| { let (t, b, a) = match r { - Smithing::Transform { template, base, addition, .. } | Smithing::Trim { template, base, addition, .. } => (template, base, addition), + Smithing::Transform { + template, + base, + addition, + .. + } + | Smithing::Trim { + template, + base, + addition, + .. + } => (template, base, addition), }; [t, b, a][slot].test(stack) }) @@ -444,24 +580,43 @@ impl StationRecipes { slot < 3 && self.slot_ok(slot, stack) } /// `SmithingMenu.createResult`. - pub fn smithing_result(&self, e: &Enchantments, template: Option<&ItemStack>, base: Option<&ItemStack>, addition: Option<&ItemStack>) -> Option { + pub fn smithing_result( + &self, + e: &Enchantments, + template: Option<&ItemStack>, + base: Option<&ItemStack>, + addition: Option<&ItemStack>, + ) -> Option { let (template, base, addition) = (template?, base?, addition?); for r in &self.smithing { match r { - Smithing::Transform { template: t, base: b, addition: a, result } => { + Smithing::Transform { + template: t, + base: b, + addition: a, + result, + } => { if t.test(template) && b.test(base) && a.test(addition) { // SmithingTransformRecipe: transmute the base keeping its components. return Some(base.transmute(result, 1)); } } - Smithing::Trim { template: t, base: b, addition: a, pattern } => { + Smithing::Trim { + template: t, + base: b, + addition: a, + pattern, + } => { if t.test(template) && b.test(base) && a.test(addition) { let material = e.props(&addition.item)?.trim_material.clone()?; let trim = (Arc::from(material.as_str()), Arc::from(pattern.as_str())); if base.data().and_then(|d| d.trim.as_ref()) == Some(&trim) { return None; } - let mut out = ItemStack { count: 1, ..base.clone() }; + let mut out = ItemStack { + count: 1, + ..base.clone() + }; out.data_mut().trim = Some(trim); return Some(out); } @@ -511,15 +666,33 @@ mod tests { assert!(a.costs[0] >= 1 && a.costs[0] <= a.costs[2]); // The clue is the first offer's random pick from the same list. for slot in 0..3 { - let list = enchantment_list(&e, &items, 1234, slot, a.costs[slot], "minecraft:diamond_sword"); + let list = enchantment_list( + &e, + &items, + 1234, + slot, + a.costs[slot], + "minecraft:diamond_sword", + ); let clue = a.clues[slot].clone().unwrap(); assert!(list.contains(&clue)); let applied = apply_enchantment(&e, &items, 1234, slot, a.costs[slot], &s).unwrap(); assert_eq!(applied.enchantments(), &list[..]); } // Already enchanted items are not enchantable. - assert_eq!(enchant_offers(&e, &items, 1234, 15, Some(&sword(&[("minecraft:sharpness", 1)]))).costs, [0, 0, 0]); - let books = apply_enchantment(&e, &items, 99, 2, 30, &ItemStack::new("minecraft:book", 1)).unwrap(); + assert_eq!( + enchant_offers( + &e, + &items, + 1234, + 15, + Some(&sword(&[("minecraft:sharpness", 1)])) + ) + .costs, + [0, 0, 0] + ); + let books = + apply_enchantment(&e, &items, 99, 2, 30, &ItemStack::new("minecraft:book", 1)).unwrap(); assert_eq!(&*books.item, "minecraft:enchanted_book"); assert!(!books.stored_enchantments().is_empty()); } @@ -529,17 +702,44 @@ mod tests { let e = sample(); let items = sample_items(); // Sharpness II + Sharpness II book = Sharpness III; book fee 1/2 -> max(1, 0) = 1 per level. - let r = anvil_result(&e, &items, Some(&sword(&[("minecraft:sharpness", 2)])), Some(&book(&[("minecraft:sharpness", 2)])), None, "Diamond Sword", false); + let r = anvil_result( + &e, + &items, + Some(&sword(&[("minecraft:sharpness", 2)])), + Some(&book(&[("minecraft:sharpness", 2)])), + None, + "Diamond Sword", + false, + ); let out = r.result.unwrap(); assert_eq!(out.enchantment_level("minecraft:sharpness"), 3); assert_eq!(r.cost, 3); assert_eq!(out.repair_cost(), 1); // Incompatible only: no result. - let r = anvil_result(&e, &items, Some(&sword(&[("minecraft:sharpness", 1)])), Some(&book(&[("minecraft:smite", 1)])), None, "Diamond Sword", false); + let r = anvil_result( + &e, + &items, + Some(&sword(&[("minecraft:sharpness", 1)])), + Some(&book(&[("minecraft:smite", 1)])), + None, + "Diamond Sword", + false, + ); assert!(r.result.is_none()); // Max level clamps: V + V stays V. - let r = anvil_result(&e, &items, Some(&sword(&[("minecraft:sharpness", 5)])), Some(&book(&[("minecraft:sharpness", 5)])), None, "x", false); - assert_eq!(r.result.unwrap().enchantment_level("minecraft:sharpness"), 5); + let r = anvil_result( + &e, + &items, + Some(&sword(&[("minecraft:sharpness", 5)])), + Some(&book(&[("minecraft:sharpness", 5)])), + None, + "x", + false, + ); + assert_eq!( + r.result.unwrap().enchantment_level("minecraft:sharpness"), + 5 + ); assert_eq!(r.cost, 5); } @@ -549,7 +749,15 @@ mod tests { let items = sample_items(); let mut s = sword(&[]); s.data_mut().repair_cost = 7; - let r = anvil_result(&e, &items, Some(&s), None, Some("Excalibur"), "Diamond Sword", false); + let r = anvil_result( + &e, + &items, + Some(&s), + None, + Some("Excalibur"), + "Diamond Sword", + false, + ); assert_eq!(r.cost, 8); assert!(r.only_renaming); let out = r.result.unwrap(); @@ -557,15 +765,55 @@ mod tests { // Renaming alone does not raise the penalty. assert_eq!(out.repair_cost(), 7); // Same name: nothing to do. - assert!(anvil_result(&e, &items, Some(&s), None, Some("Diamond Sword"), "Diamond Sword", false).result.is_none()); + assert!( + anvil_result( + &e, + &items, + Some(&s), + None, + Some("Diamond Sword"), + "Diamond Sword", + false + ) + .result + .is_none() + ); // Too expensive at 40+ unless creative; rename-only caps at 39. s.data_mut().repair_cost = 63; - let r = anvil_result(&e, &items, Some(&s), None, Some("A"), "Diamond Sword", false); + let r = anvil_result( + &e, + &items, + Some(&s), + None, + Some("A"), + "Diamond Sword", + false, + ); assert_eq!(r.cost, 39); assert!(r.result.is_some()); - let r = anvil_result(&e, &items, Some(&s), Some(&book(&[("minecraft:unbreaking", 1)])), None, "Diamond Sword", false); + let r = anvil_result( + &e, + &items, + Some(&s), + Some(&book(&[("minecraft:unbreaking", 1)])), + None, + "Diamond Sword", + false, + ); assert!(r.cost >= 40 && r.result.is_none()); - assert!(anvil_result(&e, &items, Some(&s), Some(&book(&[("minecraft:unbreaking", 1)])), None, "Diamond Sword", true).result.is_some()); + assert!( + anvil_result( + &e, + &items, + Some(&s), + Some(&book(&[("minecraft:unbreaking", 1)])), + None, + "Diamond Sword", + true + ) + .result + .is_some() + ); assert_eq!(increased_repair_cost(0), 1); assert_eq!(increased_repair_cost(3), 7); } @@ -581,7 +829,10 @@ mod tests { let data = StationData::load(&root, &items); let e = &data.enchantments; assert_eq!(e.list.len(), 43); - assert_eq!(&*e.tag("minecraft:in_enchanting_table")[0], "minecraft:protection"); + assert_eq!( + &*e.tag("minecraft:in_enchanting_table")[0], + "minecraft:protection" + ); assert!(!e.compatible("minecraft:fortune", "minecraft:silk_touch")); assert!(e.is_curse("minecraft:binding_curse")); assert_eq!(e.full_name("minecraft:sharpness", 5).0, "Sharpness V"); @@ -589,24 +840,62 @@ mod tests { // Brewing: water + nether wart = awkward. assert_eq!(data.brewing.recipes.len(), 279); let water = ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"); - let r = data.brewing.find(&water, &ItemStack::new("minecraft:nether_wart", 1)).unwrap(); + let r = data + .brewing + .find(&water, &ItemStack::new("minecraft:nether_wart", 1)) + .unwrap(); assert_eq!(r.output.potion(), Some("minecraft:awkward")); - assert!(data.brewing.is_reagent(&ItemStack::new("minecraft:blaze_powder", 1))); + assert!( + data.brewing + .is_reagent(&ItemStack::new("minecraft:blaze_powder", 1)) + ); // Smithing: netherite upgrade keeps enchantments. let mut sword = ItemStack::new("minecraft:diamond_sword", 1); sword.enchant("minecraft:sharpness", 2); let out = data .recipes - .smithing_result(e, Some(&ItemStack::new("minecraft:netherite_upgrade_smithing_template", 1)), Some(&sword), Some(&ItemStack::new("minecraft:netherite_ingot", 1))) + .smithing_result( + e, + Some(&ItemStack::new( + "minecraft:netherite_upgrade_smithing_template", + 1, + )), + Some(&sword), + Some(&ItemStack::new("minecraft:netherite_ingot", 1)), + ) .unwrap(); - assert_eq!((&*out.item, out.enchantment_level("minecraft:sharpness")), ("minecraft:netherite_sword", 2)); - assert!(data.recipes.stonecutter(&ItemStack::new("minecraft:stone", 1)).len() >= 10); + assert_eq!( + (&*out.item, out.enchantment_level("minecraft:sharpness")), + ("minecraft:netherite_sword", 2) + ); + assert!( + data.recipes + .stonecutter(&ItemStack::new("minecraft:stone", 1)) + .len() + >= 10 + ); // Trades: every profession level set yields offers. - let ctx = crate::merchant::TradeContext { items: &items, enchantments: e, variant: "minecraft:plains" }; + let ctx = crate::merchant::TradeContext { + items: &items, + enchantments: e, + variant: "minecraft:plains", + }; for p in crate::merchant::PROFESSIONS { let set = crate::merchant::Trades::set_for(p, 1); - let mut random = crate::merchant::sequence_random(12345, &format!("minecraft:trade_set/{}", set.trim_start_matches("minecraft:"))); - assert!(!data.trades.offers_from_set(&ctx, &set, &mut random).is_empty(), "{p}"); + let mut random = crate::merchant::sequence_random( + 12345, + &format!( + "minecraft:trade_set/{}", + set.trim_start_matches("minecraft:") + ), + ); + assert!( + !data + .trades + .offers_from_set(&ctx, &set, &mut random) + .is_empty(), + "{p}" + ); } } @@ -619,7 +908,8 @@ mod tests { assert!(out.enchantments().is_empty()); assert_eq!(out.repair_cost(), 0); assert!(out.extra.is_none()); - let b = grindstone_result(&e, &items, None, Some(&book(&[("minecraft:mending", 1)]))).unwrap(); + let b = + grindstone_result(&e, &items, None, Some(&book(&[("minecraft:mending", 1)]))).unwrap(); assert_eq!(&*b.item, "minecraft:book"); assert!(grindstone_result(&e, &items, Some(&sword(&[])), None).is_none()); let mut r = LegacyRandom::new(5); diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 1daff0ab0..6fd8a64bd 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -129,7 +129,11 @@ pub struct WorkerContext { pub light: Arc, } impl Streaming { - pub fn new(generator: Arc, context: Arc, threads: usize) -> Self { + pub fn new( + generator: Arc, + context: Arc, + threads: usize, + ) -> Self { let shared = Arc::new(Shared { queue: Mutex::new(BinaryHeap::new()), ready: Condvar::new(), @@ -177,9 +181,12 @@ impl Streaming { Done::Decorated(x, z, region) } Job::Finish(proto) => Done::Generated(generator.finish(proto)), - Job::Light(x, z, region, seq, sky) => { - Done::Lit(x, z, light_chunk(&borrow(®ion), &context.light, sky), seq) - } + Job::Light(x, z, region, seq, sky) => Done::Lit( + x, + z, + light_chunk(&borrow(®ion), &context.light, sky), + seq, + ), Job::Mesh(x, sy, z, region, seq, nether) => { mesher.nether_shading = nether; Done::Meshed(x, sy, z, mesher.mesh(&borrow(®ion), sy), seq) @@ -262,7 +269,12 @@ impl Streaming { let mut region: Region = Default::default(); for dz in 0..3 { for dx in 0..3 { - region[dz][dx] = Some(world.chunks.get(&(x + dx as i32 - 1, z + dz as i32 - 1))?.clone()); + region[dz][dx] = Some( + world + .chunks + .get(&(x + dx as i32 - 1, z + dz as i32 - 1))? + .clone(), + ); } } Some(Box::new(region)) @@ -275,7 +287,10 @@ impl Streaming { } /// Advance streaming: collect finished work, then schedule more. /// Returns meshes ready for upload and columns that were unloaded. - pub fn update(&mut self, world: &mut World) -> (Vec<((i32, i32, i32), SectionMesh)>, Vec>) { + pub fn update( + &mut self, + world: &mut World, + ) -> (Vec<((i32, i32, i32), SectionMesh)>, Vec>) { let mut uploads = Vec::new(); if self.paused { return (uploads, Vec::new()); @@ -302,7 +317,9 @@ impl Streaming { } Done::Generated(mut chunk) => { let key = (chunk.x, chunk.z); - world.block_entities.extend(std::mem::take(&mut chunk.block_entities)); + world + .block_entities + .extend(std::mem::take(&mut chunk.block_entities)); let entities = std::mem::take(&mut chunk.entities); if !entities.is_empty() { world.loaded_entities.push(((chunk.x, chunk.z), entities)); @@ -381,19 +398,30 @@ impl Streaming { p.is_none() || d <= r4 * r4 }); let (protos, finishing) = (&self.protos, &self.finishing); - self.decorated - .retain(|k| protos.contains_key(k) || finishing.contains(k) || world.chunks.contains_key(k)); + self.decorated.retain(|k| { + protos.contains_key(k) || finishing.contains(k) || world.chunks.contains_key(k) + }); // Finalize chunks whose neighbourhood is decorated. let candidates: Vec<(i32, i32)> = self.protos.keys().copied().collect(); for (x, z) in candidates { - if world.chunks.contains_key(&(x, z)) || self.finishing.contains(&(x, z)) || !self.in_range(x, z, 1) { + if world.chunks.contains_key(&(x, z)) + || self.finishing.contains(&(x, z)) + || !self.in_range(x, z, 1) + { continue; } let ready = (-1..=1).all(|dz| { - (-1..=1).all(|dx| self.decorated.contains(&(x + dx, z + dz)) || world.chunks.contains_key(&(x + dx, z + dz))) + (-1..=1).all(|dx| { + self.decorated.contains(&(x + dx, z + dz)) + || world.chunks.contains_key(&(x + dx, z + dz)) + }) }); if ready && let Some(Some(_)) = self.protos.get(&(x, z)) { - let proto = self.protos.remove(&(x, z)).flatten().expect("present proto"); + let proto = self + .protos + .remove(&(x, z)) + .flatten() + .expect("present proto"); self.finishing.insert((x, z)); self.submit(self.distance(x, z) * 4, Job::Finish(proto)); } @@ -404,7 +432,9 @@ impl Streaming { let mut wanted: Vec<(i64, i32, i32)> = self .protos .iter() - .filter(|(k, p)| p.is_some() && !self.decorated.contains(k) && self.in_range(k.0, k.1, 2)) + .filter(|(k, p)| { + p.is_some() && !self.decorated.contains(k) && self.in_range(k.0, k.1, 2) + }) .map(|(k, _)| (self.distance(k.0, k.1), k.0, k.1)) .collect(); wanted.sort_unstable(); @@ -412,18 +442,27 @@ impl Streaming { if self.decorating >= workers * 2 { break; } - let keys: Vec<(i32, i32)> = (0..9).map(|i| (x + (i % 3) - 1, z + (i / 3) - 1)).collect(); + let keys: Vec<(i32, i32)> = + (0..9).map(|i| (x + (i % 3) - 1, z + (i / 3) - 1)).collect(); // A final (saved) neighbour cannot receive writes: skip decoration. if keys.iter().any(|k| world.chunks.contains_key(k)) { self.decorated.insert((x, z)); continue; } - if !keys.iter().all(|k| matches!(self.protos.get(k), Some(Some(_)))) { + if !keys + .iter() + .all(|k| matches!(self.protos.get(k), Some(Some(_)))) + { continue; } let region: Vec = keys .iter() - .map(|k| self.protos.insert(*k, None).flatten().expect("present proto")) + .map(|k| { + self.protos + .insert(*k, None) + .flatten() + .expect("present proto") + }) .collect(); let region: Box<[Proto; 9]> = match region.try_into() { Ok(r) => Box::new(r), @@ -471,8 +510,12 @@ impl Streaming { world.dirty_light.remove(&(x, z)); self.sequence += 1; self.lighting.insert((x, z), self.sequence); - self.light_snapshots.insert((x, z), self.light_edit_sequence); - self.submit(self.distance(x, z) * 4 + 1, Job::Light(x, z, region, self.sequence, self.sky_light)); + self.light_snapshots + .insert((x, z), self.light_edit_sequence); + self.submit( + self.distance(x, z) * 4 + 1, + Job::Light(x, z, region, self.sequence, self.sky_light), + ); } // Meshing once the column and its neighbours are lit. let dirty: Vec<_> = world.dirty_sections.iter().copied().collect(); @@ -489,7 +532,9 @@ impl Streaming { let region = columns .entry((x, z)) .or_insert_with(|| Self::region(world, x, z)); - let Some(region) = region.clone() else { continue }; + let Some(region) = region.clone() else { + continue; + }; world.dirty_sections.remove(&(x, sy, z)); let first = self.meshed.insert((x, z)); self.sequence += 1; @@ -516,7 +561,13 @@ impl Streaming { if positions.is_empty() { return; } - let changed = crate::light::relight(&mut world.chunks, &self.light_tables, self.sky_light, &positions, false); + let changed = crate::light::relight( + &mut world.chunks, + &self.light_tables, + self.sky_light, + &positions, + false, + ); Self::mark_light_changes(world, &changed); if !self.light_snapshots.is_empty() { for p in positions { @@ -531,11 +582,19 @@ impl Streaming { let positions: Vec<(i32, i32, i32)> = self .light_log .iter() - .filter(|(seq, p)| *seq > snapshot && ((p.0 >> 4) - x).abs() <= 1 && ((p.2 >> 4) - z).abs() <= 1) + .filter(|(seq, p)| { + *seq > snapshot && ((p.0 >> 4) - x).abs() <= 1 && ((p.2 >> 4) - z).abs() <= 1 + }) .map(|(_, p)| *p) .collect(); if !positions.is_empty() { - let changed = crate::light::relight(&mut world.chunks, &self.light_tables, self.sky_light, &positions, true); + let changed = crate::light::relight( + &mut world.chunks, + &self.light_tables, + self.sky_light, + &positions, + true, + ); Self::mark_light_changes(world, &changed); } let oldest = self.light_snapshots.values().copied().min(); @@ -552,7 +611,11 @@ impl Streaming { for dz in -1..=1 { for dy in -1..=1 { for dx in -1..=1 { - let s = ((y + dy - crate::chunk::MIN_Y) >> 4, (x + dx) >> 4, (z + dz) >> 4); + let s = ( + (y + dy - crate::chunk::MIN_Y) >> 4, + (x + dx) >> 4, + (z + dz) >> 4, + ); if last == Some(s) || !(0..SECTIONS as i32).contains(&s.0) { continue; } diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client/src/text.rs index 037153fca..553f8365e 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client/src/text.rs @@ -53,7 +53,10 @@ pub struct Style { } impl Style { pub fn color(c: u32) -> Self { - Self { color: Some(c), ..Self::default() } + Self { + color: Some(c), + ..Self::default() + } } /// Fill unset fields from `base` (Style.applyTo). pub fn inherit(&mut self, base: &Style) { @@ -106,7 +109,12 @@ impl Text { if text.is_empty() { return Self::default(); } - Self { spans: vec![Span { text, style: Style::default() }] } + Self { + spans: vec![Span { + text, + style: Style::default(), + }], + } } pub fn styled(s: impl Into, style: Style) -> Self { let mut t = Self::literal(s); @@ -145,13 +153,22 @@ impl Text { self.with_style(&Style::color(color)) } pub fn italic(self) -> Self { - self.with_style(&Style { italic: Some(true), ..Style::default() }) + self.with_style(&Style { + italic: Some(true), + ..Style::default() + }) } pub fn underlined(self) -> Self { - self.with_style(&Style { underlined: Some(true), ..Style::default() }) + self.with_style(&Style { + underlined: Some(true), + ..Style::default() + }) } pub fn bold(self) -> Self { - self.with_style(&Style { bold: Some(true), ..Style::default() }) + self.with_style(&Style { + bold: Some(true), + ..Style::default() + }) } /// Component.getString: the plain characters. pub fn plain(&self) -> String { @@ -173,7 +190,10 @@ impl Text { } let Some(code) = chars.next() else { break }; if !current.is_empty() { - out.spans.push(Span { text: std::mem::take(&mut current), style: style.clone() }); + out.spans.push(Span { + text: std::mem::take(&mut current), + style: style.clone(), + }); } let code = code.to_ascii_lowercase(); if let Some(c) = COLORS.iter().find(|c| c.0 == code) { @@ -192,13 +212,18 @@ impl Text { } } if !current.is_empty() { - out.spans.push(Span { text: current, style }); + out.spans.push(Span { + text: current, + style, + }); } out } /// Characters with their effective styles. pub fn chars(&self) -> impl Iterator { - self.spans.iter().flat_map(|s| s.text.chars().map(move |c| (c, &s.style))) + self.spans + .iter() + .flat_map(|s| s.text.chars().map(move |c| (c, &s.style))) } /// Sub-range of characters [from, to) keeping styles. pub fn slice(&self, from: usize, to: usize) -> Text { @@ -213,7 +238,10 @@ impl Text { index += 1; } if !part.is_empty() { - out.spans.push(Span { text: part, style: span.style.clone() }); + out.spans.push(Span { + text: part, + style: span.style.clone(), + }); } } out @@ -246,7 +274,11 @@ pub fn format_translation(template: &str, args: &[Text]) -> Text { j += 1; } if j > digits_start && j < chars.len() && chars[j] == '$' { - number = chars[digits_start..j].iter().collect::().parse::().ok(); + number = chars[digits_start..j] + .iter() + .collect::() + .parse::() + .ok(); j += 1; } else { j = digits_start; @@ -274,7 +306,10 @@ pub fn format_translation(template: &str, args: &[Text]) -> Text { return Text::literal(template); }; if !literal.is_empty() { - out.spans.push(Span { text: std::mem::take(&mut literal), style: Style::default() }); + out.spans.push(Span { + text: std::mem::take(&mut literal), + style: Style::default(), + }); } out.spans.extend(arg.spans.iter().cloned()); i = j + 1; @@ -283,7 +318,10 @@ pub fn format_translation(template: &str, args: &[Text]) -> Text { } } if !literal.is_empty() { - out.spans.push(Span { text: literal, style: Style::default() }); + out.spans.push(Span { + text: literal, + style: Style::default(), + }); } out } @@ -294,13 +332,25 @@ mod tests { #[test] fn formats_like_translatable_contents() { let a = [Text::literal("Steve"), Text::colored("Zombie", RED)]; - assert_eq!(format_translation("%s was slain by %s", &a).plain(), "Steve was slain by Zombie"); - assert_eq!(format_translation("%2$s then %1$s", &a).plain(), "Zombie then Steve"); - assert_eq!(format_translation("100%% sure %s", &a).plain(), "100% sure Steve"); + assert_eq!( + format_translation("%s was slain by %s", &a).plain(), + "Steve was slain by Zombie" + ); + assert_eq!( + format_translation("%2$s then %1$s", &a).plain(), + "Zombie then Steve" + ); + assert_eq!( + format_translation("100%% sure %s", &a).plain(), + "100% sure Steve" + ); // Missing arguments or unknown conversions show the template. assert_eq!(format_translation("%s %s %s", &a).plain(), "%s %s %s"); assert_eq!(format_translation("%d", &a).plain(), "%d"); - assert_eq!(format_translation("50% off %s", &a).plain(), "50% off Steve"); + assert_eq!( + format_translation("50% off %s", &a).plain(), + "50% off Steve" + ); assert_eq!(format_translation("end %", &a).plain(), "end %"); let t = format_translation("%s was slain by %s", &a); assert_eq!(t.spans.last().unwrap().style.color, Some(RED)); @@ -312,7 +362,9 @@ mod tests { assert_eq!(t.spans[0].style.color, Some(GREEN)); assert!(t.spans[1].style.is_bold()); assert_eq!(t.spans[2].style, Style::default()); - let t = Text::literal("x").append(Text::colored("y", GOLD)).with_color(RED); + let t = Text::literal("x") + .append(Text::colored("y", GOLD)) + .with_color(RED); assert_eq!(t.spans[0].style.color, Some(RED)); assert_eq!(t.spans[1].style.color, Some(GOLD)); assert_eq!(t.slice(1, 2).plain(), "y"); diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index c720d6183..e4bddd73b 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -16,8 +16,16 @@ pub struct WorldEntry { #[derive(Clone, Debug)] pub enum Mode { Main, - Select { worlds: Vec, selected: Option }, - Create { name: String, seed: String, creative: bool, focus: u8 }, + Select { + worlds: Vec, + selected: Option, + }, + Create { + name: String, + seed: String, + creative: bool, + focus: u8, + }, Multiplayer(crate::multiplayer::Screen), } #[derive(Clone, Debug, PartialEq)] @@ -25,9 +33,18 @@ pub enum Action { None, Quit, Options, - Play { folder: String }, - Create { folder: String, name: String, seed: Option, creative: bool }, - Connect { address: String }, + Play { + folder: String, + }, + Create { + folder: String, + name: String, + seed: Option, + creative: bool, + }, + Connect { + address: String, + }, } pub struct Title { pub mode: Mode, @@ -48,7 +65,12 @@ pub fn parse_seed(text: &str) -> Option { if t.is_empty() { return None; } - Some(t.parse::().unwrap_or_else(|_| i64::from(t.encode_utf16().fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(i32::from(c)))))) + Some(t.parse::().unwrap_or_else(|_| { + i64::from( + t.encode_utf16() + .fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(i32::from(c))), + ) + })) } pub fn list_worlds(saves: &Path) -> Vec { let mut worlds: Vec = std::fs::read_dir(saves) @@ -58,7 +80,9 @@ pub fn list_worlds(saves: &Path) -> Vec { .filter_map(|e| { let path = e.path(); let level = Level::read(&path)?; - let modified = std::fs::metadata(path.join("level.dat")).and_then(|m| m.modified()).ok()?; + let modified = std::fs::metadata(path.join("level.dat")) + .and_then(|m| m.modified()) + .ok()?; Some(WorldEntry { folder: e.file_name().to_string_lossy().into_owned(), name: level.name, @@ -72,32 +96,79 @@ pub fn list_worlds(saves: &Path) -> Vec { } impl Title { pub fn new(saves: PathBuf) -> Self { - Self { mode: Mode::Main, saves, started: std::time::Instant::now() } + Self { + mode: Mode::Main, + saves, + started: std::time::Instant::now(), + } } fn buttons(&self, w: f32, h: f32) -> Vec