From 6734879ff75eae9f2e6e6df1988e7fece4878b39 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 11 Oct 2026 14:11:51 +0200 Subject: [PATCH] Pass rustfmt and clippy after merging the parity branches Formats the overnight parity work, fixes the lints it introduced, and updates the LAN bot test and mob AI probe for fields added on the other side of the merges (the bot test also set a field that never existed). Co-Authored-By: Claude Opus 5.5 --- .../examples/item_model_fixture.rs | 3 +- crates/horizon-assets/src/math.rs | 72 +++- crates/horizon-assets/src/palette.rs | 59 +++- .../examples/auto_jump_probe.rs | 10 +- .../horizon-client/examples/camera_probe.rs | 14 +- .../examples/command_parse_fixture.rs | 10 +- .../examples/entity_death_loot_fixture.rs | 36 +- .../examples/frame_limiter_probe.rs | 17 +- .../horizon-client/examples/mob_ai_probe.rs | 9 +- .../examples/spawn_rules_fixture.rs | 3 +- crates/horizon-client/src/auto_jump.rs | 14 +- .../horizon-client/src/block_entity_render.rs | 172 ++++----- crates/horizon-client/src/camera.rs | 29 +- crates/horizon-client/src/command/args.rs | 86 +++-- crates/horizon-client/src/command/block.rs | 9 +- crates/horizon-client/src/command/codec.rs | 10 +- .../horizon-client/src/command/component.rs | 36 +- crates/horizon-client/src/command/item.rs | 68 +++- crates/horizon-client/src/command/mod.rs | 10 +- crates/horizon-client/src/command/packrat.rs | 12 +- crates/horizon-client/src/command/selector.rs | 7 +- crates/horizon-client/src/command/snbt.rs | 72 +++- crates/horizon-client/src/command/tests.rs | 29 +- .../horizon-client/src/command/tree_data.rs | 12 +- .../src/command/tree_execute.rs | 12 +- .../horizon-client/src/command/tree_misc.rs | 6 +- .../horizon-client/src/command/tree_world.rs | 50 ++- crates/horizon-client/src/command/vanilla.rs | 12 +- crates/horizon-client/src/game.rs | 11 +- crates/horizon-client/src/game/creatures.rs | 18 +- crates/horizon-client/src/game/lan.rs | 12 +- crates/horizon-client/src/game/machines.rs | 7 +- crates/horizon-client/src/game/mounts.rs | 4 +- crates/horizon-client/src/game/perspective.rs | 18 +- crates/horizon-client/src/game/recipe_book.rs | 15 +- crates/horizon-client/src/game/tnt.rs | 6 +- .../src/lan/command_suggestions.rs | 330 ++++++++++++++---- crates/horizon-client/src/lan/commands.rs | 31 +- crates/horizon-client/src/lan/entity.rs | 18 +- crates/horizon-client/src/lan/hub.rs | 3 +- crates/horizon-client/src/lan/tracking.rs | 4 +- crates/horizon-client/src/lib.rs | 2 +- crates/horizon-client/src/mobs.rs | 8 +- crates/horizon-client/src/mobs/control.rs | 7 +- crates/horizon-client/src/mobs/drops.rs | 10 +- crates/horizon-client/src/mobs/goals.rs | 5 +- crates/horizon-client/src/mobs/spawn_rules.rs | 62 +++- crates/horizon-client/src/window.rs | 12 +- crates/horizon-client/tests/lan_bot.rs | 6 +- crates/horizon-core/src/geometry/trig.rs | 19 +- .../examples/block_update_fixture.rs | 76 ++-- crates/horizon-world/src/level/data.rs | 5 +- crates/horizon-world/src/level/hooks.rs | 3 +- crates/horizon-world/src/level/mod.rs | 6 +- crates/horizon-world/src/level/portal.rs | 32 +- crates/horizon-world/src/level/shapes.rs | 9 +- crates/horizon-world/src/level/shelf.rs | 60 +++- crates/horizon-world/src/level/update.rs | 7 +- crates/horizon-world/src/loot.rs | 37 +- 59 files changed, 1254 insertions(+), 468 deletions(-) diff --git a/crates/horizon-assets/examples/item_model_fixture.rs b/crates/horizon-assets/examples/item_model_fixture.rs index c14ee3866..615492fe6 100644 --- a/crates/horizon-assets/examples/item_model_fixture.rs +++ b/crates/horizon-assets/examples/item_model_fixture.rs @@ -240,7 +240,8 @@ fn main() -> Result<(), Box> { let sprites = Sprites { root: root.clone(), permutations: PalettedPermutations::from_atlas( - &fs::read_to_string(root.join("assets/minecraft/atlases/items.json")).unwrap_or_default(), + &fs::read_to_string(root.join("assets/minecraft/atlases/items.json")) + .unwrap_or_default(), ), cache: RefCell::default(), }; diff --git a/crates/horizon-assets/src/math.rs b/crates/horizon-assets/src/math.rs index 74595c4d2..2f344d042 100644 --- a/crates/horizon-assets/src/math.rs +++ b/crates/horizon-assets/src/math.rs @@ -59,7 +59,10 @@ impl Mat4 { if m[0][3] == 0.0 && m[1][3] == 0.0 { if m[2][3] == 0.0 && m[3][3] == 1.0 { properties |= AFFINE; - if m[0] == [1.0, 0.0, 0.0, 0.0] && m[1] == [0.0, 1.0, 0.0, 0.0] && m[2] == [0.0, 0.0, 1.0, 0.0] { + if m[0] == [1.0, 0.0, 0.0, 0.0] + && m[1] == [0.0, 1.0, 0.0, 0.0] + && m[2] == [0.0, 0.0, 1.0, 0.0] + { properties |= TRANSLATION | ORTHONORMAL; if m[3][0] == 0.0 && m[3][1] == 0.0 && m[3][2] == 0.0 { properties |= IDENTITY; @@ -111,12 +114,20 @@ impl Mat4 { // mulAffine for c in 0..3 { for row in 0..3 { - out[c][row] = fma(m[0][row], r[c][0], fma(m[1][row], r[c][1], m[2][row] * r[c][2])); + out[c][row] = fma( + m[0][row], + r[c][0], + fma(m[1][row], r[c][1], m[2][row] * r[c][2]), + ); } out[c][3] = m[c][3]; } for row in 0..3 { - out[3][row] = fma(m[0][row], r[3][0], fma(m[1][row], r[3][1], fma(m[2][row], r[3][2], m[3][row]))); + out[3][row] = fma( + m[0][row], + r[3][0], + fma(m[1][row], r[3][1], fma(m[2][row], r[3][2], m[3][row])), + ); } out[3][3] = m[3][3]; return Self(out, AFFINE | self.1 & right.1 & ORTHONORMAL); @@ -124,7 +135,12 @@ impl Mat4 { if self.has(PERSPECTIVE) && right.has(AFFINE) { // mulPerspectiveAffine for c in 0..4 { - out[c] = [m[0][0] * r[c][0], m[1][1] * r[c][1], m[2][2] * r[c][2], m[2][3] * r[c][2]]; + out[c] = [ + m[0][0] * r[c][0], + m[1][1] * r[c][1], + m[2][2] * r[c][2], + m[2][3] * r[c][2], + ]; } out[3][2] = m[2][2] * r[3][2] + m[3][2]; out[3][3] = m[2][3] * r[3][2]; @@ -134,13 +150,24 @@ impl Mat4 { // mulAffineR for c in 0..3 { for row in 0..4 { - out[c][row] = fma(m[0][row], r[c][0], fma(m[1][row], r[c][1], m[2][row] * r[c][2])); + out[c][row] = fma( + m[0][row], + r[c][0], + fma(m[1][row], r[c][1], m[2][row] * r[c][2]), + ); } } for row in 0..4 { - out[3][row] = fma(m[0][row], r[3][0], fma(m[1][row], r[3][1], fma(m[2][row], r[3][2], m[3][row]))); + out[3][row] = fma( + m[0][row], + r[3][0], + fma(m[1][row], r[3][1], fma(m[2][row], r[3][2], m[3][row])), + ); } - return Self(out, self.1 & !(PERSPECTIVE | IDENTITY | TRANSLATION | ORTHONORMAL)); + return Self( + out, + self.1 & !(PERSPECTIVE | IDENTITY | TRANSLATION | ORTHONORMAL), + ); } // mul0 for c in 0..4 { @@ -148,7 +175,11 @@ impl Mat4 { out[c][row] = fma( m[0][row], r[c][0], - fma(m[1][row], r[c][1], fma(m[2][row], r[c][2], m[3][row] * r[c][3])), + fma( + m[1][row], + r[c][1], + fma(m[2][row], r[c][2], m[3][row] * r[c][3]), + ), ); } } @@ -162,7 +193,15 @@ impl Mat4 { // translateGeneric let mut out = *self; for row in 0..4 { - out.0[3][row] = fma(self.0[0][row], t[0], fma(self.0[1][row], t[1], fma(self.0[2][row], t[2], self.0[3][row]))); + out.0[3][row] = fma( + self.0[0][row], + t[0], + fma( + self.0[1][row], + t[1], + fma(self.0[2][row], t[2], self.0[3][row]), + ), + ); } out.1 = self.1 & !(PERSPECTIVE | IDENTITY); out @@ -186,7 +225,8 @@ impl Mat4 { out.0[c][row] = self.0[c][row] * s[c]; } } - out.1 = self.1 & !(PERSPECTIVE | IDENTITY | TRANSLATION | if one { 0 } else { ORTHONORMAL }); + out.1 = + self.1 & !(PERSPECTIVE | IDENTITY | TRANSLATION | if one { 0 } else { ORTHONORMAL }); out } /// `Matrix4f.rotate(Quaternionfc)`. @@ -228,7 +268,11 @@ impl Mat4 { // rotateGeneric for c in 0..3 { for row in 0..4 { - out.0[c][row] = fma(m[0][row], r[c][0], fma(m[1][row], r[c][1], m[2][row] * r[c][2])); + out.0[c][row] = fma( + m[0][row], + r[c][0], + fma(m[1][row], r[c][1], m[2][row] * r[c][2]), + ); } } } @@ -281,7 +325,11 @@ pub fn quaternion_xyz(x: f32, y: f32, z: f32) -> [f32; 4] { /// [0, 2π) and the axis is used as given. pub fn quaternion_from_axis_angle(angle: f32, axis: [f32; 3]) -> [f32; 4] { let tau = (std::f64::consts::PI * 2.0) as f32; - let angle = if angle < 0.0 { tau + angle % tau } else { angle } % tau; + let angle = if angle < 0.0 { + tau + angle % tau + } else { + angle + } % tau; let sin = joml_sin(angle * 0.5); let cos = cos_from_sin(sin, angle * 0.5); [axis[0] * sin, axis[1] * sin, axis[2] * sin, cos] diff --git a/crates/horizon-assets/src/palette.rs b/crates/horizon-assets/src/palette.rs index 788d1b17d..9f825d05d 100644 --- a/crates/horizon-assets/src/palette.rs +++ b/crates/horizon-assets/src/palette.rs @@ -25,7 +25,11 @@ pub struct Permutation<'a> { } fn qualified(id: &str) -> String { - if id.contains(':') { id.to_owned() } else { format!("minecraft:{id}") } + if id.contains(':') { + id.to_owned() + } else { + format!("minecraft:{id}") + } } impl PalettedPermutations { @@ -34,13 +38,29 @@ impl PalettedPermutations { let Ok(json) = serde_json::from_str::(atlas) else { return Vec::new(); }; - let sources = json.get("sources").and_then(Value::as_array).cloned().unwrap_or_default(); + let sources = json + .get("sources") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); sources .iter() - .filter(|s| s.get("type").and_then(Value::as_str).map(qualified).as_deref() == Some("minecraft:paletted_permutations")) + .filter(|s| { + s.get("type") + .and_then(Value::as_str) + .map(qualified) + .as_deref() + == Some("minecraft:paletted_permutations") + }) .filter_map(|s| { Some(Self { - textures: s.get("textures")?.as_array()?.iter().filter_map(Value::as_str).map(qualified).collect(), + textures: s + .get("textures")? + .as_array()? + .iter() + .filter_map(Value::as_str) + .map(qualified) + .collect(), palette_key: qualified(s.get("palette_key")?.as_str()?), permutations: s .get("permutations")? @@ -48,7 +68,11 @@ impl PalettedPermutations { .iter() .filter_map(|(k, v)| Some((k.clone(), qualified(v.as_str()?)))) .collect(), - separator: s.get("separator").and_then(Value::as_str).unwrap_or("_").to_owned(), + separator: s + .get("separator") + .and_then(Value::as_str) + .unwrap_or("_") + .to_owned(), }) }) .collect() @@ -57,8 +81,14 @@ impl PalettedPermutations { pub fn find(&self, sprite: &str) -> Option> { let sprite = qualified(sprite); self.textures.iter().find_map(|base| { - let suffix = sprite.strip_prefix(base.as_str())?.strip_prefix(self.separator.as_str())?; - Some(Permutation { base, palette_key: &self.palette_key, palette: self.permutations.get(suffix)? }) + let suffix = sprite + .strip_prefix(base.as_str())? + .strip_prefix(self.separator.as_str())?; + Some(Permutation { + base, + palette_key: &self.palette_key, + palette: self.permutations.get(suffix)?, + }) }) } } @@ -95,9 +125,18 @@ mod tests { let atlas = r#"{"sources":[{"type":"minecraft:paletted_permutations","palette_key":"minecraft:trim_base", "permutations":{"quartz":"minecraft:trim/quartz"},"textures":["minecraft:trims/items/boots_trim"]}]}"#; let sources = PalettedPermutations::from_atlas(atlas); - let p = sources[0].find("minecraft:trims/items/boots_trim_quartz").unwrap(); - assert_eq!((p.base, p.palette), ("minecraft:trims/items/boots_trim", "minecraft:trim/quartz")); - assert!(sources[0].find("minecraft:trims/items/boots_trim_gold").is_none()); + let p = sources[0] + .find("minecraft:trims/items/boots_trim_quartz") + .unwrap(); + assert_eq!( + (p.base, p.palette), + ("minecraft:trims/items/boots_trim", "minecraft:trim/quartz") + ); + assert!( + sources[0] + .find("minecraft:trims/items/boots_trim_gold") + .is_none() + ); let mut pixels = [0xFF11_2233, 0x8011_2233, 0x0011_2233, 0xFF44_5566]; apply_palette(&mut pixels, &[0xFF11_2233], &[0xFFAA_BBCC]).unwrap(); assert_eq!(pixels, [0xFFAA_BBCC, 0x80AA_BBCC, 0x0011_2233, 0xFF44_5566]); diff --git a/crates/horizon-client/examples/auto_jump_probe.rs b/crates/horizon-client/examples/auto_jump_probe.rs index f0f474c04..3dea957a2 100644 --- a/crates/horizon-client/examples/auto_jump_probe.rs +++ b/crates/horizon-client/examples/auto_jump_probe.rs @@ -64,7 +64,10 @@ fn main() -> Result<()> { .properties .insert(name.clone(), value.as_str().unwrap().into()); } - state = assets.registry.id(&definition).ok_or("missing fixture state")?; + state = assets + .registry + .id(&definition) + .ok_or("missing fixture state")?; } restore.push((x, y, z, scene.block(x, y, z))); scene.set(x, y, z, state)?; @@ -76,7 +79,10 @@ fn main() -> Result<()> { player.shift_key_down = p["shift"].as_bool().unwrap(); player.yaw = fl(&p["yr"]); player.pitch = fl(&p["xr"]); - let key = player.attributes.key("minecraft:movement_speed").ok_or("speed")?; + let key = player + .attributes + .key("minecraft:movement_speed") + .ok_or("speed")?; let handle = player .attributes .get_instance(Some(key)) diff --git a/crates/horizon-client/examples/camera_probe.rs b/crates/horizon-client/examples/camera_probe.rs index 889c1020a..e88e18926 100644 --- a/crates/horizon-client/examples/camera_probe.rs +++ b/crates/horizon-client/examples/camera_probe.rs @@ -86,7 +86,11 @@ impl RayWorld for Cells { ) -> std::result::Result { Ok(self.shapes[s].clone()) } - fn interaction_shape(&mut self, _: usize, _: BlockPos) -> std::result::Result { + fn interaction_shape( + &mut self, + _: usize, + _: BlockPos, + ) -> std::result::Result { Ok(VoxelShape::empty()) } fn fluid_is_source(&mut self, _: ()) -> std::result::Result { @@ -120,7 +124,9 @@ fn cells(c: &Value) -> Result { ShapeOp::OR, )?; } - world.index.insert(BlockPos::new(at[0], at[1], at[2]), world.shapes.len()); + world + .index + .insert(BlockPos::new(at[0], at[1], at[2]), world.shapes.len()); world.shapes.push(shape); } Ok(world) @@ -147,9 +153,7 @@ fn entity(s: &Value) -> (CameraEntity, Option) { dead: s["dead"].as_i64().map(|t| t as i32), }); let mount = if player { - s["mount"] - .as_array() - .map(|a| (db(&a[0]) as f32, db(&a[1]))) + s["mount"].as_array().map(|a| (db(&a[0]) as f32, db(&a[1]))) } else { None }; diff --git a/crates/horizon-client/examples/command_parse_fixture.rs b/crates/horizon-client/examples/command_parse_fixture.rs index f962b0e3b..1b6905bef 100644 --- a/crates/horizon-client/examples/command_parse_fixture.rs +++ b/crates/horizon-client/examples/command_parse_fixture.rs @@ -54,7 +54,9 @@ fn parser_id(ty: &ArgType) -> String { ArgType::ResOrTagKey(_) => "minecraft:resource_or_tag_key".into(), ArgType::StrEnum(values, _) => match values.first().copied() { Some("world_surface") => "minecraft:heightmap".into(), - Some("none") if values.len() == 3 && values[1] == "left_right" => "minecraft:template_mirror".into(), + Some("none") if values.len() == 3 && values[1] == "left_right" => { + "minecraft:template_mirror".into() + } Some("none") if values.len() == 3 => "minecraft:swing_animation".into(), _ => "minecraft:template_rotation".into(), }, @@ -194,10 +196,12 @@ fn main() -> horizon_client::Result<()> { reg.persistent_components = strings(&r["persistent_components"]); reg.learnable_recipes = strings(&r["learnable_recipes"]); for (clock, markers) in r["clock_time_markers"].as_object().into_iter().flatten() { - reg.clock_time_markers.insert(clock.clone(), strings(markers)); + reg.clock_time_markers + .insert(clock.clone(), strings(markers)); } for (id, criteria) in r["advancement_criteria"].as_object().into_iter().flatten() { - reg.advancement_criteria.insert(id.clone(), strings(criteria)); + reg.advancement_criteria + .insert(id.clone(), strings(criteria)); } reg.datapacks_enabled = strings(&r["datapacks_selected"]); let enabled = reg.datapacks_enabled.clone(); diff --git a/crates/horizon-client/examples/entity_death_loot_fixture.rs b/crates/horizon-client/examples/entity_death_loot_fixture.rs index 0e6dede38..1c9d06440 100644 --- a/crates/horizon-client/examples/entity_death_loot_fixture.rs +++ b/crates/horizon-client/examples/entity_death_loot_fixture.rs @@ -4,9 +4,7 @@ //! //! usage: entity_death_loot_fixture RESOURCES INPUT OUTPUT use horizon_client::{ - mobs::{ - Mob, MobTypes, Species, cube, drops, gear, raider, render::DYE_NAMES, sulfur_cube, - }, + mobs::{Mob, MobTypes, Species, cube, drops, gear, raider, render::DYE_NAMES, sulfur_cube}, random_sequences::RandomSequences, }; use horizon_core::{geometry::Vec3, random::LegacyRandom}; @@ -78,7 +76,8 @@ fn main() -> horizon_client::Result<()> { None => name = token, } } - let get = |k: &str, d: &'static str| -> String { c.get(k).copied().unwrap_or(d).to_owned() }; + let get = + |k: &str, d: &'static str| -> String { c.get(k).copied().unwrap_or(d).to_owned() }; let _ = writeln!(out, "== {name}"); let Some(kind) = types.types.get(c["type"]) else { let _ = writeln!(out, "error unsupported {}", c["type"]); @@ -213,11 +212,12 @@ fn main() -> horizon_client::Result<()> { kind: kind.to_owned(), ..LootEntity::default() }; - let damage = |kind: &str, source: Option, direct: Option| LootDamage { - kind: kind.to_owned(), - source, - direct, - }; + let damage = + |kind: &str, source: Option, direct: Option| LootDamage { + kind: kind.to_owned(), + source, + direct, + }; let source = match get("source", "attack").as_str() { "attack" => match &killer { None => damage("minecraft:generic", None, None), @@ -226,9 +226,17 @@ fn main() -> horizon_client::Result<()> { } Some(k) => damage("minecraft:mob_attack", Some(k.clone()), Some(k.clone())), }, - "arrow" => damage("minecraft:arrow", killer.clone(), Some(projectile("minecraft:arrow"))), + "arrow" => damage( + "minecraft:arrow", + killer.clone(), + Some(projectile("minecraft:arrow")), + ), "fireball" => match &killer { - Some(k) => damage("minecraft:fireball", Some(k.clone()), Some(projectile("minecraft:fireball"))), + Some(k) => damage( + "minecraft:fireball", + Some(k.clone()), + Some(projectile("minecraft:fireball")), + ), None => damage( "minecraft:unattributed_fireball", Some(projectile("minecraft:fireball")), @@ -236,7 +244,11 @@ fn main() -> horizon_client::Result<()> { ), }, "explosion" => match &killer { - Some(k) => damage("minecraft:player_explosion", Some(k.clone()), Some(k.clone())), + Some(k) => damage( + "minecraft:player_explosion", + Some(k.clone()), + Some(k.clone()), + ), None => damage("minecraft:explosion", None, None), }, "lightning" => damage("minecraft:lightning_bolt", None, None), diff --git a/crates/horizon-client/examples/frame_limiter_probe.rs b/crates/horizon-client/examples/frame_limiter_probe.rs index a877d05f9..7a5d4e437 100644 --- a/crates/horizon-client/examples/frame_limiter_probe.rs +++ b/crates/horizon-client/examples/frame_limiter_probe.rs @@ -62,15 +62,26 @@ fn main() -> Result<()> { now: i("now"), call: i("call"), spin: i("spin"), - overshoot: c["overshoot"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect(), + overshoot: c["overshoot"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_i64().unwrap()) + .collect(), next_overshoot: 0, - interrupts: c["interrupts"].as_array().unwrap().iter().map(|v| v.as_bool().unwrap()).collect(), + interrupts: c["interrupts"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_bool().unwrap()) + .collect(), next_interrupt: 0, parks: Vec::new(), spins: 0, queries: 0, }; - let mut limiter = FramerateLimiter::with_state(i("last"), i("average"), i("last_limit") as i32); + let mut limiter = + FramerateLimiter::with_state(i("last"), i("average"), i("last_limit") as i32); for frame in c["frames"].as_array().unwrap() { clock.now = clock.now.wrapping_add(frame[0].as_i64().unwrap()); clock.parks.clear(); diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 2406314d6..ab6cce246 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -483,6 +483,8 @@ fn main() -> horizon_client::Result<()> { biomes: &biomes, mob_griefing: true, difficulty: LocalDifficulty::new(2, world.day_time, 0, 0.0), + end: false, + world_seed: 0, }; let mut events = Vec::new(); for m in &mut mobs { @@ -498,7 +500,12 @@ fn main() -> horizon_client::Result<()> { } for e in &events { if let MobEvent::Sound(name, _, volume, pitch) = e { - let _ = writeln!(out, "{t} sound minecraft:{name} {} {}", f(*volume), f(*pitch)); + let _ = writeln!( + out, + "{t} sound minecraft:{name} {} {}", + f(*volume), + f(*pitch) + ); } else if let MobEvent::SoundId(name, _, volume, pitch) = e { let _ = writeln!(out, "{t} sound {name} {} {}", f(*volume), f(*pitch)); } diff --git a/crates/horizon-client/examples/spawn_rules_fixture.rs b/crates/horizon-client/examples/spawn_rules_fixture.rs index 8e4fff1c3..dc491be00 100644 --- a/crates/horizon-client/examples/spawn_rules_fixture.rs +++ b/crates/horizon-client/examples/spawn_rules_fixture.rs @@ -164,7 +164,8 @@ fn main() -> horizon_client::Result<()> { None => name = token, } } - let get = |k: &str, d: &'static str| -> String { c.get(k).copied().unwrap_or(d).to_owned() }; + let get = + |k: &str, d: &'static str| -> String { c.get(k).copied().unwrap_or(d).to_owned() }; let Some(kind) = types.types.get(c["type"]) else { let _ = writeln!(out, "{name} error unsupported {}", c["type"]); continue; diff --git a/crates/horizon-client/src/auto_jump.rs b/crates/horizon-client/src/auto_jump.rs index 123c84ce6..bd7bdcbad 100644 --- a/crates/horizon-client/src/auto_jump.rs +++ b/crates/horizon-client/src/auto_jump.rs @@ -148,7 +148,8 @@ pub fn update_auto_jump( let right_end = seg_end.add_vector(right_offset); let mut obstacle = NO_OBSTACLE; for b in world.collision_boxes(test_box)? { - if intersects_segment(b, left_begin, left_end) || intersects_segment(b, right_begin, right_end) + if intersects_segment(b, left_begin, left_end) + || intersects_segment(b, right_begin, right_end) { obstacle = b.max_position().y as f32; let obstacle_pos = BlockPos::containing(b.center()); @@ -175,7 +176,10 @@ pub fn update_auto_jump( } if obstacle != NO_OBSTACLE { let y_delta = (f64::from(obstacle) - p.position.y) as f32; - if !(y_delta <= 0.5) && !(y_delta > jump_height) { + // Negated as in LocalPlayer.updateAutoJump, so a NaN delta still jumps. + #[allow(clippy::neg_cmp_op_on_partial_ord)] + let jumps = !(y_delta <= 0.5) && !(y_delta > jump_height); + if jumps { return Ok(true); } } @@ -197,7 +201,11 @@ mod tests { } fn collision_boxes(&mut self, bounds: Aabb) -> Result, ()> { let b = Aabb::new(Vec3::new(1.0, 0.0, -5.0), Vec3::new(2.0, 1.0, 5.0)); - Ok(if b.intersects(bounds) { vec![b] } else { Vec::new() }) + Ok(if b.intersects(bounds) { + vec![b] + } else { + Vec::new() + }) } } #[test] diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 4e2a7704b..f3638865b 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -1434,6 +1434,92 @@ impl BlockEntityRenderer { } } +/// `BeaconRenderer.submit`: for each beam section (ARGB colour, height) the +/// rotating solid beam and its translucent glow, the last section 2048 +/// blocks tall. `origin` is the beacon block's corner relative to the camera, +/// `time` the animation time (game time mod 40 plus partial tick) and `scale` +/// the radius scale. The sprite's v range rides in the light bytes (the +/// entity shader wraps v for layer 6). +pub fn beacon_beam( + origin: Vec3, + sections: &[(u32, i32)], + time: f32, + scale: f32, + s: Rect, + out: &mut Vec, +) { + let q = |v: f32| (v * 65535.0).round().clamp(0.0, 65535.0) as u32; + let wrap = q(s.v0) | q(s.v1 - s.v0) << 16; + let o = origin + Vec3::new(0.5, 0.0, 0.5); + let mut start = 0i32; + for (i, &(color, height)) in sections.iter().enumerate() { + let height = if i == sections.len() - 1 { + 2048 + } else { + height + }; + let end = start + height; + let scroll = if height < 0 { time } else { -time }; + let v_off = frac(scroll * 0.2 - (scroll * 0.1).floor()); + let abgr = + |a: u32| a << 24 | (color & 255) << 16 | (color >> 8 & 255) << 8 | (color >> 16 & 255); + // Solid beam: radius 0.2 * scale, rotated with time. + let r = 0.2 * scale; + let rot = glam::Mat3::from_rotation_y((time * 2.25 - 45.0).to_radians()); + let corners = [ + rot * Vec3::new(0.0, 0.0, r), + rot * Vec3::new(r, 0.0, 0.0), + rot * Vec3::new(-r, 0.0, 0.0), + rot * Vec3::new(0.0, 0.0, -r), + ]; + let v2 = -1.0 + v_off; + let v1 = height as f32 * (0.5 / r) + v2; + beam_part(out, o, start, end, corners, [v1, v2], abgr(255), s, wrap); + // Glow: radius 0.25 * scale, translucent. + let g = 0.25 * scale; + let corners = [ + Vec3::new(-g, 0.0, -g), + Vec3::new(g, 0.0, -g), + Vec3::new(-g, 0.0, g), + Vec3::new(g, 0.0, g), + ]; + let v1 = height as f32 + v2; + beam_part(out, o, start, end, corners, [v1, v2], abgr(32), s, wrap); + start = end; + } +} +/// `BeaconRenderer.renderPart`: four quads between the corners (wn, en, ws, es). +#[allow(clippy::too_many_arguments)] +fn beam_part( + out: &mut Vec, + o: Vec3, + start: i32, + end: i32, + [wn, en, ws, es]: [Vec3; 4], + [v1, v2]: [f32; 2], + color: u32, + s: Rect, + wrap: u32, +) { + for (a, b) in [(wn, en), (es, ws), (en, es), (ws, wn)] { + let at = |c: Vec3, y: i32| o + c + Vec3::new(0.0, y as f32, 0.0); + for (p, uv) in [ + (at(a, end), [s.u1, v1]), + (at(a, start), [s.u1, v2]), + (at(b, start), [s.u0, v2]), + (at(b, end), [s.u0, v1]), + ] { + out.push(Vertex { + pos: p.to_array(), + uv, + layer: 6, + color, + light: wrap, + }); + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -1560,89 +1646,3 @@ mod tests { assert_eq!(out[2].uv, [0.5, 0.5]); } } - -/// `BeaconRenderer.submit`: for each beam section (ARGB colour, height) the -/// rotating solid beam and its translucent glow, the last section 2048 -/// blocks tall. `origin` is the beacon block's corner relative to the camera, -/// `time` the animation time (game time mod 40 plus partial tick) and `scale` -/// the radius scale. The sprite's v range rides in the light bytes (the -/// entity shader wraps v for layer 6). -pub fn beacon_beam( - origin: Vec3, - sections: &[(u32, i32)], - time: f32, - scale: f32, - s: Rect, - out: &mut Vec, -) { - let q = |v: f32| (v * 65535.0).round().clamp(0.0, 65535.0) as u32; - let wrap = q(s.v0) | q(s.v1 - s.v0) << 16; - let o = origin + Vec3::new(0.5, 0.0, 0.5); - let mut start = 0i32; - for (i, &(color, height)) in sections.iter().enumerate() { - let height = if i == sections.len() - 1 { - 2048 - } else { - height - }; - let end = start + height; - let scroll = if height < 0 { time } else { -time }; - let v_off = frac(scroll * 0.2 - (scroll * 0.1).floor()); - let abgr = - |a: u32| a << 24 | (color & 255) << 16 | (color >> 8 & 255) << 8 | (color >> 16 & 255); - // Solid beam: radius 0.2 * scale, rotated with time. - let r = 0.2 * scale; - let rot = glam::Mat3::from_rotation_y((time * 2.25 - 45.0).to_radians()); - let corners = [ - rot * Vec3::new(0.0, 0.0, r), - rot * Vec3::new(r, 0.0, 0.0), - rot * Vec3::new(-r, 0.0, 0.0), - rot * Vec3::new(0.0, 0.0, -r), - ]; - let v2 = -1.0 + v_off; - let v1 = height as f32 * (0.5 / r) + v2; - beam_part(out, o, start, end, corners, [v1, v2], abgr(255), s, wrap); - // Glow: radius 0.25 * scale, translucent. - let g = 0.25 * scale; - let corners = [ - Vec3::new(-g, 0.0, -g), - Vec3::new(g, 0.0, -g), - Vec3::new(-g, 0.0, g), - Vec3::new(g, 0.0, g), - ]; - let v1 = height as f32 + v2; - beam_part(out, o, start, end, corners, [v1, v2], abgr(32), s, wrap); - start = end; - } -} -/// `BeaconRenderer.renderPart`: four quads between the corners (wn, en, ws, es). -#[allow(clippy::too_many_arguments)] -fn beam_part( - out: &mut Vec, - o: Vec3, - start: i32, - end: i32, - [wn, en, ws, es]: [Vec3; 4], - [v1, v2]: [f32; 2], - color: u32, - s: Rect, - wrap: u32, -) { - for (a, b) in [(wn, en), (es, ws), (en, es), (ws, wn)] { - let at = |c: Vec3, y: i32| o + c + Vec3::new(0.0, y as f32, 0.0); - for (p, uv) in [ - (at(a, end), [s.u1, v1]), - (at(a, start), [s.u1, v2]), - (at(b, start), [s.u0, v2]), - (at(b, end), [s.u0, v1]), - ] { - out.push(Vertex { - pos: p.to_array(), - uv, - layer: 6, - color, - light: wrap, - }); - } - } -} diff --git a/crates/horizon-client/src/camera.rs b/crates/horizon-client/src/camera.rs index 329ae3e86..561a22b95 100644 --- a/crates/horizon-client/src/camera.rs +++ b/crates/horizon-client/src/camera.rs @@ -57,7 +57,11 @@ pub fn wrap_degrees(angle: f32) -> f32 { } /// `Mth.clamp(float, float, float)`. pub fn clamp(value: f32, min: f32, max: f32) -> f32 { - if value < min { min } else { java_min(value, max) } + if value < min { + min + } else { + java_min(value, max) + } } /// JOML's float trigonometry (`org.joml.Math` without fast math). @@ -130,12 +134,9 @@ pub mod joml { let yw = self.y * self.w; let k = 1.0 / (xx + yy + zz + ww); [ - (xx - yy - zz + ww) * k * x - + (2.0 * (xy - zw) * k * y + 2.0 * (xz + yw) * k * z), - 2.0 * (xy + zw) * k * x - + ((yy - xx - zz + ww) * k * y + 2.0 * (yz - xw) * k * z), - 2.0 * (xz - yw) * k * x - + (2.0 * (yz + xw) * k * y + (zz - xx - yy + ww) * k * z), + (xx - yy - zz + ww) * k * x + (2.0 * (xy - zw) * k * y + 2.0 * (xz + yw) * k * z), + 2.0 * (xy + zw) * k * x + ((yy - xx - zz + ww) * k * y + 2.0 * (yz - xw) * k * z), + 2.0 * (xz - yw) * k * x + (2.0 * (yz + xw) * k * y + (zz - xx - yy + ww) * k * z), ] } } @@ -568,8 +569,7 @@ impl Camera { if panoramic { return 90.0; } - let fov = - fov_option as f32 * lerp(partial, self.old_fov_modifier, self.fov_modifier); + let fov = fov_option as f32 * lerp(partial, self.old_fov_modifier, self.fov_modifier); modify_fov_based_on_death_or_fluid(partial, fov, effect_scale, dead, fluid) } /// `Camera.calculateHudFov`. @@ -704,7 +704,11 @@ pub fn bob_view(state: &BobState, pose: &mut Mat4) { 0.0, ); rotate_degrees(pose, 2, trig::sin(f64::from(walk * PI)) * bob * 3.0); - rotate_degrees(pose, 0, (trig::cos(f64::from(walk * PI - 0.2)) * bob).abs() * 5.0); + rotate_degrees( + pose, + 0, + (trig::cos(f64::from(walk * PI - 0.2)) * bob).abs() * 5.0, + ); } /// The bob matrix `GameRenderer.renderLevel` multiplies into the projection /// (and `renderItemInHand` into the hand's pose). @@ -767,7 +771,10 @@ mod tests { movement_speed: 0.13, using: None, }; - assert_eq!(field_of_view_modifier(&p, true, 1.0), (0.13f32 / 0.1 + 1.0) / 2.0); + assert_eq!( + field_of_view_modifier(&p, true, 1.0), + (0.13f32 / 0.1 + 1.0) / 2.0 + ); assert_eq!(field_of_view_modifier(&p, true, 0.0), 1.0); p.using = Some((UseItem::Spyglass, 3)); assert_eq!(field_of_view_modifier(&p, true, 1.0), 0.1); diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-client/src/command/args.rs index 1f24bfbf6..43770802f 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-client/src/command/args.rs @@ -540,9 +540,9 @@ pub fn parse_identifier(raw: &str) -> Option { && ns .chars() .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-')); - let path_ok = path - .chars() - .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/')); + let path_ok = path.chars().all(|c| { + c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/') + }); (ns_ok && path_ok).then(|| format!("{ns}:{path}")) } pub fn normalize(id: &str) -> String { @@ -690,7 +690,11 @@ pub fn read_double_bounds(reader: &mut Reader) -> CmdResult { } /// MinMaxBounds.FloatDegrees.fromReader (no swap check). pub fn read_float_bounds(reader: &mut Reader) -> CmdResult<(Option, Option)> { - read_bounds(reader, |s| java_parse_double(s).map(|v| v as f32), "parsing.float.invalid") + read_bounds( + reader, + |s| java_parse_double(s).map(|v| v as f32), + "parsing.float.invalid", + ) } /// Integer.parseInt over number characters. pub fn java_parse_int(s: &str) -> Option { @@ -886,7 +890,12 @@ fn java_split(s: &str) -> Vec<&str> { } /// SharedSuggestionProvider.suggestCoordinates / suggest2DCoordinates: the /// candidates `ty` parses completely. -fn suggest_coordinates(builder: &mut SuggestionsBuilder, reg: &Registries, ty: &ArgType, relevant: bool) { +fn suggest_coordinates( + builder: &mut SuggestionsBuilder, + reg: &Registries, + ty: &ArgType, + relevant: bool, +) { let remaining = builder.remaining().to_owned(); let three = matches!(ty, ArgType::BlockPos | ArgType::Vec3 { .. }); let coords: [String; 3] = if remaining.starts_with('^') { @@ -903,7 +912,11 @@ fn suggest_coordinates(builder: &mut SuggestionsBuilder, reg: &Registries, ty: & let mut result: Vec = Vec::new(); let [x, y, z] = &coords; if remaining.is_empty() { - let full = if three { format!("{x} {y} {z}") } else { format!("{x} {z}") }; + let full = if three { + format!("{x} {y} {z}") + } else { + format!("{x} {z}") + }; if valid(&full) { result.push(x.clone()); if three { @@ -965,7 +978,11 @@ fn parse_nbt_path(reader: &mut Reader) -> CmdResult<()> { // StringReader.peek past the end (StringIndexOutOfBoundsException). let len = reader.string.encode_utf16().count(); let message = format!("Index {len} out of bounds for length {len}"); - return Err(CommandError::tr_at("command.exception", &[&message], reader)); + return Err(CommandError::tr_at( + "command.exception", + &[&message], + reader, + )); } match reader.peek() { '{' => { @@ -988,7 +1005,10 @@ fn parse_nbt_path(reader: &mut Reader) -> CmdResult<()> { _ => { let s = reader.cursor; while reader.can_read() - && !matches!(reader.peek(), ' ' | '"' | '\'' | '[' | ']' | '.' | '{' | '}') + && !matches!( + reader.peek(), + ' ' | '"' | '\'' | '[' | ']' | '.' | '{' | '}' + ) { reader.skip(); } @@ -1049,10 +1069,9 @@ fn particle_options(id: &str, t: &horizon_world::nbt::Tag) -> Result<(), String> { // withAlternative(BlockState.CODEC, the block id codec). let first = match state { - horizon_world::nbt::Tag::Compound(_) => super::codec::either( - "Not a string".into(), - no_key("id", state), - ), + horizon_world::nbt::Tag::Compound(_) => { + super::codec::either("Not a string".into(), no_key("id", state)) + } _ => not_map(state), }; let _ = snbt; @@ -1121,7 +1140,10 @@ impl ArgType { reader.cursor = start; return Err(CommandError::tr_at( "argument.double.low", - &[&crate::snbt::java_double(*min), &crate::snbt::java_double(v)], + &[ + &crate::snbt::java_double(*min), + &crate::snbt::java_double(v), + ], reader, )); } @@ -1129,7 +1151,10 @@ impl ArgType { reader.cursor = start; return Err(CommandError::tr_at( "argument.double.big", - &[&crate::snbt::java_double(*max), &crate::snbt::java_double(v)], + &[ + &crate::snbt::java_double(*max), + &crate::snbt::java_double(v), + ], reader, )); } @@ -1146,10 +1171,7 @@ impl ArgType { // MessageArgument.Message.parseText. let len = reader.remaining().encode_utf16().count(); if len > 256 { - return Err(CommandError::tr( - "argument.message.too_long", - &[&len, &256], - )); + return Err(CommandError::tr("argument.message.too_long", &[&len, &256])); } let s = reader.remaining().to_owned(); if reg.permission >= 2 { @@ -1329,7 +1351,11 @@ impl ArgType { ArgType::HexColor => { let text = reader.read_unquoted_string(); if !matches!(text.len(), 3 | 6) { - return Err(CommandError::tr_at("argument.hexcolor.invalid", &[&text], reader)); + return Err(CommandError::tr_at( + "argument.hexcolor.invalid", + &[&text], + reader, + )); } // Integer.parseInt(s, begin, end, 16) per channel: a bad digit // escapes Brigadier as a dispatcher parse exception. @@ -1341,7 +1367,11 @@ impl ArgType { if let Some(i) = digits.find(|ch: char| !ch.is_ascii_hexdigit()) { let index = i + usize::from(signed); let message = format!("Error at index {index} in: \"{c}\""); - return Err(CommandError::tr_at("command.exception", &[&message], reader)); + return Err(CommandError::tr_at( + "command.exception", + &[&message], + reader, + )); } } let v = i64::from_str_radix(text, 16).unwrap_or(0); @@ -1361,7 +1391,10 @@ impl ArgType { .take_while(|c| c.is_ascii_hexdigit() || *c == '-') .map(char::len_utf8) .sum(); - match (run > 0).then(|| super::selector::java_uuid(&rest[..run])).flatten() { + match (run > 0) + .then(|| super::selector::java_uuid(&rest[..run])) + .flatten() + { Some(_) => { let text = rest[..run].to_owned(); reader.cursor += run; @@ -1391,7 +1424,11 @@ impl ArgType { let v = reader.read_float()?; let unit = reader.read_unquoted_string(); let Some(m) = time_unit(unit) else { - return Err(CommandError::tr_at("argument.time.invalid_unit", &[], reader)); + return Err(CommandError::tr_at( + "argument.time.invalid_unit", + &[], + reader, + )); }; // Math.round(float): floor(x + 0.5). let ticks = (v * m as f32 + 0.5).floor() as i32; @@ -1425,7 +1462,10 @@ impl ArgType { // ParserBasedArgument.withCodec: SNBT, then the codec (errors at the start). let tag = super::snbt::parse_tag_argument(reader)?; let (decoded, key) = if matches!(self, ArgType::Style) { - (super::component::decode_style(&tag), "argument.style.invalid") + ( + super::component::decode_style(&tag), + "argument.style.invalid", + ) } else { (super::component::decode(&tag), "argument.component.invalid") }; diff --git a/crates/horizon-client/src/command/block.rs b/crates/horizon-client/src/command/block.rs index 0656a7898..db38a6fbd 100644 --- a/crates/horizon-client/src/command/block.rs +++ b/crates/horizon-client/src/command/block.rs @@ -379,7 +379,8 @@ impl<'r, 'a> BlockParser<'r, 'a> { } let prefix = b.remaining_lower(); for (name, _) in definition { - if !self.properties.iter().any(|(n, _)| n == name) && name.starts_with(&prefix) { + if !self.properties.iter().any(|(n, _)| n == name) && name.starts_with(&prefix) + { b.suggest(format!("{name}=")); } } @@ -439,11 +440,7 @@ impl<'r, 'a> BlockParser<'r, 'a> { } /// BlockStateParser.parseForBlock / parseForTesting (the reader is rewound on errors). -pub fn parse( - reader: &mut Reader, - reg: &Registries, - for_testing: bool, -) -> CmdResult { +pub fn parse(reader: &mut Reader, reg: &Registries, for_testing: bool) -> CmdResult { let cursor = reader.cursor; let r = BlockParser::new(reader, reg, for_testing, true).parse(); if r.is_err() { diff --git a/crates/horizon-client/src/command/codec.rs b/crates/horizon-client/src/command/codec.rs index f0febe13a..783d26e30 100644 --- a/crates/horizon-client/src/command/codec.rs +++ b/crates/horizon-client/src/command/codec.rs @@ -86,10 +86,7 @@ fn provider_fields(id: &str, map: &Compound, t: &Tag) -> Result<(), String> { } } /// A holder list codec: a single element, a `#tag`, or a list. -fn element_or_list( - t: &Tag, - element: &dyn Fn(&Tag) -> Result<(), String>, -) -> Result<(), String> { +fn element_or_list(t: &Tag, element: &dyn Fn(&Tag) -> Result<(), String>) -> Result<(), String> { let first = match element(t) { Ok(()) => return Ok(()), Err(e) => e, @@ -179,7 +176,6 @@ pub fn resource_or_id(reader: &mut Reader, reg: &Registries, registry: &str) -> } reader.cursor = start; let tag = super::snbt::parse_tag_argument(reader)?; - decode(registry, &tag, reg).map_err(|m| { - CommandError::tr_at("argument.resource_or_id.failed_to_parse", &[&m], reader) - }) + decode(registry, &tag, reg) + .map_err(|m| CommandError::tr_at("argument.resource_or_id.failed_to_parse", &[&m], reader)) } diff --git a/crates/horizon-client/src/command/component.rs b/crates/horizon-client/src/command/component.rs index 114a90ccf..9bc0668d5 100644 --- a/crates/horizon-client/src/command/component.rs +++ b/crates/horizon-client/src/command/component.rs @@ -47,7 +47,11 @@ fn is_string(t: &Tag) -> bool { matches!(t, Tag::String(_)) } fn string(t: &Tag) -> R { - if is_string(t) { Ok(()) } else { err("Not a string") } + if is_string(t) { + Ok(()) + } else { + err("Not a string") + } } fn string_of(t: &Tag) -> Option { match t { @@ -131,9 +135,9 @@ pub fn identifier(t: &Tag) -> Result<(), String> { "Not a valid resource location: {s} Non [a-z0-9_.-] character in namespace of location: {ns}:{path}" )); } - let path_ok = path - .chars() - .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/')); + let path_ok = path.chars().all(|c| { + c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/') + }); if !path_ok { return Err(format!( "Not a valid resource location: {s} Non [a-z0-9/._-] character in path of location: {ns}:{path}" @@ -208,7 +212,13 @@ fn style_fields(map: &Compound) -> R { if let Some(c) = get(map, "color") { color(c)?; } - for key in ["bold", "italic", "underlined", "strikethrough", "obfuscated"] { + for key in [ + "bold", + "italic", + "underlined", + "strikethrough", + "obfuscated", + ] { if let Some(v) = get(map, key) && bool_value(v).is_err() { @@ -262,12 +272,13 @@ fn content(kind: &str, map: &Compound) -> bool { _ => false, }, "selector" => { - get(map, "selector").is_some_and(selector_string) && optional_component(map, "separator") + get(map, "selector").is_some_and(selector_string) + && optional_component(map, "separator") } "nbt" => { - let path_ok = get(map, "nbt").and_then(string_of).is_some_and(|p| { - crate::nbt_path::NbtPath::parse(&p).is_ok() - }); + let path_ok = get(map, "nbt") + .and_then(string_of) + .is_some_and(|p| crate::nbt_path::NbtPath::parse(&p).is_ok()); let source = if let Some(e) = get(map, "entity") { selector_string(e) } else if let Some(b) = get(map, "block") { @@ -336,10 +347,9 @@ fn full(t: &Tag) -> R { style_fields(map) } fn component(t: &Tag) -> R { - either( - either(string(t), || non_empty_list(t, &component)), - || full(t), - ) + either(either(string(t), || non_empty_list(t, &component)), || { + full(t) + }) } /// ComponentSerialization.CODEC.parse: the error message on failure. pub fn decode(t: &Tag) -> Result<(), String> { diff --git a/crates/horizon-client/src/command/item.rs b/crates/horizon-client/src/command/item.rs index 909b918fa..e0ed4a516 100644 --- a/crates/horizon-client/src/command/item.rs +++ b/crates/horizon-client/src/command/item.rs @@ -1,7 +1,9 @@ //! ItemParser (item stacks with components, `stone[damage=5]`) and //! ItemPredicateArgument (ComponentPredicateParser's packrat grammar: //! `#logs[count~1..|!damage]`), with vanilla's errors and suggestions. -use super::args::{ItemInput, Registries, is_id_char, parse_identifier, read_identifier, suggest_resources}; +use super::args::{ + ItemInput, Registries, is_id_char, parse_identifier, read_identifier, suggest_resources, +}; use super::codec::{either, is_number, not_map, snbt}; use super::packrat::{Grammar, Reason, State, Sugg, Term, Value, alt, ch, opt, seq}; use super::{CmdResult, CommandError, Reader, SuggestionsBuilder}; @@ -159,7 +161,10 @@ impl ItemState<'_, '_> { self.sugg = ISugg::Component; let ty = self.component_type()?; if visited.contains(&ty) { - return Err(CommandError::tr("arguments.item.component.repeated", &[&ty])); + return Err(CommandError::tr( + "arguments.item.component.repeated", + &[&ty], + )); } visited.push(ty); self.sugg = ISugg::Nothing; @@ -167,7 +172,10 @@ impl ItemState<'_, '_> { } else { let ty = self.component_type()?; if visited.contains(&ty) { - return Err(CommandError::tr("arguments.item.component.repeated", &[&ty])); + return Err(CommandError::tr( + "arguments.item.component.repeated", + &[&ty], + )); } visited.push(ty.clone()); self.sugg = ISugg::Assignment; @@ -401,10 +409,12 @@ fn predicate_grammar() -> Grammar { "type", alt(vec![element, seq(vec![ch('#'), Term::Cut, tag]), any]), |s| { - Some(IV::Type(match s.scope.get_any(&["element_type", "tag_type"]) { - Some(IV::Elem(t)) => Some(t), - _ => None, - })) + Some(IV::Type( + match s.scope.get_any(&["element_type", "tag_type"]) { + Some(IV::Elem(t)) => Some(t), + _ => None, + }, + )) }, ); g.put_term("any_type", ch('*'), |_| Some(IV::Unit)); @@ -415,7 +425,11 @@ fn predicate_grammar() -> Grammar { if r.ids("minecraft:item").iter().any(|i| i == id) { Ok(IV::Elem(TypeRes::Item(id.to_owned()))) } else { - Err(CommandError::tr_at("argument.item.id.invalid", &[&id], reader)) + Err(CommandError::tr_at( + "argument.item.id.invalid", + &[&id], + reader, + )) } }) }); @@ -426,7 +440,11 @@ fn predicate_grammar() -> Grammar { if r.tags("minecraft:item").iter().any(|i| i == id) { Ok(IV::Elem(TypeRes::Tag(id.to_owned()))) } else { - Err(CommandError::tr_at("arguments.item.tag.unknown", &[&id], reader)) + Err(CommandError::tr_at( + "arguments.item.tag.unknown", + &[&id], + reader, + )) } }) }); @@ -509,29 +527,49 @@ fn predicate_grammar() -> Grammar { if id == "minecraft:count" { return Ok(IV::Comp(id.to_owned())); } - let known = r.ids("minecraft:data_component_type").iter().any(|c| c == id); + let known = r + .ids("minecraft:data_component_type") + .iter() + .any(|c| c == id); if known && r.persistent_components.iter().any(|c| c == id) { Ok(IV::Comp(id.to_owned())) } else { - Err(CommandError::tr_at("arguments.item.component.unknown", &[&id], reader)) + Err(CommandError::tr_at( + "arguments.item.component.unknown", + &[&id], + reader, + )) } }) }); g.put_custom("predicate_type", move |s| { let r = reg(s); let mut list = vec!["minecraft:count".to_owned()]; - list.extend(r.ids("minecraft:data_component_predicate_type").iter().cloned()); + list.extend( + r.ids("minecraft:data_component_predicate_type") + .iter() + .cloned(), + ); lookup(s, id, Rc::new(list), &|id, reader| { if id == "minecraft:count" - || r.ids("minecraft:data_component_predicate_type").iter().any(|c| c == id) + || r.ids("minecraft:data_component_predicate_type") + .iter() + .any(|c| c == id) { return Ok(IV::Pred(id.to_owned())); } - if r.ids("minecraft:data_component_type").iter().any(|c| c == id) { + if r.ids("minecraft:data_component_type") + .iter() + .any(|c| c == id) + { // A component existence predicate (decodes Unit). return Ok(IV::Pred(format!("exists:{id}"))); } - Err(CommandError::tr_at("arguments.item.predicate.unknown", &[&id], reader)) + Err(CommandError::tr_at( + "arguments.item.predicate.unknown", + &[&id], + reader, + )) }) }); g.put_custom("tag", |s| super::snbt::rule_in(s, IV::Tag)); diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-client/src/command/mod.rs index f0c89fb01..e6931852a 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-client/src/command/mod.rs @@ -616,7 +616,8 @@ pub fn merge_suggestions(input: &str, list: Vec) -> (Range, Vec = Vec::with_capacity(out.len()); for s in out { - let pos = sorted.partition_point(|x| compare_suggestions(x, &s) != std::cmp::Ordering::Greater); + let pos = + sorted.partition_point(|x| compare_suggestions(x, &s) != std::cmp::Ordering::Greater); sorted.insert(pos, s); } ((start, end), sorted) @@ -644,7 +645,8 @@ impl Suggests { for id in ®.summonable { if args::resource_matches(&contents, id) { let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id)); - let name = crate::lang::get(&format!("entity.{ns}.{}", path.replace('/', "."))); + let name = + crate::lang::get(&format!("entity.{ns}.{}", path.replace('/', "."))); builder.suggest_tooltip(id.clone(), name); } } @@ -673,7 +675,9 @@ impl Suggests { .trigger_scores .iter() .filter(|(_, scores)| { - targets.iter().any(|t| scores.get(t).is_none_or(|locked| *locked)) + targets + .iter() + .any(|t| scores.get(t).is_none_or(|locked| *locked)) }) .map(|(o, _)| o.as_str()) .collect(); diff --git a/crates/horizon-client/src/command/packrat.rs b/crates/horizon-client/src/command/packrat.rs index 996f84291..42f42d9f4 100644 --- a/crates/horizon-client/src/command/packrat.rs +++ b/crates/horizon-client/src/command/packrat.rs @@ -94,13 +94,11 @@ impl Scope { let current = self.top_marker; let n = self.top_entry - self.top_marker; self.setup_new_frame(); - let mut source = current + 1; let mut target = self.top_entry; - for _ in 0..n { + for source in current + 1..current + 1 + n { target += 1; let key = self.stack[source].0; self.set(target, key, None); - source += 1; } self.top_entry = target; } @@ -139,11 +137,13 @@ impl Scope { } } pub fn get(&self, atom: Atom) -> Option { - self.value_index(&[atom]).and_then(|i| self.stack[i].1.clone()) + self.value_index(&[atom]) + .and_then(|i| self.stack[i].1.clone()) } /// Scope.getAny: the newest of several atoms. pub fn get_any(&self, atoms: &[Atom]) -> Option { - self.value_index(atoms).and_then(|i| self.stack[i].1.clone()) + self.value_index(atoms) + .and_then(|i| self.stack[i].1.clone()) } /// Whether the atom has an entry (even a null one). pub fn has(&self, atom: Atom) -> bool { @@ -385,7 +385,7 @@ impl<'g, V: Value> State<'g, V> { r } fn first_error(&self) -> CommandError { - for (_, reason) in &self.errors { + if let Some((_, reason)) = self.errors.first() { return match reason { Reason::Delayed(key, args) => { let args: Vec<&dyn std::fmt::Display> = diff --git a/crates/horizon-client/src/command/selector.rs b/crates/horizon-client/src/command/selector.rs index 6b65de823..eb4e637a4 100644 --- a/crates/horizon-client/src/command/selector.rs +++ b/crates/horizon-client/src/command/selector.rs @@ -143,7 +143,12 @@ pub fn java_uuid(name: &str) -> Option { Some((u128::from(msb) << 64) | u128::from(lsb)) } -fn rollback(reader: &mut Reader, start: usize, key: &str, args: &[&dyn std::fmt::Display]) -> CommandError { +fn rollback( + reader: &mut Reader, + start: usize, + key: &str, + args: &[&dyn std::fmt::Display], +) -> CommandError { reader.cursor = start; CommandError::tr_at(key, args, reader) } diff --git a/crates/horizon-client/src/command/snbt.rs b/crates/horizon-client/src/command/snbt.rs index 042f6daa1..05fe6d9bc 100644 --- a/crates/horizon-client/src/command/snbt.rs +++ b/crates/horizon-client/src/command/snbt.rs @@ -153,7 +153,9 @@ fn parse_small(s: &str, radix: u32, lo: i32, hi: i32) -> Result { } fn parse_unsigned_int(s: &str, radix: u32) -> Result { if s.starts_with('-') { - return Err(format!("Illegal leading minus sign on unsigned string {s}.")); + return Err(format!( + "Illegal leading minus sign on unsigned string {s}." + )); } let len = s.chars().count(); if len <= 5 || (radix == 10 && len <= 9) { @@ -168,7 +170,9 @@ fn parse_unsigned_int(s: &str, radix: u32) -> Result { } fn parse_unsigned_long(s: &str, radix: u32) -> Result { if s.starts_with('-') { - return Err(format!("Illegal leading minus sign on unsigned string {s}.")); + return Err(format!( + "Illegal leading minus sign on unsigned string {s}." + )); } let digits = s.strip_prefix('+').unwrap_or(s); match u64::from_str_radix(digits, radix) { @@ -338,7 +342,11 @@ pub fn grammar() -> Grammar { |s| s.scope.get("integer_suffix"), ); g.put_custom("binary_numeral", |s| { - number_run(s, |c| matches!(c, '0' | '1' | '_'), "snbt.parser.expected_binary_numeral") + number_run( + s, + |c| matches!(c, '0' | '1' | '_'), + "snbt.parser.expected_binary_numeral", + ) }); g.put_custom("decimal_numeral", |s| { number_run( @@ -394,7 +402,10 @@ pub fn grammar() -> Grammar { } else if let Some(h) = get_str(s, "hex_numeral") { (Base::Hex, h) } else { - (Base::Binary, get_str(s, "binary_numeral").unwrap_or_default()) + ( + Base::Binary, + get_str(s, "binary_numeral").unwrap_or_default(), + ) }; Some(SV::Int(IntLit { minus, @@ -408,8 +419,14 @@ pub fn grammar() -> Grammar { g.put_term( "float_type_suffix", alt(vec![ - seq(vec![chs('f', 'F'), Term::Marker("float_type_suffix", SV::Type(TypeSuffix::Float))]), - seq(vec![chs('d', 'D'), Term::Marker("float_type_suffix", SV::Type(TypeSuffix::Double))]), + seq(vec![ + chs('f', 'F'), + Term::Marker("float_type_suffix", SV::Type(TypeSuffix::Float)), + ]), + seq(vec![ + chs('d', 'D'), + Term::Marker("float_type_suffix", SV::Type(TypeSuffix::Double)), + ]), ]), |s| s.scope.get("float_type_suffix"), ); @@ -420,7 +437,10 @@ pub fn grammar() -> Grammar { seq(vec![chs('e', 'E'), opt(sign), decimal]), |s| { let minus = matches!(s.scope.get("sign"), Some(SV::Sign(true))); - Some(SV::Exp(minus, get_str(s, "decimal_numeral").unwrap_or_default())) + Some(SV::Exp( + minus, + get_str(s, "decimal_numeral").unwrap_or_default(), + )) }, ); let sign = g.named("sign"); @@ -470,7 +490,11 @@ pub fn grammar() -> Grammar { float_tag(&text, ty, s).map(SV::Tag) }, ); - for (name, n) in [("string_hex_2", 2), ("string_hex_4", 4), ("string_hex_8", 8)] { + for (name, n) in [ + ("string_hex_2", 2), + ("string_hex_4", 4), + ("string_hex_8", 8), + ] { g.put_custom(name, move |s| { greedy( s, @@ -521,7 +545,9 @@ pub fn grammar() -> Grammar { if let Some(SV::Str(plain)) = s.scope.get_any(&["string_escape_sequence"]) { return Some(SV::Str(plain)); } - if let Some(SV::Str(h)) = s.scope.get_any(&["string_hex_2", "string_hex_4", "string_hex_8"]) + if let Some(SV::Str(h)) = + s.scope + .get_any(&["string_hex_2", "string_hex_4", "string_hex_8"]) { let cp = u32::from_str_radix(&h, 16).unwrap_or(u32::MAX); if cp > 0x10ffff { @@ -531,7 +557,9 @@ pub fn grammar() -> Grammar { )); return None; } - return Some(SV::Str(char::from_u32(cp).unwrap_or('\u{fffd}').to_string())); + return Some(SV::Str( + char::from_u32(cp).unwrap_or('\u{fffd}').to_string(), + )); } // Character.codePointOf: Unicode names are not tabulated here. s.store_at_mark(delayed("snbt.parser.invalid_character_name")); @@ -663,7 +691,8 @@ pub fn grammar() -> Grammar { let qs = g.named("quoted_string_literal"); let uq = g.named("unquoted_string"); g.put_term("map_key", alt(vec![qs, uq]), |s| { - s.scope.get_any(&["quoted_string_literal", "unquoted_string"]) + s.scope + .get_any(&["quoted_string_literal", "unquoted_string"]) }); let key = g.named("map_key"); let lit = g.named("literal"); @@ -712,9 +741,18 @@ pub fn grammar() -> Grammar { g.put_term( "array_prefix", alt(vec![ - seq(vec![ch('B'), Term::Marker("array_prefix", SV::Prefix(ArrayPrefix::Byte))]), - seq(vec![ch('L'), Term::Marker("array_prefix", SV::Prefix(ArrayPrefix::Long))]), - seq(vec![ch('I'), Term::Marker("array_prefix", SV::Prefix(ArrayPrefix::Int))]), + seq(vec![ + ch('B'), + Term::Marker("array_prefix", SV::Prefix(ArrayPrefix::Byte)), + ]), + seq(vec![ + ch('L'), + Term::Marker("array_prefix", SV::Prefix(ArrayPrefix::Long)), + ]), + seq(vec![ + ch('I'), + Term::Marker("array_prefix", SV::Prefix(ArrayPrefix::Int)), + ]), ]), |s| s.scope.get("array_prefix"), ); @@ -890,7 +928,11 @@ thread_local! { pub fn parse_tag_argument(reader: &mut Reader) -> CmdResult { GRAMMAR.with(|g| match g.parse_for_commands(reader)? { SV::Tag(t) => Ok(t), - _ => Err(CommandError::tr_at("argument.nbt.expected.compound", &[], reader)), + _ => Err(CommandError::tr_at( + "argument.nbt.expected.compound", + &[], + reader, + )), }) } /// TagParser.parseCompoundAsArgument. diff --git a/crates/horizon-client/src/command/tests.rs b/crates/horizon-client/src/command/tests.rs index ed4fe4123..ea29da523 100644 --- a/crates/horizon-client/src/command/tests.rs +++ b/crates/horizon-client/src/command/tests.rs @@ -37,9 +37,18 @@ fn reg() -> Registries { }, ); }; - registry("minecraft:worldgen/biome", &["minecraft:desert", "minecraft:plains"]); - registry("minecraft:damage_type", &["minecraft:fall", "minecraft:magic"]); - registry("minecraft:attribute", &["minecraft:max_health", "minecraft:scale"]); + registry( + "minecraft:worldgen/biome", + &["minecraft:desert", "minecraft:plains"], + ); + registry( + "minecraft:damage_type", + &["minecraft:fall", "minecraft:magic"], + ); + registry( + "minecraft:attribute", + &["minecraft:max_health", "minecraft:scale"], + ); registry("minecraft:item_modifier", &["a:b"]); registry("minecraft:predicate", &["a:b"]); registry( @@ -54,7 +63,14 @@ fn reg() -> Registries { "minecraft:entity_type", &["minecraft:pig", "minecraft:player", "minecraft:zombie"], ); - registry("minecraft:item", &["minecraft:diamond", "minecraft:diamond_sword", "minecraft:stone"]); + registry( + "minecraft:item", + &[ + "minecraft:diamond", + "minecraft:diamond_sword", + "minecraft:stone", + ], + ); r } fn run(input: &str) -> CmdResult<(String, Vec)> { @@ -436,7 +452,10 @@ fn world_command_trees() { "particle minecraft:dust{color:[1.0,0.0,0.0],scale:2.0} ~ ~ ~ 0.1 0.1 0.1 0 10 force @a", "particle", ), - ("particle minecraft:block{block_state:\"minecraft:stone\"} ~ ~ ~", "particle"), + ( + "particle minecraft:block{block_state:\"minecraft:stone\"} ~ ~ ~", + "particle", + ), ("attribute @s minecraft:max_health get 2", "attribute.get"), ( "attribute @s minecraft:max_health base set 40", diff --git a/crates/horizon-client/src/command/tree_data.rs b/crates/horizon-client/src/command/tree_data.rs index 003c5c045..34ce17bea 100644 --- a/crates/horizon-client/src/command/tree_data.rs +++ b/crates/horizon-client/src/command/tree_data.rs @@ -52,7 +52,11 @@ pub fn register(d: &mut Dispatcher, root: usize) { d.requires(compute, GAMEMASTERS); context_sources(d, compute, &mut |d, node| { let f = d.literal(node, "float"); - let p = d.argument(f, "provider", ArgType::ResourceOrId("minecraft:context_float_provider")); + let p = d.argument( + f, + "provider", + ArgType::ResourceOrId("minecraft:context_float_provider"), + ); d.executes(p, "compute"); let scale = d.argument( p, @@ -64,7 +68,11 @@ pub fn register(d: &mut Dispatcher, root: usize) { ); d.executes(scale, "compute"); let i = d.literal(node, "integer"); - let p = d.argument(i, "provider", ArgType::ResourceOrId("minecraft:context_int_provider")); + let p = d.argument( + i, + "provider", + ArgType::ResourceOrId("minecraft:context_int_provider"), + ); d.executes(p, "compute"); }); diff --git a/crates/horizon-client/src/command/tree_execute.rs b/crates/horizon-client/src/command/tree_execute.rs index 1fd4e444b..53085410a 100644 --- a/crates/horizon-client/src/command/tree_execute.rs +++ b/crates/horizon-client/src/command/tree_execute.rs @@ -48,7 +48,11 @@ pub fn register(d: &mut Dispatcher, root: usize) { let t = d.argument(as_, "targets", ENTITIES); d.redirect(t, ex); let over = d.literal(positioned, "over"); - let hm = d.argument(over, "heightmap", ArgType::StrEnum(HEIGHTMAPS, "argument.enum.invalid")); + let hm = d.argument( + over, + "heightmap", + ArgType::StrEnum(HEIGHTMAPS, "argument.enum.invalid"), + ); d.redirect(hm, ex); let rotated = d.literal(ex, "rotated"); let rot = d.argument(rotated, "rot", ArgType::Rotation); @@ -179,7 +183,11 @@ fn conditionals(d: &mut Dispatcher, m: usize, ex: usize) { conditional(d, targets, ex); let predicate = d.literal(m, "predicate"); - let p = d.argument(predicate, "predicate", ArgType::ResourceOrId("minecraft:predicate")); + let p = d.argument( + predicate, + "predicate", + ArgType::ResourceOrId("minecraft:predicate"), + ); conditional(d, p, ex); let stopwatch = d.literal(m, "stopwatch"); diff --git a/crates/horizon-client/src/command/tree_misc.rs b/crates/horizon-client/src/command/tree_misc.rs index 221b1fe5d..a66fd5f37 100644 --- a/crates/horizon-client/src/command/tree_misc.rs +++ b/crates/horizon-client/src/command/tree_misc.rs @@ -169,7 +169,11 @@ fn item(d: &mut Dispatcher, root: usize) { d.argument(p, "targetPos", ArgType::BlockPos) }; let slot = d.argument(target, "slot", ArgType::SlotSource); - let modifier = d.argument(slot, "modifier", ArgType::ResourceOrId("minecraft:item_modifier")); + let modifier = d.argument( + slot, + "modifier", + ArgType::ResourceOrId("minecraft:item_modifier"), + ); d.executes(modifier, "item.modify"); } for mode in ["replace", "fill", "override"] { diff --git a/crates/horizon-client/src/command/tree_world.rs b/crates/horizon-client/src/command/tree_world.rs index 892275102..0bd2edd3b 100644 --- a/crates/horizon-client/src/command/tree_world.rs +++ b/crates/horizon-client/src/command/tree_world.rs @@ -56,19 +56,31 @@ pub fn register(d: &mut Dispatcher, root: usize) { let place = d.literal(root, "place"); d.requires(place, GAMEMASTERS); let feature = d.literal(place, "feature"); - let f = d.argument(feature, "feature", ArgType::ResourceOrId("minecraft:worldgen/feature")); + let f = d.argument( + feature, + "feature", + ArgType::ResourceOrId("minecraft:worldgen/feature"), + ); d.executes(f, "place.feature"); let pos = d.argument(f, "pos", ArgType::BlockPos); d.executes(pos, "place.feature"); let jigsaw = d.literal(place, "jigsaw"); - let pool = d.argument(jigsaw, "pool", ArgType::ResKey("minecraft:worldgen/template_pool")); + let pool = d.argument( + jigsaw, + "pool", + ArgType::ResKey("minecraft:worldgen/template_pool"), + ); let target = d.argument(pool, "target", ArgType::Id("none")); let depth = d.argument(target, "max_depth", ArgType::Integer { min: 1, max: 20 }); d.executes(depth, "place.jigsaw"); let position = d.argument(depth, "position", ArgType::BlockPos); d.executes(position, "place.jigsaw"); let structure = d.literal(place, "structure"); - let st = d.argument(structure, "structure", ArgType::ResKey("minecraft:worldgen/structure")); + let st = d.argument( + structure, + "structure", + ArgType::ResKey("minecraft:worldgen/structure"), + ); d.executes(st, "place.structure"); let pos = d.argument(st, "pos", ArgType::BlockPos); d.executes(pos, "place.structure"); @@ -89,7 +101,10 @@ pub fn register(d: &mut Dispatcher, root: usize) { let mirror = d.argument( rotation, "mirror", - ArgType::StrEnum(&["none", "left_right", "front_back"], "argument.enum.invalid"), + ArgType::StrEnum( + &["none", "left_right", "front_back"], + "argument.enum.invalid", + ), ); d.executes(mirror, "place"); let integrity = d.argument(mirror, "integrity", ArgType::Float { min: 0.0, max: 1.0 }); @@ -160,7 +175,14 @@ fn rotate_swing(d: &mut Dispatcher, root: usize) { for hand in ["mainhand", "offhand"] { let h = d.literal(targets, hand); d.executes(h, "swing"); - let animation = d.argument(h, "animation", ArgType::StrEnum(&["none", "whack", "stab"], "argument.swing_animation.invalid")); + let animation = d.argument( + h, + "animation", + ArgType::StrEnum( + &["none", "whack", "stab"], + "argument.swing_animation.invalid", + ), + ); d.executes(animation, "swing"); let duration = d.argument(animation, "duration", ArgType::Time { min: 1 }); d.executes(duration, "swing"); @@ -285,7 +307,11 @@ fn fillbiome(d: &mut Dispatcher, root: usize) { let biome = d.argument(to, "biome", ArgType::Res("minecraft:worldgen/biome")); d.executes(biome, "fillbiome"); let replace = d.literal(biome, "replace"); - let filter = d.argument(replace, "filter", ArgType::ResOrTag("minecraft:worldgen/biome")); + let filter = d.argument( + replace, + "filter", + ArgType::ResOrTag("minecraft:worldgen/biome"), + ); d.executes(filter, "fillbiome"); } @@ -357,7 +383,11 @@ fn loot(d: &mut Dispatcher, root: usize) { // Sources. for t in targets { let fish = d.literal(t, "fish"); - let table = d.argument(fish, "loot_table", ArgType::ResourceOrId("minecraft:loot_table")); + let table = d.argument( + fish, + "loot_table", + ArgType::ResourceOrId("minecraft:loot_table"), + ); let pos = d.argument(table, "pos", ArgType::BlockPos); d.executes(pos, "loot.fish"); for hand in ["mainhand", "offhand"] { @@ -367,7 +397,11 @@ fn loot(d: &mut Dispatcher, root: usize) { let tool = d.argument(pos, "tool", ArgType::Item); d.executes(tool, "loot.fish"); let l = d.literal(t, "loot"); - let lt = d.argument(l, "loot_table", ArgType::ResourceOrId("minecraft:loot_table")); + let lt = d.argument( + l, + "loot_table", + ArgType::ResourceOrId("minecraft:loot_table"), + ); d.executes(lt, "loot.loot"); let kill = d.literal(t, "kill"); let target = d.argument(kill, "target", ENTITY); diff --git a/crates/horizon-client/src/command/vanilla.rs b/crates/horizon-client/src/command/vanilla.rs index 2c982e470..495f36966 100644 --- a/crates/horizon-client/src/command/vanilla.rs +++ b/crates/horizon-client/src/command/vanilla.rs @@ -322,13 +322,21 @@ pub fn build_with(dev: bool) -> Dispatcher { let locate = d.literal(root, "locate"); d.requires(locate, GAMEMASTERS); let s = d.literal(locate, "structure"); - let a = d.argument(s, "structure", ArgType::ResOrTagKey("minecraft:worldgen/structure")); + let a = d.argument( + s, + "structure", + ArgType::ResOrTagKey("minecraft:worldgen/structure"), + ); d.executes(a, "locate.structure"); let b = d.literal(locate, "biome"); let a = d.argument(b, "biome", ArgType::ResOrTag("minecraft:worldgen/biome")); d.executes(a, "locate.biome"); let p = d.literal(locate, "poi"); - let a = d.argument(p, "poi", ArgType::ResOrTag("minecraft:point_of_interest_type")); + let a = d.argument( + p, + "poi", + ArgType::ResOrTag("minecraft:point_of_interest_type"), + ); d.executes(a, "locate.poi"); if dev { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index aa7bb7cd5..e83908171 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1304,7 +1304,10 @@ impl Game<'_> { .sections .iter() .enumerate() - .filter(|(_, s)| s.blocks.maybe_has(|id| facts.get(BlockStateId(id)).random_ticks)) + .filter(|(_, s)| { + s.blocks + .maybe_has(|id| facts.get(BlockStateId(id)).random_ticks) + }) .map(|(i, _)| MIN_Y + i as i32 * 16) .collect(); ticking.push((x, z, sections)); @@ -1692,7 +1695,8 @@ impl Game<'_> { // FallingBlockEntity.tick: off the ground, it gives up after 600 // ticks (100 outside the world) and drops itself as an item. let y = next.y.floor() as i32; - let outside = y <= horizon_client::chunk::MIN_Y || y >= horizon_client::chunk::MIN_Y + 384; + let outside = + y <= horizon_client::chunk::MIN_Y || y >= horizon_client::chunk::MIN_Y + 384; if !solid && (f.age > 100 && outside || f.age > 600) { if f.drop_item && entity_drops { dropped.push((f.state, next)); @@ -7204,7 +7208,8 @@ impl Game<'_> { } } MouseButton::Right => { - self.toggles.button(3, pressed, false, self.settings.toggle_use); + self.toggles + .button(3, pressed, false, self.settings.toggle_use); self.right = self.toggles.is_down(3); if pressed { self.use_item()?; diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index de1bbedb7..50d0d1aab 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -812,7 +812,8 @@ impl Game<'_> { fn drop_death_loot(&mut self, m: &mut Mob, by_player: bool, consumed: bool, pos: [f64; 3]) { use horizon_client::mobs::{DamageKind, Who, drops}; use horizon_world::loot::{LootDamage, LootEntity}; - let Some(loot) = horizon_client::structure_blocks::loot_data(&self.options.resources) else { + let Some(loot) = horizon_client::structure_blocks::loot_data(&self.options.resources) + else { return; }; let player = || { @@ -2732,7 +2733,10 @@ impl Game<'_> { pub(super) fn portal_spawn(&mut self, pos: [i32; 3]) { // ChunkMap.anyPlayerCloseEnoughForSpawning: a non-spectator within 128 // blocks of the chunk centre. - let centre = [f64::from((pos[0] >> 4) * 16 + 8), f64::from((pos[2] >> 4) * 16 + 8)]; + let centre = [ + f64::from((pos[0] >> 4) * 16 + 8), + f64::from((pos[2] >> 4) * 16 + 8), + ]; let spectator = self.spectator(); let Some(close) = self.player.as_ref().filter(|_| !spectator).map(|p| { let (dx, dz) = (p.position.x - centre[0], p.position.z - centre[1]); @@ -2744,7 +2748,9 @@ impl Game<'_> { return; } let mut y = pos[1]; - while &*self.res.facts.get(self.world.block(pos[0], y, pos[2])).name == "minecraft:nether_portal" { + while &*self.res.facts.get(self.world.block(pos[0], y, pos[2])).name + == "minecraft:nether_portal" + { y -= 1; } // isValidSpawn: a sturdy top face (portal frames emit no light). @@ -2752,7 +2758,11 @@ impl Game<'_> { if below.sturdy_full & (1 << 1) == 0 { return; } - let at = [f64::from(pos[0]) + 0.5, f64::from(y + 1), f64::from(pos[2]) + 0.5]; + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(y + 1), + f64::from(pos[2]) + 0.5, + ]; let _ = self.spawn_mob("minecraft:zombified_piglin", at, false); } } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 8fb31db45..ca54a3a91 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -186,7 +186,11 @@ fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> { if e.chested { meta.push((19, serializer::BOOLEAN, Value::Bool(true))); } - meta.push((20, serializer::INT, Value::Int(i32::from(e.variant2.max(1))))); + meta.push(( + 20, + serializer::INT, + Value::Int(i32::from(e.variant2.max(1))), + )); if e.variant != 0 { meta.push((21, serializer::INT, Value::Int(i32::from(e.variant)))); } @@ -205,7 +209,11 @@ fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> { ) { let index = if kind == "minecraft:villager" { 19 } else { 20 }; let level = i32::from(e.variant3.max(1)); - meta.push((index, serializer::VILLAGER_DATA, Value::Ids(vec![t, p, level]))); + meta.push(( + index, + serializer::VILLAGER_DATA, + Value::Ids(vec![t, p, level]), + )); } } // AbstractCubeMob.ID_SIZE. diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index ef66e1d96..e6c73a13b 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -605,7 +605,12 @@ impl Game<'_> { let Some(slot) = slot else { self.dispenser_event(1001, key, 0); if !dropper { - self.post_block_game_event("minecraft:block_activate", [pos.x, pos.y, pos.z], None, Some(state)); + self.post_block_game_event( + "minecraft:block_activate", + [pos.x, pos.y, pos.z], + None, + Some(state), + ); } return Ok(()); }; diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index 9fb26ec83..9f6ce609b 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -462,8 +462,8 @@ impl Game<'_> { }; let m = &self.mobs[i]; let atlas = &self.res.atlas; - let hearts = horizon_client::hud_layout::vehicle_max_hearts(m.attrs.max_health as f32); - let draws = horizon_client::hud_layout::vehicle_health(w, h, hearts, m.health as f32); + let hearts = horizon_client::hud_layout::vehicle_max_hearts(m.attrs.max_health); + let draws = horizon_client::hud_layout::vehicle_health(w, h, hearts, m.health); horizon_client::hud_layout::paint(batch, atlas, &draws); if m.extra.saddled { let x = (w / 2 - 91) as f32; diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index 2f1e36602..cd387342f 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -3,16 +3,16 @@ //! `getMaxZoom`), and the local player drawn as a model: in third person //! and in the inventory (`InventoryScreen.extractEntityInInventoryFollowsMouse`). use super::{Game, Screen}; -use horizon_client::{ - hud::HudBatch, - mobs::{Anim, Brain, Mob, MobType}, - pose::Pose, -}; use horizon_client::{ blocks::BlockFacts, camera::{CameraEntity, LivingCamera}, collisions::SceneCollisions, }; +use horizon_client::{ + hud::HudBatch, + mobs::{Anim, Brain, Mob, MobType}, + pose::Pose, +}; use horizon_core::{ geometry::{Aabb, ShapeOp, Vec3, VoxelShape}, position::BlockPos, @@ -272,10 +272,14 @@ impl Game<'_> { 4096, ) .ok()?; - (!hit.miss).then(|| [hit.hit.location.x, hit.hit.location.y, hit.hit.location.z]) + (!hit.miss).then_some([hit.hit.location.x, hit.hit.location.y, hit.hit.location.z]) }); self.view = view; - Some((glam::DVec3::from_array(view.position), view.y_rot, view.x_rot)) + Some(( + glam::DVec3::from_array(view.position), + view.y_rot, + view.x_rot, + )) } /// Keep the player's model in step with the player (`LivingEntity.tick` /// body turning, `WalkAnimationState`, the swing and the pose). diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 95470203d..1a1095bd4 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -490,7 +490,8 @@ impl Game<'_> { if !open { self.recipe_ui.overlay = None; } - self.audio.play("minecraft:ui.button.click", None, 0.25, 1.0); + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); return true; } if !self.book_open(book_type) || self.spectator() { @@ -518,12 +519,14 @@ impl Game<'_> { if self.recipe_ui.page + 1 < pages && inside(cursor, xo + 93.0, yo + 137.0, 12.0, 17.0) { self.recipe_ui.page += 1; - self.audio.play("minecraft:ui.button.click", None, 0.25, 1.0); + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); return true; } if self.recipe_ui.page > 0 && inside(cursor, xo + 38.0, yo + 137.0, 12.0, 17.0) { self.recipe_ui.page -= 1; - self.audio.play("minecraft:ui.button.click", None, 0.25, 1.0); + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); return true; } } @@ -570,7 +573,8 @@ impl Game<'_> { let filtering = !self.book_filtering(book_type); self.level.recipe_book.filtering[book_type.index()] = filtering; self.recipe_ui.page = 0; - self.audio.play("minecraft:ui.button.click", None, 0.25, 1.0); + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); return true; } // Tabs. @@ -581,7 +585,8 @@ impl Game<'_> { self.recipe_ui.tab = Some(tab); self.recipe_ui.page = 0; } - self.audio.play("minecraft:ui.button.click", None, 0.25, 1.0); + self.audio + .play("minecraft:ui.button.click", None, 0.25, 1.0); return true; } } diff --git a/crates/horizon-client/src/game/tnt.rs b/crates/horizon-client/src/game/tnt.rs index d8435da21..71b88cc9b 100644 --- a/crates/horizon-client/src/game/tnt.rs +++ b/crates/horizon-client/src/game/tnt.rs @@ -48,7 +48,11 @@ impl Game<'_> { } else { self.audio.play( "minecraft:entity.tnt.primed", - Some([f64::from(pos.x) + 0.5, f64::from(pos.y), f64::from(pos.z) + 0.5]), + Some([ + f64::from(pos.x) + 0.5, + f64::from(pos.y), + f64::from(pos.z) + 0.5, + ]), 1.0, 1.0, ); diff --git a/crates/horizon-client/src/lan/command_suggestions.rs b/crates/horizon-client/src/lan/command_suggestions.rs index 1afb299d4..e55e6ef92 100644 --- a/crates/horizon-client/src/lan/command_suggestions.rs +++ b/crates/horizon-client/src/lan/command_suggestions.rs @@ -4,77 +4,224 @@ //! VanillaCommandSuggestionsExporter; do not edit by hand. pub const SUGGESTIONS: &[(&str, &str)] = &[ - ("advancement grant targets only advancement criterion", "minecraft:ask_server"), - ("advancement revoke targets only advancement criterion", "minecraft:ask_server"), - ("attribute target attribute modifier remove id", "minecraft:ask_server"), - ("attribute target attribute modifier value get id", "minecraft:ask_server"), + ( + "advancement grant targets only advancement criterion", + "minecraft:ask_server", + ), + ( + "advancement revoke targets only advancement criterion", + "minecraft:ask_server", + ), + ( + "attribute target attribute modifier remove id", + "minecraft:ask_server", + ), + ( + "attribute target attribute modifier value get id", + "minecraft:ask_server", + ), ("bossbar get id", "minecraft:ask_server"), ("bossbar remove id", "minecraft:ask_server"), ("bossbar set id", "minecraft:ask_server"), ("data get storage target", "minecraft:ask_server"), ("data merge storage target", "minecraft:ask_server"), - ("data modify block target targetPath append from storage source", "minecraft:ask_server"), - ("data modify block target targetPath append string storage source", "minecraft:ask_server"), - ("data modify block target targetPath insert index from storage source", "minecraft:ask_server"), - ("data modify block target targetPath insert index string storage source", "minecraft:ask_server"), - ("data modify block target targetPath merge from storage source", "minecraft:ask_server"), - ("data modify block target targetPath merge string storage source", "minecraft:ask_server"), - ("data modify block target targetPath prepend from storage source", "minecraft:ask_server"), - ("data modify block target targetPath prepend string storage source", "minecraft:ask_server"), - ("data modify block target targetPath set from storage source", "minecraft:ask_server"), - ("data modify block target targetPath set string storage source", "minecraft:ask_server"), - ("data modify entity target targetPath append from storage source", "minecraft:ask_server"), - ("data modify entity target targetPath append string storage source", "minecraft:ask_server"), - ("data modify entity target targetPath insert index from storage source", "minecraft:ask_server"), - ("data modify entity target targetPath insert index string storage source", "minecraft:ask_server"), - ("data modify entity target targetPath merge from storage source", "minecraft:ask_server"), - ("data modify entity target targetPath merge string storage source", "minecraft:ask_server"), - ("data modify entity target targetPath prepend from storage source", "minecraft:ask_server"), - ("data modify entity target targetPath prepend string storage source", "minecraft:ask_server"), - ("data modify entity target targetPath set from storage source", "minecraft:ask_server"), - ("data modify entity target targetPath set string storage source", "minecraft:ask_server"), + ( + "data modify block target targetPath append from storage source", + "minecraft:ask_server", + ), + ( + "data modify block target targetPath append string storage source", + "minecraft:ask_server", + ), + ( + "data modify block target targetPath insert index from storage source", + "minecraft:ask_server", + ), + ( + "data modify block target targetPath insert index string storage source", + "minecraft:ask_server", + ), + ( + "data modify block target targetPath merge from storage source", + "minecraft:ask_server", + ), + ( + "data modify block target targetPath merge string storage source", + "minecraft:ask_server", + ), + ( + "data modify block target targetPath prepend from storage source", + "minecraft:ask_server", + ), + ( + "data modify block target targetPath prepend string storage source", + "minecraft:ask_server", + ), + ( + "data modify block target targetPath set from storage source", + "minecraft:ask_server", + ), + ( + "data modify block target targetPath set string storage source", + "minecraft:ask_server", + ), + ( + "data modify entity target targetPath append from storage source", + "minecraft:ask_server", + ), + ( + "data modify entity target targetPath append string storage source", + "minecraft:ask_server", + ), + ( + "data modify entity target targetPath insert index from storage source", + "minecraft:ask_server", + ), + ( + "data modify entity target targetPath insert index string storage source", + "minecraft:ask_server", + ), + ( + "data modify entity target targetPath merge from storage source", + "minecraft:ask_server", + ), + ( + "data modify entity target targetPath merge string storage source", + "minecraft:ask_server", + ), + ( + "data modify entity target targetPath prepend from storage source", + "minecraft:ask_server", + ), + ( + "data modify entity target targetPath prepend string storage source", + "minecraft:ask_server", + ), + ( + "data modify entity target targetPath set from storage source", + "minecraft:ask_server", + ), + ( + "data modify entity target targetPath set string storage source", + "minecraft:ask_server", + ), ("data modify storage target", "minecraft:ask_server"), - ("data modify storage target targetPath append from storage source", "minecraft:ask_server"), - ("data modify storage target targetPath append string storage source", "minecraft:ask_server"), - ("data modify storage target targetPath insert index from storage source", "minecraft:ask_server"), - ("data modify storage target targetPath insert index string storage source", "minecraft:ask_server"), - ("data modify storage target targetPath merge from storage source", "minecraft:ask_server"), - ("data modify storage target targetPath merge string storage source", "minecraft:ask_server"), - ("data modify storage target targetPath prepend from storage source", "minecraft:ask_server"), - ("data modify storage target targetPath prepend string storage source", "minecraft:ask_server"), - ("data modify storage target targetPath set from storage source", "minecraft:ask_server"), - ("data modify storage target targetPath set string storage source", "minecraft:ask_server"), + ( + "data modify storage target targetPath append from storage source", + "minecraft:ask_server", + ), + ( + "data modify storage target targetPath append string storage source", + "minecraft:ask_server", + ), + ( + "data modify storage target targetPath insert index from storage source", + "minecraft:ask_server", + ), + ( + "data modify storage target targetPath insert index string storage source", + "minecraft:ask_server", + ), + ( + "data modify storage target targetPath merge from storage source", + "minecraft:ask_server", + ), + ( + "data modify storage target targetPath merge string storage source", + "minecraft:ask_server", + ), + ( + "data modify storage target targetPath prepend from storage source", + "minecraft:ask_server", + ), + ( + "data modify storage target targetPath prepend string storage source", + "minecraft:ask_server", + ), + ( + "data modify storage target targetPath set from storage source", + "minecraft:ask_server", + ), + ( + "data modify storage target targetPath set string storage source", + "minecraft:ask_server", + ), ("data remove storage target", "minecraft:ask_server"), ("datapack disable name", "minecraft:ask_server"), ("datapack enable name", "minecraft:ask_server"), - ("datapack enable name after existing", "minecraft:ask_server"), - ("datapack enable name before existing", "minecraft:ask_server"), + ( + "datapack enable name after existing", + "minecraft:ask_server", + ), + ( + "datapack enable name before existing", + "minecraft:ask_server", + ), ("debug function name", "minecraft:ask_server"), ("deop targets", "minecraft:ask_server"), ("execute if data storage source", "minecraft:ask_server"), ("execute if function name", "minecraft:ask_server"), ("execute if score target", "minecraft:ask_server"), - ("execute if score target targetObjective < source", "minecraft:ask_server"), - ("execute if score target targetObjective <= source", "minecraft:ask_server"), - ("execute if score target targetObjective = source", "minecraft:ask_server"), - ("execute if score target targetObjective > source", "minecraft:ask_server"), - ("execute if score target targetObjective >= source", "minecraft:ask_server"), + ( + "execute if score target targetObjective < source", + "minecraft:ask_server", + ), + ( + "execute if score target targetObjective <= source", + "minecraft:ask_server", + ), + ( + "execute if score target targetObjective = source", + "minecraft:ask_server", + ), + ( + "execute if score target targetObjective > source", + "minecraft:ask_server", + ), + ( + "execute if score target targetObjective >= source", + "minecraft:ask_server", + ), ("execute if stopwatch id", "minecraft:ask_server"), ("execute store result bossbar id", "minecraft:ask_server"), ("execute store result score targets", "minecraft:ask_server"), - ("execute store result storage target", "minecraft:ask_server"), + ( + "execute store result storage target", + "minecraft:ask_server", + ), ("execute store success bossbar id", "minecraft:ask_server"), - ("execute store success score targets", "minecraft:ask_server"), - ("execute store success storage target", "minecraft:ask_server"), + ( + "execute store success score targets", + "minecraft:ask_server", + ), + ( + "execute store success storage target", + "minecraft:ask_server", + ), ("execute summon entity", "minecraft:summonable_entities"), ("execute unless data storage source", "minecraft:ask_server"), ("execute unless function name", "minecraft:ask_server"), ("execute unless score target", "minecraft:ask_server"), - ("execute unless score target targetObjective < source", "minecraft:ask_server"), - ("execute unless score target targetObjective <= source", "minecraft:ask_server"), - ("execute unless score target targetObjective = source", "minecraft:ask_server"), - ("execute unless score target targetObjective > source", "minecraft:ask_server"), - ("execute unless score target targetObjective >= source", "minecraft:ask_server"), + ( + "execute unless score target targetObjective < source", + "minecraft:ask_server", + ), + ( + "execute unless score target targetObjective <= source", + "minecraft:ask_server", + ), + ( + "execute unless score target targetObjective = source", + "minecraft:ask_server", + ), + ( + "execute unless score target targetObjective > source", + "minecraft:ask_server", + ), + ( + "execute unless score target targetObjective >= source", + "minecraft:ask_server", + ), ("execute unless stopwatch id", "minecraft:ask_server"), ("function name", "minecraft:ask_server"), ("function name with storage source", "minecraft:ask_server"), @@ -83,37 +230,88 @@ pub const SUGGESTIONS: &[(&str, &str)] = &[ ("pardon-ip target", "minecraft:ask_server"), ("place template template", "minecraft:ask_server"), ("playsound sound", "minecraft:available_sounds"), - ("posteffect add targets posteffect", "minecraft:post_effects"), - ("posteffect remove targets posteffect", "minecraft:post_effects"), + ( + "posteffect add targets posteffect", + "minecraft:post_effects", + ), + ( + "posteffect remove targets posteffect", + "minecraft:post_effects", + ), ("random reset sequence", "minecraft:ask_server"), ("random roll range sequence", "minecraft:ask_server"), ("random value range sequence", "minecraft:ask_server"), ("schedule clear function", "minecraft:ask_server"), ("schedule function function", "minecraft:ask_server"), ("scoreboard players add targets", "minecraft:ask_server"), - ("scoreboard players display name targets", "minecraft:ask_server"), - ("scoreboard players display numberformat targets", "minecraft:ask_server"), + ( + "scoreboard players display name targets", + "minecraft:ask_server", + ), + ( + "scoreboard players display numberformat targets", + "minecraft:ask_server", + ), ("scoreboard players enable targets", "minecraft:ask_server"), - ("scoreboard players enable targets objective", "minecraft:ask_server"), + ( + "scoreboard players enable targets objective", + "minecraft:ask_server", + ), ("scoreboard players get target", "minecraft:ask_server"), ("scoreboard players list target", "minecraft:ask_server"), - ("scoreboard players operation targets", "minecraft:ask_server"), - ("scoreboard players operation targets targetObjective operation source", "minecraft:ask_server"), + ( + "scoreboard players operation targets", + "minecraft:ask_server", + ), + ( + "scoreboard players operation targets targetObjective operation source", + "minecraft:ask_server", + ), ("scoreboard players remove targets", "minecraft:ask_server"), ("scoreboard players reset targets", "minecraft:ask_server"), ("scoreboard players set targets", "minecraft:ask_server"), ("stopsound targets * sound", "minecraft:available_sounds"), - ("stopsound targets ambient sound", "minecraft:available_sounds"), - ("stopsound targets block sound", "minecraft:available_sounds"), - ("stopsound targets hostile sound", "minecraft:available_sounds"), - ("stopsound targets master sound", "minecraft:available_sounds"), - ("stopsound targets music sound", "minecraft:available_sounds"), - ("stopsound targets neutral sound", "minecraft:available_sounds"), - ("stopsound targets player sound", "minecraft:available_sounds"), - ("stopsound targets record sound", "minecraft:available_sounds"), + ( + "stopsound targets ambient sound", + "minecraft:available_sounds", + ), + ( + "stopsound targets block sound", + "minecraft:available_sounds", + ), + ( + "stopsound targets hostile sound", + "minecraft:available_sounds", + ), + ( + "stopsound targets master sound", + "minecraft:available_sounds", + ), + ( + "stopsound targets music sound", + "minecraft:available_sounds", + ), + ( + "stopsound targets neutral sound", + "minecraft:available_sounds", + ), + ( + "stopsound targets player sound", + "minecraft:available_sounds", + ), + ( + "stopsound targets record sound", + "minecraft:available_sounds", + ), ("stopsound targets ui sound", "minecraft:available_sounds"), - ("stopsound targets voice sound", "minecraft:available_sounds"), - ("stopsound targets weather sound", "minecraft:available_sounds"), + ( + "stopsound targets voice sound", + "minecraft:available_sounds", + ), + ( + "stopsound targets weather sound", + "minecraft:available_sounds", + ), ("stopwatch query id", "minecraft:ask_server"), ("stopwatch remove id", "minecraft:ask_server"), ("stopwatch restart id", "minecraft:ask_server"), diff --git a/crates/horizon-client/src/lan/commands.rs b/crates/horizon-client/src/lan/commands.rs index dd3d36fe9..26def5d7e 100644 --- a/crates/horizon-client/src/lan/commands.rs +++ b/crates/horizon-client/src/lan/commands.rs @@ -172,13 +172,16 @@ fn fill( names.sort(); for name in names { let child = &children[name]; - let required = if path.is_empty() && !dedicated && OPEN_WHEN_INTEGRATED.contains(&name.as_str()) { - 0 - } else { - required_level(child) - }; + let required = + if path.is_empty() && !dedicated && OPEN_WHEN_INTEGRATED.contains(&name.as_str()) { + 0 + } else { + required_level(child) + }; if required > level - || path.len() == 1 && path[0] == "gamerule" && EXPERIMENTAL_RULES.contains(&name.as_str()) + || path.len() == 1 + && path[0] == "gamerule" + && EXPERIMENTAL_RULES.contains(&name.as_str()) { continue; } @@ -212,7 +215,16 @@ fn fill( }); nodes[target].children.push(index); paths.insert(path.clone(), index); - fill(child, index, path, level, dedicated, suggestions, nodes, paths); + fill( + child, + index, + path, + level, + dedicated, + suggestions, + nodes, + paths, + ); path.pop(); } } @@ -331,7 +343,10 @@ mod tests { assert_eq!(guest.nodes[2].redirect, Some(1)); let op = tree.packet(2, true, &builtin); let names: Vec<_> = op.nodes.iter().map(|n| n.name.as_str()).collect(); - assert_eq!(names, ["", "me", "say", "stop", "tell", "action", "message"]); + assert_eq!( + names, + ["", "me", "say", "stop", "tell", "action", "message"] + ); assert!(op.nodes[2].restricted); } } diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index 179a75a82..3b926b372 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -188,17 +188,21 @@ impl Tracker { }) } } else if rotate { - Some(play::Clientbound::MoveEntityRot(MoveEntityRot(MoveEntity { - id: e.id, - delta: None, - rotation: Some((rotation.1, rotation.0)), - on_ground: e.on_ground, - }))) + Some(play::Clientbound::MoveEntityRot(MoveEntityRot( + MoveEntity { + id: e.id, + delta: None, + rotation: Some((rotation.1, rotation.0)), + on_ground: e.on_ground, + }, + ))) } else { None }; if s.track_deltas { - let diff: f64 = (0..3).map(|k| (e.velocity[k] - s.velocity[k]).powi(2)).sum(); + let diff: f64 = (0..3) + .map(|k| (e.velocity[k] - s.velocity[k]).powi(2)) + .sum(); let still = e.velocity.iter().all(|v| *v == 0.0); if diff > 1.0e-7 || diff > 0.0 && still { s.velocity = e.velocity; diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index dd8126698..ed9771043 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -12,12 +12,12 @@ use super::{ guest::{Guest, stack_to_network}, }; use crate::{items::ItemStack, world::World}; +use horizon_protocol::ids::play::clientbound as ids; use horizon_protocol::{ entity_data::{Value, serializer}, packets::play::{self, Clientbound as C, Serverbound as S}, text::{literal, translatable}, }; -use horizon_protocol::ids::play::clientbound as ids; use horizon_world::nbt::{JavaString, Tag}; use std::sync::{Arc, atomic::Ordering}; @@ -440,7 +440,6 @@ impl Hub { g.send(&C::Commands(packet)); } - /// ServerGamePacketListenerImpl.teleport: move the client and wait for its confirmation. pub fn teleport(&mut self, i: usize, position: Option<[f64; 3]>) { let g = &mut self.guests[i]; diff --git a/crates/horizon-client/src/lan/tracking.rs b/crates/horizon-client/src/lan/tracking.rs index d0853507f..61b471de6 100644 --- a/crates/horizon-client/src/lan/tracking.rs +++ b/crates/horizon-client/src/lan/tracking.rs @@ -172,5 +172,7 @@ pub const TRACKING: &[(&str, u8, u32, bool)] = &[ pub fn settings(kind: &str) -> (u8, u32, bool) { TRACKING .binary_search_by(|row| row.0.cmp(kind)) - .map_or((5, 3, true), |i| (TRACKING[i].1, TRACKING[i].2, TRACKING[i].3)) + .map_or((5, 3, true), |i| { + (TRACKING[i].1, TRACKING[i].2, TRACKING[i].3) + }) } diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index ce36a21de..53685eeb2 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -16,8 +16,8 @@ pub mod block_entity_render; pub mod block_transform; pub mod blocks; pub mod bossbar; -pub mod camera; pub mod brewing; +pub mod camera; pub mod cauldron; pub mod chat; pub mod chunk; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 8379fc8c2..1f139a11a 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -46,8 +46,8 @@ pub mod render; pub mod riders; pub mod shulker; pub mod sniffer; -pub mod spawning; pub mod spawn_rules; +pub mod spawning; pub mod species; pub mod sulfur_cube; pub mod tame; @@ -1097,9 +1097,9 @@ impl Mob { // dealDefaultKnockback, unless the damage type is tagged no_knockback; // a source without a position knocks in a random direction. if knock && !source.no_knockback() { - let (dx, dz) = source - .from - .map_or((0.0, 0.0), |f| (f[0] - self.position.x, f[2] - self.position.z)); + let (dx, dz) = source.from.map_or((0.0, 0.0), |f| { + (f[0] - self.position.x, f[2] - self.position.z) + }); self.knockback(0.4, dx, dz); } ai::after_hurt(self, &source); diff --git a/crates/horizon-client/src/mobs/control.rs b/crates/horizon-client/src/mobs/control.rs index 4e2dd124f..361b1b13a 100644 --- a/crates/horizon-client/src/mobs/control.rs +++ b/crates/horizon-client/src/mobs/control.rs @@ -363,10 +363,9 @@ impl Mob { at[2] - self.position.z, ); let sd = (xd * xd + zd * zd).sqrt(); - let x = - (yd.abs() > EPSILON || sd.abs() > EPSILON).then(|| -trig::atan2_degrees(yd, sd)); - let y = (zd.abs() > EPSILON || xd.abs() > EPSILON) - .then(|| trig::atan2_degrees(zd, xd) - 90.0); + let x = (yd.abs() > EPSILON || sd.abs() > EPSILON).then(|| -trig::atan2_degrees(yd, sd)); + let y = + (zd.abs() > EPSILON || xd.abs() > EPSILON).then(|| trig::atan2_degrees(zd, xd) - 90.0); (x, y) } /// JumpControl.tick. diff --git a/crates/horizon-client/src/mobs/drops.rs b/crates/horizon-client/src/mobs/drops.rs index 42010afd9..102a5a5b6 100644 --- a/crates/horizon-client/src/mobs/drops.rs +++ b/crates/horizon-client/src/mobs/drops.rs @@ -399,7 +399,10 @@ pub fn die(m: &mut Mob, d: &Death, sequences: &mut RandomSequences) -> (Vec i32 { let mut result = reward; for slot in SLOTS { // EquipmentSlot.canIncreaseExperience: all but the saddle. - if slot != "saddle" && slot_item(m, slot).is_some() && drop_chance(m, slot) <= 1.0 { + if slot != "saddle" + && slot_item(m, slot).is_some() + && drop_chance(m, slot) <= 1.0 + { result += 1 + m.random.next_int_bound(3).unwrap_or(0); } } diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 059e58462..c5439479b 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -199,9 +199,8 @@ impl Mob { let center = horizon_core::geometry::trig::atan2(zd, xd) - f64::from(std::f32::consts::FRAC_PI_2); let yrad = center + f64::from(2.0 * self.random.next_float() - 1.0) * max_rad; - let dist = - (min + self.random.next_double().sqrt() * (max - min)) - * f64::from(std::f32::consts::SQRT_2); + let dist = (min + self.random.next_double().sqrt() * (max - min)) + * f64::from(std::f32::consts::SQRT_2); let xt = -dist * yrad.sin(); let zt = dist * yrad.cos(); if xt.abs() > max || zt.abs() > max { diff --git a/crates/horizon-client/src/mobs/spawn_rules.rs b/crates/horizon-client/src/mobs/spawn_rules.rs index f64918bd4..40806b04e 100644 --- a/crates/horizon-client/src/mobs/spawn_rules.rs +++ b/crates/horizon-client/src/mobs/spawn_rules.rs @@ -252,14 +252,21 @@ pub fn is_spawn_position_ok(s: Species, l: &L, x: i32, y: i32, z: && is_valid_empty_spawn(s, l, x, y + 1, z) } data::Placement::InWater => { - fluid(l, x, y, z) == Fluid::Water && flags(l, x, y + 1, z) & data::REDSTONE_CONDUCTOR == 0 + fluid(l, x, y, z) == Fluid::Water + && flags(l, x, y + 1, z) & data::REDSTONE_CONDUCTOR == 0 } data::Placement::InLava => fluid(l, x, y, z) == Fluid::Lava, data::Placement::NoRestrictions => true, } } /// `Monster.isDarkEnoughToSpawn`. -pub fn is_dark_enough(l: &L, random: &mut impl RandomSource, x: i32, y: i32, z: i32) -> bool { +pub fn is_dark_enough( + l: &L, + random: &mut impl RandomSource, + x: i32, + y: i32, + z: i32, +) -> bool { if l.sky_light(x, y, z) > random.next_int_bound(32).unwrap_or(0) { return false; } @@ -290,7 +297,8 @@ fn monster_rules( y: i32, z: i32, ) -> bool { - (reason.ignores_light() || is_dark_enough(l, random, x, y, z)) && mob_rules(s, l, reason, x, y, z) + (reason.ignores_light() || is_dark_enough(l, random, x, y, z)) + && mob_rules(s, l, reason, x, y, z) } /// `Animal.checkAnimalSpawnRules` with the given spawnable-on tag. fn animal_rules(l: &L, reason: Reason, on: &str, x: i32, y: i32, z: i32) -> bool { @@ -336,14 +344,17 @@ pub fn check_spawn_rules( if frequent { random.next_int_bound(15).unwrap_or(1) == 0 && can_spawn } else { - random.next_int_bound(40).unwrap_or(1) == 0 && y < l.sea_level() - 5 && can_spawn + random.next_int_bound(40).unwrap_or(1) == 0 + && y < l.sea_level() - 5 + && can_spawn } } else { true } } S::Guardian | S::ElderGuardian => { - (random.next_int_bound(20).unwrap_or(1) == 0 || !can_see_sky_from_below_water(l, x, y, z)) + (random.next_int_bound(20).unwrap_or(1) == 0 + || !can_see_sky_from_below_water(l, x, y, z)) && !l.peaceful() && (reason.is_spawner() || fluid(l, x, y, z) == Fluid::Water) && fluid(l, x, y - 1, z) == Fluid::Water @@ -351,10 +362,16 @@ pub fn check_spawn_rules( S::TropicalFish => { fluid(l, x, y - 1, z) == Fluid::Water && name(l, x, y + 1, z) == "minecraft:water" - && (l.biome_tag("minecraft:allows_tropical_fish_spawns_at_any_height", x, y, z) - || surface_water(l, x, y, z)) + && (l.biome_tag( + "minecraft:allows_tropical_fish_spawns_at_any_height", + x, + y, + z, + ) || surface_water(l, x, y, z)) + } + S::Armadillo => { + tag(l, "minecraft:armadillo_spawnable_on", x, y - 1, z) && bright(l, x, y, z) } - S::Armadillo => tag(l, "minecraft:armadillo_spawnable_on", x, y - 1, z) && bright(l, x, y, z), S::Bat => { if y >= l.world_surface(x, z) || random.next_boolean() { return false; @@ -387,9 +404,18 @@ pub fn check_spawn_rules( return false; } reason.is_spawner() - || !l.player_near(f64::from(x) + 0.5, f64::from(y) + 0.5, f64::from(z) + 0.5, 5.0) + || !l.player_near( + f64::from(x) + 0.5, + f64::from(y) + 0.5, + f64::from(z) + 0.5, + 5.0, + ) } - S::IronGolem | S::SnowGolem | S::Villager | S::Phantom | S::Shulker + S::IronGolem + | S::SnowGolem + | S::Villager + | S::Phantom + | S::Shulker | S::WanderingTrader => mob_rules(s, l, reason, x, y, z), S::Frog => tag(l, "minecraft:frogs_spawnable_on", x, y - 1, z) && bright(l, x, y, z), S::Ghast => { @@ -405,7 +431,9 @@ pub fn check_spawn_rules( S::Goat => tag(l, "minecraft:goats_spawnable_on", x, y - 1, z) && bright(l, x, y, z), S::MagmaCube => !l.peaceful(), S::SulfurCube => true, - S::Mooshroom => tag(l, "minecraft:mooshrooms_spawnable_on", x, y - 1, z) && bright(l, x, y, z), + S::Mooshroom => { + tag(l, "minecraft:mooshrooms_spawnable_on", x, y - 1, z) && bright(l, x, y, z) + } S::Nautilus => { let sea = l.sea_level(); y >= sea - 25 @@ -420,7 +448,13 @@ pub fn check_spawn_rules( S::PolarBear => { if l.biome_tag("minecraft:polar_bears_spawn_on_alternate_blocks", x, y, z) { bright(l, x, y, z) - && tag(l, "minecraft:polar_bears_spawnable_on_alternate", x, y - 1, z) + && tag( + l, + "minecraft:polar_bears_spawnable_on_alternate", + x, + y - 1, + z, + ) } else { animal_rules(l, reason, "minecraft:animals_spawnable_on", x, y, z) } @@ -582,7 +616,9 @@ impl SpawnLevel for super::MobWorld<'_> { } fn player_near(&self, x: f64, y: f64, z: f64, distance: f64) -> bool { self.player.as_ref().is_some_and(|p| { - let d = (p.position.x - x).powi(2) + (p.position.y - y).powi(2) + (p.position.z - z).powi(2); + let d = (p.position.x - x).powi(2) + + (p.position.y - y).powi(2) + + (p.position.z - z).powi(2); p.alive && !p.creative && !p.spectator && d < distance * distance }) } diff --git a/crates/horizon-client/src/window.rs b/crates/horizon-client/src/window.rs index bfcb973dd..d621a02c3 100644 --- a/crates/horizon-client/src/window.rs +++ b/crates/horizon-client/src/window.rs @@ -176,7 +176,11 @@ impl LimiterClock for SystemClock { /// `Minecraft.runTick`'s frame-limiter step: only limits below 260 /// (the "unlimited" setting) pace frames. -pub fn end_frame(limiter: &mut FramerateLimiter, framerate_limit: i32, clock: &mut impl LimiterClock) { +pub fn end_frame( + limiter: &mut FramerateLimiter, + framerate_limit: i32, + clock: &mut impl LimiterClock, +) { if framerate_limit < 260 { limiter.limit_display_fps(framerate_limit, clock); } @@ -188,7 +192,11 @@ impl FramerateLimiter { } /// The limiter's static state: `lastFrameTime`, `averageOvershootNs` /// and `lastFramerateLimit`. - pub fn with_state(last_frame_time: i64, average_overshoot_ns: i64, last_framerate_limit: i32) -> Self { + pub fn with_state( + last_frame_time: i64, + average_overshoot_ns: i64, + last_framerate_limit: i32, + ) -> Self { Self { last_frame_time, average_overshoot_ns, diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index c8ee6e6c2..d82bf4858 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -184,13 +184,15 @@ impl Server { }; let mut ctx = TickCtx { world: &mut self.world, - host: &host, + host: Some(&host), entities, next_entity: &mut self.next_entity, spawn: [8.5, f64::from(MIN_Y + 5), 8.5], difficulty: 2, difficulty_locked: false, clock_rate: 1.0, + tick_rate: 20.0, + tick_frozen: false, }; let events = self.hub.tick(&mut ctx); for event in events { @@ -238,6 +240,7 @@ fn server(resources: &Path) -> Server { hardcore: false, view_distance: 3, simulation_distance: 3, + dedicated: false, dimension: "minecraft:overworld".into(), seed: 1234, max_players: 8, @@ -419,7 +422,6 @@ fn guests_see_each_other_and_the_world_entities() { data: 0, meta: Vec::new(), equipment: Vec::new(), - send_velocity: false, }; let first = thread::spawn(move || { let mut bot = connect(port, "Alex", false)?; diff --git a/crates/horizon-core/src/geometry/trig.rs b/crates/horizon-core/src/geometry/trig.rs index 36c0b069d..d2c3a0746 100644 --- a/crates/horizon-core/src/geometry/trig.rs +++ b/crates/horizon-core/src/geometry/trig.rs @@ -102,6 +102,7 @@ impl Mth for f32 { } /// fdlibm `__ieee754_asin`, as `StrictMath.asin` (and so `Math.asin`) computes it. +#[allow(clippy::excessive_precision, clippy::approx_constant, clippy::eq_op)] // fdlibm's constants and NaN, verbatim. pub fn fdlibm_asin(x: f64) -> f64 { const PIO2_HI: f64 = 1.570_796_326_794_896_558_00e+00; const PIO2_LO: f64 = 6.123_233_995_736_766_035_87e-17; @@ -160,9 +161,21 @@ mod tests { #[test] fn atan2_matches_the_client_tables() { for (y, x, r) in [ - (0x402f_3b4b_8041_4df1_u64, 0xc018_53ca_369b_9e91_u64, 0x3fff_1334_9f9d_e798_u64), - (0xc025_d316_35f2_9de8, 0xc018_fb4a_7ec4_3ba8, 0xc000_b996_6547_a498), - (0xc026_5d9c_2b5a_472d, 0xc030_954d_c2dc_3d10, 0xc004_62e7_82d4_c97e), + ( + 0x402f_3b4b_8041_4df1_u64, + 0xc018_53ca_369b_9e91_u64, + 0x3fff_1334_9f9d_e798_u64, + ), + ( + 0xc025_d316_35f2_9de8, + 0xc018_fb4a_7ec4_3ba8, + 0xc000_b996_6547_a498, + ), + ( + 0xc026_5d9c_2b5a_472d, + 0xc030_954d_c2dc_3d10, + 0xc004_62e7_82d4_c97e, + ), ] { assert_eq!(atan2(f64::from_bits(y), f64::from_bits(x)).to_bits(), r); } diff --git a/crates/horizon-world/examples/block_update_fixture.rs b/crates/horizon-world/examples/block_update_fixture.rs index 0e5e28f91..9590c90bb 100644 --- a/crates/horizon-world/examples/block_update_fixture.rs +++ b/crates/horizon-world/examples/block_update_fixture.rs @@ -53,8 +53,17 @@ impl LevelAccess for Cells { } /// Fresh block entities hold nothing, but a lectern whose state has a book /// reads page progress 1 of an empty book: signal 14. - fn block_entity_analog_signal(&self, _pos: BlockPos, state: BlockStateId, _direction: Direction) -> i32 { - if self.lecterns_with_books.contains(&state) { 14 } else { 0 } + fn block_entity_analog_signal( + &self, + _pos: BlockPos, + state: BlockStateId, + _direction: Direction, + ) -> i32 { + if self.lecterns_with_books.contains(&state) { + 14 + } else { + 0 + } } /// A chest's fresh block entity: nobody has it open. fn recheck_container_openers(&mut self, _pos: BlockPos) -> Option<(i32, i32)> { @@ -62,7 +71,10 @@ impl LevelAccess for Cells { } /// A fresh command block entity: unpowered and not automatic. fn set_command_block_powered(&mut self, pos: BlockPos, powered: bool) -> Option<(bool, bool)> { - Some((self.command_blocks.insert(pos, powered).unwrap_or(false), false)) + Some(( + self.command_blocks.insert(pos, powered).unwrap_or(false), + false, + )) } fn random(&mut self) -> &mut LegacyRandom { &mut self.random @@ -137,16 +149,18 @@ fn main() -> Result<(), Box> { let registry = load_registry(resources)?; let behaviours = Behaviours::load(®istry, resources)?; let air = registry.default_state("minecraft:air").unwrap(); - let lecterns_with_books: std::rc::Rc> = std::rc::Rc::new( - (0..registry.len() as u32) - .map(BlockStateId) - .filter(|&id| { - registry.state(id).is_some_and(|s| { - s.name == "minecraft:lectern" && s.properties.get("has_book").is_some_and(|v| v == "true") + let lecterns_with_books: std::rc::Rc> = + std::rc::Rc::new( + (0..registry.len() as u32) + .map(BlockStateId) + .filter(|&id| { + registry.state(id).is_some_and(|s| { + s.name == "minecraft:lectern" + && s.properties.get("has_book").is_some_and(|v| v == "true") + }) }) - }) - .collect(), - ); + .collect(), + ); let mut out = std::io::BufWriter::new(std::fs::File::create(output)?); for (index, line) in std::io::BufReader::new(std::fs::File::open(cases)?) .lines() @@ -320,28 +334,36 @@ fn main() -> Result<(), Box> { // Dispensing from the fixture's empty block entities, as the // client does: the fail event, plus `block_activate` for a // dispenser; a crafter without a recipe only fails. - LevelEvent::BlockEvent { kind: "dispense", pos, state } => { - match behaviours.table.name(*state) { - "minecraft:crafter" => { - let _ = writeln!(result, "L 1050 {} 0", p(*pos)); - } - "minecraft:dispenser" => { - let _ = writeln!(result, "L 1001 {} 0", p(*pos)); - let _ = writeln!(result, "G {} minecraft:block_activate", p(*pos)); - } - _ => { - let _ = writeln!(result, "L 1001 {} 0", p(*pos)); - } + LevelEvent::BlockEvent { + kind: "dispense", + pos, + state, + } => match behaviours.table.name(*state) { + "minecraft:crafter" => { + let _ = writeln!(result, "L 1050 {} 0", p(*pos)); } - } + "minecraft:dispenser" => { + let _ = writeln!(result, "L 1001 {} 0", p(*pos)); + let _ = writeln!(result, "G {} minecraft:block_activate", p(*pos)); + } + _ => { + let _ = writeln!(result, "L 1001 {} 0", p(*pos)); + } + }, // DriedGhastBlock.spawnGhastling, as the client does it. - LevelEvent::BlockEvent { kind: "spawn_ghastling", .. } => { + LevelEvent::BlockEvent { + kind: "spawn_ghastling", + .. + } => { let _ = writeln!(result, "E minecraft:happy_ghast"); let _ = writeln!(result, "S entity minecraft:entity.ghastling.spawn"); } // A fresh shrieker has warning level 0 and so never responds, // and no player is near enough for a portal to spawn a piglin. - LevelEvent::BlockEvent { kind: "shrieker_respond" | "portal_spawn", .. } => {} + LevelEvent::BlockEvent { + kind: "shrieker_respond" | "portal_spawn", + .. + } => {} LevelEvent::BlockEvent { kind, .. } => { let _ = writeln!(result, "X {kind}"); } diff --git a/crates/horizon-world/src/level/data.rs b/crates/horizon-world/src/level/data.rs index a3736fb20..3c62a39a4 100644 --- a/crates/horizon-world/src/level/data.rs +++ b/crates/horizon-world/src/level/data.rs @@ -995,7 +995,10 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result 1, Some("WEATHERED") => 2, Some("OXIDIZED") => 3, diff --git a/crates/horizon-world/src/level/hooks.rs b/crates/horizon-world/src/level/hooks.rs index d91198035..677b12a4b 100644 --- a/crates/horizon-world/src/level/hooks.rs +++ b/crates/horizon-world/src/level/hooks.rs @@ -34,7 +34,8 @@ impl Sim<'_, L> { Class::Command => { // CommandBlock.setPoweredAndUpdate let signal = self.has_neighbor_signal(pos); - if let Some((was_powered, automatic)) = self.level.set_command_block_powered(pos, signal) + if let Some((was_powered, automatic)) = + self.level.set_command_block_powered(pos, signal) && signal && !was_powered && !automatic diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 4f240ae6b..166483709 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -351,7 +351,11 @@ pub trait LevelAccess { /// `CommandBlockEntity.setPowered` for the command block entity at `pos`: /// stores `powered` and returns the previous flag and `isAutomatic`, or /// None when there is no command block entity. - fn set_command_block_powered(&mut self, _pos: BlockPos, _powered: bool) -> Option<(bool, bool)> { + fn set_command_block_powered( + &mut self, + _pos: BlockPos, + _powered: bool, + ) -> Option<(bool, bool)> { None } /// Weak/strong signal of a block-entity-driven source (trapped chest diff --git a/crates/horizon-world/src/level/portal.rs b/crates/horizon-world/src/level/portal.rs index 81a6a0562..047f474d9 100644 --- a/crates/horizon-world/src/level/portal.rs +++ b/crates/horizon-world/src/level/portal.rs @@ -21,7 +21,10 @@ pub struct PortalShape { impl PortalShape { pub const fn is_valid(&self) -> bool { - self.width >= MIN_WIDTH && self.width <= MAX_WIDTH && self.height >= MIN_HEIGHT && self.height <= MAX_HEIGHT + self.width >= MIN_WIDTH + && self.width <= MAX_WIDTH + && self.height >= MIN_HEIGHT + && self.height <= MAX_HEIGHT } pub const fn is_complete(&self) -> bool { self.is_valid() && self.portal_blocks == self.width * self.height @@ -36,13 +39,15 @@ fn step(pos: BlockPos, dir: Direction, n: i32) -> BlockPos { impl Sim<'_, L> { fn portal_frame(&self, state: BlockStateId) -> bool { let b = self.b; - b.tag("minecraft:nether_portal_frame").is_some_and(|tag| b.in_set(state, tag)) + b.tag("minecraft:nether_portal_frame") + .is_some_and(|tag| b.in_set(state, tag)) } /// `PortalShape.isEmpty`: air, fire or a portal block. fn portal_empty(&self, state: BlockStateId) -> bool { let b = self.b; b.is_air(state) - || b.tag("minecraft:fire").is_some_and(|tag| b.in_set(state, tag)) + || b.tag("minecraft:fire") + .is_some_and(|tag| b.in_set(state, tag)) || b.is_block(state, b.named.nether_portal) } fn portal_distance_until_edge_above_frame(&self, pos: BlockPos, dir: Direction) -> i32 { @@ -60,8 +65,19 @@ impl Sim<'_, L> { } /// `PortalShape.findAnyShape`. pub fn find_portal_shape(&self, pos: BlockPos, x_axis: bool) -> PortalShape { - let right = if x_axis { Direction::West } else { Direction::South }; - let mut shape = PortalShape { x_axis, right, bottom_left: pos, width: 0, height: 0, portal_blocks: 0 }; + let right = if x_axis { + Direction::West + } else { + Direction::South + }; + let mut shape = PortalShape { + x_axis, + right, + bottom_left: pos, + width: 0, + height: 0, + portal_blocks: 0, + }; // calculateBottomLeft let min_y = self.level.min_y().max(pos.y - MAX_HEIGHT); let mut start = pos; @@ -103,7 +119,11 @@ impl Sim<'_, L> { } let top = step(shape.bottom_left, Direction::Up, height); let has_top = (0..width).all(|i| self.portal_frame(self.state(step(top, right, i)))); - shape.height = if (MIN_HEIGHT..=MAX_HEIGHT).contains(&height) && has_top { height } else { 0 }; + shape.height = if (MIN_HEIGHT..=MAX_HEIGHT).contains(&height) && has_top { + height + } else { + 0 + }; shape } } diff --git a/crates/horizon-world/src/level/shapes.rs b/crates/horizon-world/src/level/shapes.rs index 242be2713..154e4b582 100644 --- a/crates/horizon-world/src/level/shapes.rs +++ b/crates/horizon-world/src/level/shapes.rs @@ -11,7 +11,11 @@ use super::{ update::{above, below, rel}, }; use crate::{fluid::FluidKind, registry::BlockStateId}; -use horizon_core::{geometry::{Axis, Direction}, position::BlockPos, random::RandomSource}; +use horizon_core::{ + geometry::{Axis, Direction}, + position::BlockPos, + random::RandomSource, +}; impl Sim<'_, L> { /// `BlockState.updateShape(level, ticks, pos, direction, neighbourPos, neighbourState, random)`. @@ -794,7 +798,8 @@ impl Sim<'_, L> { Class::NetherPortal => { let x_axis = table.text(state, p.axis) == "x"; let update_axis = axis_of(dir); - let wrong_axis = update_axis != if x_axis { Axis::X } else { Axis::Z } && update_axis != Axis::Y; + let wrong_axis = + update_axis != if x_axis { Axis::X } else { Axis::Z } && update_axis != Axis::Y; if !wrong_axis && !b.is_block(nstate, block) && !self.find_portal_shape(pos, x_axis).is_complete() diff --git a/crates/horizon-world/src/level/shelf.rs b/crates/horizon-world/src/level/shelf.rs index 44a011190..f060fa530 100644 --- a/crates/horizon-world/src/level/shelf.rs +++ b/crates/horizon-world/src/level/shelf.rs @@ -84,12 +84,22 @@ impl Sim<'_, L> { /// `ShelfBlock.isConnectable`. fn shelf_connectable(&self, state: BlockStateId) -> bool { let b = self.b; - b.tag("minecraft:wooden_shelves").is_some_and(|tag| b.in_set(state, tag)) + b.tag("minecraft:wooden_shelves") + .is_some_and(|tag| b.in_set(state, tag)) && b.table.has(state, b.props.powered) && b.table.bool(state, b.props.powered) } - fn chain_neighbor(&mut self, n: &mut Neighbors, left: bool, steps: i32) -> (BlockPos, Option) { - let dir = if left { clockwise(n.facing) } else { counter_clockwise(n.facing) }; + fn chain_neighbor( + &mut self, + n: &mut Neighbors, + left: bool, + steps: i32, + ) -> (BlockPos, Option) { + let dir = if left { + clockwise(n.facing) + } else { + counter_clockwise(n.facing) + }; let mut pos = n.center; for _ in 0..steps { pos = rel(pos, dir); @@ -105,7 +115,10 @@ impl Sim<'_, L> { fn shelf_set_part(&mut self, pos: BlockPos, part: Part) { let state = self.state(pos); if self.shelf_part(state) != part { - let next = self.b.table.set_text(state, self.b.props.side_chain, part.name()); + let next = self + .b + .table + .set_text(state, self.b.props.side_chain, part.name()); self.set_block_and_update(pos, next); } } @@ -115,7 +128,11 @@ impl Sim<'_, L> { if !self.shelf_connectable(state) { return 0; } - let mut n = Neighbors { facing: self.b.facing(state), center: pos, cache: HashMap::new() }; + let mut n = Neighbors { + facing: self.b.facing(state), + center: pos, + cache: HashMap::new(), + }; let mut size = 1; for (left, end) in [(true, Part::Left), (false, Part::Right)] { for steps in 1..MAX_CHAIN_LENGTH as i32 { @@ -132,7 +149,11 @@ impl Sim<'_, L> { } /// `SideChainPartBlock.updateNeighborsAfterPoweringDown`. pub(crate) fn shelf_after_powering_down(&mut self, pos: BlockPos, state: BlockStateId) { - let mut n = Neighbors { facing: self.b.facing(state), center: pos, cache: HashMap::new() }; + let mut n = Neighbors { + facing: self.b.facing(state), + center: pos, + cache: HashMap::new(), + }; if let (at, Some(part)) = self.chain_neighbor(&mut n, true, 1) { self.shelf_set_part(at, part.disconnected_from_the_right()); } @@ -150,11 +171,23 @@ impl Sim<'_, L> { if updated_by_neighbor { return; } - let mut n = Neighbors { facing: self.b.facing(state), center: pos, cache: HashMap::new() }; + let mut n = Neighbors { + facing: self.b.facing(state), + center: pos, + cache: HashMap::new(), + }; let (left_pos, left) = self.chain_neighbor(&mut n, true, 1); let (right_pos, right) = self.chain_neighbor(&mut n, false, 1); - let on_left = if left.is_some() { self.shelf_chain_size(left_pos) } else { 0 }; - let on_right = if right.is_some() { self.shelf_chain_size(right_pos) } else { 0 }; + let on_left = if left.is_some() { + self.shelf_chain_size(left_pos) + } else { + 0 + }; + let on_right = if right.is_some() { + self.shelf_chain_size(right_pos) + } else { + 0 + }; let mut own = Part::Unconnected; let mut length = 1; if on_left > 0 && length + on_left <= MAX_CHAIN_LENGTH { @@ -189,13 +222,18 @@ impl Sim<'_, L> { } let mut next = b.table.set_bool(state, b.props.powered, signal); if !signal { - next = b.table.set_text(next, b.props.side_chain, Part::Unconnected.name()); + next = b + .table + .set_text(next, b.props.side_chain, Part::Unconnected.name()); } self.set_block_and_update(pos, next); let (sound, event) = if signal { ("minecraft:block.shelf.activate", "minecraft:block_activate") } else { - ("minecraft:block.shelf.deactivate", "minecraft:block_deactivate") + ( + "minecraft:block.shelf.deactivate", + "minecraft:block_deactivate", + ) }; self.sound(pos, &sound.into(), 1.0, 1.0); self.game_event_state(pos, event, next); diff --git a/crates/horizon-world/src/level/update.rs b/crates/horizon-world/src/level/update.rs index 1fd90c33e..15117c890 100644 --- a/crates/horizon-world/src/level/update.rs +++ b/crates/horizon-world/src/level/update.rs @@ -188,7 +188,12 @@ impl Sim<'_, L> { pub fn prime_tnt(&mut self, pos: BlockPos) { let rot = self.random().next_double() * f64::from(std::f32::consts::TAU); self.emit(LevelEvent::PrimeTnt { pos, rot }); - self.sound(pos, &std::sync::Arc::from("minecraft:entity.tnt.primed"), 1.0, 1.0); + self.sound( + pos, + &std::sync::Arc::from("minecraft:entity.tnt.primed"), + 1.0, + 1.0, + ); self.game_event(pos, "minecraft:prime_fuse"); } pub fn level_event(&mut self, id: i32, pos: BlockPos, data: i32) { diff --git a/crates/horizon-world/src/loot.rs b/crates/horizon-world/src/loot.rs index b863e9659..fccfa4c77 100644 --- a/crates/horizon-world/src/loot.rs +++ b/crates/horizon-world/src/loot.rs @@ -683,7 +683,8 @@ impl Context<'_, R> { { continue; } - if !effect["requirements"].is_null() && !self.condition(&effect["requirements"]) { + if !effect["requirements"].is_null() && !self.condition(&effect["requirements"]) + { continue; } let value = level_value(&effect["effect"]["value"], *level); @@ -731,21 +732,22 @@ impl Context<'_, R> { .is_some_and(|stack| self.item_matches(item, stack)) }) } - "minecraft:components" => v.as_object().into_iter().flatten().all(|(c, want)| { - match c.as_str() { - "minecraft:sheep/color" => e - .sheep - .as_ref() - .is_some_and(|(color, _)| want.as_str() == Some(color)), - "minecraft:frog/variant" => { - e.frog_variant.is_some() && want.as_str() == e.frog_variant.as_deref() - } - _ => false, + "minecraft:components" => v.as_object().into_iter().flatten().all(|(c, want)| match c + .as_str() + { + "minecraft:sheep/color" => e + .sheep + .as_ref() + .is_some_and(|(color, _)| want.as_str() == Some(color)), + "minecraft:frog/variant" => { + e.frog_variant.is_some() && want.as_str() == e.frog_variant.as_deref() } + _ => false, }), - "minecraft:type_specific/sheep" => e.sheep.as_ref().is_some_and(|(_, sheared)| { - v["sheared"].as_bool().is_none_or(|w| w == *sheared) - }), + "minecraft:type_specific/sheep" => e + .sheep + .as_ref() + .is_some_and(|(_, sheared)| v["sheared"].as_bool().is_none_or(|w| w == *sheared)), "minecraft:type_specific/cube_mob" => { e.cube_size.is_some_and(|size| int_bounds(&v["size"], size)) } @@ -1237,7 +1239,7 @@ impl Context<'_, R> { + e["quality"].as_i64().unwrap_or(0) as f32 * luck; w.floor().max(0.0) as i32 }; - let total: i32 = valid.iter().map(|e| weight(e)).sum(); + let total: i32 = valid.iter().map(&weight).sum(); if total == 0 || valid.is_empty() { return; } @@ -1289,7 +1291,10 @@ impl Context<'_, R> { let items = self.data.holder_set("item", &entry["items"]); for item in items { if entry["weight"].as_i64().unwrap_or(1) > 0 { - out.push(Choice { entry, item: Some(item) }); + out.push(Choice { + entry, + item: Some(item), + }); } } true