diff --git a/crates/horizon-client/examples/ambient_fixture.rs b/crates/horizon-client/examples/ambient_fixture.rs index 666235008..d75a1b568 100644 --- a/crates/horizon-client/examples/ambient_fixture.rs +++ b/crates/horizon-client/examples/ambient_fixture.rs @@ -131,6 +131,7 @@ fn main() { let tick = TickContext { player_underwater: ambience.was_underwater(), player_removed: removed, + ..TickContext::default() }; engine.tick(false, &tick, &mut backend); } diff --git a/crates/horizon-client/examples/arrow_probe.rs b/crates/horizon-client/examples/arrow_probe.rs index 545d7ae4d..20c0883e3 100644 --- a/crates/horizon-client/examples/arrow_probe.rs +++ b/crates/horizon-client/examples/arrow_probe.rs @@ -4,7 +4,8 @@ use horizon_client::{ Result, arrows::{ - self, ArrowEvent, ArrowParticle, ArrowScene, ArrowSound, BlockReaction, Pickup, Touch, + self, ArrowEvent, ArrowParticle, ArrowScene, ArrowSound, BlockReaction, EntityHit, Pickup, + Touch, }, assets::Assets, blocks::BlockFacts, @@ -12,11 +13,11 @@ use horizon_client::{ items::ItemStack, mobs::Who, motion::{LAVA, MotionResources, WATER}, - projectiles::{Projectile, ProjectileKind}, + projectiles::{Hit, Projectile, ProjectileKind}, world::World, }; use horizon_core::{ - geometry::Vec3, + geometry::{Aabb, Vec3}, random::{LegacyRandom, RandomSource}, }; use serde_json::Value; @@ -89,11 +90,16 @@ fn main() -> Result<()> { &ItemStack::new("minecraft:arrow", 1), f["intangible"].as_bool().unwrap(), )); + // The entity in the way: its box and whether it takes the damage. + let mut target: Option<(Aabb, bool)> = None; for op in f["ops"].as_array().unwrap() { let mut events = Vec::new(); let mut touched = "-".to_string(); match op["mode"].as_str().unwrap() { "tick" => { + // The game's part of an entity hit: the damage it deals + // (recorded after the tick's own events). + let mut hurt = None; if !arrow.arrow.as_ref().unwrap().removed { let no_rain = |_| false; let view = ArrowScene { @@ -106,9 +112,35 @@ fn main() -> Result<()> { mob_griefing: true, tnt_explodes: true, }; - arrows::tick(&mut arrow, &view, &[]); + let targets: Vec<_> = target.iter().map(|t| (Who::Mob(2), t.0)).collect(); + let (_, hit) = arrows::tick(&mut arrow, &view, &targets); + if let (Hit::Entity { .. }, Some((_, takes))) = (hit, target) { + let mut st = arrow.arrow.take().unwrap(); + let damage = arrow.arrow_damage(&mut st.random); + hurt = Some((st.events.len(), damage)); + arrow.arrow = Some(st); + let outcome = if takes { + EntityHit::Hurt + } else { + EntityHit::Refused + }; + arrows::finish_entity_hit(&mut arrow, &view, outcome); + } } - for event in arrow.arrow.as_mut().unwrap().events.drain(..) { + let a = arrow.arrow.as_mut().unwrap(); + let (drop_at, dropped) = (arrow.position, a.pickup_item.count); + let raised = std::mem::take(&mut a.events); + let count = raised.len(); + for (i, event) in raised.into_iter().map(Some).chain([None]).enumerate() { + if let Some((at, damage)) = hurt + && at == i + { + events.push(format!("hurt {:08x}", damage.to_bits())); + } + let Some(event) = event else { + debug_assert_eq!(i, count); + break; + }; match event { ArrowEvent::Particle { kind, @@ -191,9 +223,28 @@ fn main() -> Result<()> { }, ArrowEvent::SplashEvent => events.push("splash-event".into()), ArrowEvent::ShootEvent => events.push("shoot-event".into()), + ArrowEvent::Drop => events.push(format!( + "drop {} {dropped}", + bits(Vec3::new( + drop_at.x, + drop_at.y + f64::from(0.1f32), + drop_at.z + )) + )), } } } + "target" => { + // EntityDimensions.scalable(0.6, 1.8).makeBoundingBox. + let at = vector(&op["position"]); + let w = f64::from(0.6f32) / 2.0; + let h = f64::from(1.8f32); + let b = Aabb::new( + Vec3::new(at.x - w, at.y, at.z - w), + Vec3::new(at.x + w, at.y + h, at.z + w), + ); + target = Some((b, op["takes"].as_bool().unwrap())); + } "block" => { let p = &op["position"]; let mut state = assets diff --git a/crates/horizon-client/examples/natural_spawn_fixture.rs b/crates/horizon-client/examples/natural_spawn_fixture.rs index af15b9fde..3ce9f6c5a 100644 --- a/crates/horizon-client/examples/natural_spawn_fixture.rs +++ b/crates/horizon-client/examples/natural_spawn_fixture.rs @@ -13,6 +13,10 @@ //! `mobs::spawner::Spawner` loaded from the case's SNBT on the same world and //! print its events tick by tick. //! +//! Trial spawner cases (`mode=trial`, tools/test_trial_spawner_parity.py) tick +//! a `mobs::trial_spawner::TrialSpawner` with the game time advancing and +//! print its states, events, spawns and ejected items. +//! //! usage: natural_spawn_fixture RESOURCES INPUT OUTPUT use horizon_client::{ assets::Assets, @@ -31,6 +35,7 @@ use horizon_client::{ }, spawner::{Spawner, SpawnerAdded, SpawnerEvent, SpawnerLevel, SpawnerSpawn}, species::{self, Baby}, + trial_spawner::{TrialEvent, TrialPlayer, TrialSpawner, TrialSpawnerLevel, TrialState}, }, }; use horizon_core::{ @@ -38,11 +43,11 @@ use horizon_core::{ random::{LegacyRandom, RandomSource}, }; use horizon_world::{ - block_collision::BlockCollisionRegistry, chunk::BlockState, registry::BlockStateId, + block_collision::BlockCollisionRegistry, chunk::BlockState, nbt::Tag, registry::BlockStateId, }; use serde_json::Value; use std::{ - cell::RefCell, + cell::{Cell, RefCell}, collections::{BTreeMap, HashMap, HashSet}, fmt::Write as _, fs, @@ -106,6 +111,12 @@ struct World<'a> { spawners_work: bool, /// Types and boxes of living entities (case entities, then spawned mobs). entities: RefCell>, + /// Blocks set since the case started (a trial spawner's states). + placed: RefCell>, + /// The game time (trial cases advance it). + time: Cell, + /// The mobs a trial spawner added: UUID, position and box. + trial_mobs: RefCell>, } impl World<'_> { fn biome_at(&self, x: i32, y: i32, z: i32) -> &str { @@ -129,6 +140,15 @@ impl World<'_> { } impl SpawnLevel for World<'_> { fn state(&self, x: i32, y: i32, z: i32) -> BlockStateId { + if let Some((_, s)) = self + .placed + .borrow() + .iter() + .rev() + .find(|(p, _)| *p == [x, y, z]) + { + return *s; + } self.blocks .iter() .rev() @@ -341,6 +361,50 @@ impl SpawnerLevel for World<'_> { } } +impl TrialSpawnerLevel for World<'_> { + fn game_time(&self) -> i64 { + self.time.get() + } + fn mob_spawning(&self) -> bool { + self.spawn_mobs + } + fn players(&self) -> Vec { + self.players + .iter() + .enumerate() + .map(|(i, (p, mode))| TrialPlayer { + uuid: [0, 0, 0, i as i32 + 1], + block: p.map(|v| v.floor() as i32), + eye: [p[0], p[1] + f64::from(1.62f32), p[2]], + creative: mode == "creative", + spectator: mode == "spectator", + }) + .collect() + } + fn visual_hit(&self, from: [f64; 3], to: [f64; 3]) -> Option<[i32; 3]> { + let lookup = |x: i32, y: i32, z: i32| self.state(x, y, z); + let mut scene = LookupCollisions { + block: &lookup, + binding: self.s.collision, + }; + let v = |p: [f64; 3]| horizon_core::geometry::Vec3::new(p[0], p[1], p[2]); + horizon_client::mobs::visual_clip( + self.s.facts, + self.s.collision, + &mut scene, + &lookup, + v(from), + v(to), + ) + .flatten() + } + fn entity_block(&self, uuid: [i32; 4]) -> Option<[i32; 3]> { + let mobs = self.trial_mobs.borrow(); + let (_, p, _) = mobs.iter().find(|(u, ..)| *u == uuid)?; + Some(p.map(|v| v.floor() as i32)) + } +} + /// The box a mob is left with by `finalizeSpawn` under the oracle's fixed random. fn neutral_box(l: &World, r: &SpawnRequest) -> Aabb { let t = &l.s.types.types[r.entity]; @@ -407,6 +471,13 @@ fn main() -> horizon_client::Result<()> { let facts = BlockFacts::load(root, registry)?; let data = MobData::load(root, &facts); let items = Items::tags_only(root)?; + // Trial spawner rewards: the loot tables and the configs. + let loot = if input.contains("mode=trial") { + horizon_client::mobs::trial_spawner::load_registry(root); + horizon_client::structure_blocks::loot_data(root) + } else { + None + }; let types = MobTypes::load(root)?; let biomes = Biomes::load(root)?; let structures = StructureSpawns::load(root); @@ -593,6 +664,9 @@ fn main() -> horizon_client::Result<()> { unloaded, spawn_mobs: get("rules", "1") != "0", spawners_work: get("spawners", "1") != "0", + placed: RefCell::new(Vec::new()), + time: Cell::new(0), + trial_mobs: RefCell::new(Vec::new()), entities: RefCell::new( case_entities .iter() @@ -629,6 +703,9 @@ fn main() -> horizon_client::Result<()> { let mode = get("mode", "chunk"); if mode == "spawner" { spawner_case(&world, &get, &mut random, &mut log)?; + } else if mode == "trial" { + let loot = loot.as_ref().ok_or("no loot tables")?; + trial_case(&world, registry, loot, &get, &mut random, &mut log)?; } else if mode == "gen" { let mut gen_random = LegacyRandom::new(get("gseed", "0").parse()?); // The level random of the spawn predicates: no creature's predicate @@ -831,3 +908,196 @@ fn spawner_case( log.push(format!("next {}", random.next_int_bound(1000).unwrap_or(0))); Ok(()) } + +/// `TrialSpawner.tickServer` `ticks` times from game time `t0` at `spos` on a +/// trial spawner block in state `state` (ominous with `ominous=1`) loaded from +/// `snbt` (base64 SNBT), as the oracle logs it. Every `kill` ticks the mobs it +/// spawned die. +fn trial_case( + world: &World, + registry: &horizon_world::registry::BlockRegistry, + loot: &horizon_world::loot::LootData, + get: &dyn Fn(&str, &'static str) -> String, + random: &mut LegacyRandom, + log: &mut Vec, +) -> horizon_client::Result<()> { + let v: Vec = get("spos", "0,0,0") + .split(',') + .map(|n| n.parse().unwrap_or(0)) + .collect(); + let pos = [v[0], v[1], v[2]]; + let block_state = |state: TrialState, ominous: bool| { + parse_state(&format!( + "minecraft:trial_spawner[trial_spawner_state={},ominous={ominous}]", + state.name() + )) + }; + let mut state = + TrialState::from_name(&get("state", "waiting_for_players")).ok_or("bad state")?; + let mut ominous = get("ominous", "0") == "1"; + world + .placed + .borrow_mut() + .push((pos, registry.resolve(&block_state(state, ominous))?)); + let text = horizon_client::skins::base64_decode(&get("snbt", "")).ok_or("bad snbt")?; + let tag = horizon_world::nbt::parse_snbt(&String::from_utf8(text)?)?.0; + let mut spawner = TrialSpawner::load(&tag); + let ticks: i64 = get("ticks", "1").parse()?; + let t0: i64 = get("t0", "0").parse()?; + let kill: i64 = get("kill", "0").parse()?; + let seed = world.seed; + let mut sequences = horizon_client::random_sequences::RandomSequences::default(); + let center = pos.map(|v| f64::from(v) + 0.5); + for tick in 0..ticks { + world.time.set(t0 + tick); + let mut events = Vec::new(); + let mut spawned = std::collections::VecDeque::new(); + let mut items = Vec::new(); + let mut spawn = |l: &World, r: &SpawnerSpawn| { + let t = l.s.types.types.get(r.id)?; + // Slime.readAdditionalSaveData: size Size + 1, clamped to 1..=127. + let size = match r.entity.get(&horizon_world::nbt::JavaString::from("Size")) { + Some(Tag::Byte(v)) => i32::from(*v), + Some(Tag::Short(v)) => i32::from(*v), + Some(Tag::Int(v)) => *v, + Some(Tag::Long(v)) => *v as i32, + _ => 0, + }; + let size = if matches!(r.id, "minecraft:slime" | "minecraft:magma_cube") { + size.saturating_add(1).clamp(1, 127) + } else { + 1 + }; + let [x, y, z] = r.position; + let scale = size as f32; + let bounds = spawn_box(x, y, z, t.width as f32 * scale, t.height as f32 * scale); + l.entities.borrow_mut().push((r.id.to_owned(), bounds)); + let uuid = [1, 0, 0, l.trial_mobs.borrow().len() as i32]; + l.trial_mobs.borrow_mut().push((uuid, r.position, bounds)); + spawned.push_back(format!( + "{tick} spawn {} {} {} {} {}", + r.id, + bits(x), + bits(y), + bits(z), + if size == 1 { + yaw_text(r.id, r.yaw) + } else { + "head".to_owned() + } + )); + Some(uuid) + }; + let mut eject = |table: &str, random: &mut LegacyRandom| { + let drops = match loot.random_sequence(table) { + Some(s) => loot.roll_split(table, sequences.get(s, seed)), + None => loot.roll_split(table, random), + }; + for stack in &drops { + random.next_double(); + let spread = 0.017_227_5 * 2.0; + let v = [ + random.triangle(0.0, spread), + random.triangle(0.2, spread), + random.triangle(0.0, spread), + ]; + items.push(format!( + "{tick} item {} {} {} {} {} {} {} {}", + stack.item, + stack.count, + bits(center[0]), + bits(center[1] + 0.7 - 0.125), + bits(center[2]), + bits(v[0]), + bits(v[1]), + bits(v[2]) + )); + } + !drops.is_empty() + }; + let next = spawner.server_tick( + world, + random, + pos, + state, + ominous, + &mut spawn, + &mut eject, + &mut events, + ); + for e in events { + match e { + TrialEvent::BlockUpdated => log.push(format!("{tick} update")), + TrialEvent::LevelEvent(id, _, data) => { + // A spawn's events follow its tryAddFreshEntityWithPassengers, + // a reward's its items. + match id { + 3011 => log.extend(spawned.pop_front()), + 3014 => log.append(&mut items), + _ => {} + } + log.push(format!("{tick} levent {id} {data}")); + } + TrialEvent::Sound(name) => log.push(format!( + "{tick} sound minecraft:{name} {} {} {} 1.0 1.0", + bits(center[0]), + bits(center[1]), + bits(center[2]) + )), + TrialEvent::EntityPlace(_, p) => log.push(format!( + "{tick} gevent minecraft:entity_place {} {} {}", + p[0], p[1], p[2] + )), + TrialEvent::OminousSet(set) => { + ominous = set; + world + .placed + .borrow_mut() + .push((pos, registry.resolve(&block_state(state, ominous))?)); + log.push(format!("{tick} state {} {ominous}", state.name())); + } + } + } + if next != state || spawner.is_ominous != ominous { + state = next; + ominous = spawner.is_ominous; + world + .placed + .borrow_mut() + .push((pos, registry.resolve(&block_state(state, ominous))?)); + log.push(format!("{tick} state {} {ominous}", state.name())); + } + if kill > 0 && tick % kill == kill - 1 { + let dead: Vec = world + .trial_mobs + .borrow_mut() + .drain(..) + .map(|(.., b)| b) + .collect(); + world + .entities + .borrow_mut() + .retain(|(_, b)| !dead.iter().any(|d| d == b)); + if !dead.is_empty() { + log.push(format!("{tick} kill {}", dead.len())); + } + } + } + log.push(format!( + "end state={} players={} mobs={} cooldown={} next_spawn={} total={} data={} eject={}", + state.name(), + spawner.detected_players.len(), + spawner.current_mobs.len(), + spawner.cooldown_ends_at, + spawner.next_mob_spawns_at, + spawner.total_mobs_spawned, + spawner + .next_spawn_data + .as_ref() + .and_then(|d| d.id()) + .unwrap_or_else(|| "-".into()), + spawner.ejecting_loot_table.as_deref().unwrap_or("-") + )); + log.push(format!("next {}", random.next_int_bound(1000).unwrap_or(0))); + Ok(()) +} diff --git a/crates/horizon-client/examples/sound_engine_fixture.rs b/crates/horizon-client/examples/sound_engine_fixture.rs index 5bc8f1a61..c42ea8bf9 100644 --- a/crates/horizon-client/examples/sound_engine_fixture.rs +++ b/crates/horizon-client/examples/sound_engine_fixture.rs @@ -5,7 +5,7 @@ mod common; use common::{Fake, d, describe, f, flush, result_name}; use horizon_client::sound_engine::{ - Attenuation, Backend, InstanceId, SoundEngine, SoundInstance, TickContext, + Attenuation, Backend, CartSound, InstanceId, SoundEngine, SoundInstance, TickContext, }; use horizon_client::sound_events::SoundRegistry; use horizon_core::random::LegacyRandom; @@ -19,6 +19,9 @@ fn main() { let mut backend = Fake::default(); let mut ctx = TickContext::default(); let mut instances: BTreeMap = BTreeMap::new(); + // Script cart names to entity ids (a removed cart leaves the level). + let mut cart_ids: BTreeMap = BTreeMap::new(); + let mut removed: BTreeMap = BTreeMap::new(); let input = std::fs::read_to_string(&args[2]).expect("input"); let mut out = std::io::BufWriter::new(std::fs::File::create(&args[3]).expect("output")); for line in input.lines() { @@ -49,6 +52,21 @@ fn main() { "loop" => SoundInstance::biome_loop(&event, random), "uloop" => SoundInstance::under_liquid_loop(&event, random), "usub" => SoundInstance::under_liquid_sub(&event, random), + "cart" | "rcart" | "rcartu" => { + let id = cart_ids[a[3]]; + let cart = ctx + .carts + .iter() + .find(|c| c.id == id) + .or_else(|| removed.get(&id)) + .copied() + .expect("cart"); + if a[2] == "cart" { + SoundInstance::minecart(&cart, random) + } else { + SoundInstance::riding_minecart(&cart, a[2] == "rcartu", random) + } + } _ => panic!("{line}"), }; if let Some(old) = instances.remove(a[1]) { @@ -92,6 +110,26 @@ fn main() { ctx.player_underwater = a[1] == "1"; ctx.player_removed = a[2] == "1"; } + "cart" => { + let next = cart_ids.len() as u32 + 1; + let id = *cart_ids.entry(a[1].to_owned()).or_insert(next); + ctx.carts.retain(|c| c.id != id); + let cart = CartSound { + id, + position: [d(a[2]), d(a[3]), d(a[4])], + // Vec3.horizontalDistance. + speed: (d(a[5]) * d(a[5]) + d(a[7]) * d(a[7])).sqrt(), + }; + if a[8] == "1" { + // Out of the level, still there for a later play. + removed.insert(id, cart); + } else { + removed.remove(&id); + ctx.carts.push(cart); + } + } + "ride" => ctx.vehicle = cart_ids.get(a[1]).copied(), + "freeze" => ctx.frozen = a[1] == "1", "tick" => engine.tick(a[1] == "1", &ctx, &mut backend), "forget" => { if let Some(id) = instances.remove(a[1]) { diff --git a/crates/horizon-client/src/arrows.rs b/crates/horizon-client/src/arrows.rs index d89d82161..30b501011 100644 --- a/crates/horizon-client/src/arrows.rs +++ b/crates/horizon-client/src/arrows.rs @@ -1,8 +1,9 @@ //! `AbstractArrow.tick` for arrows, tipped and spectral arrows: the flight with //! its water inertia and bubbles, the base tick's fluids (currents, splash), //! bubble columns and water along the path, sticking in blocks, falling out -//! when the block goes, and despawning. Entity hits and their effects stay -//! with the game (`projectile_hit`). +//! when the block goes, and despawning. The tick stops at an entity it hits: +//! the game hurts the entity (`projectile_hit`), then `finish_entity_hit` +//! spends the arrow or turns it back and ends the tick. use crate::{ blocks::BlockFacts, collisions::SceneCollisions, @@ -113,6 +114,9 @@ pub enum ArrowEvent { /// The SPLASH and PROJECTILE_SHOOT game events. SplashEvent, ShootEvent, + /// `spawnAtLocation(pickupItem, 0.1)`: a turned-back arrow too slow to fly + /// on drops what picking it up gives. + Drop, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ArrowParticle { @@ -124,7 +128,7 @@ pub enum ArrowParticle { pub enum ArrowSound { /// `entity.generic.splash` (an arrow's splash and high-speed splash). Splash, - /// The arrow's hit-ground sound (`entity.arrow.hit`). + /// The arrow's `soundEvent` (`entity.arrow.hit`), for blocks and entities. HitGround, /// `entity.generic.extinguish_fire`. Extinguish, @@ -382,14 +386,17 @@ fn signum(v: f64) -> f64 { v } } -/// One arrow tick: whether to keep it and what it hit. +/// One arrow tick: whether to keep it and what it hit. An arrow that hit an +/// entity stops there and is not kept: the game hands it to +/// `finish_entity_hit` once it has hurt the entity. pub fn tick(p: &mut Projectile, scene: &ArrowScene, targets: &[(Who, Aabb)]) -> (bool, Hit) { let Some(mut st) = p.arrow.take() else { return (false, Hit::None); }; // Entity.setOldPosAndRot: the renderer interpolates from here, in flight - // and stuck alike. + // and stuck alike; ServerLevel.tickNonPassenger counts the tick. p.previous = p.position; + p.age += 1; let hit = Ticker { p, st: &mut st, @@ -397,10 +404,44 @@ pub fn tick(p: &mut Projectile, scene: &ArrowScene, targets: &[(Who, Aabb)]) -> } .tick(targets); p.stuck = st.in_ground; - let keep = !st.removed; + let keep = !st.removed && !matches!(hit, Hit::Entity { .. }); p.arrow = Some(st); (keep, hit) } +/// What became of the entity an arrow hit (`AbstractArrow.onHitEntity`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EntityHit { + /// `hurtOrSimulate` succeeded: the arrow is spent, with its hit sound. + Hurt, + /// It failed (a raised shield, invulnerability): the arrow turns back. + Refused, + /// The entity turned it first (`Entity.deflection`: breezes). + Deflected, +} +/// The rest of the tick of an arrow that hit an entity: whether to keep it. +pub fn finish_entity_hit(p: &mut Projectile, scene: &ArrowScene, outcome: EntityHit) -> bool { + let Some(mut st) = p.arrow.take() else { + return false; + }; + let mut ticker = Ticker { + p, + st: &mut st, + scene, + }; + match outcome { + EntityHit::Hurt => { + ticker.hit_sound(); + ticker.st.removed = true; + } + EntityHit::Refused => ticker.turn_back(), + EntityHit::Deflected => {} + } + ticker.finish(); + p.stuck = st.in_ground; + let keep = !st.removed; + p.arrow = Some(st); + keep +} struct Ticker<'p, 's, 'a, 'r> { p: &'p mut Projectile, st: &'s mut ArrowState, @@ -517,10 +558,20 @@ impl Ticker<'_, '_, '_, '_> { ); if physics { hit = self.step_move_and_hit(original, end, targets); + if matches!(hit, Hit::Entity { .. }) { + return hit; + } } else { self.p.position = end; self.apply_effects_from_blocks(original, end); } + self.finish(); + hit + } + /// The end of a tick in flight: drag and gravity, then `Projectile.tick` + /// and `Entity.baseTick`'s fluid and fire phases. + fn finish(&mut self) { + let physics = !self.st.no_physics; if !self.st.was_touching_water { self.p.velocity = self.p.velocity.scale(f64::from(0.99f32)); } @@ -547,7 +598,6 @@ impl Ticker<'_, '_, '_, '_> { self.st.removed = true; } self.st.first_tick = false; - hit } /// `getDeltaMovement().add(0, y, 0)`: the zeros added to x and z also /// turn a negative zero positive. @@ -589,16 +639,23 @@ impl Ticker<'_, '_, '_, '_> { self.st.life = 0; } /// `AbstractArrow.stepMoveAndHit`: the nearest entity on the way, else the - /// block (not piercing: the game removes an arrow that hits an entity). + /// block (piercing is not modelled). fn step_move_and_hit(&mut self, from: Vec3, to: Vec3, targets: &[(Who, Aabb)]) -> Hit { let block = self.scene.clip(from, to); let end = block.map_or(to, |b| b.0); + // findHitEntities: ProjectileUtil.computeMargin and the search box. + let margin = f64::from(((self.p.age as i32 - 2) as f32 / 20.0).clamp(0.0, 0.3)); + let area = bounds(from) + .expand_towards(self.p.velocity) + .inflate(Vec3::new(1.0, 1.0, 1.0)); let mut best: Option<(Who, Vec3, f64)> = None; for (who, b) in targets { - if Some(*who) == self.p.owner && !self.p.left_owner { + if Some(*who) == self.p.owner && !self.p.left_owner || !b.intersects(area) { continue; } - if let Some(at) = b.inflate(Vec3::new(0.3, 0.3, 0.3)).clip(from, end) { + if let Some(at) = self.entity_hit(b, from, end, margin) { + // Sorted by the distance to the entity's position (the + // stable sort keeps the first of equals). let c = b.center(); let d = from.distance_squared(Vec3::new(c.x, b.min_position().y, c.z)); if best.is_none_or(|bb| d < bb.2) { @@ -610,8 +667,6 @@ impl Ticker<'_, '_, '_, '_> { self.p.position = next; self.apply_effects_from_blocks(from, next); if let Some((who, at, _)) = best { - // The game hurts it; the arrow is spent (piercing is not modelled). - self.st.removed = true; return Hit::Entity { who, at }; } let Some((at, pos, face)) = block else { @@ -631,6 +686,49 @@ impl Ticker<'_, '_, '_, '_> { face, } } + /// `ProjectileUtil.getManyEntityHitResult` for one entity box: where the + /// path enters it, else where it enters the box grown by `margin`, if a + /// line from there towards the centre (stopped by blocks) reaches the box. + fn entity_hit(&self, b: &Aabb, from: Vec3, to: Vec3, margin: f64) -> Option { + if let Some(at) = b.clip(from, to) { + return Some(at); + } + if margin <= 0.0 { + return None; + } + let outside = b + .inflate(Vec3::new(margin, margin, margin)) + .clip(from, to)?; + let centre = b.center(); + let towards = self.scene.clip(outside, centre).map_or(centre, |h| h.0); + b.clip(outside, towards).map(|_| outside) + } + /// `playSound(soundEvent, 1, 1.2 / (random * 0.2 + 0.9))`. + fn hit_sound(&mut self) { + let pitch = 1.2 / (self.st.random.next_float() * 0.2 + 0.9); + self.st.events.push(ArrowEvent::Sound { + sound: ArrowSound::HitGround, + volume: 1.0, + pitch, + }); + } + /// `onHitEntity` when the entity took no damage: `deflect(REVERSE, 0.2)`, + /// a half turn give or take ten degrees at a tenth of the speed; one + /// left almost still drops its pickup (ALLOWED) and is discarded. + fn turn_back(&mut self) { + let power = 0.2; + let rotation = 170.0 + self.st.random.next_float() * 20.0; + let v = self.p.velocity; + let k = -power * 0.5; + self.p.velocity = Vec3::new(v.x * k, v.y * k, v.z * k); + self.p.yaw += rotation; + if self.p.velocity.length_squared() < 1.0e-7 { + if self.st.pickup == Pickup::Allowed { + self.st.events.push(ArrowEvent::Drop); + } + self.st.removed = true; + } + } /// `AbstractArrow.onHitBlock`: back off the face by 0.05 along each axis /// it moved on, stop, and stick. fn on_hit_block(&mut self, pos: BlockPos, state: BlockStateId) { @@ -649,12 +747,7 @@ impl Ticker<'_, '_, '_, '_> { self.p.position.z - signum(v.z) * offset, ); self.p.velocity = Vec3::ZERO; - let pitch = 1.2 / (self.st.random.next_float() * 0.2 + 0.9); - self.st.events.push(ArrowEvent::Sound { - sound: ArrowSound::HitGround, - volume: 1.0, - pitch, - }); + self.hit_sound(); self.st.in_ground = true; self.st.shake = 7; self.p.set_critical(false); diff --git a/crates/horizon-client/src/clock.rs b/crates/horizon-client/src/clock.rs index 57e66e5fc..865a348bc 100644 --- a/crates/horizon-client/src/clock.rs +++ b/crates/horizon-client/src/clock.rs @@ -393,6 +393,10 @@ impl FixedStep { pub fn frozen(&self) -> bool { self.manager.base.is_frozen() } + /// `runsNormally` as of the last `world_runs`. + pub fn runs_normally(&self) -> bool { + self.manager.base.runs_normally() + } pub fn set_frozen(&mut self, frozen: bool) { self.manager.base.set_frozen(frozen); } diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 4870216cd..777e90054 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -68,6 +68,8 @@ pub enum BlockEntity { Crafter(Crafter), /// `SpawnerBlockEntity` (`crate::mobs::spawner`). Spawner(Box), + /// `TrialSpawnerBlockEntity` (`crate::mobs::trial_spawner`). + TrialSpawner(Box), /// `BeehiveBlockEntity` of beehives and bee nests (`crate::beehive`). Beehive(Box), } @@ -187,6 +189,9 @@ impl BlockEntity { if name == "minecraft:spawner" { return Some(Self::Spawner(Box::default())); } + if name == "minecraft:trial_spawner" { + return Some(Self::TrialSpawner(Box::default())); + } if name == "minecraft:beehive" || name == "minecraft:bee_nest" { return Some(Self::Beehive(Box::default())); } @@ -266,6 +271,7 @@ impl BlockEntity { Self::Crafter(_) => "minecraft:crafter", Self::CreakingHeart(_) => "minecraft:creaking_heart", Self::Spawner(_) => "minecraft:mob_spawner", + Self::TrialSpawner(_) => "minecraft:trial_spawner", Self::Beehive(_) => "minecraft:beehive", } } @@ -276,9 +282,11 @@ impl BlockEntity { Self::Brewing(b) => b.items.iter().flatten().cloned().collect(), Self::Sign(_) => Vec::new(), Self::Jukebox(j) => j.record.iter().cloned().collect(), - Self::Beacon(_) | Self::CreakingHeart(_) | Self::Spawner(_) | Self::Beehive(_) => { - Vec::new() - } + Self::Beacon(_) + | Self::CreakingHeart(_) + | Self::Spawner(_) + | Self::TrialSpawner(_) + | Self::Beehive(_) => Vec::new(), Self::Lectern(l) => l.book.iter().cloned().collect(), Self::Sculk(_) => Vec::new(), Self::Banner(_) => Vec::new(), @@ -297,7 +305,10 @@ impl BlockEntity { | Self::Sculk(_) | Self::Banner(_) => &[], Self::Crafter(c) => &c.items, - Self::CreakingHeart(_) | Self::Spawner(_) | Self::Beehive(_) => &[], + Self::CreakingHeart(_) + | Self::Spawner(_) + | Self::TrialSpawner(_) + | Self::Beehive(_) => &[], } } pub fn slots_mut(&mut self) -> &mut [Option] { @@ -312,7 +323,10 @@ impl BlockEntity { | Self::Sculk(_) | Self::Banner(_) => &mut [], Self::Crafter(c) => &mut c.items, - Self::CreakingHeart(_) | Self::Spawner(_) | Self::Beehive(_) => &mut [], + Self::CreakingHeart(_) + | Self::Spawner(_) + | Self::TrialSpawner(_) + | Self::Beehive(_) => &mut [], } } } diff --git a/crates/horizon-client/src/debug_chart.rs b/crates/horizon-client/src/debug_chart.rs new file mode 100644 index 000000000..68a469415 --- /dev/null +++ b/crates/horizon-client/src/debug_chart.rs @@ -0,0 +1,579 @@ +//! The debug charts (26.3 `debugchart`): F3+2 shows the frame times and, in +//! single player, the integrated server's tick times; F3+3 the ping and, on a +//! remote server, the bandwidth. Each chart keeps the last 240 samples +//! (`LocalSampleLogger`) and draws one bar per sample over a 60 pixel high +//! box (`AbstractDebugChart`). +use crate::{ + font::Font, + hud_layout::{GuiDraw, argb, fill}, + text::Text, +}; +use std::{ + collections::VecDeque, + time::{Duration, Instant}, +}; + +/// `LocalSampleLogger.CAPACITY`. +pub const CAPACITY: usize = 240; +/// `AbstractDebugChart.CHART_HEIGHT`. +pub const CHART_HEIGHT: i32 = 60; +/// `TpsDebugDimensions`: a tick sample's values. +pub const FULL_TICK: usize = 0; +pub const TICK_SERVER_METHOD: usize = 1; +pub const SCHEDULED_TASKS: usize = 2; +pub const IDLE: usize = 3; + +/// `LocalSampleLogger`: the last [`CAPACITY`] samples, oldest first; a +/// sample has up to four values (`TpsDebugDimensions`), the first the main. +#[derive(Clone, Debug, Default)] +pub struct SampleLogger { + samples: VecDeque<[i64; 4]>, +} +impl SampleLogger { + /// `logSample`. + pub fn log(&mut self, value: i64) { + self.log_full([value, 0, 0, 0]); + } + /// `logFullSample`. + pub fn log_full(&mut self, sample: [i64; 4]) { + if self.samples.len() == CAPACITY { + self.samples.pop_front(); + } + self.samples.push_back(sample); + } + pub fn len(&self) -> usize { + self.samples.len() + } + pub fn is_empty(&self) -> bool { + self.samples.is_empty() + } + pub fn reset(&mut self) { + self.samples.clear(); + } + fn get(&self, index: usize, dimension: usize) -> i64 { + self.samples[index][dimension] + } +} + +/// `DebugScreenOverlay`'s chart switches and the samples behind them. +#[derive(Clone, Debug, Default)] +pub struct DebugCharts { + /// `renderFpsCharts` (F3+2). + pub fps: bool, + /// `renderNetworkCharts` (F3+3). + pub network: bool, + /// `renderLightmapTexture` (F3+4). + pub lightmap: bool, + /// `frameTimeLogger`: nanoseconds between frames. + pub frame_times: SampleLogger, + /// `tickTimeLogger`: the integrated server's ticks. + pub tick_times: SampleLogger, + /// `pingLogger`: milliseconds. + pub ping: SampleLogger, + /// `bandwidthLogger`: bytes received per tick. + pub bandwidth: SampleLogger, + previous_tick: Option, + bytes_seen: Option, +} +impl DebugCharts { + /// `toggleFpsCharts`; `overlay` is the debug overlay's visibility. + pub fn toggle_fps(&mut self, overlay: &mut bool) { + self.fps = !*overlay || !self.fps; + if self.fps { + *overlay = true; + self.network = false; + self.lightmap = false; + } + } + /// `toggleNetworkCharts`. + pub fn toggle_network(&mut self, overlay: &mut bool) { + self.network = !*overlay || !self.network; + if self.network { + *overlay = true; + self.fps = false; + self.lightmap = false; + } + } + /// `toggleLightmapTexture`. + pub fn toggle_lightmap(&mut self, overlay: &mut bool) { + self.lightmap = !*overlay || !self.lightmap; + if self.lightmap { + *overlay = true; + self.fps = false; + self.network = false; + } + } + /// `reset`: leaving a world. + pub fn reset(&mut self) { + self.tick_times.reset(); + self.ping.reset(); + self.bandwidth.reset(); + self.previous_tick = None; + self.bytes_seen = None; + } + /// One integrated server tick that started at `started` and ran its + /// tick method for `method` (`MinecraftServer.logFullTickTime` and + /// `logTickMethodTime`): the full tick runs from one start to the next, + /// and what the tick method leaves of it is idle. + pub fn log_tick(&mut self, started: Instant, method: Duration) { + let method = method.as_nanos() as i64; + let full = self + .previous_tick + .map_or(method, |p| (started - p).as_nanos() as i64) + .max(method); + self.previous_tick = Some(started); + self.tick_times.log_full([full, method, 0, full - method]); + } + /// `BandwidthDebugMonitor.tick`: the bytes received since the last + /// tick, from the connection's running total. + pub fn log_bandwidth(&mut self, total: i64) { + if let Some(seen) = self.bytes_seen { + self.bandwidth.log(total - seen); + } + self.bytes_seen = Some(total); + } + /// The charts along the bottom of the screen (`extractRenderState`): + /// frame times left and tick times right, or bandwidth left (remote + /// servers only) and ping right. `mspt` is the level's milliseconds + /// per tick. + pub fn draw( + &self, + font: &Font, + width: i32, + height: i32, + framerate_limit: u32, + mspt: f32, + remote: bool, + ) -> Vec { + let mut out = Vec::new(); + let max_width = width / 2; + let chart_width = Chart::width(max_width); + if self.fps { + let fps = Chart::Fps { framerate_limit }; + out.extend(fps.draw(font, &self.frame_times, 0, chart_width, height)); + if !self.tick_times.is_empty() { + let tps = Chart::Tps { mspt }; + out.extend(tps.draw( + font, + &self.tick_times, + width - chart_width, + chart_width, + height, + )); + } + } + if self.network { + if remote { + out.extend(Chart::Bandwidth.draw(font, &self.bandwidth, 0, chart_width, height)); + } + out.extend(Chart::Ping.draw( + font, + &self.ping, + width - chart_width, + chart_width, + height, + )); + } + out + } +} + +/// The lightmap view (`showLightmapTexture`): the 16 by 16 texture at 64 +/// by 64 in the bottom right corner on a black border, sky light up and +/// block light right (the blit flips the texture's rows). `pixels` are RGBA +/// rows of sky level by block level. +pub fn lightmap(pixels: &[u8; 16 * 16 * 4], width: i32, height: i32) -> Vec { + let (x, y) = (width - 64 - 2, height - 64 - 2); + let mut out = vec![fill(x - 1, y - 1, x + 64 + 1, y + 64 + 1, 0xFF00_0000)]; + for (i, p) in pixels.as_chunks::<4>().0.iter().enumerate() { + let (sky, block) = ((i / 16) as i32, (i % 16) as i32); + let color = argb(255, u32::from(p[0]), u32::from(p[1]), u32::from(p[2])); + let (cx, cy) = (x + block * 4, y + (15 - sky) * 4); + out.push(fill(cx, cy, cx + 4, cy + 4, color)); + } + out +} + +/// The four charts and what each needs to scale its bars. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Chart { + /// `FpsDebugChart`: frame durations in nanoseconds; the frame rate limit + /// option (`maxFps`). + Fps { framerate_limit: u32 }, + /// `TpsDebugChart`: tick samples in nanoseconds; the level's + /// milliseconds per tick. + Tps { mspt: f32 }, + /// `PingDebugChart`: round trips in milliseconds. + Ping, + /// `BandwidthDebugChart`: bytes received per tick. + Bandwidth, +} + +/// The labels' colour and the backdrop of the box and shaded labels. +const LABEL: u32 = 0xFFE0_E0E0; +const BACKDROP: u32 = 0x9050_5050; +const WHITE: u32 = 0xFFFF_FFFF; +const GREEN: u32 = 0xFF00_FF00; +const YELLOW: u32 = 0xFFFF_FF00; +const RED: u32 = 0xFFFF_0000; +const CYAN: u32 = 0xFF00_FFFF; +/// `BandwidthDebugChart.MID_COLOR`. +const LAVENDER: u32 = 0xFFA0_A0FF; +/// `TpsDebugChart`'s bar parts. +const TICK_METHOD_COLOR: u32 = 0xFF99_1111; +const TASK_COLOR: u32 = 0xFFBA_995F; +const OTHER_COLOR: u32 = 0xFF5F_0E8C; +const MEGABYTE: f64 = 1_048_576.0; + +impl Chart { + /// `AbstractDebugChart.getWidth`. + pub fn width(max_width: i32) -> i32 { + (CAPACITY as i32 + 2).min(max_width) + } + /// `getFullHeight`: the box and the min/avg/max line above it. + pub fn full_height() -> i32 { + CHART_HEIGHT + 9 + } + /// `AbstractDebugChart.extractRenderState`. + pub fn draw( + self, + font: &Font, + samples: &SampleLogger, + left: i32, + width: i32, + bottom: i32, + ) -> Vec { + let mut out = vec![fill( + left, + bottom - CHART_HEIGHT, + left + width, + bottom, + BACKDROP, + )]; + let (mut sum, mut min, mut max) = (0i64, i64::from(i32::MAX), i64::from(i32::MIN)); + let start = CAPACITY.saturating_sub((width - 2).max(0) as usize); + let count = samples.len().saturating_sub(start); + for i in 0..count { + let x = left + i as i32 + 1; + let index = start + i; + let value = self.aggregated(samples, index); + min = min.min(value); + max = max.max(value); + sum += value; + self.bars(&mut out, samples, bottom, x, index); + } + horizontal_line( + &mut out, + left, + left + width - 1, + bottom - CHART_HEIGHT, + WHITE, + ); + horizontal_line(&mut out, left, left + width - 1, bottom - 1, WHITE); + vertical_line(&mut out, left, bottom - CHART_HEIGHT, bottom, WHITE); + vertical_line( + &mut out, + left + width - 1, + bottom - CHART_HEIGHT, + bottom, + WHITE, + ); + if count > 0 { + let y = bottom - CHART_HEIGHT - 9; + let min_text = format!("{} min", self.display(min as f64)); + let avg_text = format!("{} avg", self.display(sum as f64 / count as f64)); + let max_text = format!("{} max", self.display(max as f64)); + text(&mut out, min_text, left + 2, y, LABEL, true); + let avg_x = left + width / 2 - font.width(&avg_text) as i32 / 2; + text(&mut out, avg_text, avg_x, y, LABEL, true); + let max_x = left + width - font.width(&max_text) as i32 - 2; + text(&mut out, max_text, max_x, y, LABEL, true); + } + self.lines_and_labels(&mut out, font, left, width, bottom); + out + } + fn bars( + self, + out: &mut Vec, + samples: &SampleLogger, + bottom: i32, + x: i32, + index: usize, + ) { + let value = samples.get(index, 0); + let height = self.height(value as f64); + out.push(fill(x, bottom - height, x + 1, bottom, self.color(value))); + if let Chart::Tps { .. } = self { + let method = samples.get(index, TICK_SERVER_METHOD); + let method_h = self.height(method as f64); + out.push(fill(x, bottom - method_h, x + 1, bottom, TICK_METHOD_COLOR)); + let tasks = samples.get(index, SCHEDULED_TASKS); + let tasks_h = self.height(tasks as f64); + out.push(fill( + x, + bottom - method_h - tasks_h, + x + 1, + bottom - method_h, + TASK_COLOR, + )); + let other = value - samples.get(index, IDLE) - method - tasks; + let other_h = self.height(other as f64); + out.push(fill( + x, + bottom - other_h - tasks_h - method_h, + x + 1, + bottom - tasks_h - method_h, + OTHER_COLOR, + )); + } + } + /// `getValueForAggregation`: a tick's time without its idle part. + fn aggregated(self, samples: &SampleLogger, index: usize) -> i64 { + match self { + Chart::Tps { .. } => samples.get(index, 0) - samples.get(index, IDLE), + _ => samples.get(index, 0), + } + } + /// `extractAdditionalLinesAndLabels`. + fn lines_and_labels( + self, + out: &mut Vec, + font: &Font, + left: i32, + width: i32, + bottom: i32, + ) { + match self { + Chart::Fps { framerate_limit } => { + shaded(out, font, "30 fps", left + 1, bottom - CHART_HEIGHT + 1); + shaded(out, font, "60 fps", left + 1, bottom - 30 + 1); + horizontal_line(out, left, left + width - 1, bottom - 30, WHITE); + if framerate_limit > 0 && framerate_limit <= 250 { + let y = bottom - self.height(1.0e9 / f64::from(framerate_limit)) - 1; + horizontal_line(out, left, left + width - 1, y, CYAN); + } + } + Chart::Tps { mspt } => { + let tps = 1000.0 / mspt; + shaded( + out, + font, + &format!("{tps:.1} tps"), + left + 1, + bottom - CHART_HEIGHT + 1, + ); + } + Chart::Ping => shaded(out, font, "500 ms", left + 1, bottom - CHART_HEIGHT + 1), + Chart::Bandwidth => { + for bytes in [64.0, 1024.0, 16384.0] { + let y = bottom - bandwidth_height(bytes); + shaded(out, font, &bandwidth_display(bytes), left + 1, y + 1); + horizontal_line(out, left, left + width - 1, y, WHITE); + } + let y = bottom - bandwidth_height(MEGABYTE) + 1; + shaded(out, font, &bandwidth_display(MEGABYTE), left + 1, y); + } + } + } + /// `toDisplayString`. + fn display(self, sample: f64) -> String { + match self { + Chart::Fps { .. } | Chart::Tps { .. } => format!("{} ms", java_round(sample / 1.0e6)), + Chart::Ping => format!("{} ms", java_round(sample)), + Chart::Bandwidth => bandwidth_display(sample * 20.0), + } + } + /// `getSampleHeight`. + fn height(self, sample: f64) -> i32 { + match self { + Chart::Fps { .. } => java_round(sample / 1.0e6 * 60.0 / 33.333333333333336) as i32, + Chart::Tps { mspt } => java_round(sample / 1.0e6 * 60.0 / f64::from(mspt)) as i32, + Chart::Ping => java_round(sample * 60.0 / 500.0) as i32, + Chart::Bandwidth => bandwidth_height(sample * 20.0), + } + } + /// `getSampleColor`. + fn color(self, sample: i64) -> u32 { + let s = sample as f64; + match self { + Chart::Fps { .. } => gradient(s / 1.0e6, 0.0, GREEN, 28.0, YELLOW, 56.0, RED), + Chart::Tps { mspt } => { + let m = f64::from(mspt); + gradient(s / 1.0e6, m, GREEN, m * 1.125, YELLOW, m * 1.25, RED) + } + Chart::Ping => gradient(s, 0.0, GREEN, 250.0, YELLOW, 500.0, RED), + Chart::Bandwidth => gradient(s * 20.0, 0.0, CYAN, 8192.0, LAVENDER, 1.048576e7, RED), + } + } +} + +/// `BandwidthDebugChart.toDisplayStringInternal`. +fn bandwidth_display(bytes_per_second: f64) -> String { + if bytes_per_second >= MEGABYTE { + format!("{:.1} MiB/s", bytes_per_second / MEGABYTE) + } else if bytes_per_second >= 1024.0 { + format!("{:.1} KiB/s", bytes_per_second / 1024.0) + } else { + format!("{} B/s", bytes_per_second.floor() as i64) + } +} +/// `BandwidthDebugChart.getSampleHeightInternal`: logarithmic, 1 MiB/s at +/// the top. +fn bandwidth_height(bytes_per_second: f64) -> i32 { + java_round((bytes_per_second + 1.0).ln() * 60.0 / MEGABYTE.ln()) as i32 +} +/// `Math.round(double)`: halves round up. +fn java_round(v: f64) -> i64 { + (v + 0.5).floor() as i64 +} +/// `AbstractDebugChart.getSampleColor(sample, min, minColor, mid, ...)`. +fn gradient( + sample: f64, + min: f64, + min_color: u32, + mid: f64, + mid_color: u32, + max: f64, + max_color: u32, +) -> u32 { + let sample = sample.clamp(min, max); + if sample < mid { + srgb_lerp(((sample - min) / (mid - min)) as f32, min_color, mid_color) + } else { + srgb_lerp(((sample - mid) / (max - mid)) as f32, mid_color, max_color) + } +} +/// `ARGB.srgbLerp`: each channel by `Mth.lerpInt`. +fn srgb_lerp(alpha: f32, p0: u32, p1: u32) -> u32 { + let channel = |shift: u32| { + let (a, b) = (((p0 >> shift) & 255) as i32, ((p1 >> shift) & 255) as i32); + (a + (alpha * (b - a) as f32).floor() as i32) as u32 + }; + argb(channel(24), channel(16), channel(8), channel(0)) +} +/// `GuiGraphicsExtractor.horizontalLine`. +fn horizontal_line(out: &mut Vec, x0: i32, x1: i32, y: i32, color: u32) { + out.push(fill(x0.min(x1), y, x0.max(x1) + 1, y + 1, color)); +} +/// `GuiGraphicsExtractor.verticalLine`. +fn vertical_line(out: &mut Vec, x: i32, y0: i32, y1: i32, color: u32) { + out.push(fill(x, y0.min(y1) + 1, x + 1, y0.max(y1), color)); +} +fn text(out: &mut Vec, s: String, x: i32, y: i32, color: u32, shadow: bool) { + out.push(GuiDraw::Text { + text: Text::literal(s), + x, + y, + color, + shadow, + }); +} +/// `extractStringWithShade`: a label on a dark backdrop, without shadow. +fn shaded(out: &mut Vec, font: &Font, s: &str, x: i32, y: i32) { + out.push(fill(x, y, x + font.width(s) as i32 + 1, y + 9, BACKDROP)); + text(out, s.to_owned(), x + 1, y + 1, LABEL, false); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_logger_keeps_the_last_240_samples() { + let mut l = SampleLogger::default(); + for i in 0..300 { + l.log(i); + } + assert_eq!(l.len(), CAPACITY); + assert_eq!(l.get(0, 0), 60); + assert_eq!(l.get(CAPACITY - 1, 0), 299); + } + + #[test] + fn chart_toggles_show_the_overlay_and_exclude_each_other() { + let mut c = DebugCharts::default(); + let mut overlay = false; + c.toggle_fps(&mut overlay); + assert!(overlay && c.fps); + c.toggle_network(&mut overlay); + assert!(c.network && !c.fps); + c.toggle_network(&mut overlay); + assert!(!c.network && overlay); + c.toggle_lightmap(&mut overlay); + c.toggle_fps(&mut overlay); + assert!(c.fps && !c.lightmap); + // With the overlay hidden, the key shows it again with the chart on. + c.toggle_fps(&mut overlay); + overlay = false; + c.toggle_fps(&mut overlay); + assert!(overlay && c.fps); + } + + #[test] + fn the_lightmap_puts_full_sky_light_at_the_top_left() { + let mut pixels = [0u8; 16 * 16 * 4]; + // Sky 15, block 0: the last row's first texel. + pixels[15 * 64..15 * 64 + 4].copy_from_slice(&[10, 20, 30, 255]); + let draws = lightmap(&pixels, 427, 240); + assert_eq!(draws[0], fill(360, 173, 426, 239, 0xFF00_0000)); + assert_eq!(draws.len(), 257); + assert!(draws.contains(&fill(361, 174, 365, 178, 0xFF0A_141E))); + } + + #[test] + fn ticks_and_bandwidth_log_their_differences() { + let mut c = DebugCharts::default(); + let t0 = Instant::now(); + c.log_tick(t0, Duration::from_millis(5)); + c.log_tick(t0 + Duration::from_millis(50), Duration::from_millis(7)); + assert_eq!( + c.tick_times.samples[1], + [50_000_000, 7_000_000, 0, 43_000_000] + ); + c.log_bandwidth(1000); + c.log_bandwidth(1600); + assert_eq!(c.bandwidth.len(), 1); + assert_eq!(c.bandwidth.get(0, 0), 600); + } + + #[test] + fn heights_match_vanilla_scales() { + let fps = Chart::Fps { + framerate_limit: 260, + }; + // 33.3 ms (30 fps) fills the chart; 16.7 ms half of it. + assert_eq!(fps.height(33_333_333.0), 60); + assert_eq!(fps.height(16_666_667.0), 30); + let tps = Chart::Tps { mspt: 50.0 }; + assert_eq!(tps.height(25e6), 30); + assert_eq!(Chart::Ping.height(250.0), 30); + // 1 MiB/s at the top; 52 bytes per tick is 1 KiB/s. + assert_eq!(bandwidth_height(MEGABYTE), 60); + assert_eq!(Chart::Bandwidth.height(51.2), 30); + } + + #[test] + fn labels_match_vanilla_formats() { + assert_eq!( + Chart::Fps { framerate_limit: 0 }.display(16_500_000.0), + "17 ms" + ); + assert_eq!(Chart::Ping.display(12.4), "12 ms"); + assert_eq!(Chart::Bandwidth.display(3.0), "60 B/s"); + assert_eq!(Chart::Bandwidth.display(100.0), "2.0 KiB/s"); + assert_eq!(bandwidth_display(MEGABYTE), "1.0 MiB/s"); + } + + #[test] + fn colours_go_green_yellow_red() { + let fps = Chart::Fps { framerate_limit: 0 }; + assert_eq!(fps.color(0), GREEN); + assert_eq!(fps.color(28_000_000), YELLOW); + assert_eq!(fps.color(100_000_000), RED); + // Halfway between green and yellow: Mth.lerpInt floors. + assert_eq!(fps.color(14_000_000), 0xFF7F_FF00); + let tps = Chart::Tps { mspt: 50.0 }; + assert_eq!(tps.color(10_000_000), GREEN); + assert_eq!(Chart::Bandwidth.color(0), CYAN); + } +} diff --git a/crates/horizon-client/src/first_person.rs b/crates/horizon-client/src/first_person.rs index ba40f2679..a25d9f537 100644 --- a/crates/horizon-client/src/first_person.rs +++ b/crates/horizon-client/src/first_person.rs @@ -31,7 +31,9 @@ pub enum ItemPose { }, } -/// `submitArmWithItem`: the main-hand item pose, before the model transform. +/// `submitArmWithItem`: the pose of an item in the hand on the `left` or +/// right arm, before the model transform. Only the main hand's charged +/// crossbow is turned aside. pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) -> glam::Mat4 { use glam::{Mat4, Vec3}; use horizon_core::geometry::trig::Mth; @@ -127,6 +129,25 @@ pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) - m } +/// `FirstPersonHandsAndItems.evaluateWhichHandsToRender`: whether the main +/// and the off hand show, from what each holds (item and whether it is a +/// charged crossbow) and the item in use with its hand. A bow or crossbow +/// being drawn hides the other hand, and a charged crossbow in the main hand +/// hides the off hand unless the off hand is the one in use. +pub fn hands_to_render(held: [Option<(&str, bool)>; 2], using: Option<(Hand, &str)>) -> [bool; 2] { + let bow_like = |id: &str| matches!(id, "minecraft:bow" | "minecraft:crossbow"); + let charged_crossbow = + |h: Option<(&str, bool)>| h.is_some_and(|(id, c)| c && id == "minecraft:crossbow"); + if !held.iter().flatten().any(|&(id, _)| bow_like(id)) { + return [true, true]; + } + match using { + None => [true, !charged_crossbow(held[0])], + Some((hand, id)) if bow_like(id) => [hand == Hand::Main, hand == Hand::Off], + Some((hand, _)) => [true, !(hand == Hand::Main && charged_crossbow(held[1]))], + } +} + /// `InteractionHand`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Hand { @@ -719,6 +740,36 @@ impl Clicks { mod tests { use super::*; #[test] + fn drawing_a_bow_or_holding_a_charged_crossbow_hides_a_hand() { + let (bow, apple) = ( + Some(("minecraft:bow", false)), + Some(("minecraft:apple", false)), + ); + let charged = Some(("minecraft:crossbow", true)); + assert_eq!(hands_to_render([apple, apple], None), [true, true]); + assert_eq!(hands_to_render([bow, apple], None), [true, true]); + assert_eq!(hands_to_render([charged, apple], None), [true, false]); + assert_eq!(hands_to_render([apple, charged], None), [true, true]); + let drawing = |hand| Some((hand, "minecraft:bow")); + assert_eq!( + hands_to_render([bow, apple], drawing(Hand::Main)), + [true, false] + ); + assert_eq!( + hands_to_render([apple, bow], drawing(Hand::Off)), + [false, true] + ); + let eating = |hand| Some((hand, "minecraft:apple")); + assert_eq!( + hands_to_render([apple, charged], eating(Hand::Main)), + [true, false] + ); + assert_eq!( + hands_to_render([charged, apple], eating(Hand::Off)), + [true, true] + ); + } + #[test] fn a_swing_lasts_its_duration_and_restarts_after_half() { let mut s = SwingState::default(); assert!(s.start_if_able(Hand::Main, SwingAnimation::DEFAULT, 6)); diff --git a/crates/horizon-client/src/front.rs b/crates/horizon-client/src/front.rs index 72b70a56b..e6224683f 100644 --- a/crates/horizon-client/src/front.rs +++ b/crates/horizon-client/src/front.rs @@ -154,6 +154,7 @@ impl Title { seed, creative, focus, + .. } => { let caret = (self.started.elapsed().as_millis() / 500).is_multiple_of(2); create_page(ui, x, w, name, seed, *creative, *focus, caret); @@ -379,14 +380,7 @@ impl Title { }; } } - CREATE => { - self.mode = Mode::Create { - name: "New World".into(), - seed: String::new(), - creative: false, - focus: 0, - } - } + CREATE => self.mode = Title::new_world(), DELETE_WORLD => { if let Some(world) = selected.and_then(|i| worlds.get(i)).cloned() { self.mode = Mode::Delete { world }; @@ -814,6 +808,7 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) { selected, pings, lan, + .. } => { let games = lan.games(); let sub = match servers.len() { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index e8c5fb0f4..c58dcefe0 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -116,6 +116,7 @@ mod titles; mod tnt; mod totem; mod trading; +mod trial_spawner; mod trident; mod villagers; mod wandering_trader; @@ -136,6 +137,7 @@ use horizon_client::{ creative::{Creative, Names}, entities::{Experience, ExperienceOrb, ItemEntity}, environment::Environment, + first_person::Hand, gfx::{Frame, Renderer}, hud::{HudAtlas, HudBatch, rgba}, hud_layout, hud_overlays, @@ -751,6 +753,10 @@ struct Game<'a> { ambience: horizon_client::ambience::Ambience, /// The sound engine was told the game paused (pauseAllExcept). sound_paused: bool, + /// Minecarts whose `MinecartSoundInstance` is playing. + cart_sounds: HashSet, + /// The minecart the riding sounds were started for (`LocalPlayer.startRiding`). + riding_cart_sounds: Option, dropped: Vec, next_entity: u32, particles: horizon_client::particles::ParticleEngine, @@ -796,6 +802,9 @@ struct Game<'a> { armor: [Option; 4], /// The off hand (Inventory slot 40, saved as slot 150; menu slot 504 here). offhand: Option, + /// The hand an item use acts with (`InteractionHand`): the off hand only + /// for its turn in `use_item` and while its item is being used. + hand: Hand, /// The shield's item cooldown after an axe disabled it (ticks). shield_cooldown: u32, /// The source of a command run through /execute (the player otherwise). @@ -949,6 +958,8 @@ struct Game<'a> { /// KeyboardHandler's debug key state (game/debug_keys.rs), the physical /// keys held, and the debug renderers F3+B and F3+G switch on. debug_keys: horizon_client::debug_keys::DebugKeys, + /// The F3 overlay's charts (F3+2, F3+3). + debug_charts: horizon_client::debug_chart::DebugCharts, show_hitboxes: bool, show_chunk_borders: bool, /// PauseScreen.showPauseMenu (false after F3+Escape). @@ -1192,8 +1203,36 @@ impl Game<'_> { } None } + /// The stack in the hand that acts (`getItemInHand(hand)`). fn held(&self) -> Option<&ItemStack> { - self.inventory[self.selected].as_ref() + self.stack_in(self.held_slot()) + } + fn held_mut(&mut self) -> &mut Option { + self.stack_in_mut(self.held_slot()) + } + /// The slot of the hand that acts: the selected one, or `OFFHAND_SLOT`. + fn held_slot(&self) -> usize { + match self.hand { + Hand::Main => self.selected, + Hand::Off => shield::OFFHAND_SLOT, + } + } + /// `LivingEntity.getUsedItemHand`: the hand of the item in use. + fn used_hand(&self) -> Option { + self.using.map(|(slot, _)| { + if slot == shield::OFFHAND_SLOT { + Hand::Off + } else { + Hand::Main + } + }) + } + /// Run `f` with `hand` acting (`held`, `consume_held`, `swing_arm`). + fn with_hand(&mut self, hand: Hand, f: impl FnOnce(&mut Self) -> T) -> T { + let prior = std::mem::replace(&mut self.hand, hand); + let out = f(self); + self.hand = prior; + out } /// Inventory.add: returns the stack that did not fit. fn give(&mut self, mut stack: ItemStack) -> Option { @@ -2232,20 +2271,22 @@ impl Game<'_> { self.process_level_events()?; Ok(()) } - fn use_item(&mut self) -> Result<()> { + /// The hand whose use ended the click, if any. + fn use_item(&mut self) -> Result> { self.with_player_actor(|game| game.use_item_as_player()) } - fn use_item_as_player(&mut self) -> Result<()> { + /// `Minecraft.startUseItem`: the main hand, then the off hand. + fn use_item_as_player(&mut self) -> Result> { // Spectators only look (MultiPlayerGameMode.useItemOn/useItem pass). if self.spectator() { - return Ok(()); + return Ok(None); } // A carrot or warped fungus on a stick boosts the ridden pig or strider. if self.riding.is_some() && let Some(item) = self.held().map(|s| s.item.clone()) && self.use_steering_stick(&item) { - return Ok(()); + return Ok(Some(Hand::Main)); } if self.interact_frame() || self.interact_armor_stand() @@ -2254,7 +2295,7 @@ impl Game<'_> { || self.interact_mob()? || self.interact_knot() { - return Ok(()); + return Ok(Some(Hand::Main)); } // An EntityHitResult may fall through to Item.use, never to useItemOn. let block_hit = if self.entity_targeted() { @@ -2262,59 +2303,72 @@ impl Game<'_> { } else { self.pick() }; + for hand in Hand::BOTH { + if self.with_hand(hand, |game| game.use_hand(block_hit.as_ref()))? { + return Ok(Some(hand)); + } + } + Ok(None) + } + /// One hand's turn in `startUseItem`: `useItemOn` the block aimed at, + /// then `useItem`. Whether the click ends here (it acted or failed). + fn use_hand(&mut self, block_hit: Option<&Hit>) -> Result { + // isSecondaryUseActive with something in either hand keeps blocks + // from reacting. let sneaking = self.keys.contains(&KeyCode::ShiftLeft); - let mut anchor_passed = None; - // MultiPlayerGameMode.useItemOn: blocks react first unless sneaking with an item. - if !(sneaking && self.held().is_some()) - && let Some(hit) = block_hit.as_ref() + let hands_full = self.stack_in(self.selected).is_some() || self.offhand.is_some(); + let mut anchor_passed = false; + // MultiPlayerGameMode.useItemOn: blocks react first. + if !(sneaking && hands_full) + && let Some(hit) = block_hit { let held = self.held().cloned(); if self.use_lectern(hit.pos, held.as_ref()) { self.swing_arm(); - return Ok(()); + return Ok(true); } if self.use_jukebox(hit.pos, held.as_ref()) { self.swing_arm(); - return Ok(()); + return Ok(true); } if self.use_composter(hit.pos, held.as_ref()) { self.swing_arm(); - return Ok(()); + return Ok(true); } match self.use_respawn_anchor(hit.pos, held.as_ref())? { respawn_anchor::AnchorUse::Charged => { self.swing_arm(); - return Ok(()); + return Ok(true); } // The main hand passes; its item is used, then the off hand's glowstone. - respawn_anchor::AnchorUse::Pass => anchor_passed = Some(hit.pos), + respawn_anchor::AnchorUse::Pass => anchor_passed = true, respawn_anchor::AnchorUse::Other => {} } - let face = match hit.face { - [0, 1, 0] => Direction::Up, - [0, -1, 0] => Direction::Down, - [0, 0, -1] => Direction::North, - [0, 0, 1] => Direction::South, - [-1, 0, 0] => Direction::West, - _ => Direction::East, - }; - let player = PlayerContext { - yaw: self.yaw, - pitch: self.pitch, - may_build: self.may_build(), - can_eat: self.creative - || self - .player - .as_ref() - .is_some_and(|p| p.health.food.food < 20), - game_master: false, - }; - let at = Vec3::new(hit.point[0], hit.point[1], hit.point[2]); - let item = held.as_ref().map(|s| s.item.to_string()); - let result = if anchor_passed.is_some() { - horizon_world::level::InteractionResult::Pass - } else { - self.with_level(|b, level, ticks| { + // TRY_WITH_EMPTY_HAND: only the main hand's turn uses the block + // itself (useWithoutItem). + if !anchor_passed && self.hand == Hand::Main { + let face = match hit.face { + [0, 1, 0] => Direction::Up, + [0, -1, 0] => Direction::Down, + [0, 0, -1] => Direction::North, + [0, 0, 1] => Direction::South, + [-1, 0, 0] => Direction::West, + _ => Direction::East, + }; + let player = PlayerContext { + yaw: self.yaw, + pitch: self.pitch, + may_build: self.may_build(), + can_eat: self.creative + || self + .player + .as_ref() + .is_some_and(|p| p.health.food.food < 20), + game_master: false, + }; + let at = Vec3::new(hit.point[0], hit.point[1], hit.point[2]); + let item = held.as_ref().map(|s| s.item.to_string()); + let result = self.with_level(|b, level, ticks| { b.use_item_on( level, ticks, @@ -2324,29 +2378,22 @@ impl Game<'_> { player, item.as_deref(), ) - }) - }; - self.process_level_events()?; - if result.consumes_action() { - self.swing_arm(); - return Ok(()); + }); + self.process_level_events()?; + if result.consumes_action() { + self.swing_arm(); + return Ok(true); + } } } let Some(stack) = self.held().cloned() else { - // Minecraft.startUseItem goes on to the off hand. - if let Some(pos) = anchor_passed - && self.charge_anchor_from_offhand(pos)? - { - return Ok(()); - } - self.use_offhand(); - return Ok(()); + return Ok(false); }; let Some(info) = self.res.items.get(&stack.item).cloned() else { - return Ok(()); + return Ok(false); }; if block_hit.is_some() && (self.use_bone_meal(&stack)? || self.ignite_tnt(&stack)?) { - return Ok(()); + return Ok(true); } use horizon_client::first_person::UseResult; let swings = self.swings_started; @@ -2355,18 +2402,18 @@ impl Game<'_> { if (UseResult::Success { swing }).should_swing(swings, self.swings_started) { self.swing_arm(); } - return Ok(()); + return Ok(true); } - UseResult::Fail => return Ok(()), + UseResult::Fail => return Ok(true), UseResult::Pass => {} } if self.use_potion_item(&stack)? || ((block_hit.is_some() || !stack.item.ends_with("_spawn_egg")) && self.throw_item(&stack)?) { - return Ok(()); + return Ok(true); } - if self.raise_shield(self.selected) + if self.raise_shield(self.held_slot()) || self.use_fishing_rod(&stack) || self.use_crossbow(&stack) || self.use_trident(&stack) @@ -2377,27 +2424,29 @@ impl Game<'_> { // placed first (useItemOn before useItem). || (!(info.block.is_some() && block_hit.is_some()) && self.equip_from_hand(&stack)) { - return Ok(()); + return Ok(true); } if &*stack.item == "minecraft:spyglass" { self.use_spyglass(); - return Ok(()); + return Ok(true); } if &*stack.item == "minecraft:bow" { - if self.using.is_none() && (self.creative || self.arrow_slot().is_some()) { - self.using = Some((self.selected, 0)); + if self.using.is_none() + && (self.creative || self.projectile_slot("minecraft:bow").is_some()) + { + self.using = Some((self.held_slot(), 0)); } - return Ok(()); + return Ok(true); } // Block foods attempt placement before starting consumption. if !(info.block.is_some() && block_hit.is_some()) && self.start_eating(&info) { - return Ok(()); + return Ok(true); } // BoatItem.use also performs its own fluid/block raycast. if self.place_boat(&stack) { - return Ok(()); + return Ok(true); } - if let Some(hit) = block_hit.as_ref() + if let Some(hit) = block_hit && (self.launch_firework(hit, &stack) || self.place_minecart(hit, &stack) || self.place_painting(hit, &stack) @@ -2405,28 +2454,20 @@ impl Game<'_> { || self.place_armor_stand(hit, &stack) || self.place_end_crystal(hit, &stack)) { - return Ok(()); + return Ok(true); } if self.use_ender_eye(&stack, block_hit.is_some())? { - return Ok(()); + return Ok(true); } let Some(hit) = block_hit else { - self.use_offhand(); - return Ok(()); + return Ok(false); }; if info.block.is_none() { - if let Some(pos) = anchor_passed - && self.charge_anchor_from_offhand(pos)? - { - return Ok(()); - } - self.use_offhand(); - return Ok(()); + return Ok(false); } if !self.may_build() { // ItemStack.useOn passes in adventure mode; useItem eats. - self.start_eating(&info); - return Ok(()); + return Ok(self.start_eating(&info)); } let face = match hit.face { [0, 1, 0] => Direction::Up, @@ -2456,7 +2497,7 @@ impl Game<'_> { if self.start_eating(&info) { self.stats.add("used", &stack.item, 1); } - return Ok(()); + return Ok(true); }; let target = [pos.x, pos.y, pos.z]; if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) { @@ -2493,9 +2534,9 @@ impl Game<'_> { self.consume_held(); // SolidBucketItem.useOn: BucketItem.getEmptySuccessItem in hand. if solid_bucket && !self.creative { - self.inventory[self.selected] = Some(ItemStack::new("minecraft:bucket", 1)); + *self.held_mut() = Some(ItemStack::new("minecraft:bucket", 1)); } - Ok(()) + Ok(true) } /// `Consumable.startConsuming` for held food the player can eat /// (`Player.canEat`): the right click is held for `consume_seconds`. @@ -2510,7 +2551,7 @@ impl Game<'_> { return false; } if self.using.is_none() { - self.using = Some((self.selected, 0)); + self.using = Some((self.held_slot(), 0)); } true } @@ -2518,16 +2559,24 @@ impl Game<'_> { if self.creative { return; } - if let Some(s) = self.inventory[self.selected].as_mut() { + let cell = self.held_mut(); + if let Some(s) = cell.as_mut() { s.count -= 1; if s.count == 0 { - self.inventory[self.selected] = None; + *cell = None; } } } fn tick_using(&mut self) { // ItemCooldowns.tick for the shield. self.shield_cooldown = self.shield_cooldown.saturating_sub(1); + let Some(hand) = self.used_hand() else { + return; + }; + self.with_hand(hand, Self::tick_used_item); + } + /// `LivingEntity.updatingUsingItem` for the item in use, its hand acting. + fn tick_used_item(&mut self) { let Some((slot, ticks)) = self.using else { return; }; @@ -2538,13 +2587,13 @@ impl Game<'_> { // Switching hotbar slots only ends a main-hand use. let hand_changed = slot != self.selected && slot != shield::OFFHAND_SLOT; if !self.right || hand_changed || self.screen != Screen::Playing { - if &*stack.item == "minecraft:bow" && slot == self.selected { + if &*stack.item == "minecraft:bow" && !hand_changed { self.release_bow(ticks); } if &*stack.item == "minecraft:spyglass" { self.stop_spyglass(); } - if &*stack.item == "minecraft:trident" && slot == self.selected { + if &*stack.item == "minecraft:trident" && !hand_changed { self.release_trident(ticks); } self.using = None; @@ -2866,6 +2915,7 @@ impl Game<'_> { } fn tick(&mut self) -> Result<()> { self.tick_debug_keys()?; + self.tick_debug_charts(); if self.remote.is_some() { return self.tick_remote(); } @@ -3656,7 +3706,7 @@ impl Game<'_> { 2 => "north (Towards negative Z)", _ => "east (Towards positive X)", }; - let lines = [ + let mut lines = vec![ format!("Horizon 26.3 (Rust) {:.0} fps", self.fps), format!( "C: {} chunks, {} sections drawn / {}", @@ -3699,7 +3749,9 @@ impl Game<'_> { self.world.day_time / 24000, self.world.day_time % 24000 ), + String::new(), ]; + lines.extend(self.debug_chart_lines()); for (i, line) in lines.iter().enumerate() { if line.is_empty() { continue; @@ -3722,6 +3774,22 @@ impl Game<'_> { false, ); } + let charts = self.debug_charts.draw( + &atlas.font, + w as i32, + h as i32, + self.settings.max_fps, + 1000.0 / self.clock.rate(), + self.remote.is_some(), + ); + hud_layout::paint(&mut batch, atlas, &charts); + if self.debug_charts.lightmap + && let Some(r) = &self.renderer + { + let view = + horizon_client::debug_chart::lightmap(&r.lightmap_pixels, w as i32, h as i32); + hud_layout::paint(&mut batch, atlas, &view); + } } if !self.ui.hide_gui && let Some((text, at)) = &self.message @@ -3805,6 +3873,7 @@ impl Game<'_> { | BlockEntity::Banner(_) | BlockEntity::CreakingHeart(_) | BlockEntity::Spawner(_) + | BlockEntity::TrialSpawner(_) | BlockEntity::Beehive(_), ) => {} None => { @@ -4055,6 +4124,7 @@ impl Game<'_> { | BlockEntity::Banner(_) | BlockEntity::CreakingHeart(_) | BlockEntity::Spawner(_) + | BlockEntity::TrialSpawner(_) | BlockEntity::Beehive(_), ) => {} None if self.mount_active() => self.draw_mount_background(batch, ox, oy), @@ -5400,6 +5470,33 @@ impl Game<'_> { } best } + /// `Player.getAttackStrengthScale(0.5)`. + fn attack_strength_scale(&self) -> f32 { + let speed = self + .held() + .and_then(|h| self.res.items.get(&h.item)) + .map_or(0.0, |i| i.attack_speed); + let delay = 20.0 / (4.0 + speed).max(0.1); + ((self.attack_ticks as f32 + 0.5) / delay).clamp(0.0, 1.0) + } + /// `Player.attack`'s sounds when a vehicle takes the hit (it always does, + /// and can't be hit critically): knockback when sprinting at full + /// strength, then strong or weak. Before `swing_arm` resets the charge. + pub(super) fn vehicle_attack_sounds(&mut self) { + let full = self.attack_strength_scale() > 0.9; + let player = self.player.as_ref(); + let from = player.map(|p| [p.position.x, p.position.y, p.position.z]); + if full && player.is_some_and(|p| p.sprinting) { + self.audio + .play("minecraft:entity.player.attack.knockback", from, 1.0, 1.0); + } + let sound = if full { + "minecraft:entity.player.attack.strong" + } else { + "minecraft:entity.player.attack.weak" + }; + self.audio.play(sound, from, 1.0, 1.0); + } /// Player.attack with the attack-strength charge, crits and knockback. fn attack(&mut self) -> bool { if self.spectator() { @@ -5446,16 +5543,8 @@ impl Game<'_> { return false; } } - let held = self.held().cloned(); - let modifiers = held - .as_ref() - .and_then(|h| self.res.items.get(&h.item)) - .map(|i| (i.attack_damage, i.attack_speed)) - .unwrap_or((0.0, 0.0)); - let damage = 1.0 + modifiers.0 + self.effect_attack_bonus(); - let speed = (4.0 + modifiers.1).max(0.1); - let delay = 20.0 / speed; - let scale = ((self.attack_ticks as f32 + 0.5) / delay).clamp(0.0, 1.0); + let damage = hand_damage + self.effect_attack_bonus(); + let scale = self.attack_strength_scale(); let mut amount = damage * (0.2 + scale * scale * 0.8); let target_kind = self.mobs[index].kind.id.clone(); let target_kind = format!("minecraft:{}", target_kind.trim_start_matches("minecraft:")); @@ -5566,6 +5655,7 @@ impl Game<'_> { self.tick_beacons(); self.tick_creaking_hearts()?; self.tick_spawners()?; + self.tick_trial_spawners()?; self.tick_beehives(); let mut lit_changes = Vec::new(); for (pos, entity) in self.world.block_entities.iter_mut() { @@ -5823,6 +5913,7 @@ impl Game<'_> { name: Option<&str>, seed: Option, creative: bool, + create: Option<&horizon_client::title::WorldOptions>, ) -> Result<()> { self.perf.world_opening(); let save_root = std::env::current_dir()?.join("saves").join(folder); @@ -5843,7 +5934,9 @@ impl Game<'_> { .map(|d| horizon_client::random_sequences::RandomSequences::from_nbt(&d)) .unwrap_or_default(); self.border = Default::default(); - let level = Level::read(&save_root).unwrap_or_else(|| Level { + let existing = Level::read(&save_root); + let created = existing.is_none(); + let level = existing.unwrap_or_else(|| Level { name: name.unwrap_or(folder).to_owned(), // WorldOptions.randomSeed when no seed was given. seed: seed.unwrap_or_else(|| { @@ -5860,6 +5953,13 @@ impl Game<'_> { ..Level::default() }); let mut level = level; + // CreateWorldScreen's choices, before streaming reads the generator. + if created && let Some(o) = create { + level.hardcore = o.hardcore; + level.difficulty = horizon_client::title::DIFFICULTIES[o.difficulty()].into(); + level.allow_commands = Some(o.commands(creative)); + horizon_client::save::write_world_gen_settings(&save_root, level.seed, o.world_gen())?; + } horizon_client::crash::set_detail("World", format!("{} (saves/{folder})", level.name)); if let Some(d) = &self.options.dimension { level.dimension = d.clone(); @@ -6301,6 +6401,7 @@ impl Game<'_> { self.save.flush(); self.session_lock = None; horizon_client::crash::clear_detail("World"); + self.debug_charts.reset(); self.streaming.paused = true; self.world = World::new(self.res.facts.air, 0); self.player = None; @@ -6445,8 +6546,7 @@ impl Game<'_> { self.0.creative } fn hand(&mut self) -> &mut Option { - let selected = self.0.selected; - &mut self.0.inventory[selected] + self.0.held_mut() } fn add(&mut self, stack: &mut ItemStack) -> bool { let before = stack.count; @@ -6478,7 +6578,7 @@ impl Game<'_> { else { return Ok(false); }; - let Some(held) = self.inventory[self.selected].as_ref() else { + let Some(held) = self.held() else { return Ok(false); }; let removes_dye = cauldron::removes_dye(&self.res.items, &held.item); @@ -6543,6 +6643,16 @@ impl Game<'_> { else { return Ok(false); }; + // playerHasBlockingItemUseIntent: a shield in the off hand is raised + // instead, unless sneaking. + let shield = self + .offhand + .as_ref() + .and_then(|s| self.res.items.get(&s.item)) + .is_some_and(|i| i.blocks_attacks.is_some()); + if shield && !self.keys.contains(&KeyCode::ShiftLeft) { + return Ok(false); + } let face_name = match face { [0, -1, 0] => "down", [0, 1, 0] => "up", @@ -6601,6 +6711,7 @@ impl Game<'_> { 1.0, ); self.damage_held(damage); + self.post_block_game_event("minecraft:block_change", pos, self.sculk_actor(), Some(new)); Ok(true) } fn set_state_named(&mut self, pos: [i32; 3], name: &str, keep: &[&str]) -> Result { @@ -6625,19 +6736,23 @@ impl Game<'_> { if self.creative { return; } - let amount = match self.inventory[self.selected].clone() { + let amount = match self.held().cloned() { Some(held) => self.durability_loss(&held, amount), None => amount, }; - if let Some(stack) = self.inventory[self.selected].as_mut() - && let Some(info) = self.res.items.get(&stack.item) - && info.max_damage > 0 + let max = self + .held() + .and_then(|s| self.res.items.get(&s.item)) + .map_or(0, |i| i.max_damage); + let cell = self.held_mut(); + if let Some(stack) = cell.as_mut() + && max > 0 { stack.damage += amount; - if stack.damage >= info.max_damage { + if stack.damage >= max { let broken = stack.item.clone(); + *cell = None; self.stats.add("broken", &broken, 1); - self.inventory[self.selected] = None; if let Some(eye) = self.eye_position() { self.audio.play( "minecraft:entity.item.break", @@ -6717,8 +6832,8 @@ impl Game<'_> { damage: 0, extra: None, }; - if self.inventory[self.selected].is_none() { - self.inventory[self.selected] = Some(filled); + if self.held().is_none() { + *self.held_mut() = Some(filled); } else if let Some(rest) = self.give(filled) && let Some(eye) = self.eye_position() { @@ -6772,7 +6887,7 @@ impl Game<'_> { } self.trigger_block("minecraft:placed_block", target, stack); if !self.creative { - self.inventory[self.selected] = Some(ItemStack::new("minecraft:bucket", 1)); + *self.held_mut() = Some(ItemStack::new("minecraft:bucket", 1)); } return Ok(UseResult::Success { swing: true }); } @@ -7014,10 +7129,7 @@ impl Game<'_> { if power < 0.1 { return; } - let arrow_slot = self - .inventory - .iter() - .position(|s| s.as_ref().is_some_and(|s| &*s.item == "minecraft:arrow")); + let arrow_slot = self.projectile_slot("minecraft:bow"); if arrow_slot.is_none() && !self.creative { return; } @@ -7041,7 +7153,7 @@ impl Game<'_> { // using the ammo, so the arrow is CREATIVE_ONLY; else setOwner(player) // lets it be picked up. let ammo = arrow_slot - .and_then(|i| self.inventory[i].clone()) + .and_then(|i| self.stack_in(i).cloned()) .unwrap_or_else(|| ItemStack::new("minecraft:arrow", 1)); if let Some(a) = arrow.arrow.as_mut() { a.set_item(&horizon_client::arrows::drawn_ammo( @@ -7078,17 +7190,19 @@ impl Game<'_> { if !self.creative && !infinity && let Some(i) = arrow_slot - && let Some(s) = self.inventory[i].as_mut() { - s.count -= 1; - if s.count == 0 { - self.inventory[i] = None; + let cell = self.stack_in_mut(i); + if let Some(s) = cell.as_mut() { + s.count -= 1; + if s.count == 0 { + *cell = None; + } } } self.damage_held(1); } - /// FirstPersonHandsAndItemsRenderer: the right arm or held item in view - /// space, converted to camera-relative world space. + /// FirstPersonHandsAndItemsRenderer: the right arm or the held items of + /// both hands in view space, converted to camera-relative world space. fn hand_geometry(&mut self, alpha: f64) -> Vec { let mut out = Vec::new(); // GameRenderer.renderItemInHand: F1 hides the hand with the HUD. @@ -7104,15 +7218,18 @@ impl Game<'_> { return out; } let a = alpha as f32; - // FirstPersonHandsAndItemsRenderer: the swing of the hand that - // swings, and its inverse arm height (the swap scale is 1 for every - // item but spears). - let attack = if self.swing.attack_hand() == horizon_client::first_person::Hand::Main { - self.swing.animation(a) - } else { - 0.0 - }; - let inverse_height = 1.0 - self.heights.interpolated(a)[0]; + // FirstPersonHandsAndItemsRenderer: the swing goes to the hand that + // swings; each hand has its inverse arm height (the swap scale is 1 + // for every item but spears). + let swing = self.swing.animation(a); + let attacks = Hand::BOTH.map(|h| { + if self.swing.attack_hand() == h { + swing + } else { + 0.0 + } + }); + let inverse_heights = self.heights.interpolated(a).map(|h| 1.0 - h); let view = horizon_client::camera::view_matrix(self.yaw, self.pitch); // The hand sway: both hands turn by a tenth of the bobs' lag. let [sway_x, sway_y] = self.sway.rotation(a, self.pitch, self.yaw); @@ -7127,15 +7244,30 @@ impl Game<'_> { ); let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); let deg = |d: f32| d.to_radians(); - let sqrt_attack = attack.sqrt(); - if self.held_map_geometry(to_world, attack, inverse_height, packed, &mut out) { + if self.held_map_geometry(to_world, attacks[0], inverse_heights[0], packed, &mut out) { return out; } - let [main_item, _] = self.visible_hand_items(); - match main_item { - None => { + let shown = self.hands_to_render(); + let used_hand = self.used_hand(); + for (i, (hand, item)) in Hand::BOTH + .into_iter() + .zip(self.visible_hand_items()) + .enumerate() + { + if !shown[i] { + continue; + } + let (attack, inverse_height) = (attacks[i], inverse_heights[i]); + let sqrt_attack = attack.sqrt(); + // The main hand on its arm, the off hand on the other one. + let left = self.settings.main_hand_left != (hand == Hand::Off); + let Some(stack) = item else { + // Only the main hand's empty arm shows. + if hand == Hand::Off { + continue; + } let Some(arm) = self.res.player_arm.clone() else { - return out; + continue; }; let Some(r) = self .res @@ -7144,7 +7276,7 @@ impl Game<'_> { .get("entity/player/wide/steve") .copied() else { - return out; + continue; }; // renderPlayerArm (right arm) let x_swing = -0.3 * (sqrt_attack * std::f32::consts::PI).sin(); @@ -7182,75 +7314,88 @@ impl Game<'_> { 0, &mut out, ); + continue; + }; + let mut owner = self.player_owner(Some(&stack)); + // The other hand may hold an equal stack: only the used + // hand's item is in use, only the main hand's selected. + owner.using_this_item &= used_hand == Some(hand); + if hand == Hand::Off { + owner.is_selected = false; + owner.is_carried = false; } - Some(stack) => { - let mut owner = self.player_owner(Some(&stack)); - // The hand renderer's copy of the main hand stack. - owner.fishing_cast_with_this_item = - self.main_hand_rod() && self.cast_rod() == Some(&stack); - let using = owner.using_this_item && owner.use_item_remaining_ticks > 0; - let ticks_used = - owner.use_duration as f32 - (owner.use_item_remaining_ticks as f32 - a + 1.0); - use horizon_client::first_person::ItemPose; - let pose = match &*stack.item { - "minecraft:bow" if using => ItemPose::Bow { ticks_used }, - "minecraft:crossbow" => { - let charged = stack.data().is_some_and(|d| !d.charged.is_empty()); - ItemPose::Crossbow { - ticks_used: (using && !charged).then_some(ticks_used), - charge_duration: owner.crossbow_charge_duration as f32, - charged, - } + // The hand renderer's copy of the main hand stack. + owner.fishing_cast_with_this_item = + self.main_hand_rod() && self.cast_rod() == Some(&stack); + let using = owner.using_this_item && owner.use_item_remaining_ticks > 0; + let ticks_used = + owner.use_duration as f32 - (owner.use_item_remaining_ticks as f32 - a + 1.0); + use horizon_client::first_person::ItemPose; + let pose = match &*stack.item { + "minecraft:bow" if using => ItemPose::Bow { ticks_used }, + "minecraft:crossbow" => { + let charged = stack.data().is_some_and(|d| !d.charged.is_empty()); + ItemPose::Crossbow { + ticks_used: (using && !charged).then_some(ticks_used), + charge_duration: owner.crossbow_charge_duration as f32, + // Only the main hand turns a charged crossbow aside. + charged: charged && hand == Hand::Main, } - "minecraft:trident" if using => ItemPose::Trident { ticks_used }, - _ if using => { - let components = self - .res - .item_renderer - .models - .components(&horizon_client::item_render::stack_view(&stack)); - let animation = components - .get("minecraft:consumable") - .map(horizon_client::first_person::consumable_animation); - if matches!( - animation, - Some( - horizon_world::consumable::UseAnimation::Eat - | horizon_world::consumable::UseAnimation::Drink - ) - ) { - ItemPose::Eat { - remaining: owner.use_item_remaining_ticks as f32, - duration: owner.use_duration as f32, - partial: a, - } - } else { - ItemPose::Using + } + "minecraft:trident" if using => ItemPose::Trident { ticks_used }, + _ if using => { + let components = self + .res + .item_renderer + .models + .components(&horizon_client::item_render::stack_view(&stack)); + let animation = components + .get("minecraft:consumable") + .map(horizon_client::first_person::consumable_animation); + if matches!( + animation, + Some( + horizon_world::consumable::UseAnimation::Eat + | horizon_world::consumable::UseAnimation::Drink + ) + ) { + ItemPose::Eat { + remaining: owner.use_item_remaining_ticks as f32, + duration: owner.use_duration as f32, + partial: a, } + } else { + ItemPose::Using } - _ => ItemPose::Swing, - }; - let left = self.settings.main_hand_left; - let m = to_world - * horizon_client::first_person::item_pose(left, inverse_height, attack, pose); - let context = if left { - horizon_assets::item_model::DisplayContext::FirstPersonLeftHand - } else { - horizon_assets::item_model::DisplayContext::FirstPersonRightHand - }; - let state = self.resolve_item(&stack, context, Some(&owner), 4); - let light = self.world.light( - eye[0].floor() as i32, - eye[1].floor() as i32, - eye[2].floor() as i32, - ); - self.submit_item_world( - &state, - m, - horizon_client::block_entity_render::vertex_light(light), - &mut out, - ); - } + } + _ => ItemPose::Swing, + }; + let m = to_world + * horizon_client::first_person::item_pose(left, inverse_height, attack, pose); + // Seeded by the player id plus the context ordinal. + let (context, seed) = if left { + ( + horizon_assets::item_model::DisplayContext::FirstPersonLeftHand, + 3, + ) + } else { + ( + horizon_assets::item_model::DisplayContext::FirstPersonRightHand, + 4, + ) + }; + let state = self.resolve_item(&stack, context, Some(&owner), seed); + let light = self.world.light( + eye[0].floor() as i32, + eye[1].floor() as i32, + eye[2].floor() as i32, + ); + self.submit_item_world( + &state, + m, + horizon_client::block_entity_render::vertex_light(light), + &mut out, + ); } out } @@ -8264,6 +8409,7 @@ impl Game<'_> { } else { None }, + menu_blur: self.menu_blur(), }; let result = match self.renderer.as_mut() { Some(renderer) => horizon_client::spans::time("renderer", || renderer.render(&frame)), @@ -8273,6 +8419,18 @@ impl Game<'_> { self.entity_vertices = entities; result } + /// `Screen.extractBlurredBackground` over the panorama: every classic + /// screen of the title menus but the title itself (`TitleScreen` + /// doesn't blur), when `menuBackgroundBlurriness` is at least 1. + fn menu_blur(&self) -> Option { + let blurred = !horizon_client::ui_theme::horizon() + && self.title.as_ref().is_some_and(|t| { + self.screen == Screen::Options + || !matches!(t.mode, horizon_client::title::Mode::Main) + }); + let radius = self.settings.menu_blur as f32; + (blurred && radius >= 1.0).then_some(radius) + } /// `LevelExtractor` / `LevelRenderer`: the world border wall this frame. fn border_draw( &mut self, @@ -8698,6 +8856,11 @@ impl ApplicationHandler for Game<'_> { if self.screen == Screen::Inventory || self.creative_inventory_open() { self.inventory_drag_move(); } + if let Some(title) = &mut self.title + && !horizon_client::ui_theme::horizon() + { + title.drag(self.cursor, (b.width, b.height)); + } if self.dragging && self.screen == Screen::Options { let _ = b; self.options_drag()?; @@ -8773,6 +8936,15 @@ impl ApplicationHandler for Game<'_> { )?; } } + WindowEvent::MouseInput { + state: ElementState::Released, + button: MouseButton::Left, + .. + } if self.title.is_some() && self.screen != Screen::Options => { + if let Some(title) = &mut self.title { + title.release(); + } + } WindowEvent::MouseInput { state, button: MouseButton::Left, @@ -8806,13 +8978,18 @@ impl ApplicationHandler for Game<'_> { Action::Language => { self.open_options_at(true, horizon_client::options_ui::Page::Language) } - Action::Play { folder } => self.open_world(&folder, None, None, false)?, + Action::Play { folder } => { + self.open_world(&folder, None, None, false, None)? + } Action::Create { folder, name, seed, creative, - } => self.open_world(&folder, Some(&name), seed, creative)?, + options, + } => { + self.open_world(&folder, Some(&name), seed, creative, Some(&options))? + } Action::Connect { address } => { self.connect_server(&address, &self.options.player_name())? } @@ -9074,6 +9251,7 @@ impl ApplicationHandler for Game<'_> { // In single player the tick is the integrated server's. if self.remote.is_none() { self.perf.tick(tick.elapsed().as_secs_f32() * 1000.0); + self.debug_charts.log_tick(tick, tick.elapsed()); } self.tick_ambience(); self.tick_fov(); @@ -9160,6 +9338,7 @@ impl ApplicationHandler for Game<'_> { } if rendered { self.frame_stats.record(elapsed.as_secs_f32() * 1000.0); + self.debug_charts.frame_times.log(elapsed.as_nanos() as i64); if self.frames == 0 { // The launcher times Play to this line (launcher/src/perf.rs). log::info!( @@ -9288,6 +9467,7 @@ pub fn run() -> Result<()> { log::info!("load assets: {:.2}s", started.elapsed().as_secs_f32()); let facts = BlockFacts::load(&root, assets.registry)?; let mob_data = horizon_client::mobs::MobData::load(&root, &facts); + horizon_client::mobs::trial_spawner::load_registry(&root); log::info!("load facts: {:.2}s", started.elapsed().as_secs_f32()); let items = Items::load(&root, assets.registry, &facts)?; log::info!("load items: {:.2}s", started.elapsed().as_secs_f32()); @@ -9502,6 +9682,8 @@ pub fn run() -> Result<()> { music: Default::default(), ambience: Default::default(), sound_paused: false, + cart_sounds: HashSet::new(), + riding_cart_sounds: None, dropped: Vec::new(), next_entity: 0, particles, @@ -9534,6 +9716,7 @@ pub fn run() -> Result<()> { title: None, armor: [None, None, None, None], offhand: None, + hand: Hand::Main, shield_cooldown: 0, command_source: None, titles: Default::default(), @@ -9638,6 +9821,7 @@ pub fn run() -> Result<()> { world_options: None, friends: None, debug_keys: Default::default(), + debug_charts: Default::default(), show_hitboxes: false, show_chunk_borders: false, pause_menu: true, @@ -9737,7 +9921,7 @@ pub fn run() -> Result<()> { } Some(folder) => { let (seed, creative) = (game.options.seed, game.options.creative); - game.open_world(&folder, None, Some(seed), creative)?; + game.open_world(&folder, None, Some(seed), creative, None)?; } None => { let title = Title::new( diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 02638f64f..4c5c0fbbe 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -19,27 +19,99 @@ pub(super) struct Toast { icon: String, frame: Frame, title: Text, - shown: Option, - /// A `RecipeToast`: the icon is a recipe result. - recipe: bool, + slide: Slide, + /// A `RecipeToast`: the crafting station and result of each display + /// unlocked while it lasts (`recipeItems`); empty for an advancement. + recipes: Vec<(String, ItemStack)>, + /// `RecipeToast.changed` and `lastChanged`. + changed: bool, + last_changed: i64, } impl Toast { - pub(super) fn is_recipe(&self) -> bool { - self.recipe - } - pub(super) fn was_shown(&self) -> bool { - self.shown.is_some() - } - /// `RecipeToast`: "New Recipe(s) Unlocked!" with the recipe's result. - pub(super) fn recipe(icon: &str) -> Self { + /// `RecipeToast.addOrUpdate` on a new toast. + pub(super) fn recipe(items: Vec<(String, ItemStack)>) -> Self { Self { - icon: icon.to_owned(), + icon: String::new(), frame: Frame::Task, title: Text::literal(""), - shown: None, - recipe: true, + slide: Slide::default(), + recipes: items, + changed: true, + last_changed: 0, } } + pub(super) fn is_recipe(&self) -> bool { + !self.recipes.is_empty() + } + /// `RecipeToast.addItem`: more displays on a toast still queued or shown. + pub(super) fn add_recipes(&mut self, items: Vec<(String, ItemStack)>) { + self.recipes.extend(items); + self.changed = true; + } + /// `Toast.update` with `fullyVisibleForMs`: whether it wants to be shown. + fn wants_show(&mut self, fully_for: i64, multiplier: f64) -> bool { + let time = 5000.0 * multiplier; + if self.recipes.is_empty() { + // AdvancementToast. + return (fully_for as f64) < time; + } + if self.changed { + self.last_changed = fully_for; + self.changed = false; + } + ((fully_for - self.last_changed) as f64) < time + } + /// `RecipeToast.displayedRecipeIndex`: the displays take turns over the + /// toast's display time. + fn displayed_recipe(&self, fully_for: i64, multiplier: f64) -> usize { + let n = self.recipes.len() as f64; + (fully_for as f64 / (5000.0 * multiplier / n).max(1.0) % n) as usize + } +} +/// `ToastManager.ToastInstance`: slides a toast in and out over 600 ms, +/// eased by the square, and counts how long it has been fully shown. +#[derive(Default)] +struct Slide { + /// When it first updated; the times below are milliseconds since. + origin: Option, + begun: bool, + /// `animationStartTime`. + start: i64, + /// `becameFullyVisibleAt`. + fully_at: i64, + show: bool, + /// `visiblePortion`: 0 off screen, 1 fully in. + portion: f32, + /// `fullyVisibleFor`. + fully_for: i64, +} +impl Slide { + const MS: i64 = 600; + /// `ToastInstance.update` at `now`; `wants_show` is the toast's own + /// update. The visibility it switched to (the sound to play), and whether + /// it has finished sliding out. + fn update(&mut self, now: i64, wants_show: impl FnOnce(i64) -> bool) -> (Option, bool) { + let was = self.show; + if !self.begun { + self.begun = true; + self.start = now; + self.show = true; + } + if self.show && now - self.start <= Self::MS { + self.fully_at = now; + } + self.fully_for = now - self.fully_at; + let progress = ((now - self.start) as f32 / Self::MS as f32).clamp(0.0, 1.0); + let progress = progress * progress; + self.portion = if self.show { progress } else { 1.0 - progress }; + let wanted = wants_show(self.fully_for); + if wanted != self.show { + self.start = now - ((1.0 - self.portion) * Self::MS as f32) as i64; + self.show = wanted; + } + let finished = !self.show && now - self.start > Self::MS; + ((self.show != was).then_some(self.show), finished) + } } #[derive(Default)] pub(super) struct AdvState { @@ -430,8 +502,10 @@ impl Game<'_> { icon: d.icon.clone(), frame: d.frame, title: text_of(&d.title), - shown: None, - recipe: false, + slide: Slide::default(), + recipes: Vec::new(), + changed: false, + last_changed: 0, }); } if d.announce && self.ui.rules.bool("show_advancement_messages") { @@ -679,45 +753,57 @@ impl Game<'_> { c["from"].as_str().is_none_or(|f| f == from) && c["to"].as_str().is_none_or(|t| t == to) }); } - /// `ToastManager` with the `AdvancementToast`. + /// `ToastManager` with the `AdvancementToast` and the `RecipeToast`, + /// one at a time. pub(super) fn draw_toasts(&mut self, batch: &mut HudBatch) { + let multiplier = f64::from(self.settings.notification_display_time); let Some(t) = self.adv.toasts.front_mut() else { return; }; - let shown = *t.shown.get_or_insert_with(Instant::now); - let ms = shown.elapsed().as_millis() as f32; - // AdvancementToast.DISPLAY_TIME: 5 s, sliding 600 ms in and out. - if ms > 5600.0 { + let first = t.slide.origin.is_none(); + let origin = *t.slide.origin.get_or_insert_with(Instant::now); + let now = origin.elapsed().as_millis() as i64; + let mut slide = std::mem::take(&mut t.slide); + let (sound, finished) = slide.update(now, |fully| t.wants_show(fully, multiplier)); + t.slide = slide; + if finished { self.adv.toasts.pop_front(); return; } - let slide = if ms < 600.0 { - ms / 600.0 - } else if ms > 5000.0 { - 1.0 - (ms - 5000.0) / 600.0 - } else { - 1.0 - }; - let (title, frame, icon, recipe) = (t.title.clone(), t.frame, t.icon.clone(), t.recipe); - if recipe { - // RecipeToast: black description under a purple title. + let x = batch.width - 160.0 * t.slide.portion; + let fully_for = t.slide.fully_for; + let (title, frame, icon) = (t.title.clone(), t.frame, t.icon.clone()); + let recipe = t + .is_recipe() + .then(|| t.recipes[t.displayed_recipe(fully_for, multiplier)].clone()); + // ToastManager.update: the sound of the new visibility, and a + // challenge's own sound as it leaves the queue. + if let Some(show) = sound { + let event = if show { "ui.toast.in" } else { "ui.toast.out" }; + self.audio + .play(&format!("minecraft:{event}"), None, 1.0, 1.0); + } + if first && recipe.is_none() && frame == Frame::Challenge { + self.audio + .play("minecraft:ui.toast.challenge_complete", None, 1.0, 1.0); + } + if let Some((station, item)) = recipe { + // RecipeToast: black description under a purple title, the + // station at 0.6 scale in the corner over the cycling result. let atlas = &self.res.atlas; - let x = batch.width - 160.0 * slide; batch.sprite(atlas, "gui/sprites/toast/recipe", x, 0.0); let title = self.translate("recipe.toast.title", "New Recipe(s) Unlocked!"); let description = self.translate("recipe.toast.description", "Check your recipe book"); let atlas = &self.res.atlas; batch.text(atlas, &title, x + 30.0, 7.0, 0xFF50_0050, false); batch.text(atlas, &description, x + 30.0, 18.0, 0xFF00_0000, false); - self.draw_item(batch, &ItemStack::new(&icon, 1), x + 8.0, 8.0); + let start = batch.vertices.len(); + self.draw_item_model(batch, &ItemStack::new(&station, 1), x + 3.0, 3.0); + batch.scale_since(start, x, 0.0, 0.6, 0.6); + self.draw_item_model(batch, &item, x + 8.0, 8.0); return; } - if frame == Frame::Challenge && ms < 50.0 { - self.audio - .play("minecraft:ui.toast.challenge_complete", None, 1.0, 1.0); - } let atlas = &self.res.atlas; - let x = batch.width - 160.0 * slide; batch.sprite(atlas, "gui/sprites/toast/advancement", x, 0.0); let (key, color) = match frame { Frame::Task => ("advancements.toast.task", 0xFF00_FFFF), @@ -813,3 +899,94 @@ pub(super) fn text_of(v: &Value) -> Text { Text::empty() } } + +#[cfg(test)] +mod tests { + use super::*; + + fn recipes(n: usize) -> Toast { + Toast::recipe( + (0..n) + .map(|i| { + let item = ItemStack::new(&format!("minecraft:item_{i}"), 1); + ("minecraft:crafting_table".to_owned(), item) + }) + .collect(), + ) + } + /// Drives a toast frame by frame (every `step` ms) and returns the slide + /// portions at the given times and when it finished. + fn run(toast: &mut Toast, step: i64, until: i64, at: &[i64]) -> (Vec, Option) { + let mut slide = Slide::default(); + let mut seen = Vec::new(); + for now in (0..=until).step_by(step as usize) { + let (_, finished) = slide.update(now, |f| toast.wants_show(f, 1.0)); + if finished { + return (seen, Some(now)); + } + if at.contains(&now) { + seen.push(slide.portion); + } + } + (seen, None) + } + + #[test] + fn toasts_slide_in_squared_and_out_after_five_seconds() { + let mut toast = recipes(1); + let (portions, finished) = run(&mut toast, 10, 10_000, &[0, 300, 600, 3000]); + // (300 / 600)² = 0.25: ToastInstance.calculateVisiblePortion. + assert_eq!(portions, [0.0, 0.25, 1.0, 1.0]); + // Fully in at 600, shown 5000 ms, out over 600 more. + assert!( + finished.is_some_and(|t| (6200..=6220).contains(&t)), + "{finished:?}" + ); + } + + #[test] + fn the_first_update_plays_the_show_sound_and_the_hide_sound_follows() { + let mut toast = recipes(1); + let mut slide = Slide::default(); + assert_eq!(slide.update(0, |f| toast.wants_show(f, 1.0)).0, Some(true)); + assert_eq!(slide.update(100, |f| toast.wants_show(f, 1.0)).0, None); + assert_eq!( + slide.update(5600, |f| toast.wants_show(f, 1.0)).0, + Some(false) + ); + } + + #[test] + fn recipe_toasts_cycle_through_their_displays_over_the_display_time() { + let toast = recipes(4); + let shown: Vec = [0, 1249, 1250, 2500, 3750, 4999, 5000] + .iter() + .map(|&t| toast.displayed_recipe(t, 1.0)) + .collect(); + assert_eq!(shown, [0, 0, 1, 2, 3, 3, 0]); + // notificationDisplayTime doubles each turn. + assert_eq!(toast.displayed_recipe(2500, 2.0), 1); + } + + #[test] + fn unlocking_more_recipes_keeps_the_toast_up_five_more_seconds() { + let mut toast = recipes(1); + let mut slide = Slide::default(); + let mut finished = None; + for now in (0..=20_000).step_by(10) { + if now == 4000 { + toast.add_recipes(recipes(1).recipes); + } + if slide.update(now, |f| toast.wants_show(f, 1.0)).1 { + finished = Some(now); + break; + } + } + assert_eq!(toast.recipes.len(), 2); + // lastChanged moved to 3400 ms fully shown: hidden at 8400 + 600. + assert!( + finished.is_some_and(|t| (9600..=9620).contains(&t)), + "{finished:?}" + ); + } +} diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index af70b738a..243351af6 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -485,11 +485,19 @@ impl Game<'_> { seed, creative, focus, + options, } => json!({ "mode": "create-world", + "tab": (["game", "world", "more"][options.tab.min(2)]), "fields": { "name": name, "seed": seed }, "focus": match focus { 0 => "name", 1 => "seed", _ => "none" }, "creative": creative, + "hardcore": options.hardcore, + "difficulty": horizon_client::title::DIFFICULTIES[options.difficulty()], + "allow_commands": options.commands(*creative), + "superflat": options.flat, + "generate_structures": options.structures, + "bonus_chest": options.bonus_chest(), }), Mode::Edit { world, @@ -1322,10 +1330,17 @@ impl Game<'_> { let title = self.title.as_mut().ok_or("no title screen")?; if let Some(field) = &field { match &mut title.mode { - horizon_client::title::Mode::Create { focus, .. } => { + horizon_client::title::Mode::Create { focus, options, .. } => { + // Each box is on its own tab. *focus = match field.as_str() { - "name" => 0, - "seed" => 1, + "name" => { + options.tab = 0; + 0 + } + "seed" => { + options.tab = 1; + 1 + } other => { return Err(format!( "the create-world fields are name and seed, not {other}" diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index 94e9422ed..78eb22330 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -565,9 +565,9 @@ impl Game<'_> { held.count -= 1; if held.count == 0 { // The worn piece comes back to the hand. - self.inventory[self.selected] = current; + *self.held_mut() = current; } else { - self.inventory[self.selected] = Some(held); + *self.held_mut() = Some(held); if let Some(old) = current && let Some(rest) = self.give(old) && let Some(eye) = self.eye_position() diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index 5f2897c67..9a06c6777 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -666,6 +666,7 @@ impl Game<'_> { if !self.before_block(d) || self.mob_hit().is_some_and(|m| m.1 < d) { return false; } + self.vehicle_attack_sounds(); let b = &mut self.boats[i]; b.hurt_dir = -b.hurt_dir; b.hurt_time = 10; diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index 7bf687899..3904ab465 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -59,7 +59,7 @@ impl Game<'_> { pages.push(String::new()); } BookScreen::Edit { - slot: self.selected, + slot: self.held_slot(), pages, page: 0, signing: false, @@ -104,7 +104,7 @@ impl Game<'_> { while pages.len() > 1 && pages.last().is_some_and(String::is_empty) { pages.pop(); } - if let Some(stack) = self.inventory.get_mut(slot).and_then(Option::as_mut) + if let Some(stack) = self.stack_in_mut(slot).as_mut() && &*stack.item == "minecraft:writable_book" { if sign { diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index bc53e54a3..af981b798 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -488,7 +488,7 @@ impl Game<'_> { let folder = arg(1)?; let seed = words.get(2).map(|s| s.parse::()).transpose()?; let creative = words.get(3) == Some(&"creative"); - self.open_world(folder, Some(folder), seed, creative)?; + self.open_world(folder, Some(folder), seed, creative, None)?; ok() } "connect" => { diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index f9f102e93..aea114d30 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -5,6 +5,7 @@ use super::{Dim, Game, view_vector}; use horizon_client::{ Result, + arrows::EntityHit, blocks::Fluid, collisions::SceneCollisions, items::ItemStack, @@ -25,14 +26,16 @@ use horizon_core::{ use std::sync::Arc; /// The world impact sound after successful arrow damage, including self-shots. -fn arrow_impact_sound( - random: &mut impl RandomSource, - hurt: bool, -) -> Option<(&'static str, f32, f32)> { - hurt.then(|| { - let pitch = 1.2 / (random.next_float() * 0.2 + 0.9); - ("minecraft:entity.arrow.hit", 1.0, pitch) - }) +/// `AbstractArrow.onHitEntity`'s damage: the crit bonus comes from the +/// arrow's own random. +fn arrow_damage(arrow: &mut Projectile, fallback: &mut impl RandomSource) -> f32 { + let mut state = arrow.arrow.take(); + let damage = match state.as_mut() { + Some(a) => arrow.arrow_damage(&mut a.random), + None => arrow.arrow_damage(fallback), + }; + arrow.arrow = state; + damage } /// Mob-system state owned by the game. @@ -1528,20 +1531,8 @@ impl Game<'_> { self.world.random.next_float() }; let w = self.mob_world_base(&[]); - // Level.isRainingAt: raining, open to the sky (the biome's - // precipitation is not checked here). - let (raining, world) = (w.raining, w.world); - let rain = move |p: BlockPos| raining && world.light(p.x, p.y, p.z) >> 4 == 15; - let scene = horizon_client::arrows::ArrowScene { - world: w.world, - registry: w.registry, - facts: w.facts, - collision: w.collision, - fluids: &self.motion.fluids, - raining: &rain, - mob_griefing: self.ui.rules.bool("mob_griefing"), - tnt_explodes: self.ui.rules.bool("tnt_explodes"), - }; + let rain = self.arrow_rain(); + let scene = self.arrow_scene(&rain); // Arrows also hit minecarts (VehicleEntity is pickable). let mut arrow_targets = targets.clone(); arrow_targets.extend(self.carts.iter().map(|c| (Who::Mob(c.id), c.bounds()))); @@ -1568,8 +1559,10 @@ impl Game<'_> { && breezes.contains(&id) { super::wind::reverse(p, jitter); - if let Some(a) = p.arrow.as_mut() { - a.removed = false; + if p.arrow.is_some() { + horizon_client::arrows::finish_entity_hit(p, &scene, EntityHit::Deflected); + let a = p.arrow.as_mut().expect("an arrow"); + arrow_events.extend(a.events.drain(..).map(|e| (p.position, e))); } deflections.push([at.x, at.y, at.z]); return true; @@ -1680,7 +1673,53 @@ impl Game<'_> { ArrowEvent::SplashEvent => { self.projectile_event("minecraft:splash", None, [at.x, at.y, at.z]); } - ArrowEvent::ShootEvent => {} + // finish_arrow_hit drops the pickup, which it holds. + ArrowEvent::ShootEvent | ArrowEvent::Drop => {} + } + } + /// `Level.isRainingAt` for arrows: raining, open to the sky (the biome's + /// precipitation is not checked here). + fn arrow_rain(&self) -> impl Fn(BlockPos) -> bool + '_ { + let raining = self.world.weather.levels(1.0).0 > 0.2; + move |p: BlockPos| raining && self.world.light(p.x, p.y, p.z) >> 4 == 15 + } + /// The level as arrows see it. + fn arrow_scene<'s>( + &'s self, + rain: &'s dyn Fn(BlockPos) -> bool, + ) -> horizon_client::arrows::ArrowScene<'s, 's> { + horizon_client::arrows::ArrowScene { + world: &self.world, + registry: self.res.assets.registry, + facts: &self.res.facts, + collision: self.collision, + fluids: &self.motion.fluids, + raining: rain, + mob_griefing: self.ui.rules.bool("mob_griefing"), + tnt_explodes: self.ui.rules.bool("tnt_explodes"), + } + } + /// The rest of the tick of an arrow that hit an entity + /// (`arrows::finish_entity_hit`): its sounds and drop, and back among the + /// projectiles if it flies on. + fn finish_arrow_hit(&mut self, mut arrow: Projectile, outcome: EntityHit) { + let keep = { + let rain = self.arrow_rain(); + horizon_client::arrows::finish_entity_hit(&mut arrow, &self.arrow_scene(&rain), outcome) + }; + let Some(a) = arrow.arrow.as_mut() else { + return; + }; + let (events, item) = (std::mem::take(&mut a.events), a.pickup_item.clone()); + for event in events { + if event == horizon_client::arrows::ArrowEvent::Drop { + self.spawn_at_location(arrow.position, f64::from(0.1f32), item.clone()); + } else { + self.arrow_event(arrow.position, event); + } + } + if keep { + self.creatures.projectiles.push(arrow); } } fn projectile_hit(&mut self, p: &Projectile, hit: Hit) -> Result<()> { @@ -1720,14 +1759,12 @@ impl Game<'_> { && let Some(i) = self.carts.iter().position(|c| c.id == id) { // AbstractArrow.onHitEntity on a minecart. - let amount = p.arrow_damage(&mut self.world.random) + p.bonus.damage; + let mut arrow = p.clone(); + let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage; let burning = p.arrow.as_ref().is_some_and(|a| a.on_fire()); let creative = p.owner == Some(Who::Player) && self.creative; self.arrow_hits_cart(i, amount, p.velocity, burning, creative); - if let Some((sound, volume, pitch)) = arrow_impact_sound(&mut self.world.random, true) { - self.audio - .play(sound, Some([at.x, at.y, at.z]), volume, pitch); - } + self.finish_arrow_hit(arrow, EntityHit::Hurt); return Ok(()); } let atp = [at.x, at.y, at.z]; @@ -1747,16 +1784,9 @@ impl Game<'_> { }; match (&p.kind, hit) { (ProjectileKind::Arrow { effect, .. }, Hit::Entity { who, .. }) => { - let amount = p.arrow_damage(&mut self.world.random) + p.bonus.damage; - // Punch pushes along the flight, Flame burns for five seconds. - let flight = (p.velocity.x * p.velocity.x + p.velocity.z * p.velocity.z).sqrt(); - if p.bonus.punch > 0 && flight > 1e-6 { - let k = f64::from(p.bonus.punch) * 0.6 / flight; - self.handle_mob_events(vec![MobEvent::Push { - target: who, - velocity: [p.velocity.x * k, 0.1, p.velocity.z * k], - }])?; - } + let mut arrow = p.clone(); + let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage; + let player_fire = self.player.as_ref().map(|pl| pl.fire_ticks); // AbstractArrow.onHitEntity: a burning arrow sets its target alight. if p.arrow.as_ref().is_some_and(|a| a.on_fire()) { self.handle_mob_events(vec![MobEvent::Ignite { @@ -1788,10 +1818,27 @@ impl Game<'_> { hurt } }; - if let Some((sound, volume, pitch)) = - arrow_impact_sound(&mut self.world.random, hurt) - { - self.audio.play(sound, Some(atp), volume, pitch); + // doKnockback: Punch pushes along the flight. + let flight = (p.velocity.x * p.velocity.x + p.velocity.z * p.velocity.z).sqrt(); + if hurt && p.bonus.punch > 0 && flight > 1e-6 { + let k = f64::from(p.bonus.punch) * 0.6 / flight; + self.handle_mob_events(vec![MobEvent::Push { + target: who, + velocity: [p.velocity.x * k, 0.1, p.velocity.z * k], + }])?; + } + match (hurt, who) { + (true, _) => self.finish_arrow_hit(arrow, EntityHit::Hurt), + // What the player took no damage from (a raised shield) + // keeps its fire as it was and turns the arrow back. + (false, Who::Player) => { + if let (Some(pl), Some(ticks)) = (self.player.as_mut(), player_fire) { + pl.set_remaining_fire_ticks(ticks); + } + self.finish_arrow_hit(arrow, EntityHit::Refused); + } + // Mobs' refusals don't follow hurtServer yet: the arrow is gone. + (false, Who::Mob(_)) => {} } } // AbstractArrow.onHitBlock plays its sound itself (ArrowEvent). @@ -2569,11 +2616,11 @@ impl Game<'_> { self.audio.play(sound, Some(eye), 0.5, pitch); self.swing_arm(); if !self.creative - && let Some(s) = self.inventory[self.selected].as_mut() + && let Some(s) = self.held_mut().as_mut() { s.count -= 1; if s.count == 0 { - self.inventory[self.selected] = None; + *self.held_mut() = None; } } Ok(true) @@ -2615,11 +2662,11 @@ impl Game<'_> { } self.swing_arm(); if !self.creative - && let Some(s) = self.inventory[self.selected].as_mut() + && let Some(s) = self.held_mut().as_mut() { s.count -= 1; if s.count == 0 { - self.inventory[self.selected] = None; + *self.held_mut() = None; } } Ok(true) @@ -2945,32 +2992,3 @@ impl Game<'_> { let _ = self.spawn_mob("minecraft:zombified_piglin", at, false); } } - -#[cfg(test)] -mod tests { - use super::*; - use horizon_core::random::LegacyRandom; - - #[test] - fn arrow_impact_uses_world_sound_volume_and_seeded_pitch() { - let mut random = LegacyRandom::new(0); - assert_eq!( - arrow_impact_sound(&mut random, true), - Some(( - "minecraft:entity.arrow.hit", - 1.0, - f32::from_bits(0x3f92d167) - )) - ); - let mut expected = LegacyRandom::new(0); - expected.next_float(); - assert_eq!(random.next_float(), expected.next_float()); - } - - #[test] - fn rejected_arrow_damage_is_silent_without_drawing_pitch() { - let mut random = LegacyRandom::new(0); - assert_eq!(arrow_impact_sound(&mut random, false), None); - assert_eq!(random.next_float(), LegacyRandom::new(0).next_float()); - } -} diff --git a/crates/horizon-client/src/game/crossbow.rs b/crates/horizon-client/src/game/crossbow.rs index 335f62785..70ccba8d3 100644 --- a/crates/horizon-client/src/game/crossbow.rs +++ b/crates/horizon-client/src/game/crossbow.rs @@ -1,8 +1,10 @@ //! Crossbows (`CrossbowItem`): charging with the start/middle/end sounds -//! (Quick Charge), loading arrows into `charged_projectiles` (Multishot -//! loads three), and shooting critical arrows at power 3.15 with the fanned -//! Multishot angles and their shot pitches. -use super::{Game, view_vector}; +//! (Quick Charge), loading arrows or a held firework rocket into +//! `charged_projectiles` (Multishot loads three), and shooting critical +//! arrows at power 3.15, or rockets at 1.6 for three durability, with the +//! fanned Multishot angles and their shot pitches. `Player.getProjectile` +//! finds the ammo for bows and crossbows. +use super::{Game, shield::OFFHAND_SLOT, view_vector}; use horizon_client::{ items::ItemStack, mobs::Who, @@ -11,6 +13,31 @@ use horizon_client::{ use horizon_core::{geometry::Vec3, random::RandomSource}; const CROSSBOW: &str = "minecraft:crossbow"; +const FIREWORK_ROCKET: &str = "minecraft:firework_rocket"; + +/// `ProjectileWeaponItem.ARROW_ONLY`, for the arrows Horizon shoots. +fn is_arrow(stack: &ItemStack) -> bool { + &*stack.item == "minecraft:arrow" +} + +/// `Player.getProjectile`: what `weapon` supports in the off hand, then in +/// the main hand (`getHeldProjectile`; crossbows also take firework rockets +/// there), else the first arrows in the inventory. The slot of the stack. +fn projectile_slot( + weapon: &str, + hands: [(usize, Option<&ItemStack>); 2], + inventory: &[Option], +) -> Option { + let held = |s: &ItemStack| is_arrow(s) || weapon == CROSSBOW && &*s.item == FIREWORK_ROCKET; + hands + .into_iter() + .find_map(|(slot, s)| s.is_some_and(held).then_some(slot)) + .or_else(|| { + inventory + .iter() + .position(|s| s.as_ref().is_some_and(is_arrow)) + }) +} impl Game<'_> { pub(super) fn charge_ticks(stack: &ItemStack) -> u32 { @@ -42,10 +69,10 @@ impl Game<'_> { ], } } - pub(super) fn arrow_slot(&self) -> Option { - self.inventory - .iter() - .position(|s| s.as_ref().is_some_and(|s| &*s.item == "minecraft:arrow")) + /// `Player.getProjectile` for `weapon` (`projectile_slot`). + pub(super) fn projectile_slot(&self, weapon: &str) -> Option { + let hands = [OFFHAND_SLOT, self.selected].map(|slot| (slot, self.stack_in(slot))); + projectile_slot(weapon, hands, &self.inventory) } /// `CrossbowItem.use`: shoot when charged, else start charging. pub(super) fn use_crossbow(&mut self, stack: &ItemStack) -> bool { @@ -58,8 +85,10 @@ impl Game<'_> { } if stack.data().is_some_and(|d| !d.charged.is_empty()) { self.shoot_crossbow(); - } else if (self.arrow_slot().is_some() || self.creative) && self.using.is_none() { - self.using = Some((self.selected, 0)); + } else if (self.projectile_slot(CROSSBOW).is_some() || self.creative) + && self.using.is_none() + { + self.using = Some((self.held_slot(), 0)); } true } @@ -88,16 +117,17 @@ impl Game<'_> { } else { 1 }; - let slot_ammo = self.arrow_slot(); + let slot_ammo = self.projectile_slot(CROSSBOW); let ammo = slot_ammo - .and_then(|i| self.inventory[i].clone()) + .and_then(|i| self.stack_in(i).cloned()) .unwrap_or_else(|| ItemStack::new("minecraft:arrow", 1)); if !self.creative { let Some(i) = slot_ammo else { return }; - if let Some(s) = self.inventory[i].as_mut() { + let cell = self.stack_in_mut(i); + if let Some(s) = cell.as_mut() { s.count -= 1; if s.count == 0 { - self.inventory[i] = None; + *cell = None; } } } @@ -105,7 +135,7 @@ impl Game<'_> { let drawn = (0..shots) .map(|i| horizon_client::arrows::drawn_ammo(&ammo, self.creative || i > 0)) .collect(); - if let Some(bow) = self.inventory[slot].as_mut() { + if let Some(bow) = self.stack_in_mut(slot).as_mut() { bow.data_mut().charged = drawn; } let pitch = 1.0 / (self.world.random.next_float() * 0.5 + 1.0) + 0.2; @@ -117,12 +147,18 @@ impl Game<'_> { let Some(eye) = self.eye_position() else { return; }; - let Some(bow) = self.inventory[self.selected].as_mut() else { + let Some(bow) = self.held_mut().as_mut() else { return; }; let charged = std::mem::take(&mut bow.data_mut().charged); bow.tidy(); let count = charged.len(); + // getShootingPower: a rocket among them slows every shot. + let power = if charged.iter().any(|s| &*s.item == FIREWORK_ROCKET) { + 1.6 + } else { + 3.15 + }; // ProjectileWeaponItem.shoot: angles fanned 10 degrees apart. let spread = if count > 1 { 10.0 } else { 0.0 }; let view = glam::DVec3::from_array(view_vector(self.yaw, self.pitch)); @@ -140,22 +176,38 @@ impl Game<'_> { }; let dir = glam::DQuat::from_axis_angle(up.normalize_or_zero(), angle.to_radians()) * view; - let kind = ProjectileKind::Arrow { - base_damage: 2.0, - critical: true, - effect: None, - }; - let mut arrow = Projectile::new( - kind, - Vec3::new(eye[0], eye[1] - 0.1, eye[2]), - Some(Who::Player), - ); - if let Some(a) = arrow.arrow.as_mut() { - a.set_item(ammo); - a.set_owner(Some(Who::Player)); + // createProjectile: a rocket shot at an angle from 0.15 under the + // eyes, spread by its own random; three durability. + let rocket = &*ammo.item == FIREWORK_ROCKET; + if rocket { + let at = Vec3::new(eye[0], eye[1] - f64::from(0.15f32), eye[2]); + let mut shot = Projectile::new(ProjectileKind::Snowball, at, None); + shot.shoot( + &mut super::dispenser::entity_random(), + dir.to_array(), + power, + 1.0, + ); + self.launch_angled_rocket(at, shot.velocity, ammo); + } + if !rocket { + let kind = ProjectileKind::Arrow { + base_damage: 2.0, + critical: true, + effect: None, + }; + let mut arrow = Projectile::new( + kind, + Vec3::new(eye[0], eye[1] - 0.1, eye[2]), + Some(Who::Player), + ); + if let Some(a) = arrow.arrow.as_mut() { + a.set_item(ammo); + a.set_owner(Some(Who::Player)); + } + arrow.shoot(&mut self.world.random, dir.to_array(), power, 1.0); + self.creatures.projectiles.push(arrow); } - arrow.shoot(&mut self.world.random, dir.to_array(), 3.15, 1.0); - self.creatures.projectiles.push(arrow); self.player_projectile_shot(); let pitch = if index == 0 { 1.0 @@ -165,7 +217,43 @@ impl Game<'_> { }; self.audio .play("minecraft:item.crossbow.shoot", Some(eye), 1.0, pitch); - self.damage_held(1); + self.damage_held(if rocket { 3 } else { 1 }); } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn held_projectiles_come_before_the_inventory() { + let stack = |item: &str| Some(ItemStack::new(item, 1)); + let (crossbow, rocket, arrow) = ( + stack(CROSSBOW), + stack(FIREWORK_ROCKET), + stack("minecraft:arrow"), + ); + let mut inventory = vec![None; 36]; + inventory[5] = arrow.clone(); + // The weapon in hotbar slot 0, `off` in the off hand. + let slot = |weapon, off: &Option, inventory: &[Option]| { + let hands = [(OFFHAND_SLOT, off.as_ref()), (0, crossbow.as_ref())]; + projectile_slot(weapon, hands, inventory) + }; + // The off hand's rocket loads a crossbow; a bow only takes arrows. + assert_eq!(slot(CROSSBOW, &rocket, &inventory), Some(OFFHAND_SLOT)); + assert_eq!(slot("minecraft:bow", &rocket, &inventory), Some(5)); + assert_eq!( + slot("minecraft:bow", &arrow, &inventory), + Some(OFFHAND_SLOT) + ); + assert_eq!(slot(CROSSBOW, &None, &inventory), Some(5)); + // A rocket in the inventory is not ammo. + inventory[5] = rocket.clone(); + assert_eq!(slot(CROSSBOW, &None, &inventory), None); + // The main hand's rocket, with the crossbow in the off hand. + let hands = [(OFFHAND_SLOT, crossbow.as_ref()), (3, rocket.as_ref())]; + assert_eq!(projectile_slot(CROSSBOW, hands, &inventory), Some(3)); + } +} diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index 0f49cd459..05380d980 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -151,7 +151,7 @@ impl Game<'_> { } } /// `Util.getMillis` (positive: KeyboardHandler treats 0 as unset). - fn debug_millis(&self) -> i64 { + pub(super) fn debug_millis(&self) -> i64 { self.started.elapsed().as_millis() as i64 + 1_000_000 } /// `KeyboardHandler.tick`: the debug crash countdown. @@ -180,6 +180,79 @@ impl Game<'_> { } Ok(()) } + /// The network charts' samples each tick: `PingDebugMonitor.tick` while + /// they show, `BandwidthDebugMonitor.tick` always. + pub(super) fn tick_debug_charts(&mut self) { + let shown = self.debug && self.debug_charts.network; + let Some(r) = &self.remote else { + // The integrated server answers within the tick. + if shown { + self.debug_charts.ping.log(0); + } + return; + }; + let received = r + .session + .counters + .lock() + .unwrap() + .as_ref() + .map(|c| c.bytes_in.load(std::sync::atomic::Ordering::Relaxed)); + if let Some(total) = received { + self.debug_charts.log_bandwidth(total); + } + if shown { + use horizon_protocol::packets::{play::Serverbound, status::Ping}; + let time = self.debug_millis(); + self.send(Serverbound::PingRequest(Ping { time })); + } + } + /// The overlay's chart lines (`DebugScreenOverlay`'s "Debug charts"). + pub(super) fn debug_chart_lines(&self) -> [String; 3] { + let keys = &self.settings.keys; + let modifier = keys.get("key.debug.modifier"); + let key = |mapping: &str| { + let prefix = if modifier == "key.keyboard.unknown" { + String::new() + } else { + format!("{}+", keybinds::display_name(modifier).plain()) + }; + format!( + "[{prefix}{}]", + keybinds::display_name(keys.get(mapping)).plain() + ) + }; + let chart = |mapping: &str, name: &str, on: bool| { + format!( + "{} {name} {}", + key(mapping), + if on { "visible" } else { "hidden" } + ) + }; + let remote = self.remote.is_some(); + let c = &self.debug_charts; + [ + format!( + "Debug charts: {}; {};", + chart("key.debug.profilingChart", "Profiler", false), + chart( + "key.debug.fpsCharts", + if remote { "fps" } else { "fps + tps" }, + c.fps + ), + ), + format!( + "{}; {}", + chart( + "key.debug.networkCharts", + if remote { "Bandwidth + Ping" } else { "Ping" }, + c.network + ), + chart("key.debug.lightmapTexture", "Lightmap", c.lightmap), + ), + format!("To edit: press {}", key("key.debug.debugOptions")), + ] + } /// `KeyMapping.getTranslatedKeyMessage`. fn key_text(&self, mapping: &str) -> Text { keybinds::display_name(self.settings.keys.get(mapping)) @@ -339,16 +412,25 @@ impl Game<'_> { }); true } + DebugAction::FpsCharts => { + self.debug_charts.toggle_fps(&mut self.debug); + true + } + DebugAction::NetworkCharts => { + self.debug_charts.toggle_network(&mut self.debug); + true + } + DebugAction::LightmapTexture => { + self.debug_charts.toggle_lightmap(&mut self.debug); + true + } // Screens and overlays Horizon does not draw yet (the debug - // options screen, the profiler and its charts, the lightmap, the - // texture dump): the keys are used up as in vanilla. + // options screen, the profiler and its chart, the texture dump): + // the keys are used up as in vanilla. DebugAction::DebugOptions | DebugAction::DumpDynamicTextures | DebugAction::Profiling - | DebugAction::ProfilingChart - | DebugAction::FpsCharts - | DebugAction::NetworkCharts - | DebugAction::LightmapTexture => true, + | DebugAction::ProfilingChart => true, DebugAction::ShowHitboxes | DebugAction::ShowChunkBorders | DebugAction::SwitchGameMode diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index f4e410e2f..e73de6988 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -372,7 +372,13 @@ impl Game<'_> { let world_dir = std::env::current_dir()?.join(&universe).join(&level_name); let folder = world_dir.to_string_lossy().into_owned(); let new_world = !world_dir.join("level.dat").exists(); - self.open_world(&folder, Some(&level_name), Some(props.seed), game_mode == 1)?; + self.open_world( + &folder, + Some(&level_name), + Some(props.seed), + game_mode == 1, + None, + )?; if new_world { self.level.hardcore = props.hardcore; } diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index f8440f06e..0d8043ecc 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -514,9 +514,15 @@ impl Game<'_> { } self.using = None; self.inventory[self.selected] = stack.clone(); - let used_before = stack - .as_ref() - .map_or(0, |s| self.stats.get("used", &s.item)); + self.offhand = parse_stack(op["offhand"].as_str().unwrap_or("-"))?; + // The used statistic of each item held, once. + let mut items: Vec<_> = [stack.as_ref(), self.offhand.as_ref()] + .into_iter() + .flatten() + .map(|s| s.item.clone()) + .collect(); + items.dedup(); + let used_before: Vec<_> = items.iter().map(|i| self.stats.get("used", i)).collect(); self.forced_hit = Some(super::Hit { pos: [pos.x, pos.y, pos.z], face: [0, 1, 0], @@ -542,10 +548,10 @@ impl Game<'_> { out.push(format!("msg {key}")); } } - if let Some(s) = &stack { - let used = self.stats.get("used", &s.item) - used_before; + for (item, before) in items.iter().zip(used_before) { + let used = self.stats.get("used", item) - before; if used != 0 { - out.push(format!("stat {} minecraft:used {used}", s.item)); + out.push(format!("stat {item} minecraft:used {used}")); } } let using = self @@ -553,8 +559,9 @@ impl Game<'_> { .and_then(|(slot, _)| self.stack_in(slot)) .map_or("-".to_owned(), |s| s.item.to_string()); out.push(format!( - "held {} using {using}", - canon_stack(self.inventory[self.selected].as_ref()) + "held {} offhand {} using {using}", + canon_stack(self.inventory[self.selected].as_ref()), + canon_stack(self.offhand.as_ref()) )); out.push(match self.respawn_config { Some(c) => format!( @@ -568,6 +575,7 @@ impl Game<'_> { }); self.player = None; self.using = None; + self.offhand = None; Ok(out) } diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index e8ceb5be3..15f24f82f 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -950,7 +950,7 @@ impl Game<'_> { "minecraft:firework_rocket" => { let mut shot = Projectile::new(ProjectileKind::Snowball, at, None); shot.shoot(&mut own, dir, power, uncertainty); - self.launch_dispensed_rocket(at, shot.velocity, &one); + self.launch_angled_rocket(at, shot.velocity, &one); } _ => { let kind = match item.as_str() { diff --git a/crates/horizon-client/src/game/fireworks.rs b/crates/horizon-client/src/game/fireworks.rs index cd4e01a16..0e074025f 100644 --- a/crates/horizon-client/src/game/fireworks.rs +++ b/crates/horizon-client/src/game/fireworks.rs @@ -85,8 +85,9 @@ impl Game<'_> { self.swing_arm(); true } - /// `FireworkRocketItem.asProjectile` shot out of a dispenser. - pub(super) fn launch_dispensed_rocket(&mut self, at: Vec3, velocity: Vec3, stack: &ItemStack) { + /// A rocket shot at an angle (`DATA_SHOT_AT_ANGLE`): out of a dispenser + /// (`FireworkRocketItem.asProjectile`) or a crossbow. + pub(super) fn launch_angled_rocket(&mut self, at: Vec3, velocity: Vec3, stack: &ItemStack) { let mut rocket = self.new_rocket(at, stack, false); rocket.velocity = velocity; rocket.angled = true; diff --git a/crates/horizon-client/src/game/fov.rs b/crates/horizon-client/src/game/fov.rs index 102248861..778c0f0a2 100644 --- a/crates/horizon-client/src/game/fov.rs +++ b/crates/horizon-client/src/game/fov.rs @@ -146,7 +146,7 @@ impl Game<'_> { /// `SpyglassItem.use`: start scoping. pub(super) fn use_spyglass(&mut self) { if self.using.is_none() { - self.using = Some((self.selected, 0)); + self.using = Some((self.held_slot(), 0)); let at = self.eye_position(); self.audio.play("minecraft:item.spyglass.use", at, 1.0, 1.0); } diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index ec5123424..3d5f7ca44 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -42,9 +42,9 @@ impl Game<'_> { self.swings_started += 1; } } - /// `swing(InteractionHand.MAIN_HAND)` with the default animation. + /// `swing(hand)` for the hand that acts, with the default animation. pub(super) fn swing_arm(&mut self) { - self.swing_hand(Hand::Main, SwingAnimation::DEFAULT); + self.swing_hand(self.hand, SwingAnimation::DEFAULT); } /// `Player.resetAttackStrengthTicker`. pub(super) fn reset_attack_strength(&mut self) { @@ -166,18 +166,23 @@ impl Game<'_> { if self.clicks.destroying.active || self.hands_busy() { return Ok(()); } - let before = self.held().cloned(); + let before = [self.stack_in(self.selected).cloned(), self.offhand.clone()]; let swings = self.swings_started; let using = self.using.is_some(); - self.use_item()?; + let Some(hand) = self.use_item()? else { + return Ok(()); + }; + let (before, after) = match hand { + Hand::Main => (&before[0], self.stack_in(self.selected).cloned()), + Hand::Off => (&before[1], self.offhand.clone()), + }; let swung = self.swings_started != swings; - let after = self.held().cloned(); - let spent = match (&before, &after) { + let spent = match (before, &after) { (Some(a), Some(b)) => a.count != b.count || a.item != b.item || self.creative, _ => false, }; if (swung && spent) || (!using && self.using.is_some() && after.is_some()) { - self.heights.item_used(Hand::Main); + self.heights.item_used(hand); } Ok(()) } @@ -272,6 +277,22 @@ impl Game<'_> { .and_then(|h| self.res.items.get(&h.item)) .map_or(0.0, |i| f64::from(i.attack_speed)) } + /// `evaluateWhichHandsToRender`: which of the main and off hand show. + pub(super) fn hands_to_render(&self) -> [bool; 2] { + let held = |slot| { + self.stack_in(slot) + .map(|s: &ItemStack| (&*s.item, s.data().is_some_and(|d| !d.charged.is_empty()))) + }; + let using = self.used_hand().zip( + self.using + .and_then(|(slot, _)| self.stack_in(slot)) + .map(|s| &*s.item), + ); + horizon_client::first_person::hands_to_render( + [held(self.selected), held(super::shield::OFFHAND_SLOT)], + using, + ) + } /// The visible main- and off-hand items. pub(super) fn visible_hand_items(&self) -> [Option; 2] { [ diff --git a/crates/horizon-client/src/game/maps.rs b/crates/horizon-client/src/game/maps.rs index 3da532a31..e2d4617fc 100644 --- a/crates/horizon-client/src/game/maps.rs +++ b/crates/horizon-client/src/game/maps.rs @@ -482,7 +482,7 @@ impl Game<'_> { if self.creative { self.give_or_drop_stack(filled); } else if stack.count == 1 { - self.inventory[self.selected] = Some(filled); + *self.held_mut() = Some(filled); } else { self.consume_held(); self.give_or_drop_stack(filled); diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 47b1ab053..06d5466da 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -13,6 +13,7 @@ use horizon_client::{ mesher::Vertex, mobs::{Part, anim::Poses}, particles::{ParticleOptions, ParticleType}, + sound_engine::{CartSound, SoundEngine, SoundInstance, Sounds}, }; use horizon_core::{ geometry::{Aabb, Vec3}, @@ -786,6 +787,42 @@ impl Game<'_> { } } } + /// `ClientPacketListener.postAddEntitySoundInstance` for the carts that + /// joined the level since the last tick, and `LocalPlayer.startRiding`'s + /// two inside sounds when the player got in one; then what the sound + /// instances read this tick (the ridden cart and every cart). + pub(super) fn start_cart_sounds(&mut self) -> (Option, Vec) { + let carts: Vec = self + .carts + .iter() + .map(|c| CartSound { + id: c.id, + position: [c.position.x, c.position.y, c.position.z], + // Vec3.horizontalDistance. + speed: (c.velocity.x * c.velocity.x + c.velocity.z * c.velocity.z).sqrt(), + }) + .collect(); + self.cart_sounds + .retain(|id| carts.iter().any(|c| c.id == *id)); + for cart in &carts { + if self.cart_sounds.insert(cart.id) { + let instance = SoundInstance::minecart(cart, SoundEngine::unseeded()); + self.audio.play_instance(instance, false); + } + } + let vehicle = self.riding.filter(|id| carts.iter().any(|c| c.id == *id)); + if vehicle != self.riding_cart_sounds + && let Some(cart) = carts.iter().find(|c| Some(c.id) == vehicle) + { + for underwater in [true, false] { + let instance = + SoundInstance::riding_minecart(cart, underwater, SoundEngine::unseeded()); + self.audio.play_instance(instance, false); + } + } + self.riding_cart_sounds = vehicle; + (vehicle, carts) + } /// The rider's tick: the cart moves with the rider's input as its push. pub(super) fn tick_cart_riding(&mut self, keys: Keys) -> bool { let Some(i) = self.carts.iter().position(|c| Some(c.id) == self.riding) else { @@ -1044,6 +1081,7 @@ impl Game<'_> { let burning = self .held() .is_some_and(|s| s.enchantment_level("minecraft:fire_aspect") > 0); + self.vehicle_attack_sounds(); self.hurt_cart(i, damage, self.creative, burning); self.swing_arm(); true diff --git a/crates/horizon-client/src/game/music.rs b/crates/horizon-client/src/game/music.rs index 59c14f998..43607ab44 100644 --- a/crates/horizon-client/src/game/music.rs +++ b/crates/horizon-client/src/game/music.rs @@ -28,9 +28,13 @@ impl Game<'_> { } self.sound_paused = self.pause; } + let (vehicle, carts) = self.start_cart_sounds(); let ctx = TickContext { player_underwater: self.ambience.was_underwater(), player_removed: self.player.is_none(), + vehicle, + carts, + frozen: !self.clock.runs_normally(), }; self.audio.tick(self.pause, &ctx); } diff --git a/crates/horizon-client/src/game/natural_spawning.rs b/crates/horizon-client/src/game/natural_spawning.rs index 83d7ddfb3..0992bac02 100644 --- a/crates/horizon-client/src/game/natural_spawning.rs +++ b/crates/horizon-client/src/game/natural_spawning.rs @@ -26,7 +26,7 @@ use std::collections::HashMap; /// The game level as natural spawning reads it. pub(super) struct GameLevel<'g, 'a> { pub(super) game: &'g Game<'a>, - w: MobWorld<'g>, + pub(super) w: MobWorld<'g>, /// Boxes of the mobs this pass created, not yet in the game's list. pub(super) pending: std::cell::RefCell>, /// The types and boxes of what a spawner created this tick. diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 683e57c9e..826480bd6 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -89,7 +89,7 @@ impl Game<'_> { match &*stack.item { "minecraft:potion" | "minecraft:ominous_bottle" => { if self.using.is_none() { - self.using = Some((self.selected, 0)); + self.using = Some((self.held_slot(), 0)); } Ok(true) } @@ -177,8 +177,8 @@ impl Game<'_> { return; } self.consume_held(); - if self.inventory[self.selected].is_none() { - self.inventory[self.selected] = Some(filled); + if self.held().is_none() { + *self.held_mut() = Some(filled); } else if let Some(rest) = self.give(filled) && let Some(eye) = self.eye_position() { @@ -218,15 +218,15 @@ impl Game<'_> { self.apply_effect_action(a); } if !self.creative { - if let Some(s) = self.inventory[slot].as_mut() { + if let Some(s) = self.stack_in_mut(slot).as_mut() { s.count -= 1; if s.count == 0 { - self.inventory[slot] = None; + *self.stack_in_mut(slot) = None; } } let bottle = ItemStack::new("minecraft:glass_bottle", 1); - if self.inventory[slot].is_none() { - self.inventory[slot] = Some(bottle); + if self.stack_in(slot).is_none() { + *self.stack_in_mut(slot) = Some(bottle); } else if let Some(rest) = self.give(bottle) { self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40); } diff --git a/crates/horizon-client/src/game/powder_snow.rs b/crates/horizon-client/src/game/powder_snow.rs index 091114131..7d0a7770d 100644 --- a/crates/horizon-client/src/game/powder_snow.rs +++ b/crates/horizon-client/src/game/powder_snow.rs @@ -119,7 +119,7 @@ impl Game<'_> { } return; } - let held = &mut self.inventory[self.selected]; + let held = self.held_mut(); let last = held.as_ref().is_none_or(|s| s.count <= 1); if last { *held = Some(filled); diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index 1f1fa3507..9e73d790c 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -1224,11 +1224,11 @@ impl Game<'_> { self.audio .play("minecraft:item.ominous_bottle.dispose", Some(eye), 1.0, 1.0); if !self.creative - && let Some(s) = self.inventory[slot].as_mut() + && let Some(s) = self.stack_in_mut(slot).as_mut() { s.count -= 1; if s.count == 0 { - self.inventory[slot] = None; + *self.stack_in_mut(slot) = None; } } } diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 67e79eb6a..ef4caa988 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -197,28 +197,59 @@ impl Game<'_> { search.reset_blink(); } - /// The toast for newly unlocked recipes: one for a burst of unlocks. + /// `RecipeToast.addOrUpdate` for each display of the recipes just + /// unlocked: its crafting station and result join the toast still + /// queued or shown, or a new one. pub(super) fn recipe_toast(&mut self, recipes: &[String]) { if recipes.is_empty() || self.adv.quiet { return; } self.ensure_book(); - let icon = self - .recipe_ui - .book - .as_ref() - .and_then(|b| recipes.iter().find_map(|id| b.entry(id))) - .map(|e| e.result.item.to_string()); - let Some(icon) = icon else { return }; - let fresh = self - .adv - .toasts - .back() - .is_some_and(|t| t.is_recipe() && !t.was_shown()); - if !fresh { - self.adv + let index = &self.res.stations.recipe_index; + let book = self.recipe_ui.book.as_ref(); + // SmithingTrimDemoSlotDisplay draws from a random of its own. + let mut random = super::dispenser::entity_random(); + let mut items = Vec::new(); + for id in recipes { + let Some(station) = index.toast_station(id) else { + continue; + }; + for display in index.display_ids(id) { + // The book's displays carry their resolved results; the + // other recipe types name theirs, and trims are demos. + let result = book + .and_then(|b| { + b.entry_of_display(display) + .map(|i| b.entries[i].result.clone()) + }) + .or_else(|| index.result(id).map(|r| ItemStack::new(r, 1))) + .or_else(|| { + self.res.stations.recipes.trim_demo( + &self.res.stations.enchantments, + id, + &mut |n| { + horizon_core::random::RandomSource::next_int_bound( + &mut random, + n as i32, + ) + .unwrap_or(0) as usize + }, + ) + }); + if let Some(result) = result { + items.push((station.to_owned(), result)); + } + } + } + if items.is_empty() { + return; + } + match self.adv.toasts.iter_mut().find(|t| t.is_recipe()) { + Some(toast) => toast.add_recipes(items), + None => self + .adv .toasts - .push_back(super::advancements::Toast::recipe(&icon)); + .push_back(super::advancements::Toast::recipe(items)), } } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3ec2b9924..6ad981151 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -272,6 +272,7 @@ impl Game<'_> { r.session.disconnect(); } horizon_client::crash::clear_detail("Server"); + self.debug_charts.reset(); self.tab_list.reset(); self.score.board = Default::default(); self.streaming = Streaming::new(Arc::new(NoTerrain), self.res.context.clone(), 1); @@ -736,6 +737,11 @@ impl Game<'_> { fn handle_packet(&mut self, packet: C) -> Result<()> { match packet { + // PingDebugMonitor.onPongReceived. + C::PongResponse(p) => { + let delay = self.debug_millis() - p.time; + self.debug_charts.ping.log(delay); + } C::Login(p) => { if let Some(r) = self.remote.as_mut() { r.online_mode = p.online_mode; diff --git a/crates/horizon-client/src/game/respawn_anchor.rs b/crates/horizon-client/src/game/respawn_anchor.rs index f2f21469f..834d1ad44 100644 --- a/crates/horizon-client/src/game/respawn_anchor.rs +++ b/crates/horizon-client/src/game/respawn_anchor.rs @@ -4,6 +4,7 @@ //! (`ServerPlayer.findRespawnAndUseSpawnBlock`, `PlayerList.respawn`), //! using a charge. use super::{Dim, Game}; +use horizon_client::first_person::Hand; use horizon_client::{ Result, blocks::Fluid, @@ -104,7 +105,7 @@ impl Game<'_> { .play("minecraft:block.respawn_anchor.charge", Some(at), 1.0, 1.0); Ok(()) } - /// `RespawnAnchorBlock.useItemOn` with `held` in the main hand. + /// `RespawnAnchorBlock.useItemOn` with `held` in the hand that acts. pub(super) fn use_respawn_anchor( &mut self, pos: [i32; 3], @@ -126,37 +127,11 @@ impl Game<'_> { } return Ok(AnchorUse::Charged); } - if fuel(self.offhand.as_ref()) && chargeable { + if self.hand == Hand::Main && fuel(self.offhand.as_ref()) && chargeable { return Ok(AnchorUse::Pass); } Ok(AnchorUse::Other) } - /// The off hand's glowstone on an anchor the main hand passed on. - pub(super) fn charge_anchor_from_offhand(&mut self, pos: [i32; 3]) -> Result { - let state = self.world.block(pos[0], pos[1], pos[2]); - let fuel = self - .offhand - .as_ref() - .is_some_and(|s| &*s.item == "minecraft:glowstone"); - if !self.is_anchor(state) || !fuel || self.anchor_charges(state) >= 4 { - return Ok(false); - } - let used = self.offhand.clone(); - self.charge_anchor(pos, state, Some(Who::Player))?; - if !self.creative - && let Some(s) = self.offhand.as_mut() - { - s.count -= 1; - if s.count == 0 { - self.offhand = None; - } - } - if let Some(stack) = used { - self.trigger_block("minecraft:item_used_on_block", pos, &stack); - } - self.swing_arm(); - Ok(true) - } /// `RespawnAnchorBlock.useWithoutItem` on a charged anchor: outside the /// Nether it explodes; inside, it becomes the respawn point. pub(super) fn respawn_anchor_used(&mut self, pos: [i32; 3]) -> Result<()> { diff --git a/crates/horizon-client/src/game/shield.rs b/crates/horizon-client/src/game/shield.rs index 2821738c5..733dae55f 100644 --- a/crates/horizon-client/src/game/shield.rs +++ b/crates/horizon-client/src/game/shield.rs @@ -23,7 +23,7 @@ impl Game<'_> { self.inventory.get(slot)?.as_ref() } } - fn stack_in_mut(&mut self, slot: usize) -> &mut Option { + pub(super) fn stack_in_mut(&mut self, slot: usize) -> &mut Option { if slot == OFFHAND_SLOT { &mut self.offhand } else { @@ -47,10 +47,6 @@ impl Game<'_> { } true } - /// Main-hand use fell through: try the off hand (Minecraft.startUseItem). - pub(super) fn use_offhand(&mut self) -> bool { - self.raise_shield(OFFHAND_SLOT) - } /// `LivingEntity.getItemBlockingWith` and the inputs of `applyItemBlocking` /// for an attack from `from` (`DamageSource.getSourcePosition`). pub(super) fn player_blocking( diff --git a/crates/horizon-client/src/game/spawner.rs b/crates/horizon-client/src/game/spawner.rs index ef61d58ee..30b8cc67b 100644 --- a/crates/horizon-client/src/game/spawner.rs +++ b/crates/horizon-client/src/game/spawner.rs @@ -20,7 +20,7 @@ use std::collections::{HashMap, HashSet}; type Pos = (i32, i32, i32); /// What a spawner tick decided to add, created once the level is free. -enum Planned { +pub(super) enum Planned { /// `finalizeSpawn` ran on a fresh mob. Finalized(Mob), /// A mob loaded from the spawn data (with its passengers). @@ -113,7 +113,12 @@ impl Game<'_> { spawner.server_tick(&level, &mut random, pos, &mut spawn, &mut events); } self.world.random = random; - // Provisional ids (counting down from u32::MAX) become the mobs' ids. + let ids = self.add_planned(planned); + self.apply_spawner_events(key, events, &ids) + } + /// Creates the mobs a spawner tick planned; their provisional ids + /// (counting down from u32::MAX) map to the mobs' ids. + pub(super) fn add_planned(&mut self, planned: Vec) -> HashMap { let mut ids = HashMap::new(); for (i, plan) in planned.into_iter().enumerate() { let provisional = u32::MAX - i as u32; @@ -133,11 +138,11 @@ impl Game<'_> { ids.insert(provisional, id); } } - self.apply_spawner_events(key, events, &ids) + ids } /// The spawner's `loadEntityRecursive` and `tryAddFreshEntityWithPassengers`: /// the mob it will add (created after the tick) and its box. - fn plan_spawner_mob( + pub(super) fn plan_spawner_mob( &self, l: &super::natural_spawning::GameLevel, r: &SpawnerSpawn, @@ -151,6 +156,8 @@ impl Game<'_> { let facts = self.biome_facts(x.floor() as i32, y.floor() as i32, z.floor() as i32); let difficulty = self.local_difficulty(r.position); spawning::finalize(&mut mob, &facts, &difficulty); + // TrialSpawner.spawnMob: setPersistenceRequired. + mob.persistent = r.trial; horizon_client::mobs::raider::finalize( &mut mob, horizon_client::mobs::raider::Reason::Other, @@ -187,6 +194,9 @@ impl Game<'_> { Tag::Float(0f32.to_bits()), ]), ); + if r.trial { + tag.insert("PersistenceRequired".into(), Tag::Byte(1)); + } let tag = Tag::Compound(tag); let mob = horizon_client::entity_nbt::mob_from_nbt(&tag, &self.res.mob_types, 0)?; let bounds = mob.bounds(); diff --git a/crates/horizon-client/src/game/trial_spawner.rs b/crates/horizon-client/src/game/trial_spawner.rs new file mode 100644 index 000000000..6427cbeb1 --- /dev/null +++ b/crates/horizon-client/src/game/trial_spawner.rs @@ -0,0 +1,230 @@ +//! Trial spawners in the game: `TrialSpawner.tickServer` for every trial +//! spawner (`mobs::trial_spawner`), the block's state as it changes, the mobs +//! it adds and the rewards it ejects. +use super::{Game, natural_spawning::GameLevel, spawner::Planned}; +use horizon_client::{ + Result, + containers::BlockEntity, + items::ItemStack, + mobs::{ + Who, + spawner::SpawnerSpawn, + trial_spawner::{ + TrialEvent, TrialPlayer, TrialSpawner, TrialSpawnerLevel, TrialState, Uuid, + }, + }, +}; +use horizon_core::{ + geometry::Vec3, + random::{LegacyRandom, RandomSource}, +}; +use horizon_world::nbt::Tag; +use std::collections::HashMap; + +type Pos = (i32, i32, i32); + +impl TrialSpawnerLevel for GameLevel<'_, '_> { + fn game_time(&self) -> i64 { + self.game.world.game_time + } + fn mob_spawning(&self) -> bool { + self.game.ui.rules.bool("spawn_mobs") + } + fn players(&self) -> Vec { + let (Some(p), Some(view)) = (self.game.player.as_ref(), self.game.player_view()) else { + return Vec::new(); + }; + vec![TrialPlayer { + uuid: self.game.level.player_uuid.unwrap_or_default(), + block: [p.position.x, p.position.y, p.position.z].map(|v| v.floor() as i32), + eye: view.eye, + creative: self.game.creative, + spectator: self.game.spectator(), + }] + } + fn visual_hit(&self, from: [f64; 3], to: [f64; 3]) -> Option<[i32; 3]> { + let v = |p: [f64; 3]| Vec3::new(p[0], p[1], p[2]); + self.w.visual_hit(v(from), v(to)) + } + fn entity_block(&self, uuid: Uuid) -> Option<[i32; 3]> { + let (id, _) = self.game.persist.uuids.iter().find(|(_, u)| **u == uuid)?; + let m = self.game.mobs.iter().find(|m| m.id == *id)?; + (!m.removed && m.alive()) + .then(|| [m.position.x, m.position.y, m.position.z].map(|v| v.floor() as i32)) + } +} + +impl Game<'_> { + /// Every trial spawner's server tick. + pub(super) fn tick_trial_spawners(&mut self) -> Result<()> { + let keys: Vec = self + .world + .block_entities + .iter() + .filter(|(_, e)| matches!(e, BlockEntity::TrialSpawner(_))) + .map(|(k, _)| *k) + .collect(); + for key in keys { + let state = self.world.block(key.0, key.1, key.2); + let Some(block) = self.res.assets.registry.state(state).cloned() else { + continue; + }; + if block.name != "minecraft:trial_spawner" { + continue; + } + let Some(BlockEntity::TrialSpawner(mut spawner)) = + self.world.block_entities.remove(&key) + else { + continue; + }; + let current = block + .properties + .get("trial_spawner_state") + .and_then(|s| TrialState::from_name(s)) + .unwrap_or_default(); + let ominous = block.properties.get("ominous").is_some_and(|v| v == "true"); + let result = self.server_tick_trial_spawner(key, &mut spawner, current, ominous); + self.world + .block_entities + .insert(key, BlockEntity::TrialSpawner(spawner)); + result?; + } + Ok(()) + } + fn server_tick_trial_spawner( + &mut self, + key: Pos, + spawner: &mut TrialSpawner, + current: TrialState, + ominous: bool, + ) -> Result<()> { + let pos = [key.0, key.1, key.2]; + let mut random = std::mem::replace(&mut self.world.random, LegacyRandom::new(0)); + let mut sequences = std::mem::take(&mut self.rand_sequences); + let mut events = Vec::new(); + let mut planned: Vec = Vec::new(); + let mut uuids: Vec<(u32, Uuid)> = Vec::new(); + let mut ejected: Vec<(ItemStack, [f64; 3])> = Vec::new(); + let next = { + let level = self.natural_level(); + let loot = horizon_client::structure_blocks::loot_data(&self.options.resources); + let seed = self.level.seed; + let mut spawn = |l: &GameLevel, r: &SpawnerSpawn| { + let added = l.game.plan_spawner_mob(l, r, &mut planned)?; + let uuid = match planned.last_mut() { + Some(Planned::Loaded(Tag::Compound(tag))) => { + let tag_uuid = + horizon_client::entity_nbt::uuid(&Tag::Compound(tag.clone())); + tag_uuid.unwrap_or_else(|| { + let uuid = horizon_client::save::random_uuid(); + tag.insert("UUID".into(), Tag::IntArray(uuid.to_vec())); + uuid + }) + } + _ => horizon_client::save::random_uuid(), + }; + uuids.push((added.id, uuid)); + Some(uuid) + }; + // TrialSpawner.ejectReward: the table's items, each thrown up out + // of the spawner (DefaultDispenseItemBehavior.spawnItem, accuracy 2). + let mut eject = |table: &str, random: &mut LegacyRandom| { + let Some(loot) = &loot else { + return false; + }; + let drops = match loot.random_sequence(table) { + Some(s) => loot.roll_split(table, sequences.get(s, seed)), + None => loot.roll_split(table, random), + }; + for stack in &drops { + // The power, which only scales the direction's x and z (0 going up). + random.next_double(); + let spread = 0.017_227_5 * 2.0; + let v = [ + random.triangle(0.0, spread), + random.triangle(0.2, spread), + random.triangle(0.0, spread), + ]; + ejected.push(( + horizon_client::structure_blocks::loot_item_with_components(stack), + v, + )); + } + !drops.is_empty() + }; + spawner.server_tick( + &level, + &mut random, + pos, + current, + ominous, + &mut spawn, + &mut eject, + &mut events, + ) + }; + self.world.random = random; + self.rand_sequences = sequences; + let ids = self.add_planned(planned); + let mut by_uuid = HashMap::new(); + for (provisional, uuid) in uuids { + if let Some(id) = ids.get(&provisional) { + self.persist.uuids.insert(*id, uuid); + by_uuid.insert(uuid, *id); + } + } + let center = pos.map(|v| f64::from(v) + 0.5); + // Vec3.atBottomCenterOf(pos).relative(UP, 1.2), lowered by spawnItem. + let above = [center[0], center[1] + 0.7 - 0.125, center[2]]; + for (stack, v) in ejected { + self.spawn_item(stack, above, v, 0); + } + if next != current || ominous != spawner.is_ominous { + self.set_trial_spawner_state(key, next, spawner.is_ominous)?; + } + for event in events { + match event { + TrialEvent::BlockUpdated => self.trial_spawner_updated(key), + TrialEvent::LevelEvent(id, at, data) => self.level_event_at(id, at, data), + TrialEvent::Sound(name) => { + self.audio + .play(&format!("minecraft:{name}"), Some(center), 1.0, 1.0) + } + // Written with the state above. + TrialEvent::OminousSet(_) => {} + TrialEvent::EntityPlace(uuid, at) => { + let who = by_uuid.get(&uuid).map(|id| Who::Mob(*id)); + self.post_block_game_event("minecraft:entity_place", at, who, None); + } + } + } + Ok(()) + } + /// `setState` (and `removeOminous`): the block's state and ominous flag. + fn set_trial_spawner_state( + &mut self, + key: Pos, + state: TrialState, + ominous: bool, + ) -> Result<()> { + let current = self.world.block(key.0, key.1, key.2); + let Some(mut block) = self.res.assets.registry.state(current).cloned() else { + return Ok(()); + }; + block + .properties + .insert("trial_spawner_state".into(), state.name().into()); + block + .properties + .insert("ominous".into(), ominous.to_string()); + let id = self.res.assets.registry.resolve(&block)?; + self.level_set([key.0, key.1, key.2], id) + } + /// `markUpdated`: the clients load the new update tag. + fn trial_spawner_updated(&mut self, key: Pos) { + if let Some(log) = self.world.block_log.as_mut() { + log.push(key); + } + self.world.modified.insert((key.0 >> 4, key.2 >> 4)); + } +} diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index aef884601..179ade374 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -78,7 +78,7 @@ impl Game<'_> { return true; } if self.using.is_none() { - self.using = Some((self.selected, 0)); + self.using = Some((self.held_slot(), 0)); } true } @@ -99,7 +99,7 @@ impl Game<'_> { if ticks < 10 { return; } - let Some(stack) = self.inventory[self.selected].clone() else { + let Some(stack) = self.held().cloned() else { return; }; let Some(eye) = self.eye_position() else { @@ -134,13 +134,13 @@ impl Game<'_> { } // hurtWithoutBreaking, then the thrown copy. if !self.creative - && let Some(s) = self.inventory[self.selected].as_mut() + && let Some(s) = self.held_mut().as_mut() { s.damage += 1; } - let thrown = self.inventory[self.selected].clone().unwrap_or(stack); + let thrown = self.held().cloned().unwrap_or(stack); if !self.creative { - self.inventory[self.selected] = None; + *self.held_mut() = None; } let start = Vec3::new(eye[0], eye[1] - 0.1, eye[2]); let mut projectile = horizon_client::projectiles::Projectile::new( diff --git a/crates/horizon-client/src/game/wind.rs b/crates/horizon-client/src/game/wind.rs index 105e27984..9dae29564 100644 --- a/crates/horizon-client/src/game/wind.rs +++ b/crates/horizon-client/src/game/wind.rs @@ -71,11 +71,11 @@ impl Game<'_> { self.stats.add("used", "minecraft:wind_charge", 1); self.swing_arm(); if !self.creative - && let Some(s) = self.inventory[self.selected].as_mut() + && let Some(s) = self.held_mut().as_mut() { s.count -= 1; if s.count == 0 { - self.inventory[self.selected] = None; + *self.held_mut() = None; } } Ok(true) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 540ea49a0..8b7f26125 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -170,6 +170,9 @@ pub struct Frame<'a> { pub block_flicker: f32, /// Blur and grade the frame under a Horizon-style menu (`post`). pub post: Option, + /// `Screen.extractBlurredBackground`: blur the frame by this radius + /// (`menuBackgroundBlurriness`) before the screen is drawn over it. + pub menu_blur: Option, } /// One frame of the world border wall (`WorldBorderRenderer.render`). #[derive(Clone, Debug)] @@ -198,6 +201,9 @@ pub struct Renderer { gpu_timer: Option, /// GPU frame times (ms) read back since the caller last drained them. pub gpu_times: Vec, + /// The last lightmap written, RGBA rows of sky level by block level + /// (F3+4 shows it). + pub lightmap_pixels: [u8; 16 * 16 * 4], /// Time the last `render` spent blocked on the GPU or the display /// (acquiring, presenting, offscreen pacing), excluded from CPU time. pub last_wait: std::time::Duration, @@ -288,6 +294,8 @@ pub struct Renderer { pub hud: HudRenderer, /// The menus' backdrop blur, made on first use. post: Option, + /// Vanilla's menu background blur, made on first use. + menu_blur: Option, pub info: wgpu::AdapterInfo, pub suspended: bool, pub drawn_sections: usize, @@ -1364,6 +1372,7 @@ impl Renderer { in_flight: std::collections::VecDeque::new(), gpu_timer, gpu_times: Vec::new(), + lightmap_pixels: [0; 16 * 16 * 4], last_wait: std::time::Duration::ZERO, last_encode: std::time::Duration::ZERO, window, @@ -1433,6 +1442,7 @@ impl Renderer { world_post, hud, post: None, + menu_blur: None, info, suspended: size.width == 0 || size.height == 0, drawn_sections: 0, @@ -1729,7 +1739,7 @@ impl Renderer { world_projection(fov_degrees, aspect, far) * bob * crate::camera::view_matrix(yaw, pitch) } fn update_lightmap( - &self, + &mut self, sky: &Sky, darkness: f32, gamma: f32, @@ -1785,6 +1795,7 @@ impl Renderer { depth_or_array_layers: 1, }, ); + self.lightmap_pixels = pixels; } fn animate(&mut self, tick: u64) { animate_sprites( @@ -2396,6 +2407,23 @@ impl Renderer { pass.draw_indexed(0..6, (i * 4) as i32, 0..1); } } + if let Some(radius) = frame.menu_blur + && self.config.usage.contains(wgpu::TextureUsages::COPY_SRC) + { + let format = self.config.format; + let device = &self.device; + self.menu_blur + .get_or_insert_with(|| crate::menu_blur::MenuBlur::new(device, format)) + .apply( + &self.device, + &self.queue, + &mut encoder, + &target_texture, + &view_target, + [self.config.width, self.config.height], + radius, + ); + } if let Some(grade) = &frame.post && self.config.usage.contains(wgpu::TextureUsages::COPY_SRC) { diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index a9a4864ce..db0677d5f 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -583,6 +583,10 @@ impl HurtWorld for Environment<'_> { self.event(HealthEvent::DamageBroadcast { source: self.source.type_id(), }); + // The player hears its own hurt sound from handleDamageEvent; a + // blocked hit sends the block sound (onBlocked) instead. + let sound = hurt_sound(&self.source.definition().effects); + self.events.push(MotionEvent::HurtSound(sound)); Ok(()) } fn mark_hurt(&mut self, _: &mut State) -> io::Result<()> { @@ -619,11 +623,9 @@ impl HurtWorld for Environment<'_> { *self.dead = true; self.phase("death-request") } + /// `Player.playSound` leaves the player itself out: others hear this one. fn hurt_sound(&mut self, _: &mut State) -> io::Result<()> { - self.phase("hurt-sound")?; - let sound = hurt_sound(&self.source.definition().effects); - self.events.push(MotionEvent::HurtSound(sound)); - Ok(()) + self.phase("hurt-sound") } fn game_time(&mut self, _: &mut State) -> io::Result { Ok(self.game_time) diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 40bc0d2ea..8ea888fa7 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -45,6 +45,7 @@ pub mod crash; pub mod creative; pub mod data_cmd; pub mod datapack; +pub mod debug_chart; pub mod debug_keys; pub mod effects; pub mod enchant; @@ -93,6 +94,7 @@ pub mod lang; pub mod light; pub mod logging; pub mod menu; +pub mod menu_blur; pub mod merchant; pub mod mesher; pub mod minimap; diff --git a/crates/horizon-client/src/menu_blur.rs b/crates/horizon-client/src/menu_blur.rs new file mode 100644 index 000000000..65251f678 --- /dev/null +++ b/crates/horizon-client/src/menu_blur.rs @@ -0,0 +1,249 @@ +//! Vanilla's menu background blur (`GameRenderer.processBlurEffect`, the +//! `minecraft:blur` post chain): three rounds of a horizontal then a vertical +//! `post/box_blur` pass over the frame drawn so far, `menuBackgroundBlurriness` +//! framebuffer pixels wide, before the screen is drawn over it. Works in the +//! frame's own (gamma) values, as vanilla's main target does, and needs a +//! swapchain that can be copied from. + +/// `blur.json`: the passes' directions, ping-ponging between the copied +/// frame and a swap texture; the last one writes the frame. +const PASSES: [[f32; 2]; 6] = [ + [1.0, 0.0], + [0.0, 1.0], + [1.0, 0.0], + [0.0, 1.0], + [1.0, 0.0], + [0.0, 1.0], +]; + +#[repr(C)] +#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] +struct Uniform { + size_dir: [f32; 4], + radius: [f32; 4], +} + +pub struct MenuBlur { + layout: wgpu::BindGroupLayout, + pipeline: wgpu::RenderPipeline, + sampler: wgpu::Sampler, + uniforms: Vec, + /// The copied frame (`minecraft:main`) and `swap`. + targets: Vec<(wgpu::Texture, wgpu::TextureView)>, + size: [u32; 2], + format: wgpu::TextureFormat, +} +impl MenuBlur { + /// `format` is the swapchain's; the blur works in its non-sRGB view. + pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self { + let format = format.remove_srgb_suffix(); + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Menu blur"), + source: wgpu::ShaderSource::Wgsl(include_str!("menu_blur.wgsl").into()), + }); + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Menu blur bindings"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + ], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Menu blur"), + bind_group_layouts: &[Some(&layout)], + ..Default::default() + }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Menu blur pass"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_main"), + buffers: &[], + compilation_options: Default::default(), + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_main"), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + compilation_options: Default::default(), + }), + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + multiview_mask: None, + cache: None, + }); + // The post chain's "bilinear": true inputs, clamped like render targets. + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("Menu blur"), + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + ..Default::default() + }); + let uniforms = PASSES + .iter() + .map(|_| { + device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Menu blur pass"), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }) + }) + .collect(); + Self { + layout, + pipeline, + sampler, + uniforms, + targets: Vec::new(), + size: [0, 0], + format, + } + } + fn ensure(&mut self, device: &wgpu::Device, size: [u32; 2]) { + if self.size == size && !self.targets.is_empty() { + return; + } + self.size = size; + self.targets = (0..2) + .map(|_| { + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("Menu blur target"), + size: wgpu::Extent3d { + width: size[0], + height: size[1], + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: self.format, + usage: wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + let view = texture.create_view(&Default::default()); + (texture, view) + }) + .collect(); + } + /// Blur `frame` (the swapchain texture) in place through `target`, its + /// non-sRGB view, by `radius` pixels (`menuBackgroundBlurriness`). + #[allow(clippy::too_many_arguments)] + pub fn apply( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + frame: &wgpu::Texture, + target: &wgpu::TextureView, + size: [u32; 2], + radius: f32, + ) { + self.ensure(device, size); + encoder.copy_texture_to_texture( + frame.as_image_copy(), + self.targets[0].0.as_image_copy(), + wgpu::Extent3d { + width: size[0], + height: size[1], + depth_or_array_layers: 1, + }, + ); + for (i, dir) in PASSES.iter().enumerate() { + let data = Uniform { + size_dir: [size[0] as f32, size[1] as f32, dir[0], dir[1]], + radius: [radius, 0.0, 0.0, 0.0], + }; + queue.write_buffer(&self.uniforms[i], 0, bytemuck::bytes_of(&data)); + let source = &self.targets[i % 2].1; + let output = if i + 1 == PASSES.len() { + target + } else { + &self.targets[(i + 1) % 2].1 + }; + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Menu blur pass"), + layout: &self.layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(source), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Sampler(&self.sampler), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: self.uniforms[i].as_entire_binding(), + }, + ], + }); + let attachments = [Some(wgpu::RenderPassColorAttachment { + view: output, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), + store: wgpu::StoreOp::Store, + }, + })]; + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Menu blur pass"), + color_attachments: &attachments, + ..Default::default() + }); + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, &group, &[]); + pass.draw(0..3, 0..1); + } + } +} + +#[cfg(test)] +mod tests { + #[test] + fn box_blur_shader_validates() { + let module = naga::front::wgsl::parse_str(include_str!("menu_blur.wgsl")).unwrap(); + naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::all(), + ) + .validate(&module) + .unwrap(); + } +} diff --git a/crates/horizon-client/src/menu_blur.wgsl b/crates/horizon-client/src/menu_blur.wgsl new file mode 100644 index 000000000..d8b15fa94 --- /dev/null +++ b/crates/horizon-client/src/menu_blur.wgsl @@ -0,0 +1,32 @@ +// Vanilla's post/box_blur.fsh: one direction of a box blur of 2·Radius + 1 +// pixels, reading two pixels per linear sample. +struct Blur { + // InSize (pixels), BlurDir. + size_dir: vec4, + // Radius, unused, unused, unused. + radius: vec4, +} +@group(0) @binding(0) var src: texture_2d; +@group(0) @binding(1) var samp: sampler; +@group(0) @binding(2) var blur: Blur; +struct Out { + @builtin(position) clip: vec4, + @location(0) uv: vec2, +} +@vertex fn vs_main(@builtin(vertex_index) i: u32) -> Out { + let p = vec2(f32((i << 1u) & 2u), f32(i & 2u)); + var out: Out; + out.clip = vec4(p * 2.0 - 1.0, 0.0, 1.0); + out.uv = vec2(p.x, 1.0 - p.y); + return out; +} +@fragment fn fs_main(in: Out) -> @location(0) vec4 { + let step = blur.size_dir.zw / blur.size_dir.xy; + let radius = round(blur.radius.x); + var blurred = vec4(0.0); + for (var a = -radius + 0.5; a <= radius; a += 2.0) { + blurred += textureSampleLevel(src, samp, in.uv + step * a, 0.0); + } + blurred += textureSampleLevel(src, samp, in.uv + step * radius, 0.0) / 2.0; + return blurred / (radius + 0.5); +} diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 4f751aaa1..a98cbb897 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -65,6 +65,7 @@ pub mod sulfur_cube; pub mod tame; pub mod trader; pub mod transport_items; +pub mod trial_spawner; pub mod undead; pub mod vex; pub mod villager; @@ -74,6 +75,7 @@ pub mod warden_brain; pub mod witch; pub mod wither; mod world; +pub use world::visual_clip; pub mod zombie_villager; use crate::{blocks::BlockFacts, mesher::Vertex, world::World}; diff --git a/crates/horizon-client/src/mobs/spawner.rs b/crates/horizon-client/src/mobs/spawner.rs index 726164a89..5ed23b44a 100644 --- a/crates/horizon-client/src/mobs/spawner.rs +++ b/crates/horizon-client/src/mobs/spawner.rs @@ -107,11 +107,17 @@ impl SpawnData { } /// The entity compound is only its `id` (`hasNoConfiguration`): the /// spawned mob is finalized. - fn unconfigured(&self) -> bool { + pub(crate) fn unconfigured(&self) -> bool { self.entity.len() == 1 && self.id().is_some() } /// `CustomSpawnRules.isValidPosition`. - fn valid_position(r: CustomSpawnRules, l: &L, x: i32, y: i32, z: i32) -> bool { + pub(crate) fn valid_position( + r: CustomSpawnRules, + l: &L, + x: i32, + y: i32, + z: i32, + ) -> bool { let block = l.block_light(x, y, z); let sky = (l.sky_light(x, y, z) - l.sky_darken()).max(0); (r.block.0..=r.block.1).contains(&block) && (r.sky.0..=r.sky.1).contains(&sky) @@ -135,8 +141,19 @@ pub fn normalize_id(s: &str) -> Option { .then(|| format!("{ns}:{path}")) } +/// How much a slime's or magma cube's box is scaled by the size its data +/// loads (`Slime.readAdditionalSaveData`: Size + 1, kept in 1..=127), which +/// the obstruction test sees before `finalizeSpawn` picks one. +pub(crate) fn cube_scale(id: &str, entity: &Compound) -> f32 { + if !matches!(id, "minecraft:slime" | "minecraft:magma_cube") { + return 1.0; + } + number(entity.get(&JavaString::from("Size"))) + .map_or(1, |size| (size as i32).saturating_add(1).clamp(1, 127)) as f32 +} + /// A whole number from any numeric tag (`NumericTag.intValue`: floats floor). -fn number(tag: Option<&Tag>) -> Option { +pub(crate) fn number(tag: Option<&Tag>) -> Option { Some(match tag? { Tag::Byte(v) => i64::from(*v), Tag::Short(v) => i64::from(*v), @@ -255,6 +272,9 @@ pub struct SpawnerSpawn<'a> { /// `finalizeSpawn(SPAWNER)` runs (the data is just an id). pub finalize: bool, pub equipment: Option<&'a Tag>, + /// A trial spawner's mob (`EntitySpawnReason.TRIAL_SPAWNER`): it is + /// always persistent. + pub trial: bool, } /// An entity the level added: its id, box and whether it is a mob. #[derive(Clone, Copy, Debug)] @@ -370,25 +390,8 @@ impl Spawner { Next::Potential(i) => self.potentials.get_mut(*i).map(|(d, _)| d), } } - /// `WeightedList.getRandom`: one draw over the total weight, none when - /// the list weighs nothing. fn random_potential(&self, random: &mut impl RandomSource) -> Option { - let total: i64 = self.potentials.iter().map(|(_, w)| i64::from(*w)).sum(); - if total == 0 { - return None; - } - let mut pick = i64::from( - random - .next_int_bound(total.min(i64::from(i32::MAX)) as i32) - .unwrap_or(0), - ); - for (i, (_, w)) in self.potentials.iter().enumerate() { - pick -= i64::from(*w); - if pick < 0 { - return Some(i); - } - } - None + weighted_index(self.potentials.iter().map(|(_, w)| *w), random) } /// `getOrCreateNextSpawnData`: a potential at random, or empty data. fn next_or_create(&mut self, random: &mut impl RandomSource, events: &mut Vec) { @@ -555,7 +558,14 @@ impl Spawner { placed[1].floor() as i32, placed[2].floor() as i32, ]; - let bounds = spawn_selection::spawn_box(placed[0], placed[1], placed[2], width, height); + let scale = cube_scale(&id, &data.entity); + let bounds = spawn_selection::spawn_box( + placed[0], + placed[1], + placed[2], + width * scale, + height * scale, + ); let rules_ok = data.custom_spawn_rules.is_some() || spawn_selection::mob_spawn_rules(s, l, own[0], own[1], own[2]); if !rules_ok @@ -570,6 +580,7 @@ impl Spawner { yaw, finalize: data.unconfigured(), equipment: data.equipment.as_ref(), + trial: false, }; let Some(result) = spawn(l, &request) else { self.delay(random, events); @@ -643,6 +654,30 @@ impl Spawner { } } +/// `WeightedList.getRandom`: one draw over the total weight, none when the +/// list weighs nothing. +pub fn weighted_index( + weights: impl Iterator + Clone, + random: &mut impl RandomSource, +) -> Option { + let total: i64 = weights.clone().map(i64::from).sum(); + if total == 0 { + return None; + } + let mut pick = i64::from( + random + .next_int_bound(total.min(i64::from(i32::MAX)) as i32) + .unwrap_or(0), + ); + for (i, w) in weights.enumerate() { + pick -= i64::from(w); + if pick < 0 { + return Some(i); + } + } + None +} + /// `Entity.setPos` of a fresh mob: a shulker sits at the centre of its block. pub fn entity_position(s: Species, at: [f64; 3]) -> [f64; 3] { if s == Species::Shulker { @@ -657,7 +692,7 @@ pub fn entity_position(s: Species, at: [f64; 3]) -> [f64; 3] { } /// `Vec3.CODEC`: a list of three doubles. -fn read_pos(tag: Option<&Tag>) -> Option<[f64; 3]> { +pub(crate) fn read_pos(tag: Option<&Tag>) -> Option<[f64; 3]> { let Tag::List(v) = tag? else { return None; }; diff --git a/crates/horizon-client/src/mobs/trial_spawner.rs b/crates/horizon-client/src/mobs/trial_spawner.rs new file mode 100644 index 000000000..c422e1b66 --- /dev/null +++ b/crates/horizon-client/src/mobs/trial_spawner.rs @@ -0,0 +1,886 @@ +//! The trial spawner (`TrialSpawner` as `TrialSpawnerBlockEntity` runs it): +//! its configs, saved state (`TrialSpawnerStateData`) and the server tick that +//! walks `TrialSpawnerState`: waiting for players, spawning its waves while +//! they fight, ejecting a reward per player, then cooling down. +//! +//! The state lives in the block (`trial_spawner_state`); the tick reads it and +//! reports the next one. The level's random drives the tick in vanilla's draw +//! order; what the spawner asks of the level goes through +//! [`TrialSpawnerLevel`], so the game and a differential test world answer the +//! same questions. +use super::{ + spawn_rules::{self, Reason}, + spawn_selection, + spawner::{self, SpawnData, SpawnerLevel, SpawnerSpawn}, +}; +use horizon_core::{position::BlockPos, random::RandomSource}; +use horizon_world::nbt::{Compound, JavaString, Tag}; +use std::{collections::HashMap, path::Path, sync::OnceLock}; + +/// An entity's UUID as its four ints (`UUIDUtil.CODEC`). +pub type Uuid = [i32; 4]; + +/// `MAX_MOB_TRACKING_DISTANCE`: a spawned mob further than this stops +/// counting as one of the spawner's. +const MAX_MOB_TRACKING_DISTANCE: i64 = 47; +/// `DELAY_BEFORE_EJECT_AFTER_KILLING_LAST_MOB` and `TIME_BETWEEN_EACH_EJECTION`. +const DELAY_BEFORE_EJECT: f32 = 40.0; +const TIME_BETWEEN_EJECTIONS: f32 = 30.0; + +/// `TrialSpawnerConfig`. +#[derive(Clone, Debug, PartialEq)] +pub struct TrialConfig { + pub spawn_range: i32, + pub total_mobs: f32, + pub simultaneous_mobs: f32, + pub total_mobs_added_per_player: f32, + pub simultaneous_mobs_added_per_player: f32, + pub ticks_between_spawn: i32, + pub spawn_potentials: Vec<(SpawnData, i32)>, + pub loot_tables_to_eject: Vec<(String, i32)>, + pub items_to_drop_when_ominous: String, +} +impl Default for TrialConfig { + /// `TrialSpawnerConfig.Builder`'s defaults. + fn default() -> Self { + Self { + spawn_range: 4, + total_mobs: 6.0, + simultaneous_mobs: 2.0, + total_mobs_added_per_player: 2.0, + simultaneous_mobs_added_per_player: 1.0, + ticks_between_spawn: 40, + spawn_potentials: Vec::new(), + loot_tables_to_eject: vec![ + ("minecraft:spawners/trial_chamber/consumables".into(), 1), + ("minecraft:spawners/trial_chamber/key".into(), 1), + ], + items_to_drop_when_ominous: + "minecraft:spawners/trial_chamber/items_to_drop_when_ominous".into(), + } + } +} +impl TrialConfig { + /// `TrialSpawnerConfig.DIRECT_CODEC`; None when the tag is not a + /// compound. Read as `TagValueInput` does, keeping the partial result: + /// a field that fails to decode takes its default, and the list entries + /// that fail are dropped. + pub fn decode(tag: &Tag) -> Option { + let Tag::Compound(_) = tag else { + return None; + }; + let d = Self::default(); + let float = |k: &str, default: f32| { + tag.get(k) + .and_then(float) + .filter(|v| *v >= 0.0) + .unwrap_or(default) + }; + let int = |k: &str, default: i32, lo: i32, hi: i32| { + spawner::number(tag.get(k)) + .filter(|v| (i64::from(lo)..=i64::from(hi)).contains(v)) + .map_or(default, |v| v as i32) + }; + let list = |k: &str| match tag.get(k) { + Some(Tag::List(list)) => Some(list.iter()), + _ => None, + }; + let spawn_potentials = list("spawn_potentials").map_or_else(Vec::new, |l| { + l.filter_map(|e| Some((SpawnData::decode(e.get("data")?)?, weight(e.get("weight"))?))) + .collect() + }); + let loot_tables_to_eject = + list("loot_tables_to_eject").map_or(d.loot_tables_to_eject, |l| { + l.filter_map(|e| Some((identifier(e.get("data"))?, weight(e.get("weight"))?))) + .collect() + }); + Some(Self { + spawn_range: int("spawn_range", d.spawn_range, 1, 128), + total_mobs: float("total_mobs", d.total_mobs), + simultaneous_mobs: float("simultaneous_mobs", d.simultaneous_mobs), + total_mobs_added_per_player: float( + "total_mobs_added_per_player", + d.total_mobs_added_per_player, + ), + simultaneous_mobs_added_per_player: float( + "simultaneous_mobs_added_per_player", + d.simultaneous_mobs_added_per_player, + ), + ticks_between_spawn: int("ticks_between_spawn", d.ticks_between_spawn, 0, i32::MAX), + spawn_potentials, + loot_tables_to_eject, + items_to_drop_when_ominous: identifier(tag.get("items_to_drop_when_ominous")) + .unwrap_or(d.items_to_drop_when_ominous), + }) + } + /// `calculateTargetTotalMobs`. + pub fn target_total_mobs(&self, additional_players: i32) -> i32 { + (self.total_mobs + self.total_mobs_added_per_player * additional_players as f32).floor() + as i32 + } + /// `calculateTargetSimultaneousMobs`. + pub fn target_simultaneous_mobs(&self, additional_players: i32) -> i32 { + (self.simultaneous_mobs + + self.simultaneous_mobs_added_per_player * additional_players as f32) + .floor() as i32 + } +} + +static REGISTRY: OnceLock> = OnceLock::new(); + +/// `Registries.TRIAL_SPAWNER_CONFIG`: the configs under the resources' +/// `data//trial_spawner`, read once per process. +pub fn load_registry(root: &Path) { + REGISTRY.get_or_init(|| { + let mut out = HashMap::new(); + let Ok(namespaces) = std::fs::read_dir(root.join("data")) else { + return out; + }; + for ns in namespaces.flatten() { + let base = ns.path().join("trial_spawner"); + let mut stack = vec![base.clone()]; + while let Some(dir) = stack.pop() { + for entry in std::fs::read_dir(&dir).into_iter().flatten().flatten() { + let path = entry.path(); + if path.is_dir() { + stack.push(path); + continue; + } + let (Ok(rel), Some(ns)) = ( + path.with_extension("") + .strip_prefix(&base) + .map(Path::to_path_buf), + ns.file_name().to_str().map(str::to_owned), + ) else { + continue; + }; + let config = std::fs::read(&path) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .and_then(|v| TrialConfig::decode(&crate::scoreboard::json_to_tag(&v))); + match config { + Some(c) => { + let id = rel.to_string_lossy().replace('\\', "/"); + out.insert(format!("{ns}:{id}"), c); + } + None => log::warn!("Horizon: bad trial spawner config {}", path.display()), + } + } + } + } + out + }); +} +/// A config of the registry by id. +pub fn registry_config(id: &str) -> Option { + REGISTRY.get()?.get(id).cloned() +} + +fn float(t: &Tag) -> Option { + Some(match t { + Tag::Float(b) => f32::from_bits(*b), + Tag::Double(b) => f64::from_bits(*b) as f32, + t => spawner::number(Some(t))? as f32, + }) +} +/// `Weighted.CODEC`'s weight: a non-negative int. +fn weight(t: Option<&Tag>) -> Option { + spawner::number(t) + .filter(|w| (0..=i64::from(i32::MAX)).contains(w)) + .map(|w| w as i32) +} +/// An `Identifier` (`minecraft` when the namespace is left out). +fn identifier(t: Option<&Tag>) -> Option { + match t? { + Tag::String(s) => spawner::normalize_id(&s.to_string_lossy()), + _ => None, + } +} + +/// A `Holder` as saved: a registry id +/// (`minecraft:trial_chamber/breeze/normal`) or an inline config. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ConfigSlot { + /// The value as loaded, written back as is; None for the default. + pub saved: Option, + pub config: TrialConfig, +} + +/// `TrialSpawnerState`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum TrialState { + #[default] + Inactive, + WaitingForPlayers, + Active, + WaitingForRewardEjection, + EjectingReward, + Cooldown, +} +impl TrialState { + pub const ALL: [Self; 6] = [ + Self::Inactive, + Self::WaitingForPlayers, + Self::Active, + Self::WaitingForRewardEjection, + Self::EjectingReward, + Self::Cooldown, + ]; + /// The `trial_spawner_state` block property. + pub fn name(self) -> &'static str { + match self { + Self::Inactive => "inactive", + Self::WaitingForPlayers => "waiting_for_players", + Self::Active => "active", + Self::WaitingForRewardEjection => "waiting_for_reward_ejection", + Self::EjectingReward => "ejecting_reward", + Self::Cooldown => "cooldown", + } + } + pub fn from_name(name: &str) -> Option { + Self::ALL.into_iter().find(|s| s.name() == name) + } + /// The spin speed of the mob shown inside, None when it shows none. + pub fn spinning_mob_speed(self) -> Option { + match self { + Self::WaitingForPlayers => Some(200.0), + Self::Active => Some(1000.0), + _ => None, + } + } + pub fn capable_of_spawning(self) -> bool { + matches!(self, Self::WaitingForPlayers | Self::Active) + } +} + +/// A player the spawner can detect (`PlayerDetector.NO_CREATIVE_PLAYERS`). +#[derive(Clone, Copy, Debug)] +pub struct TrialPlayer { + pub uuid: Uuid, + pub block: [i32; 3], + pub eye: [f64; 3], + pub creative: bool, + pub spectator: bool, +} + +/// What a trial spawner did that the level shows or sends. +#[derive(Clone, Debug, PartialEq)] +pub enum TrialEvent { + /// `markUpdated`: `sendBlockUpdated` with the new update tag. + BlockUpdated, + /// `levelEvent(id, pos, data)`. + LevelEvent(i32, [i32; 3], i32), + /// `playSound(null, spawner, sound, BLOCKS)` at volume and pitch 1. + Sound(&'static str), + /// `gameEvent(entity, ENTITY_PLACE, block)` for the mob just added. + EntityPlace(Uuid, [i32; 3]), + /// `setBlockAndUpdate` of the `ominous` property alone, even when it + /// does not change (`removeOminous`). + OminousSet(bool), +} + +/// What a trial spawner reads from the level besides the spawn rules. +pub trait TrialSpawnerLevel: SpawnerLevel { + fn game_time(&self) -> i64; + /// `canSpawnInLevel`'s `spawn_mobs` game rule. + fn mob_spawning(&self) -> bool; + /// `level.getPlayers()`, in the server's order. + fn players(&self) -> Vec; + /// The block a VISUAL clip from `from` to `to` (no fluids) first hits. + fn visual_hit(&self, from: [f64; 3], to: [f64; 3]) -> Option<[i32; 3]>; + /// The block position of a living entity of this dimension, if any. + fn entity_block(&self, uuid: Uuid) -> Option<[i32; 3]>; +} + +/// `TrialSpawner` with its `TrialSpawnerStateData`. +#[derive(Clone, Debug, PartialEq)] +pub struct TrialSpawner { + pub normal: ConfigSlot, + pub ominous: ConfigSlot, + pub target_cooldown_length: i32, + pub required_player_range: i32, + pub detected_players: Vec, + pub current_mobs: Vec, + pub cooldown_ends_at: i64, + pub next_mob_spawns_at: i64, + pub total_mobs_spawned: i32, + pub next_spawn_data: Option, + pub ejecting_loot_table: Option, + /// `isOminous`, set from the block on every server tick. + pub is_ominous: bool, + /// The server's display entity exists (`getOrCreateDisplayEntity`): it is + /// made once per loaded block entity and kept. + pub has_display: bool, + pub spin: f64, + pub o_spin: f64, +} +impl Default for TrialSpawner { + fn default() -> Self { + Self { + normal: ConfigSlot::default(), + ominous: ConfigSlot::default(), + target_cooldown_length: 36000, + required_player_range: 14, + detected_players: Vec::new(), + current_mobs: Vec::new(), + cooldown_ends_at: 0, + next_mob_spawns_at: 0, + total_mobs_spawned: 0, + next_spawn_data: None, + ejecting_loot_table: None, + is_ominous: false, + has_display: false, + spin: 0.0, + o_spin: 0.0, + } + } +} + +fn uuids(tag: Option<&Tag>) -> Vec { + let Some(Tag::List(list)) = tag else { + return Vec::new(); + }; + let mut out: Vec = Vec::new(); + for t in list { + if let Tag::IntArray(v) = t + && let Ok(u) = ::try_from(v.as_slice()) + && !out.contains(&u) + { + out.push(u); + } + } + out +} +fn encode_uuids(list: &[Uuid]) -> Tag { + Tag::List(list.iter().map(|u| Tag::IntArray(u.to_vec())).collect()) +} + +impl TrialSpawner { + /// `TrialSpawner.load`, with the configs of [`load_registry`]. + pub fn load(tag: &Tag) -> Self { + Self::load_with(tag, ®istry_config) + } + /// `TrialSpawner.load`. `registry` resolves a config id. + pub fn load_with(tag: &Tag, registry: &dyn Fn(&str) -> Option) -> Self { + let long = |k: &str| match tag.get(k) { + Some(Tag::Long(v)) => *v, + t => spawner::number(t).unwrap_or(0), + }; + let mut s = Self { + detected_players: uuids(tag.get("registered_players")), + current_mobs: uuids(tag.get("current_mobs")), + cooldown_ends_at: long("cooldown_ends_at"), + next_mob_spawns_at: long("next_mob_spawns_at"), + total_mobs_spawned: spawner::number(tag.get("total_mobs_spawned")) + .filter(|v| (0..=i64::from(i32::MAX)).contains(v)) + .map_or(0, |v| v as i32), + next_spawn_data: tag.get("spawn_data").and_then(SpawnData::decode), + ejecting_loot_table: identifier(tag.get("ejecting_loot_table")), + ..Self::default() + }; + // FullConfig.MAP_CODEC, partial result kept: a field that fails to + // decode takes its default. + let slot = |k: &str| -> ConfigSlot { + let config = match tag.get(k) { + Some(Tag::String(id)) => { + spawner::normalize_id(&id.to_string_lossy()).and_then(|id| registry(&id)) + } + Some(t) => TrialConfig::decode(t), + None => None, + }; + config.map_or_else(ConfigSlot::default, |config| ConfigSlot { + saved: tag.get(k).cloned(), + config, + }) + }; + let int = |k: &str, default: i32, lo: i32, hi: i32| { + spawner::number(tag.get(k)) + .filter(|v| (i64::from(lo)..=i64::from(hi)).contains(v)) + .map_or(default, |v| v as i32) + }; + s.normal = slot("normal_config"); + s.ominous = slot("ominous_config"); + s.target_cooldown_length = int("target_cooldown_length", 36000, 0, i32::MAX); + s.required_player_range = int("required_player_range", 14, 1, 128); + s + } + /// `TrialSpawner.store`: the state data's fields that differ from their + /// defaults, then the configs. + pub fn save(&self) -> Vec<(&'static str, Tag)> { + let mut out = Vec::new(); + if !self.detected_players.is_empty() { + out.push(("registered_players", encode_uuids(&self.detected_players))); + } + if !self.current_mobs.is_empty() { + out.push(("current_mobs", encode_uuids(&self.current_mobs))); + } + if self.cooldown_ends_at != 0 { + out.push(("cooldown_ends_at", Tag::Long(self.cooldown_ends_at))); + } + if self.next_mob_spawns_at != 0 { + out.push(("next_mob_spawns_at", Tag::Long(self.next_mob_spawns_at))); + } + if self.total_mobs_spawned != 0 { + out.push(("total_mobs_spawned", Tag::Int(self.total_mobs_spawned))); + } + if let Some(d) = &self.next_spawn_data { + out.push(("spawn_data", d.encode())); + } + if let Some(t) = &self.ejecting_loot_table { + out.push(("ejecting_loot_table", Tag::String(t.as_str().into()))); + } + for (key, slot) in [ + ("normal_config", &self.normal), + ("ominous_config", &self.ominous), + ] { + if let Some(t) = &slot.saved { + out.push((key, t.clone())); + } + } + if self.target_cooldown_length != 36000 { + out.push(( + "target_cooldown_length", + Tag::Int(self.target_cooldown_length), + )); + } + if self.required_player_range != 14 { + out.push(( + "required_player_range", + Tag::Int(self.required_player_range), + )); + } + out + } + /// `TrialSpawnerStateData.getUpdateTag`. + pub fn update_tag(&self, state: TrialState) -> Tag { + let mut out = Compound::new(); + if state == TrialState::Active { + out.insert( + "next_mob_spawns_at".into(), + Tag::Long(self.next_mob_spawns_at), + ); + } + if let Some(d) = &self.next_spawn_data { + out.insert("spawn_data".into(), d.encode()); + } + Tag::Compound(out) + } + /// `activeConfig`. + pub fn active_config(&self) -> &TrialConfig { + if self.is_ominous { + &self.ominous.config + } else { + &self.normal.config + } + } + /// `resetStatistics`. + fn reset_statistics(&mut self) { + self.detected_players.clear(); + self.total_mobs_spawned = 0; + self.next_mob_spawns_at = 0; + self.cooldown_ends_at = 0; + } + /// `reset`. + fn reset(&mut self) { + self.current_mobs.clear(); + self.next_spawn_data = None; + self.reset_statistics(); + } + /// `getOrCreateNextSpawnData`: a potential at random, else empty data. + fn next_or_create( + &mut self, + random: &mut impl RandomSource, + events: &mut Vec, + ) -> &SpawnData { + if self.next_spawn_data.is_none() { + let potentials = &self.active_config().spawn_potentials; + let picked = spawner::weighted_index(potentials.iter().map(|(_, w)| *w), random) + .map(|i| potentials[i].0.clone()); + self.next_spawn_data = Some(picked.unwrap_or_default()); + events.push(TrialEvent::BlockUpdated); + } + self.next_spawn_data.get_or_insert_default() + } + /// `hasMobToSpawn`. + fn has_mob_to_spawn( + &mut self, + random: &mut impl RandomSource, + events: &mut Vec, + ) -> bool { + self.next_or_create(random, events).id().is_some() + // WeightedList.isEmpty: a total weight of 0. + || self.active_config().spawn_potentials.iter().any(|(_, w)| *w > 0) + } + /// `canSpawnInLevel`. + fn can_spawn_in_level(l: &L) -> bool { + l.spawner_blocks_work() && !l.peaceful() && l.mob_spawning() + } + /// `PlayerDetector.NO_CREATIVE_PLAYERS.detect`. + fn detect(&self, l: &L, pos: [i32; 3], line_of_sight: bool) -> Vec { + let range = f64::from(self.required_player_range); + l.players() + .into_iter() + .filter(|p| { + let d = [0, 1, 2].map(|i| f64::from(p.block[i] - pos[i])); + d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < range * range + && !p.creative + && !p.spectator + }) + .filter(|p| !line_of_sight || in_line_of_sight(l, center(pos), p.eye)) + .map(|p| p.uuid) + .collect() + } + /// `tryDetectPlayers`, every 20 ticks. + fn try_detect_players( + &mut self, + l: &L, + pos: [i32; 3], + state: TrialState, + events: &mut Vec, + ) { + let packed = BlockPos::new(pos[0], pos[1], pos[2]).pack(); + if packed.wrapping_add(l.game_time()) % 20 != 0 { + return; + } + if state == TrialState::Cooldown { + return; + } + let in_sight = self.detect(l, pos, true); + let found = if self.detected_players.is_empty() { + in_sight + } else { + self.detect(l, pos, false) + }; + let mut added = false; + for uuid in found { + if !self.detected_players.contains(&uuid) { + self.detected_players.push(uuid); + added = true; + } + } + if added { + self.next_mob_spawns_at = (l.game_time() + 40).max(self.next_mob_spawns_at); + let id = if self.is_ominous { 3019 } else { 3013 }; + events.push(TrialEvent::LevelEvent( + id, + pos, + self.detected_players.len() as i32, + )); + } + } + /// `TrialSpawner.tickServer`: the next state of the block. + #[allow(clippy::too_many_arguments)] + pub fn server_tick( + &mut self, + l: &L, + random: &mut R, + pos: [i32; 3], + state: TrialState, + ominous: bool, + spawn: &mut dyn FnMut(&L, &SpawnerSpawn) -> Option, + eject: &mut dyn FnMut(&str, &mut R) -> bool, + events: &mut Vec, + ) -> TrialState { + self.is_ominous = ominous; + let before = self.current_mobs.len(); + let max = MAX_MOB_TRACKING_DISTANCE * MAX_MOB_TRACKING_DISTANCE; + self.current_mobs.retain(|id| { + l.entity_block(*id).is_some_and(|b| { + let d = [0, 1, 2].map(|i| i64::from(b[i] - pos[i])); + d[0] * d[0] + d[1] * d[1] + d[2] * d[2] <= max + }) + }); + if self.current_mobs.len() != before { + self.next_mob_spawns_at = + l.game_time() + i64::from(self.active_config().ticks_between_spawn); + } + self.tick_and_get_next(l, random, pos, state, spawn, eject, events) + } + /// `TrialSpawnerState.tickAndGetNext`. + #[allow(clippy::too_many_arguments)] + fn tick_and_get_next( + &mut self, + l: &L, + random: &mut R, + pos: [i32; 3], + state: TrialState, + spawn: &mut dyn FnMut(&L, &SpawnerSpawn) -> Option, + eject: &mut dyn FnMut(&str, &mut R) -> bool, + events: &mut Vec, + ) -> TrialState { + use TrialState as S; + let now = l.game_time(); + match state { + S::Inactive => { + // getOrCreateDisplayEntity: made once, from the next data's id. + if !self.has_display { + let id = self.next_or_create(random, events).id(); + self.has_display = id.is_some_and(|id| l.entity_exists(&id)); + } + if self.has_display { + S::WaitingForPlayers + } else { + state + } + } + S::WaitingForPlayers => { + if !Self::can_spawn_in_level(l) { + self.reset_statistics(); + state + } else if !self.has_mob_to_spawn(random, events) { + S::Inactive + } else { + self.try_detect_players(l, pos, state, events); + if self.detected_players.is_empty() { + state + } else { + S::Active + } + } + } + S::Active => { + if !Self::can_spawn_in_level(l) { + self.reset_statistics(); + return S::WaitingForPlayers; + } + if !self.has_mob_to_spawn(random, events) { + return S::Inactive; + } + let config = self.active_config().clone(); + let additional = (self.detected_players.len() as i32 - 1).max(0); + self.try_detect_players(l, pos, state, events); + if self.total_mobs_spawned >= config.target_total_mobs(additional) { + if self.current_mobs.is_empty() { + self.cooldown_ends_at = now + i64::from(self.target_cooldown_length); + self.total_mobs_spawned = 0; + self.next_mob_spawns_at = 0; + return S::WaitingForRewardEjection; + } + } else if now >= self.next_mob_spawns_at + && (self.current_mobs.len() as i32) + < config.target_simultaneous_mobs(additional) + && let Some(uuid) = self.spawn_mob(l, random, pos, spawn, events) + { + self.current_mobs.push(uuid); + self.total_mobs_spawned += 1; + self.next_mob_spawns_at = now + i64::from(config.ticks_between_spawn); + let potentials = &config.spawn_potentials; + if let Some(i) = + spawner::weighted_index(potentials.iter().map(|(_, w)| *w), random) + { + self.next_spawn_data = Some(potentials[i].0.clone()); + events.push(TrialEvent::BlockUpdated); + } + } + state + } + S::WaitingForRewardEjection => { + let started = self.cooldown_ends_at - i64::from(self.target_cooldown_length); + if now as f32 >= started as f32 + DELAY_BEFORE_EJECT { + events.push(TrialEvent::Sound("block.trial_spawner.open_shutter")); + S::EjectingReward + } else { + state + } + } + S::EjectingReward => { + let started = self.cooldown_ends_at - i64::from(self.target_cooldown_length); + if (now - started) as f32 % TIME_BETWEEN_EJECTIONS != 0.0 { + return state; + } + if self.detected_players.is_empty() { + events.push(TrialEvent::Sound("block.trial_spawner.close_shutter")); + self.ejecting_loot_table = None; + return S::Cooldown; + } + if self.ejecting_loot_table.is_none() { + let tables = &self.active_config().loot_tables_to_eject; + self.ejecting_loot_table = + spawner::weighted_index(tables.iter().map(|(_, w)| *w), random) + .map(|i| tables[i].0.clone()); + } + if let Some(table) = self.ejecting_loot_table.clone() + && eject(&table, random) + { + events.push(TrialEvent::LevelEvent(3014, pos, 0)); + } + self.detected_players.remove(0); + state + } + S::Cooldown => { + self.try_detect_players(l, pos, state, events); + if !self.detected_players.is_empty() { + self.total_mobs_spawned = 0; + self.next_mob_spawns_at = 0; + S::Active + } else if now >= self.cooldown_ends_at { + self.is_ominous = false; + events.push(TrialEvent::OminousSet(false)); + self.reset(); + S::WaitingForPlayers + } else { + state + } + } + } + } + /// `TrialSpawner.spawnMob`: the UUID of the mob added, if one was. + fn spawn_mob( + &mut self, + l: &L, + random: &mut R, + pos: [i32; 3], + spawn: &mut dyn FnMut(&L, &SpawnerSpawn) -> Option, + events: &mut Vec, + ) -> Option { + let data = self.next_or_create(random, events).clone(); + // EntityType.by: an unknown type spawns nothing. + let id = data.id().filter(|id| l.entity_exists(id))?; + let at = match spawner::read_pos(data.entity.get(&JavaString::from("Pos"))) { + Some(p) => p, + None => { + let range = f64::from(self.active_config().spawn_range); + let x = + f64::from(pos[0]) + (random.next_double() - random.next_double()) * range + 0.5; + let y = f64::from(pos[1] + random.next_int_bound(3).unwrap_or(0) - 1); + let z = + f64::from(pos[2]) + (random.next_double() - random.next_double()) * range + 0.5; + [x, y, z] + } + }; + // Entity types Horizon cannot create spawn nothing. + let (species, width, height, _) = l.mob_type(&id)?; + let spawn_box = spawn_selection::spawn_aabb(species, at[0], at[1], at[2], width, height); + if !l.no_collision(spawn_box) || !in_line_of_sight(l, center(pos), at) { + return None; + } + let block = at.map(|v| v.floor() as i32); + if !spawn_rules::check_spawn_rules( + species, + l, + Reason::TrialSpawner, + random, + block[0], + block[1], + block[2], + ) { + return None; + } + if let Some(rules) = data.custom_spawn_rules + && !SpawnData::valid_position(rules, l, block[0], block[1], block[2]) + { + return None; + } + let yaw = random.next_float() * 360.0; + let placed = spawner::entity_position(species, at); + let own = placed.map(|v| v.floor() as i32); + let scale = spawner::cube_scale(&id, &data.entity); + let bounds = spawn_selection::spawn_box( + placed[0], + placed[1], + placed[2], + width * scale, + height * scale, + ); + if !spawn_selection::spawn_obstruction(species, l, bounds, &[], own[0], own[1], own[2]) { + return None; + } + let request = SpawnerSpawn { + entity: &data.entity, + id: &id, + position: placed, + yaw, + finalize: data.unconfigured(), + equipment: data.equipment.as_ref(), + trial: true, + }; + let uuid = spawn(l, &request)?; + let flame = i32::from(self.is_ominous); + events.push(TrialEvent::LevelEvent(3011, pos, flame)); + events.push(TrialEvent::LevelEvent(3012, block, flame)); + events.push(TrialEvent::EntityPlace(uuid, block)); + Some(uuid) + } +} + +/// `Vec3.atCenterOf`. +fn center(pos: [i32; 3]) -> [f64; 3] { + pos.map(|v| f64::from(v) + 0.5) +} +/// `TrialSpawner.inLineOfSight`: a VISUAL clip from `to` back to the spawner +/// hits nothing, or the spawner's own block. +fn in_line_of_sight(l: &L, origin: [f64; 3], to: [f64; 3]) -> bool { + match l.visual_hit(to, origin) { + None => true, + Some(b) => b == origin.map(|v| v.floor() as i32), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tag(snbt: &str) -> Tag { + horizon_world::nbt::parse_snbt(snbt).expect("snbt").0 + } + + #[test] + fn defaults_load_and_save_to_nothing() { + let s = TrialSpawner::load_with(&tag("{}"), &|_| None); + assert_eq!(s, TrialSpawner::default()); + assert!(s.save().is_empty()); + } + + #[test] + fn registry_configs_resolve_and_are_saved_by_id() { + let breeze = TrialConfig { + total_mobs: 2.0, + ..TrialConfig::default() + }; + let registry = + |id: &str| (id == "minecraft:trial_chamber/breeze/normal").then(|| breeze.clone()); + let s = TrialSpawner::load_with( + &tag( + r#"{normal_config:"minecraft:trial_chamber/breeze/normal",required_player_range:10}"#, + ), + ®istry, + ); + assert_eq!(s.normal.config.total_mobs, 2.0); + assert_eq!(s.required_player_range, 10); + let saved: Vec<_> = s.save().into_iter().map(|(k, _)| k).collect(); + assert_eq!(saved, ["normal_config", "required_player_range"]); + } + + #[test] + fn an_invalid_field_takes_its_default_alone() { + let s = TrialSpawner::load_with( + &tag( + r#"{normal_config:"minecraft:nope",required_player_range:200,target_cooldown_length:5}"#, + ), + &|_| None, + ); + assert_eq!(s.normal, ConfigSlot::default()); + assert_eq!(s.required_player_range, 14); + assert_eq!(s.target_cooldown_length, 5); + let c = TrialConfig::decode(&tag( + r#"{spawn_range:0,total_mobs:3.0f,spawn_potentials:[{data:{entity:{id:"minecraft:zombie"}},weight:-1},{data:{entity:{id:"minecraft:husk"}},weight:2}]}"#, + )) + .expect("config"); + assert_eq!(c.spawn_range, 4); + assert_eq!(c.total_mobs, 3.0); + assert_eq!(c.spawn_potentials.len(), 1); + } + + #[test] + fn targets_floor_the_per_player_additions() { + let c = TrialConfig { + simultaneous_mobs: 1.0, + simultaneous_mobs_added_per_player: 0.5, + ..TrialConfig::default() + }; + assert_eq!(c.target_simultaneous_mobs(0), 1); + assert_eq!(c.target_simultaneous_mobs(1), 1); + assert_eq!(c.target_simultaneous_mobs(2), 2); + assert_eq!(c.target_total_mobs(3), 12); + } +} diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs index 13a1b7ac3..aeafa8df4 100644 --- a/crates/horizon-client/src/mobs/world.rs +++ b/crates/horizon-client/src/mobs/world.rs @@ -2,11 +2,18 @@ //! sight (`ClipContext.Block.COLLIDER`), sky visibility, light-dependent //! values and the positions of other entities. use super::{MobWorld, Seen, Species, Who, data}; -use crate::{blocks::Fluid, collisions::SceneCollisions}; +use crate::{ + blocks::{BlockFacts, Fluid}, + collisions::SceneCollisions, +}; use horizon_core::{ geometry::{Aabb, Vec3, traverse_blocks}, position::BlockPos, }; +use horizon_world::{ + block_collision::{BlockCollisionRegistry, DynamicCollisionWorld}, + registry::BlockStateId, +}; /// Where a target entity is this tick. #[derive(Clone, Copy, Debug)] @@ -81,38 +88,23 @@ impl MobWorld<'_> { }); matches!(result, Ok(None)) } - /// Level.clip with VISUAL shapes and no fluids: true on a miss. Glass - /// (`TransparentBlock`) and bars and panes (`IronBarsBlock`) have no - /// visual shape; mud, soul sand and powder snow look like full blocks. + /// Level.clip with VISUAL shapes and no fluids: true on a miss. pub fn visual_clear_between(&self, from: Vec3, to: Vec3) -> bool { + self.visual_clip(from, to) == Some(None) + } + /// Level.clip with VISUAL shapes and no fluids: the block the segment + /// first hits, if it does. + pub fn visual_hit(&self, from: Vec3, to: Vec3) -> Option<[i32; 3]> { + self.visual_clip(from, to).flatten() + } + fn visual_clip(&self, from: Vec3, to: Vec3) -> Option> { let mut scene = SceneCollisions { world: self.world, binding: self.collision, subject: None, }; - let full = horizon_core::geometry::Aabb::new(Vec3::ZERO, Vec3::new(1.0, 1.0, 1.0)); - let result = traverse_blocks(from, to, 512, |p: BlockPos| { - let state = self.world.block(p.x, p.y, p.z); - if self.facts.is_air(state) { - return None; - } - let name = self.facts.get(state).name.trim_start_matches("minecraft:"); - if name.ends_with("glass") || name.ends_with("glass_pane") || name.ends_with("_bars") { - return None; - } - if matches!(name, "mud" | "soul_sand" | "powder_snow") { - return full - .move_by(Vec3::new(f64::from(p.x), f64::from(p.y), f64::from(p.z))) - .clip(from, to) - .map(|_| ()); - } - let shape = self - .collision - .collision_shape(&mut scene, state, [p.x, p.y, p.z]) - .ok()?; - shape.clip(from, to, p).map(|_| ()) - }); - matches!(result, Ok(None)) + let state = |x, y, z| self.world.block(x, y, z); + visual_clip(self.facts, self.collision, &mut scene, &state, from, to) } /// Level.clip with COLLIDER shapes and no fluids: where the segment /// first hits a block, if it does. @@ -260,3 +252,42 @@ impl MobWorld<'_> { .count() } } + +/// Level.clip with VISUAL shapes and no fluids: the block the segment first +/// hits, None inside when it hits nothing and outside when the segment is +/// too long to walk. Glass and copper grates (`TransparentBlock`) and bars and panes +/// (`IronBarsBlock`) have no visual shape; mud, soul sand and powder snow +/// look like full blocks. +pub fn visual_clip( + facts: &BlockFacts, + collision: &BlockCollisionRegistry, + scene: &mut W, + state: &dyn Fn(i32, i32, i32) -> BlockStateId, + from: Vec3, + to: Vec3, +) -> Option> { + let full = Aabb::new(Vec3::ZERO, Vec3::new(1.0, 1.0, 1.0)); + let result = traverse_blocks(from, to, 512, |p: BlockPos| { + let id = state(p.x, p.y, p.z); + if facts.is_air(id) { + return None; + } + let name = facts.get(id).name.trim_start_matches("minecraft:"); + if name.ends_with("glass") + || name.ends_with("glass_pane") + || name.ends_with("_bars") + || name.ends_with("copper_grate") + { + return None; + } + if matches!(name, "mud" | "soul_sand" | "powder_snow") { + return full + .move_by(Vec3::new(f64::from(p.x), f64::from(p.y), f64::from(p.z))) + .clip(from, to) + .map(|_| [p.x, p.y, p.z]); + } + let shape = collision.collision_shape(scene, id, [p.x, p.y, p.z]).ok()?; + shape.clip(from, to, p).map(|_| [p.x, p.y, p.z]) + }); + result.ok() +} diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 602590e15..b8697eeb2 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -113,6 +113,7 @@ pub enum MotionEvent { enabled: bool, }, Health(crate::health::HealthEvent), + /// `LivingEntity.handleDamageEvent`: the hurt sound the player hears. HurtSound(&'static str), Fall(crate::landing::FallEvent), Recorded { @@ -2109,6 +2110,47 @@ mod tests { .count(), 1 ); + // A shield that takes the whole arrow: onBlocked's sound, no damage + // event, so the player hears no hurt sound. + use horizon_world::blocking_rules::{BlockingRules, DamageReduction, ItemDamageFunction}; + let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap(); + let source = resources.health.damage.id("minecraft:arrow").unwrap(); + let shield = crate::health::Blocking { + rules: BlockingRules { + delay_seconds: 0.25, + disable_scale: 1.0, + reductions: vec![DamageReduction { + horizontal_angle: 90.0, + types: None, + base: 0.0, + factor: 1.0, + }], + item_damage: ItemDamageFunction { + threshold: 3.0, + base: 1.0, + factor: 1.0, + }, + }, + bypassed: false, + pierce: false, + angle: 0.0, + }; + let outcome = player + .hurt_blocking( + &resources.health, + Default::default(), + source, + 4.0, + Some(shield), + ) + .unwrap(); + assert!(!outcome.hurt && outcome.sound && outcome.blocked == 4.0); + assert!( + !player + .events + .iter() + .any(|e| matches!(e, MotionEvent::HurtSound(_))) + ); } /// Footsteps on the prepared vanilla resources, when they are present: diff --git a/crates/horizon-client/src/multiplayer.rs b/crates/horizon-client/src/multiplayer.rs index 9e7023391..a13bc7063 100644 --- a/crates/horizon-client/src/multiplayer.rs +++ b/crates/horizon-client/src/multiplayer.rs @@ -34,6 +34,7 @@ pub enum Screen { pings: Pings, /// Worlds announced on the local network, listed after the servers. lan: Scanner, + scroll: crate::ui::Scroll, }, /// Add (index None) or edit a server entry. Edit { @@ -117,6 +118,60 @@ fn entry_address(servers: &[ServerEntry], lan: &Scanner, index: usize) -> Option } } +/// JoinMultiplayerScreen's `HeaderAndFooterLayout(33, 60)`. +const HEADER: f32 = 33.0; +const FOOTER: f32 = 60.0; +/// ServerSelectionList: rows 305 wide and 36 high. +const ROW_WIDTH: f32 = 305.0; +const ROW_HEIGHT: f32 = 36.0; +/// One row of the list: the saved servers, the LAN header, the LAN games. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Row { + Server(usize), + LanHeader, + Lan(usize), +} +/// The list's top and bottom and its rows' left edge (`getRowLeft`). +fn list_area(w: f32, h: f32) -> (f32, f32, f32) { + ( + HEADER, + h - FOOTER, + (w / 2.0).floor() - (ROW_WIDTH / 2.0).floor(), + ) +} +fn rows(servers: usize, lan: usize) -> impl Iterator { + (0..servers) + .map(Row::Server) + .chain(std::iter::once(Row::LanHeader)) + .chain((0..lan).map(Row::Lan)) +} +/// `contentHeight`: the rows and 4 pixels of padding. +fn content_height(servers: usize, lan: usize) -> f32 { + (servers + 1 + lan) as f32 * ROW_HEIGHT + 4.0 +} +/// The row under `(x, y)` (`getEntryAtPosition`), scrolled by `scroll`. +fn row_at( + servers: usize, + lan: usize, + (x, y): (f32, f32), + size: (f32, f32), + scroll: f32, +) -> Option { + let (top, bottom, left) = list_area(size.0, size.1); + if y < top || y >= bottom || x < left || x >= left + ROW_WIDTH { + return None; + } + let index = ((y - top - 2.0 + scroll.trunc()) / ROW_HEIGHT).floor(); + if index < 0.0 { + return None; + } + rows(servers, lan).nth(index as usize) +} +/// `LoadingDotsText.get`. +fn loading_dots(millis: u128) -> &'static str { + ["O o o", "o O o", "o o O", "o O o"][(millis / 300 % 4) as usize] +} + impl Screen { /// The address of list row `row` (saved servers, then LAN games). pub fn address_of(&self, row: usize) -> Option { @@ -134,6 +189,7 @@ impl Screen { selected: None, pings, lan: Scanner::start(), + scroll: crate::ui::Scroll::default(), } } pub fn buttons(&self, w: f32, h: f32) -> Vec { @@ -141,44 +197,75 @@ impl Screen { (x, y, bw, label.to_owned(), enabled, id) }; match self { - // JoinMultiplayerScreen's two button rows. - Self::List { selected, .. } => vec![ - b( - w / 2.0 - 154.0, - h - 52.0, - 100.0, - "Join Server", - selected.is_some(), - 40, - ), - b( - w / 2.0 - 50.0, - h - 52.0, - 100.0, - "Direct Connection", - true, - 41, - ), - b(w / 2.0 + 54.0, h - 52.0, 100.0, "Add Server", true, 42), - b( - w / 2.0 - 154.0, - h - 28.0, - 74.0, - "Edit", - selected.is_some(), - 43, - ), - b( - w / 2.0 - 76.0, - h - 28.0, - 74.0, - "Delete", - selected.is_some(), - 44, - ), - b(w / 2.0 + 2.0, h - 28.0, 74.0, "Refresh", true, 45), - b(w / 2.0 + 80.0, h - 28.0, 74.0, "Back", true, 46), - ], + // JoinMultiplayerScreen's footer: two rows of buttons, 4 apart, + // centred in the 60-pixel footer. Join needs a server or LAN game + // selected (onSelectedChange), Edit and Delete a saved server. + Self::List { + servers, selected, .. + } => { + let (w, h) = (w.ceil(), h.ceil()); + let x = ((w - 308.0) / 2.0).floor(); + let saved = selected.is_some_and(|i| i < servers.len()); + let label = |key: &str, fallback: &str| crate::lang::get_or(key, fallback); + vec![ + b( + x, + h - 52.0, + 100.0, + &label("selectServer.select", "Join Server"), + selected.is_some(), + 40, + ), + b( + x + 104.0, + h - 52.0, + 100.0, + &label("selectServer.direct", "Direct Connection"), + true, + 41, + ), + b( + x + 208.0, + h - 52.0, + 100.0, + &label("selectServer.add", "Add Server"), + true, + 42, + ), + b( + x, + h - 28.0, + 74.0, + &label("selectServer.edit", "Edit"), + saved, + 43, + ), + b( + x + 78.0, + h - 28.0, + 74.0, + &label("selectServer.delete", "Delete"), + saved, + 44, + ), + b( + x + 156.0, + h - 28.0, + 74.0, + &label("selectServer.refresh", "Refresh"), + true, + 45, + ), + b( + x + 234.0, + h - 28.0, + 74.0, + &label("gui.back", "Back"), + true, + 46, + ), + ] + } Self::Edit { address, .. } => vec![ b( w / 2.0 - 100.0, @@ -314,7 +401,7 @@ impl Screen { } pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, blink: bool) { let (w, h) = (batch.width, batch.height); - batch.fill(atlas, 0.0, 0.0, w, h, rgba(0, 0, 0, 120)); + crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false); let centered = |batch: &mut HudBatch, text: &str, y: f32, color: u32| { let tw = HudBatch::text_width(atlas, text); batch.text(atlas, text, (w - tw) / 2.0, y, color, true); @@ -325,121 +412,205 @@ impl Screen { selected, pings, lan, + scroll, } => { - centered(batch, "Play Multiplayer", 8.0, u32::MAX); - batch.fill(atlas, 0.0, 32.0, w, h - 32.0 - 64.0, rgba(0, 0, 0, 100)); + let (w, h) = (w.ceil(), h.ceil()); + let title = crate::lang::get_or("multiplayer.title", "Play Multiplayer"); + // The header's StringWidget, centred in its 33 pixels. + let tw = HudBatch::text_width(atlas, &title); + let tx = ((w - tw.ceil()) / 2.0).floor(); + batch.text( + atlas, + &title, + tx, + ((HEADER - 9.0) / 2.0).floor(), + u32::MAX, + true, + ); + let games = lan.games(); + let (top, bottom, left) = list_area(w, h); + let content = content_height(servers.len(), games.len()); + let mut scroll = *scroll; + scroll.clamp(top, bottom, content); + // AbstractSelectionList.extractWidgetRenderState: background, + // the rows clipped to the list, separators, scrollbar. + crate::ui::list_background(batch, atlas, top, bottom, false); + let first = batch.vertices.len(); let pings = pings.lock().unwrap(); - for (i, server) in servers.iter().enumerate() { - let y = 36.0 + i as f32 * 36.0; - if y + 36.0 > h - 64.0 { - break; + let millis = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_millis()); + let gray = rgba(128, 128, 128, 255); + for (i, row) in rows(servers.len(), games.len()).enumerate() { + let y = top + 2.0 - scroll.amount.trunc() + i as f32 * ROW_HEIGHT; + if y + ROW_HEIGHT < top || y > bottom { + continue; } - let x = w / 2.0 - 152.0; - crate::widgets::target_as( - [x - 2.0, y - 2.0, 306.0, 36.0], - crate::widgets::Kind::Row, - ); - if *selected == Some(i) { - batch.fill( - atlas, - x - 2.0, - y - 2.0, - 306.0, - 36.0, - rgba(128, 128, 128, 255), - ); - batch.fill(atlas, x - 1.0, y - 1.0, 304.0, 34.0, rgba(0, 0, 0, 255)); - } - batch.sprite_scaled(atlas, "misc/unknown_server", x, y, 32.0, 32.0, u32::MAX); - batch.text(atlas, &server.name, x + 35.0, y + 1.0, u32::MAX, false); - let (line, right, color) = match pings.get(&server.ip) { - Some(Ping::Ok { - motd, players, ms, .. - }) => ( - motd.lines().next().unwrap_or("").to_owned(), - format!("{players} {ms} ms"), - rgba(128, 128, 128, 255), - ), - Some(Ping::Failed(_)) => ( - "Can't connect to server".to_owned(), - String::new(), - rgba(170, 0, 0, 255), - ), - _ => ( - "Pinging...".to_owned(), - String::new(), - rgba(128, 128, 128, 255), - ), + let index = match row { + Row::Server(k) => Some(k), + Row::Lan(k) => Some(servers.len() + k), + Row::LanHeader => None, }; - batch.text(atlas, &line, x + 35.0, y + 12.0, color, false); - batch.text( - atlas, - &server.ip, - x + 35.0, - y + 22.0, - rgba(96, 96, 96, 255), - false, - ); - if !right.is_empty() { - let tw = HudBatch::text_width(atlas, &right); - batch.text( - atlas, - &right, - x + 300.0 - tw, - y + 1.0, - rgba(128, 128, 128, 255), - false, + if index.is_some() + && y + ROW_HEIGHT / 2.0 > top + && y + ROW_HEIGHT / 2.0 < bottom + { + crate::widgets::target_as( + [left, y, ROW_WIDTH, ROW_HEIGHT], + crate::widgets::Kind::Row, ); } - } - for (k, game) in lan.games().iter().enumerate() { - let i = servers.len() + k; - let y = 36.0 + i as f32 * 36.0; - if y + 36.0 > h - 64.0 { - break; - } - let x = w / 2.0 - 152.0; - crate::widgets::target_as( - [x - 2.0, y - 2.0, 306.0, 36.0], - crate::widgets::Kind::Row, - ); - if *selected == Some(i) { + // extractSelection: a white outline round black (the list + // has focus once a row is clicked). + if index.is_some() && *selected == index { + batch.fill(atlas, left, y, ROW_WIDTH, ROW_HEIGHT, u32::MAX); batch.fill( atlas, - x - 2.0, - y - 2.0, - 306.0, - 36.0, - rgba(128, 128, 128, 255), + left + 1.0, + y + 1.0, + ROW_WIDTH - 2.0, + ROW_HEIGHT - 2.0, + rgba(0, 0, 0, 255), ); - batch.fill(atlas, x - 1.0, y - 1.0, 304.0, 34.0, rgba(0, 0, 0, 255)); } - batch.text(atlas, "LAN World", x + 35.0, y + 1.0, u32::MAX, false); - batch.text( - atlas, - &game.motd, - x + 35.0, - y + 12.0, - rgba(128, 128, 128, 255), - false, - ); - batch.text( - atlas, - &game.address, - x + 35.0, - y + 22.0, - rgba(96, 96, 96, 255), - false, - ); - } - if servers.is_empty() { - centered( - batch, - "No servers yet: add one or use Direct Connection", - h / 2.0 - 20.0, - rgba(160, 160, 160, 255), - ); + // Entry content: 2 pixels in from the row. + let (cx, cy) = (left + 2.0, y + 2.0); + match row { + Row::Server(k) => { + let server = &servers[k]; + batch.sprite_scaled( + atlas, + "misc/unknown_server", + cx, + cy, + 32.0, + 32.0, + u32::MAX, + ); + batch.text(atlas, &server.name, cx + 35.0, cy + 1.0, u32::MAX, false); + // OnlineServerEntry: up to two lines of MOTD, the + // player count left of the status icon. + let (motd, status, motd_color, icon) = match pings.get(&server.ip) { + Some(Ping::Ok { + motd, players, ms, .. + }) => ( + motd.clone(), + players.clone(), + gray, + format!( + "server_list/ping_{}", + match ms { + 0..150 => 5, + 150..300 => 4, + 300..600 => 3, + 600..1000 => 2, + _ => 1, + } + ), + ), + Some(Ping::Failed(_)) => ( + crate::lang::get_or( + "multiplayer.status.cannot_connect", + "Can't connect to server", + ), + String::new(), + rgba(255, 0, 0, 255), + "server_list/unreachable".to_owned(), + ), + _ => { + // The pinging bars bounce, offset by the row. + let frame = (millis / 100 + i as u128 * 2) & 7; + let frame = if frame > 4 { 8 - frame } else { frame }; + ( + crate::lang::get_or( + "multiplayer.status.pinging", + "Pinging...", + ), + String::new(), + gray, + format!("server_list/pinging_{}", frame + 1), + ) + } + }; + for (n, line) in wrap(&motd, ROW_WIDTH - 4.0 - 34.0, atlas) + .iter() + .take(2) + .enumerate() + { + batch.text( + atlas, + line, + cx + 35.0, + cy + 12.0 + 9.0 * n as f32, + motd_color, + false, + ); + } + let icon_x = cx + ROW_WIDTH - 4.0 - 15.0; + batch.sprite_scaled( + atlas, + &format!("gui/sprites/{icon}"), + icon_x, + cy, + 10.0, + 8.0, + u32::MAX, + ); + if !status.is_empty() { + let sw = HudBatch::text_width(atlas, &status).ceil(); + batch.text( + atlas, + &status, + icon_x - sw - 5.0, + cy + 1.0, + gray, + false, + ); + } + } + Row::LanHeader => { + // LANHeader's LoadingDotsWidget: the label, then + // the dots on its last line, both centred. + let label = crate::lang::get_or( + "lanServer.scanning", + "Scanning for games on your local network", + ); + let middle = cx + ((ROW_WIDTH - 4.0) / 2.0).floor(); + let lw = HudBatch::text_width(atlas, &label).ceil(); + let lx = middle - (lw / 2.0).floor(); + let centre = lx + (lw / 2.0).floor(); + batch.text(atlas, &label, lx, cy + 2.0, u32::MAX, false); + let dots = loading_dots(millis); + let dw = HudBatch::text_width(atlas, dots).ceil(); + batch.text( + atlas, + dots, + centre - (dw / 2.0).floor(), + cy + 28.0 - 9.0 - 2.0, + gray, + false, + ); + } + Row::Lan(k) => { + let game = &games[k]; + let header = crate::lang::get_or("lanServer.title", "LAN World"); + batch.text(atlas, &header, cx + 35.0, cy + 1.0, u32::MAX, false); + batch.text(atlas, &game.motd, cx + 35.0, cy + 12.0, gray, false); + batch.text(atlas, &game.address, cx + 35.0, cy + 23.0, gray, false); + } + } } + batch.clip_since(first, 0.0, top, w, bottom); + crate::ui::separators(batch, atlas, top, bottom, false); + crate::ui::scrollbar( + batch, + atlas, + left + ROW_WIDTH + 8.0, + top, + bottom, + content, + scroll.amount, + ); } Self::Edit { index, @@ -583,19 +754,36 @@ impl Screen { servers, selected, lan, + scroll, .. }, None, ) => { - let index = ((y - 36.0) / 36.0).floor(); - if y >= 36.0 && y < h - 64.0 && (x - w / 2.0).abs() < 154.0 { - let index = index as usize; - if let Some(address) = entry_address(servers, lan, index) { - if *selected == Some(index) { - return Outcome::Connect(address); - } - *selected = Some(index); + let (w, h) = (w.ceil(), h.ceil()); + let games = lan.games().len(); + let (top, bottom, left) = list_area(w, h); + let content = content_height(servers.len(), games); + if scroll.press((x, y), left + ROW_WIDTH + 8.0, top, bottom, content) { + return Outcome::None; + } + // Clicking a selected row again joins it; the LAN header + // takes the click without anything to join. + let index = match row_at(servers.len(), games, (x, y), (w, h), scroll.amount) { + Some(Row::Server(k)) => Some(k), + Some(Row::Lan(k)) => Some(servers.len() + k), + Some(Row::LanHeader) => { + *selected = None; + None } + None => None, + }; + if let Some(index) = index + && let Some(address) = entry_address(servers, lan, index) + { + if *selected == Some(index) { + return Outcome::Connect(address); + } + *selected = Some(index); } } ( @@ -648,6 +836,45 @@ impl Screen { } Outcome::None } + /// The mouse wheel over the server list (`scrollRate`: half a row). + pub fn wheel(&mut self, delta: f32, cursor: (f32, f32), size: (f32, f32)) { + if let Self::List { + servers, + lan, + scroll, + .. + } = self + { + let (top, bottom, _) = list_area(size.0.ceil(), size.1.ceil()); + if cursor.1 >= top && cursor.1 < bottom { + let content = content_height(servers.len(), lan.games().len()); + scroll.wheel(delta, ROW_HEIGHT / 2.0, top, bottom, content); + } + } + } + /// The pointer moved: a held scrollbar follows it. + pub fn drag(&mut self, y: f32, size: (f32, f32)) { + if let Self::List { + servers, + lan, + scroll, + .. + } = self + { + let (top, bottom, _) = list_area(size.0.ceil(), size.1.ceil()); + scroll.drag( + y, + top, + bottom, + content_height(servers.len(), lan.games().len()), + ); + } + } + pub fn release(&mut self) { + if let Self::List { scroll, .. } = self { + scroll.release(); + } + } fn focused_field(&mut self) -> Option<&mut String> { match self { Self::Edit { @@ -756,3 +983,49 @@ pub fn wrap(text: &str, width: f32, atlas: &HudAtlas) -> Vec { } lines } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_lan_header_follows_the_saved_servers() { + let all: Vec = rows(2, 1).collect(); + assert_eq!( + all, + [Row::Server(0), Row::Server(1), Row::LanHeader, Row::Lan(0)] + ); + // No saved servers: the list is the scanning header alone. + assert_eq!(rows(0, 0).collect::>(), [Row::LanHeader]); + assert_eq!(content_height(0, 0), 40.0); + } + + #[test] + fn rows_sit_two_pixels_under_the_header_and_scroll_with_the_list() { + // 427x240 GUI: the list spans 33..180, rows 305 wide from x 61. + let size = (427.0, 240.0); + assert_eq!(list_area(size.0, size.1), (33.0, 180.0, 61.0)); + assert_eq!(row_at(3, 0, (100.0, 35.0), size, 0.0), Some(Row::Server(0))); + assert_eq!(row_at(3, 0, (100.0, 70.9), size, 0.0), Some(Row::Server(0))); + assert_eq!(row_at(3, 0, (100.0, 71.0), size, 0.0), Some(Row::Server(1))); + assert_eq!( + row_at(3, 0, (100.0, 35.0), size, 36.0), + Some(Row::Server(1)) + ); + assert_eq!( + row_at(3, 0, (100.0, 143.0), size, 0.0), + Some(Row::LanHeader) + ); + assert_eq!(row_at(3, 0, (60.0, 40.0), size, 0.0), None); + assert_eq!(row_at(3, 0, (100.0, 32.0), size, 0.0), None); + } + + #[test] + fn loading_dots_step_every_300_ms() { + let frames: Vec<&str> = [0, 299, 300, 600, 900, 1200].map(loading_dots).to_vec(); + assert_eq!( + frames, + ["O o o", "O o o", "o O o", "o o O", "o O o", "O o o"] + ); + } +} diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 4b447663a..8d67dcc04 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -1699,7 +1699,11 @@ impl OptionsUi { } if self.page() == Page::Packs { let mut events = Vec::new(); - if drag || right { + if drag { + self.packs(atlas, size).drag(y as f64); + return events; + } + if right { return events; } let m = crate::screen_draw::Measure(&atlas.font); @@ -1862,6 +1866,9 @@ impl OptionsUi { } pub fn release(&mut self) -> Vec { self.scrollbar_drag_y = None; + if let Some(p) = &mut self.pack_screen { + p.release(); + } // AbstractSliderButton suppresses the press sound and plays once on // release, even if the pointer has left the widget or its value stayed. let slider = self.dragging.take().is_some(); diff --git a/crates/horizon-client/src/pack_screen.rs b/crates/horizon-client/src/pack_screen.rs index a96ea3072..934ecaf95 100644 --- a/crates/horizon-client/src/pack_screen.rs +++ b/crates/horizon-client/src/pack_screen.rs @@ -136,6 +136,8 @@ struct List { selected: Option, /// The list has a focused child (possibly an entry it no longer holds). focused: bool, + /// The pointer's last y while the scrollbar is held (`scrolling`). + held: Option, } impl List { fn new(selected_side: bool, height: i32) -> Self { @@ -149,6 +151,7 @@ impl List { entries: Vec::new(), selected: None, focused: false, + held: None, } } fn bottom(&self) -> i32 { @@ -244,6 +247,21 @@ impl List { fn scroller_height(&self) -> i32 { ((self.height * self.height) as f32 / self.content_height() as f32) as i32 } + /// `AbstractScrollArea.mouseDragged` while the scrollbar is held. + fn drag(&mut self, y: f64) { + let Some(last) = self.held else { return }; + if y < self.y as f64 { + self.set_scroll(0.0); + } else if y > self.bottom() as f64 { + self.set_scroll(self.max_scroll() as f64); + } else { + let max = self.max_scroll().max(1) as f64; + let bar = self.scroller_height().clamp(32, self.height - 8); + let scale = (max / (self.height - bar) as f64).max(1.0); + self.set_scroll(self.scroll + (y - last) * scale); + } + self.held = Some(y); + } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -490,6 +508,13 @@ impl PackScreen { && x <= (l.scroll_bar_x() + 6) as f64 && y >= l.y as f64 && y < l.bottom() as f64; + // updateScrolling: a press on the scroller holds it. + if scrolling { + self.lists[side].held = Some(y); + self.set_focus(Focus::List(side)); + return Action::None; + } + let l = &self.lists[side]; let hit = l.entry_at(x as i32, y as i32); let mut took = false; if let Some(i) = hit { @@ -516,7 +541,7 @@ impl PackScreen { } } } - if took || scrolling { + if took { self.set_focus(Focus::List(side)); } return Action::None; @@ -669,6 +694,18 @@ impl PackScreen { false } /// The mouse wheel (`AbstractScrollArea.mouseScrolled`). + /// The pointer moved with the button held: a held scrollbar follows it. + pub fn drag(&mut self, y: f64) { + for l in &mut self.lists { + l.drag(y); + } + } + /// `onRelease`. + pub fn release(&mut self) { + for l in &mut self.lists { + l.held = None; + } + } pub fn scroll(&mut self, x: f64, y: f64, amount: f64) { if self.confirm.is_some() || self.search.contains(x, y) { return; diff --git a/crates/horizon-client/src/recipe_book.rs b/crates/horizon-client/src/recipe_book.rs index 6de6416c2..2caa68cac 100644 --- a/crates/horizon-client/src/recipe_book.rs +++ b/crates/horizon-client/src/recipe_book.rs @@ -646,8 +646,31 @@ impl ClientBook { /// displays it has (`RecipeManager.listDisplaysForRecipe`). #[derive(Clone, Debug, Default)] pub struct RecipeIndex { - /// Recipe id -> (special, display count, first display id). - recipes: std::collections::BTreeMap, + recipes: std::collections::BTreeMap, +} +#[derive(Clone, Debug)] +struct Known { + special: bool, + displays: usize, + first_display: i32, + /// `RecipeDisplay.craftingStation`: the workstation item of its displays. + station: &'static str, + /// `Recipe.showNotification`: unlocking it shows the `RecipeToast`. + notify: bool, + /// `result.id`, for the recipes the book doesn't list. + result: Option, +} +/// `RecipeDisplay.craftingStation` of a recipe type. +fn crafting_station(kind: &str) -> &'static str { + match kind { + "minecraft:smelting" => "minecraft:furnace", + "minecraft:blasting" => "minecraft:blast_furnace", + "minecraft:smoking" => "minecraft:smoker", + "minecraft:campfire_cooking" => "minecraft:campfire", + "minecraft:stonecutting" => "minecraft:stonecutter", + "minecraft:smithing_transform" | "minecraft:smithing_trim" => "minecraft:smithing_table", + _ => "minecraft:crafting_table", + } } impl RecipeIndex { /// Reads `data/minecraft/recipe/*.json` under `root`. @@ -685,13 +708,23 @@ impl RecipeIndex { } else { 1 }; - recipes.insert(format!("minecraft:{stem}"), (special, displays, 0)); + recipes.insert( + format!("minecraft:{stem}"), + Known { + special, + displays, + first_display: 0, + station: crafting_station(kind), + notify: v["show_notification"].as_bool().unwrap_or(true), + result: v["result"]["id"].as_str().map(str::to_owned), + }, + ); } // RecipeManager keeps its recipes sorted by id and numbers the displays in that order. let mut next = 0; for r in recipes.values_mut() { - r.2 = next; - next += r.1 as i32; + r.first_display = next; + next += r.displays as i32; } Self { recipes } } @@ -699,10 +732,19 @@ impl RecipeIndex { self.recipes.contains_key(id) } pub fn special(&self, id: &str) -> bool { - self.recipes.get(id).is_some_and(|r| r.0) + self.recipes.get(id).is_some_and(|r| r.special) } pub fn displays(&self, id: &str) -> usize { - self.recipes.get(id).map_or(0, |r| r.1) + self.recipes.get(id).map_or(0, |r| r.displays) + } + /// The crafting station shown on its displays' toast, when unlocking it + /// shows one (`Recipe.showNotification`). + pub fn toast_station(&self, id: &str) -> Option<&'static str> { + self.recipes.get(id).filter(|r| r.notify).map(|r| r.station) + } + /// The result item id its file names (none for trims). + pub fn result(&self, id: &str) -> Option<&str> { + self.recipes.get(id).and_then(|r| r.result.as_deref()) } /// Every recipe id, in id order. pub fn ids(&self) -> impl Iterator { @@ -710,10 +752,15 @@ impl RecipeIndex { } /// The display ids of a recipe (none for a special one). pub fn display_ids(&self, id: &str) -> std::ops::Range { - self.recipes.get(id).map_or(0..0, |r| r.2..r.2 + r.1 as i32) + self.recipes.get(id).map_or(0..0, |r| { + r.first_display..r.first_display + r.displays as i32 + }) } pub fn first_display(&self, id: &str) -> Option { - self.recipes.get(id).filter(|r| r.1 > 0).map(|r| r.2) + self.recipes + .get(id) + .filter(|r| r.displays > 0) + .map(|r| r.first_display) } } @@ -836,6 +883,57 @@ mod tests { Ingredient::of(items.iter().map(|s| (*s).to_owned()).collect()) } #[test] + fn the_index_knows_each_recipes_toast_station_and_result() { + let root = std::env::temp_dir().join(format!("horizon-toast-index-{}", std::process::id())); + let dir = root.join("data/minecraft/recipe"); + std::fs::create_dir_all(&dir).unwrap(); + for (name, json) in [ + ( + "stick", + r#"{"type":"minecraft:crafting_shaped","result":{"id":"minecraft:stick"}}"#, + ), + ( + "crafting_table", + r#"{"type":"minecraft:crafting_shaped","show_notification":false,"result":{"id":"minecraft:crafting_table"}}"#, + ), + ( + "cooked_beef_from_campfire_cooking", + r#"{"type":"minecraft:campfire_cooking","result":{"id":"minecraft:cooked_beef"}}"#, + ), + ( + "stone_slab_from_stonecutting", + r#"{"type":"minecraft:stonecutting","result":{"id":"minecraft:stone_slab"}}"#, + ), + ( + "coast_trim", + r#"{"type":"minecraft:smithing_trim","pattern":"minecraft:coast"}"#, + ), + ] { + std::fs::write(dir.join(format!("{name}.json")), json).unwrap(); + } + let index = RecipeIndex::load(&root); + std::fs::remove_dir_all(&root).unwrap(); + let toast = |id: &str| (index.toast_station(id), index.result(id)); + assert_eq!( + toast("minecraft:stick"), + (Some("minecraft:crafting_table"), Some("minecraft:stick")) + ); + // show_notification: false unlocks silently. + assert_eq!(toast("minecraft:crafting_table").0, None); + assert_eq!( + toast("minecraft:cooked_beef_from_campfire_cooking"), + (Some("minecraft:campfire"), Some("minecraft:cooked_beef")) + ); + assert_eq!( + toast("minecraft:stone_slab_from_stonecutting").0, + Some("minecraft:stonecutter") + ); + assert_eq!( + toast("minecraft:coast_trim"), + (Some("minecraft:smithing_table"), None) + ); + } + #[test] fn small_recipes_are_centred_in_the_grid() { // One ingredient in a 3x3 grid goes to the middle cell. assert_eq!(place_cells(3, 3, 1, 1, &['a']), vec![('a', 4)]); diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index f0a645942..9660d237e 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -527,6 +527,7 @@ pub fn encode_block_entity( } } BlockEntity::Spawner(s) => entries.extend(s.save()), + BlockEntity::TrialSpawner(s) => entries.extend(s.save()), BlockEntity::Beehive(h) => entries.extend(h.to_nbt()), } Tag::compound(entries) @@ -656,6 +657,7 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain | BlockEntity::Banner(_) | BlockEntity::CreakingHeart(_) => {} BlockEntity::Spawner(s) => **s = crate::mobs::spawner::Spawner::load(tag), + BlockEntity::TrialSpawner(s) => **s = crate::mobs::trial_spawner::TrialSpawner::load(tag), BlockEntity::Beehive(h) => **h = crate::beehive::Beehive::from_nbt(tag), } Some((pos, entity)) @@ -1924,6 +1926,145 @@ const INT_RULES: [&str; 11] = [ /// World and player state stored in `level.dat`, the saved-data files and /// the player file. +/// The world options CreateWorldScreen sets (`WorldOptions` and the world +/// preset) that `world_gen_settings` keeps. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WorldGen { + /// The `minecraft:flat` preset (Superflat) instead of `normal`. + pub flat: bool, + pub structures: bool, + pub bonus_chest: bool, +} +impl WorldGen { + /// A saved world's choices, from its `world_gen_settings`. + pub fn read(world: &Path) -> Option { + let settings = world_gen_settings(world)?; + let flag = |key: &str, default: bool| number(settings.get(key)).map_or(default, |v| v != 0); + let generator = settings + .get("dimensions") + .and_then(|d| d.get("minecraft:overworld")) + .and_then(|o| o.get("generator")); + Some(Self { + flat: text(generator.and_then(|g| g.get("type"))) + .is_some_and(|t| t.trim_start_matches("minecraft:") == "flat"), + structures: flag("generate_structures", true), + bonus_chest: flag("bonus_chest", false), + }) + } +} +impl Default for WorldGen { + fn default() -> Self { + Self { + flat: false, + structures: true, + bonus_chest: false, + } + } +} +/// Writes a new world's `world_gen_settings` (seed, options and dimensions). +pub fn write_world_gen_settings(dir: &Path, seed: i64, options: WorldGen) -> Result<()> { + fs::create_dir_all(dir)?; + // worldgen/world_preset/flat.json's overworld: the classic flat layers. + let layer = |block: &str, height: i32| { + Tag::compound([("block", string(block)), ("height", Tag::Int(height))]) + }; + let flat = Tag::compound([ + ("type", string("minecraft:overworld")), + ( + "generator", + Tag::compound([ + ("type", string("minecraft:flat")), + ( + "settings", + Tag::compound([ + ("biome", string("minecraft:plains")), + ("features", Tag::Byte(0)), + ("lakes", Tag::Byte(0)), + ( + "layers", + Tag::List(vec![ + layer("minecraft:bedrock", 1), + layer("minecraft:dirt", 2), + layer("minecraft:grass_block", 1), + ]), + ), + ( + "structure_overrides", + Tag::List(vec![ + string("minecraft:strongholds"), + string("minecraft:villages"), + ]), + ), + ]), + ), + ]), + ), + ]); + let dimension = |kind: &str, settings: &str, source: Tag| { + Tag::compound([ + ("type", string(kind)), + ( + "generator", + Tag::compound([ + ("type", string("minecraft:noise")), + ("settings", string(settings)), + ("biome_source", source), + ]), + ), + ]) + }; + let preset = |p: &str| { + Tag::compound([ + ("type", string("minecraft:multi_noise")), + ("preset", string(p)), + ]) + }; + write_saved_data( + dir, + "world_gen_settings", + Tag::compound([ + ("seed", Tag::Long(seed)), + ( + "generate_structures", + Tag::Byte(i8::from(options.structures)), + ), + ("bonus_chest", Tag::Byte(i8::from(options.bonus_chest))), + ( + "dimensions", + Tag::compound([ + ( + "minecraft:overworld", + if options.flat { + flat + } else { + dimension( + "minecraft:overworld", + "minecraft:overworld", + preset("minecraft:overworld"), + ) + }, + ), + ( + "minecraft:the_nether", + dimension( + "minecraft:the_nether", + "minecraft:nether", + preset("minecraft:nether"), + ), + ), + ( + "minecraft:the_end", + dimension( + "minecraft:the_end", + "minecraft:end", + Tag::compound([("type", string("minecraft:the_end"))]), + ), + ), + ]), + ), + ]), + ) +} #[derive(Clone, Debug, Default)] pub struct Level { pub name: String, @@ -1966,6 +2107,9 @@ pub struct Level { pub world_spawn: Option<[i32; 3]>, pub difficulty: String, pub hardcore: bool, + /// `allowCommands` chosen on the Create New World screen; unset keeps + /// the saved value (off for a new world). + pub allow_commands: Option, /// Game rule values by name without namespace (`keep_inventory`, ...). pub game_rules: BTreeMap, pub player_uuid: Option<[i32; 4]>, @@ -2526,6 +2670,9 @@ impl Level { } if let Tag::Compound(map) = &mut data { map.entry("allowCommands".into()).or_insert(Tag::Byte(0)); + if let Some(allow) = self.allow_commands { + map.insert("allowCommands".into(), Tag::Byte(i8::from(allow))); + } map.entry("WasModded".into()).or_insert(Tag::Byte(0)); map.entry("DataPacks".into()).or_insert_with(|| { Tag::compound([ @@ -2569,63 +2716,7 @@ impl Level { } write_saved_data(dir, "world_clocks", clocks)?; if legacy || !saved_data_path(dir, "world_gen_settings").exists() { - let dimension = |kind: &str, settings: &str, source: Tag| { - Tag::compound([ - ("type", string(kind)), - ( - "generator", - Tag::compound([ - ("type", string("minecraft:noise")), - ("settings", string(settings)), - ("biome_source", source), - ]), - ), - ]) - }; - let preset = |p: &str| { - Tag::compound([ - ("type", string("minecraft:multi_noise")), - ("preset", string(p)), - ]) - }; - write_saved_data( - dir, - "world_gen_settings", - Tag::compound([ - ("seed", Tag::Long(self.seed)), - ("generate_structures", Tag::Byte(1)), - ("bonus_chest", Tag::Byte(0)), - ( - "dimensions", - Tag::compound([ - ( - "minecraft:overworld", - dimension( - "minecraft:overworld", - "minecraft:overworld", - preset("minecraft:overworld"), - ), - ), - ( - "minecraft:the_nether", - dimension( - "minecraft:the_nether", - "minecraft:nether", - preset("minecraft:nether"), - ), - ), - ( - "minecraft:the_end", - dimension( - "minecraft:the_end", - "minecraft:end", - Tag::compound([("type", string("minecraft:the_end"))]), - ), - ), - ]), - ), - ]), - )?; + write_world_gen_settings(dir, self.seed, WorldGen::default())?; } if !saved_data_path(dir, "game_rules").exists() || !self.game_rules.is_empty() { // Only rules vanilla knows: an unknown key makes it reject the file. diff --git a/crates/horizon-client/src/sound_engine.rs b/crates/horizon-client/src/sound_engine.rs index 64092f3e6..562b14100 100644 --- a/crates/horizon-client/src/sound_engine.rs +++ b/crates/horizon-client/src/sound_engine.rs @@ -17,6 +17,7 @@ use std::collections::HashMap; pub const MASTER: usize = 0; pub const MUSIC: usize = 1; pub const RECORDS: usize = 2; +pub const NEUTRAL: usize = 6; pub const PLAYERS: usize = 7; pub const AMBIENT: usize = 8; pub const UI: usize = 10; @@ -48,12 +49,30 @@ pub enum Ticking { UnderLiquidLoop { fade: i32 }, /// `UnderLiquidSubSound`. UnderLiquidSub, + /// `MinecartSoundInstance` following a minecart. + Minecart { cart: u32 }, + /// `RidingMinecartSoundInstance` for the player riding a minecart. + RidingMinecart { cart: u32, underwater: bool }, } -/// What tickable instances read about the player. -#[derive(Clone, Copy, Debug, Default)] +/// What a minecart's sound instances read about it. +#[derive(Clone, Copy, Debug)] +pub struct CartSound { + pub id: u32, + pub position: [f64; 3], + /// `getDeltaMovement().horizontalDistance()`. + pub speed: f64, +} +/// What tickable instances read about the player and the entities they follow. +#[derive(Clone, Debug, Default)] pub struct TickContext { pub player_underwater: bool, pub player_removed: bool, + /// The minecart the player rides. + pub vehicle: Option, + /// The minecarts in the level (a missing one has been removed). + pub carts: Vec, + /// `!tickRateManager().runsNormally()`. + pub frozen: bool, } /// `AbstractSoundInstance` and its subclasses' fields. #[derive(Clone, Debug)] @@ -247,6 +266,55 @@ impl SoundInstance { pub fn under_liquid_sub(id: &str, random: LegacyRandom) -> Self { Self::ambient_loop(id, random, false, Ticking::UnderLiquidSub) } + /// `new MinecartSoundInstance(minecart)`: silent until the cart rolls. + pub fn minecart(cart: &CartSound, random: LegacyRandom) -> Self { + let [x, y, z] = cart.position; + let mut s = Self::new( + "minecraft:entity.minecart.riding", + NEUTRAL, + 0.0, + 1.0, + random, + true, + 0, + Attenuation::Linear, + [ + f64::from(x as f32), + f64::from(y as f32), + f64::from(z as f32), + ], + false, + ); + s.can_start_silent = true; + s.ticking = Ticking::Minecart { cart: cart.id }; + s + } + /// `new RidingMinecartSoundInstance(player, minecart, underwater, event, 0, 0.75, 1)`. + pub fn riding_minecart(cart: &CartSound, underwater: bool, random: LegacyRandom) -> Self { + let id = if underwater { + "minecraft:entity.minecart.inside.underwater" + } else { + "minecraft:entity.minecart.inside" + }; + let mut s = Self::new( + id, + NEUTRAL, + 0.0, + 1.0, + random, + true, + 0, + Attenuation::None, + cart.position, + false, + ); + s.can_start_silent = true; + s.ticking = Ticking::RidingMinecart { + cart: cart.id, + underwater, + }; + s + } pub fn tickable(&self) -> bool { self.ticking != Ticking::No } @@ -301,6 +369,46 @@ impl SoundInstance { self.stop(); } } + Ticking::Minecart { cart } => { + let id = *cart; + let Some(cart) = ctx.carts.iter().find(|c| c.id == id) else { + self.stop(); + return; + }; + let [x, y, z] = cart.position; + self.position = [ + f64::from(x as f32), + f64::from(y as f32), + f64::from(z as f32), + ]; + // Its own `pitch` field shadows the instance's, which stays 1. + let speed = cart.speed as f32; + self.volume = if speed >= 0.01 && !ctx.frozen { + speed.clamp(0.0, 0.5) * 0.7 + } else { + 0.0 + }; + } + Ticking::RidingMinecart { cart, underwater } => { + let (id, underwater) = (*cart, *underwater); + let found = ctx.carts.iter().find(|c| c.id == id); + let Some(cart) = found.filter(|c| ctx.vehicle == Some(c.id)) else { + self.stop(); + return; + }; + if underwater != ctx.player_underwater { + self.volume = 0.0; + } else { + // Mth.clampedLerp(speed, 0, 0.75), amplified by 1. + let speed = cart.speed as f32; + self.volume = if speed >= 0.01 { + if speed > 1.0 { 0.75 } else { speed * 0.75 } + } else { + 0.0 + }; + self.position = cart.position; + } + } } } /// `LoopSoundInstance.fadeOut`. diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index d1582a6b8..35b02c12e 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -437,6 +437,7 @@ pub enum Smithing { result: String, }, Trim { + id: String, template: Ingredient, base: Ingredient, addition: Ingredient, @@ -510,6 +511,7 @@ impl StationRecipes { .to_owned(), }), "minecraft:smithing_trim" => smithing.push(Smithing::Trim { + id, template: ingredient(&v["template"], items), base: ingredient(&v["base"], items), addition: ingredient(&v["addition"], items), @@ -614,25 +616,64 @@ impl StationRecipes { base: b, addition: a, pattern, + .. } => { if t.test(template) && b.test(base) && a.test(addition) { - let material = e.props(&addition.item)?.trim_material.clone()?; - let trim = (Arc::from(material.as_str()), Arc::from(pattern.as_str())); - if base.data().and_then(|d| d.trim.as_ref()) == Some(&trim) { - return None; - } - let mut out = ItemStack { - count: 1, - ..base.clone() - }; - out.data_mut().trim = Some(trim); - return Some(out); + return apply_trim(e, base, addition, pattern); } } } } None } + /// `SmithingTrimDemoSlotDisplay.resolveForFirstStack` of a trim recipe: + /// a random base trimmed with a random material (`pick(n)` draws below n). + pub fn trim_demo( + &self, + e: &Enchantments, + id: &str, + pick: &mut dyn FnMut(usize) -> usize, + ) -> Option { + let (base, addition, pattern) = self.smithing.iter().find_map(|r| match r { + Smithing::Trim { + id: i, + base, + addition, + pattern, + .. + } if i == id => Some((&base.1, &addition.1, pattern)), + _ => None, + })?; + if base.is_empty() || addition.is_empty() { + return None; + } + // applyDemoTransformation: up to 256 draws, the first that isn't empty. + (0..256).find_map(|_| { + let base = ItemStack::new(&base[pick(base.len())], 1); + let material = ItemStack::new(&addition[pick(addition.len())], 1); + apply_trim(e, &base, &material, pattern) + }) + } +} +/// `SmithingTrimRecipe.applyTrim`: none when the material provides no trim +/// or the base already has this one. +fn apply_trim( + e: &Enchantments, + base: &ItemStack, + material: &ItemStack, + pattern: &str, +) -> Option { + let material = e.props(&material.item)?.trim_material.clone()?; + let trim = (Arc::from(material.as_str()), Arc::from(pattern)); + if base.data().and_then(|d| d.trim.as_ref()) == Some(&trim) { + return None; + } + let mut out = ItemStack { + count: 1, + ..base.clone() + }; + out.data_mut().trim = Some(trim); + Some(out) } #[cfg(test)] diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index ea399937e..f400522df 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -45,6 +45,27 @@ fn loot_item(s: &horizon_world::loot::LootStack) -> ItemStack { item } +/// A rolled stack as an item with its enchantments (stored ones on a +/// book), potion and ominous bottle level. +pub fn loot_item_with_components(s: &horizon_world::loot::LootStack) -> ItemStack { + let mut item = loot_item(s); + for (id, level) in &s.enchantments { + let level = (*level).max(0) as u32; + if &*item.item == "minecraft:enchanted_book" { + crate::item_data::set_level(&mut item.data_mut().stored_enchantments, id, level); + } else { + item.enchant(id, level); + } + } + if let Some(potion) = &s.potion { + item = item.with_potion(potion); + } + if let Some(level) = s.ominous_amplifier.filter(|l| *l > 0) { + item.data_mut().ominous_amplifier = Some(level.clamp(0, 4) as u8); + } + item +} + /// The exploration map search an item still waits for, removed from it. pub fn take_pending_map(item: &mut ItemStack) -> Option { let data = item.extra.as_deref_mut()?; @@ -123,6 +144,9 @@ pub fn block_entities( if let BlockEntity::Spawner(s) = &mut entity { **s = crate::mobs::spawner::Spawner::load(&Tag::Compound(nbt.clone())); } + if let BlockEntity::TrialSpawner(s) = &mut entity { + **s = crate::mobs::trial_spawner::TrialSpawner::load(&Tag::Compound(nbt.clone())); + } if let (BlockEntity::Chest(slots), Some(table), Some(loot)) = (&mut entity, text(nbt, "LootTable"), loot) { diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index d680b32ab..c4e568df5 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -12,12 +12,15 @@ use std::{ sync::mpsc, }; +mod create_world; #[cfg(test)] mod tests; mod world_management; +pub use create_world::{DIFFICULTIES, WorldOptions}; -const LIST_TOP: f32 = 48.0; -const LIST_BOTTOM: f32 = 58.0; +/// SelectWorldScreen's `HeaderAndFooterLayout(8 + 9 + 8 + 20 + 4, 60)`. +const LIST_TOP: f32 = 49.0; +const LIST_BOTTOM: f32 = 60.0; const ROW_HEIGHT: f32 = 36.0; const ROW_WIDTH: f32 = 270.0; @@ -80,6 +83,7 @@ pub enum Mode { seed: String, creative: bool, focus: u8, + options: WorldOptions, }, Edit { world: WorldEntry, @@ -113,6 +117,7 @@ pub enum Action { name: String, seed: Option, creative: bool, + options: WorldOptions, }, Connect { address: String, @@ -124,7 +129,7 @@ pub struct Title { pub started: std::time::Instant, search: String, search_focused: bool, - scroll: Cell, + scroll: Cell, create_return_to_main: bool, message_lines: Cell, backup: Option>>, @@ -139,7 +144,7 @@ pub struct Title { /// The saves listed for Home, re-read every couple of seconds. recent: std::cell::RefCell)>>, } -struct Button { +pub(crate) struct Button { x: f32, y: f32, w: f32, @@ -228,7 +233,7 @@ impl Title { started: now, search: String::new(), search_focused: false, - scroll: Cell::new(0.0), + scroll: Cell::default(), create_return_to_main: false, message_lines: Cell::new(1), backup: None, @@ -252,7 +257,7 @@ impl Title { pub fn enter_singleplayer(&mut self) { self.search.clear(); self.search_focused = true; - self.scroll.set(0.0); + self.scroll.set(crate::ui::Scroll::default()); let worlds = list_worlds(&self.saves); self.create_return_to_main = worlds.is_empty(); self.mode = if worlds.is_empty() { @@ -264,12 +269,13 @@ impl Title { } }; } - fn new_world() -> Mode { + pub(crate) fn new_world() -> Mode { Mode::Create { name: "New World".into(), seed: String::new(), creative: false, focus: 0, + options: WorldOptions::default(), } } fn return_to_list(&mut self, folder: Option<&str>) { @@ -324,19 +330,48 @@ impl Title { .collect::>() .into_iter() } - /// Mouse wheel over the classic world list. + /// The world list's top, bottom, rows' left edge and content height. + fn world_list(&self, worlds: &[WorldEntry], (w, h): (f32, f32)) -> (f32, f32, f32, f32) { + let (w, h) = (w.ceil(), h.ceil()); + let content = self.visible_worlds(worlds).count() as f32 * ROW_HEIGHT + 4.0; + let left = (w / 2.0).floor() - ROW_WIDTH / 2.0; + (LIST_TOP, h - LIST_BOTTOM, left, content) + } + /// The pointer moved with the button held (`mouseDragged`). + pub fn drag(&mut self, cursor: (f32, f32), size: (f32, f32)) { + if let Mode::Multiplayer(screen) = &mut self.mode { + return screen.drag(cursor.1, size); + } + if let Mode::Select { worlds, .. } = &self.mode { + let (top, bottom, _, content) = self.world_list(worlds, size); + let mut scroll = self.scroll.get(); + scroll.drag(cursor.1, top, bottom, content); + self.scroll.set(scroll); + } + } + /// The button was released (`onRelease`). + pub fn release(&mut self) { + if let Mode::Multiplayer(screen) = &mut self.mode { + screen.release(); + } + self.scroll.get_mut().release(); + } + /// Mouse wheel over the classic world and server lists. pub fn scroll_worlds(&mut self, delta: f32, cursor: (f32, f32), size: (f32, f32)) { + if let Mode::Multiplayer(screen) = &mut self.mode { + screen.wheel(delta, cursor, size); + return; + } let Mode::Select { worlds, .. } = &self.mode else { return; }; - if cursor.1 < LIST_TOP || cursor.1 >= size.1 - LIST_BOTTOM { + let (top, bottom, _, content) = self.world_list(worlds, size); + if cursor.1 < top || cursor.1 >= bottom { return; } - let max = (self.visible_worlds(worlds).count() as f32 * ROW_HEIGHT + 4.0 - - (size.1 - LIST_TOP - LIST_BOTTOM)) - .max(0.0); - self.scroll - .set((self.scroll.get() - delta * ROW_HEIGHT / 2.0).clamp(0.0, max)); + let mut scroll = self.scroll.get(); + scroll.wheel(delta, ROW_HEIGHT / 2.0, top, bottom, content); + self.scroll.set(scroll); } fn failed(&mut self, error: impl std::fmt::Display) { let return_to = Box::new(self.mode.clone()); @@ -453,11 +488,22 @@ impl Title { name, seed, creative, + options, .. } = &self.mode else { return Action::None; }; + Action::Create { + folder: self.target_folder(name), + name: name.clone(), + seed: parse_seed(seed), + creative: *creative, + options: options.clone(), + } + } + /// The folder a new world named `name` gets (`findResultFolder`). + fn target_folder(&self, name: &str) -> String { let base: String = name .chars() .map(|c| { @@ -480,12 +526,7 @@ impl Title { folder = format!("{base} ({n})"); n += 1; } - Action::Create { - folder, - name: name.clone(), - seed: parse_seed(seed), - creative: *creative, - } + folder } fn buttons(&self, w: f32, h: f32) -> Vec