diff --git a/crates/horizon-client/src/command/vanilla.rs b/crates/horizon-client/src/command/vanilla.rs index 28d29d7ab..0c9f74161 100644 --- a/crates/horizon-client/src/command/vanilla.rs +++ b/crates/horizon-client/src/command/vanilla.rs @@ -111,6 +111,28 @@ pub fn build() -> Dispatcher { d.executes(dur, "weather"); } + // raid start | stop | check | sound | spawnleader | setomen | glow + let raid = d.literal(root, "raid"); + d.requires(raid, 3); + let start = d.literal(raid, "start"); + let level = d.argument(start, "omenlvl", integer(0)); + d.executes(level, "raid.start"); + for (name, id) in [ + ("stop", "raid.stop"), + ("check", "raid.check"), + ("spawnleader", "raid.spawnleader"), + ("glow", "raid.glow"), + ] { + let n = d.literal(raid, name); + d.executes(n, id); + } + let sound = d.literal(raid, "sound"); + let kind = d.argument(sound, "type", ArgType::Greedy); + d.executes(kind, "raid.sound"); + let setomen = d.literal(raid, "setomen"); + let level = d.argument(setomen, "level", integer(0)); + d.executes(level, "raid.setomen"); + // kill [] let kill = d.literal(root, "kill"); d.requires(kill, GAMEMASTERS); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5865d0adb..96c01535d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2442,6 +2442,7 @@ impl Game<'_> { self.screen = Screen::Dead; self.capture(false); } + self.tick_omens(); self.tick_effects(); self.tick_burning(); self.tick_using(); @@ -6519,6 +6520,7 @@ impl Game<'_> { .save(&chunks, self.res.assets.registry, &self.res.biomes)?; self.save_entities()?; self.save_maps(); + self.save_raids(); self.save_fight(); self.save_stats(); self.save_advancements(); diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 50382bb9d..d0392b35b 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -261,12 +261,26 @@ impl Game<'_> { } } pub(super) fn mob_entity(&self, m: &horizon_client::mobs::Mob) -> EntityView { + // mainhand, offhand, head, chest, legs, feet. + let slot = |i: &Option>| { + i.as_ref().map(|id| item_view(&ItemStack::new(id, 1))) + }; + let mut equipment: [Option; 7] = Default::default(); + if !horizon_client::mobs::equine::is_equine(m.species()) { + equipment[0] = slot(&m.extra.main_hand); + equipment[1] = slot(&m.extra.off_hand); + equipment[2] = slot(&m.extra.head); + equipment[3] = slot(&m.extra.chest); + equipment[4] = slot(&m.extra.legs); + equipment[5] = slot(&m.extra.feet); + } EntityView { kind: m.kind.id.clone(), position: [m.position.x, m.position.y, m.position.z], on_fire: m.fire_ticks > 0, baby: m.is_baby(), on_ground: m.on_ground, + equipment, ..Default::default() } } diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 5dfff0315..31d900003 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -2,6 +2,7 @@ //! entity selectors resolved against the game, vanilla feedback and errors. mod effects; pub(super) mod execute; +mod raid; mod text_commands; use super::{Dim, Game, Screen, chat::PLAYER_NAME}; @@ -418,6 +419,7 @@ impl Game<'_> { | "teleport.targets.location" | "teleport.targets.destination" => self.cmd_teleport(id, ctx), id if id.starts_with("time.") => self.cmd_time(id, ctx), + id if id.starts_with("raid.") => self.cmd_raid(id, ctx), "weather" => self.cmd_weather(ctx), "kill" => self.cmd_kill(ctx), "summon" => self.cmd_summon(ctx), diff --git a/crates/horizon-client/src/game/commands/raid.rs b/crates/horizon-client/src/game/commands/raid.rs new file mode 100644 index 000000000..762ae7e90 --- /dev/null +++ b/crates/horizon-client/src/game/commands/raid.rs @@ -0,0 +1,108 @@ +//! `RaidCommand`: `/raid start|stop|check|spawnleader|setomen|glow|sound`. +use super::{Game, R, Text, err}; +use horizon_client::{command::Context, mobs::raider}; + +impl Game<'_> { + pub(in crate::game) fn cmd_raid(&mut self, id: &str, ctx: &Context) -> R { + let Some(player) = self.player.as_ref().map(|p| p.position) else { + return Ok(0); + }; + let at = [ + player.x.floor() as i32, + player.y.floor() as i32, + player.z.floor() as i32, + ]; + let fail = |game: &mut Self, message: &str| { + game.command_failure(Text::literal(message)); + }; + match id { + "raid.start" => { + if self.raiding_nearby(at).is_some() { + fail(self, "Raid already started close by"); + return Ok(-1); + } + let level = Self::int(ctx, "omenlvl").unwrap_or(0); + match self.raid_command_create(at, level) { + true => self.feedback(Text::literal("Created a raid in your local village")), + false => fail(self, "Failed to create a raid in your local village"), + } + Ok(1) + } + "raid.stop" => match self.raiding_nearby(at) { + Some(raid) => { + self.raid_command_stop(raid); + self.feedback(Text::literal("Stopped raid")); + Ok(1) + } + None => { + fail(self, "No raid here"); + Ok(-1) + } + }, + "raid.check" => match self.raiding_nearby(at).filter(|id| self.raid_started(*id)) { + Some(raid) => { + self.feedback(Text::literal("Found a started raid!")); + let status = self.raid_status_text(raid); + self.feedback(Text::literal(&status)); + Ok(1) + } + None => { + fail(self, "Found no started raids"); + Ok(0) + } + }, + "raid.spawnleader" => { + let kind = "minecraft:pillager"; + match self.spawn_mob_for(kind, [player.x, player.y, player.z], true, true) { + Some(id) => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + raider::set_patrol_leader(m, true); + raider::finalize(m, raider::Reason::Other); + } + self.feedback(Text::literal("Spawned a raid captain")); + Ok(1) + } + None => { + fail(self, "Pillager failed to spawn"); + Ok(0) + } + } + } + "raid.setomen" => { + let level = Self::int(ctx, "level").unwrap_or(0); + let Some(raid) = self.raiding_nearby(at) else { + fail(self, "No raid found here"); + return Ok(1); + }; + if level > horizon_client::raid::MAX_OMEN_LEVEL { + fail( + self, + &format!( + "Sorry, the max raid omen level you can set is {}", + horizon_client::raid::MAX_OMEN_LEVEL + ), + ); + } else { + let before = self.raid_set_omen(raid, level); + self.feedback(Text::literal(format!( + "Changed village's raid omen level from {before} to {level}" + ))); + } + Ok(1) + } + "raid.glow" => { + if let Some(raid) = self.raiding_nearby(at) { + self.raid_glow(raid); + } + Ok(1) + } + "raid.sound" => { + let at = [player.x + 5.0, player.y, player.z]; + self.audio + .play("minecraft:event.raid.horn", Some(at), 1.0, 1.0); + Ok(1) + } + _ => Err(err("commands.help.failed", &[])), + } + } +} diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index b7f6c0699..1198680e5 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -151,6 +151,7 @@ impl Game<'_> { gold_armor: self.wearing_gold(), hurt_by: self.player_hurt_by(), last_hurt: self.combat.last_hurt_mob.map(|(id, at)| (Who::Mob(id), at)), + hero: self.potions.effects.get("hero_of_the_village").is_some(), }) } /// Biome facts at a position for finalizeSpawn and variant rules. @@ -623,6 +624,7 @@ impl Game<'_> { self.tick_inhabited(); self.spawn_natural(); self.tick_patrol_spawner(); + self.tick_raids(); let snapshot: Vec = self.mobs.iter().map(seen).collect(); let mut events = Vec::new(); let mut mobs = std::mem::take(&mut self.mobs); @@ -646,6 +648,7 @@ impl Game<'_> { push_apart(&mut mobs); } self.mobs.append(&mut mobs); + self.sync_riders(); for m in dead { self.mob_died(&m); } @@ -666,6 +669,7 @@ impl Game<'_> { let view = self.mob_entity(m); self.trigger_entity("minecraft:player_killed_entity", "entity", &view); } + self.raider_died(m, by_player); let held = self.held().cloned(); let pos = [m.position.x, m.position.y + 0.5, m.position.z]; if !m.is_baby() { @@ -1001,6 +1005,10 @@ impl Game<'_> { MobEvent::CreakingTearDown { center, spread } => { self.creaking_tear_down(center, spread) } + MobEvent::Firework { at, color, flight } => { + self.villager_firework(at, color, flight) + } + MobEvent::ThrowGift { table, from, to } => self.throw_gift(&table, from, to), MobEvent::PatrolTarget { mob, target } => { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { horizon_client::mobs::raider::set_patrol_target(m, target); diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index 398b9a208..be4b4ec1f 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -1842,7 +1842,8 @@ impl Game<'_> { /// The boss bar (`BossHealthOverlay`): name and the pink progress bar. pub(super) fn draw_boss_bar(&self, batch: &mut HudBatch) { let dragon = self.dragon.as_ref().filter(|_| self.dim == Dim::End); - self.draw_wither_bars(batch, if dragon.is_some() { 31.0 } else { 12.0 }); + let y = self.draw_wither_bars(batch, if dragon.is_some() { 31.0 } else { 12.0 }); + self.draw_raid_bar(batch, y); let Some(d) = dragon else { return; }; diff --git a/crates/horizon-client/src/game/fireworks.rs b/crates/horizon-client/src/game/fireworks.rs index 2bd400d96..4f0c3fa9c 100644 --- a/crates/horizon-client/src/game/fireworks.rs +++ b/crates/horizon-client/src/game/fireworks.rs @@ -37,7 +37,7 @@ fn fireworks_of(stack: &ItemStack) -> (u8, Vec) { .unwrap_or((1, Vec::new())) } impl Game<'_> { - fn new_rocket(&mut self, at: Vec3, stack: &ItemStack, attached: bool) -> Rocket { + pub(super) fn new_rocket(&mut self, at: Vec3, stack: &ItemStack, attached: bool) -> Rocket { let (flight, explosions) = fireworks_of(stack); let r = &mut self.world.random; let tri = |r: &mut horizon_core::random::LegacyRandom| { diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index ab3e28827..ba5d1bc87 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -1,14 +1,28 @@ -//! Pillager patrols (`PatrolSpawner`) and the village sections they avoid. +//! Pillager patrols (`PatrolSpawner`), the raid omen, and raids (`Raids`): +//! their waves, boss bar, victory and the raiders' bookkeeping. use super::{Dim, Game}; -use horizon_client::mobs::{Species, data, raider}; -use horizon_core::random::RandomSource; -use std::collections::HashSet; +use horizon_client::mobs::villager as mobs_villager; +use horizon_client::{ + effects::EffectInstance, + hud::{HudBatch, rgba}, + mobs::{Mob, Species, data, raider}, + raid::{self, Action, BarName, RaidLevel, RaiderInfo, RaiderType, Raids, Spawn}, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; +use std::collections::{HashMap, HashSet}; /// Patrol and raid state owned by the game. #[derive(Default)] pub(super) struct Raiding { /// `PatrolSpawner.nextTick`. patrol_next_tick: i32, + raids: Raids, + loaded: bool, + /// `ServerPlayer.raidOmenPosition`. + omen_position: Option<[i32; 3]>, + /// Beds near each raid's centre, rescanned now and then (`HOME` points + /// of interest for `RaiderMoveThroughVillageGoal`). + homes: HashMap>)>, } /// `SectionPos` of a block position. @@ -30,6 +44,878 @@ pub(super) fn sections_to_village(centers: &HashSet<(i32, i32, i32)>, at: (i32, .map_or(7, |d| d.min(7)) } +/// The level as a raid sees it, with this tick's village and raider data. +struct Lvl<'a, 'g> { + game: &'a Game<'g>, + difficulty: i32, + centers: &'a HashSet<(i32, i32, i32)>, + raiders: &'a HashMap>, +} +impl RaidLevel for Lvl<'_, '_> { + fn difficulty(&self) -> i32 { + self.difficulty + } + fn has_chunk_at(&self, p: [i32; 3]) -> bool { + self.game.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) + } + fn is_village(&self, p: [i32; 3]) -> bool { + sections_to_village(self.centers, section(p)) <= 1 + } + fn village_sections_near(&self, p: [i32; 3]) -> Vec<[i32; 3]> { + let (sx, sy, sz) = section(p); + let mut out = Vec::new(); + for dx in -2..=2 { + for dy in -2..=2 { + for dz in -2..=2 { + let s = (sx + dx, sy + dy, sz + dz); + let center = [s.0 * 16 + 8, s.1 * 16 + 8, s.2 * 16 + 8]; + if self.is_village(center) { + out.push(center); + } + } + } + } + out + } + fn raiders(&self, raid: i32) -> Vec { + self.raiders.get(&raid).cloned().unwrap_or_default() + } + fn surface_height(&self, x: i32, z: i32) -> i32 { + self.game.surface_height(x, z) + } + fn is_ticking(&self, p: [i32; 3]) -> bool { + [(-10, -10), (10, -10), (-10, 10), (10, 10)] + .iter() + .all(|(dx, dz)| self.has_chunk_at([p[0] + dx, p[1], p[2] + dz])) + } + fn can_spawn_at(&self, p: [i32; 3]) -> bool { + if !self.is_ticking(p) { + return false; + } + let g = self.game; + let w = g.mob_world_base(&[]); + horizon_client::mobs::spawning::placement_ok(Species::Ravager, &w, p[0], p[1], p[2]) + || w.block_name(p[0], p[1] - 1, p[2]) == "minecraft:snow" + && g.res.facts.is_air(g.world.block(p[0], p[1], p[2])) + } +} + +/// `DyeColor.getFireworkColor`. +const FIREWORK_COLORS: [u32; 16] = [ + 0xF0F0F0, 0xEB8844, 0xC354CD, 0x6689D3, 0xDECF2A, 0x41CD34, 0xD88198, 0x434343, 0xABABAB, + 0x287697, 0x7B2FBE, 0x253192, 0x51301A, 0x3B511A, 0xB3312C, 0x1E1B1B, +]; + +fn block_of(p: Vec3) -> [i32; 3] { + [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32] +} + +impl Game<'_> { + /// `Heightmap.Types.WORLD_SURFACE`: the first free block above the + /// highest non-air one. + pub(super) fn surface_height(&self, x: i32, z: i32) -> i32 { + let top = if self.dim == Dim::Nether { 127 } else { 319 }; + (horizon_client::chunk::MIN_Y..=top) + .rev() + .find(|&y| !self.res.facts.is_air(self.world.block(x, y, z))) + .map_or(horizon_client::chunk::MIN_Y, |y| y + 1) + } + /// Every claimed village point of interest (job sites, beds, bells). + fn village_pois(&self) -> Vec<[i32; 3]> { + let mut out: Vec<[i32; 3]> = Vec::new(); + for m in &self.mobs { + if m.species() != Species::Villager || !m.alive() { + continue; + } + for p in [m.extra.home, m.extra.bed, m.extra.meeting] + .into_iter() + .flatten() + { + if !out.contains(&p) { + out.push(p); + } + } + } + out + } + fn difficulty_id(&self) -> i32 { + use horizon_world::food::Difficulty; + match self.world.health_rules.difficulty { + Difficulty::Peaceful => 0, + Difficulty::Easy => 1, + Difficulty::Normal => 2, + Difficulty::Hard => 3, + } + } + fn player_block(&self) -> Option<[i32; 3]> { + self.player.as_ref().map(|p| block_of(p.position)) + } + fn raids_path(&self) -> std::path::PathBuf { + self.world_root.join("data/minecraft/raids.dat") + } + fn load_raids(&mut self) { + if self.raiding.loaded { + return; + } + self.raiding.loaded = true; + let seed = self.world.random.next_long(); + if let Some(tag) = horizon_client::save::read_dat(&self.raids_path()) + && let Some(data) = tag.get("data") + { + self.raiding.raids = Raids::from_nbt(data, seed); + } + } + /// `Raids` as `data/minecraft/raids.dat`, when it changed. + pub(super) fn save_raids(&mut self) { + if !self.raiding.loaded || !self.raiding.raids.dirty || self.remote.is_some() { + return; + } + let tag = horizon_world::nbt::Tag::compound([ + ("data", self.raiding.raids.to_nbt()), + ( + "DataVersion", + horizon_world::nbt::Tag::Int(horizon_world::DATA_VERSION), + ), + ]); + if horizon_client::save::write_dat(&self.raids_path(), tag).is_ok() { + self.raiding.raids.dirty = false; + } + } + + /// `BadOmenMobEffect` and `RaidOmenMobEffect`, before the effects tick: + /// Bad Omen inside a village becomes Raid Omen, which starts or extends a + /// raid when it runs out. + pub(super) fn tick_omens(&mut self) { + if self.dim != Dim::Overworld || self.spectator() { + return; + } + let Some(pos) = self.player_block() else { + return; + }; + self.load_raids(); + if let Some(amp) = self.potions.effects.amplifier("bad_omen") + && self.difficulty_id() != 0 + && sections_to_village(&self.village_centers(), section(pos)) <= 1 + && self + .raiding + .raids + .nearby(pos) + .is_none_or(|(_, r)| r.omen_level < raid::MAX_OMEN_LEVEL) + { + self.potions.effects.list.retain(|e| e.id != "bad_omen"); + self.potions + .effects + .add(EffectInstance::new("raid_omen", 600, amp)); + self.raiding.omen_position = Some(pos); + let eye = self.eye_position().unwrap_or_default(); + self.audio + .play("minecraft:event.mob_effect.raid_omen", Some(eye), 1.0, 1.0); + } + let due = self + .potions + .effects + .get("raid_omen") + .filter(|e| e.duration == 1) + .map(|e| e.amplifier); + if let Some(amp) = due + && let Some(at) = self.raiding.omen_position.take() + { + self.create_or_extend_raid(at, Some(amp)); + } + } + /// `Raids.createOrExtendRaid`: the raid centres on the claimed village + /// points within 64 blocks. + fn create_or_extend_raid(&mut self, at: [i32; 3], amplifier: Option) -> Option { + if !self.ui.rules.bool("raids") || self.dim != Dim::Overworld { + return None; + } + let near: Vec<[i32; 3]> = self + .village_pois() + .into_iter() + .filter(|p| (0..3).map(|i| f64::from(p[i] - at[i]).powi(2)).sum::() <= 4096.0) + .collect(); + let center = if near.is_empty() { + at + } else { + let n = near.len() as f64; + let mean = |i: usize| near.iter().map(|p| f64::from(p[i])).sum::() / n; + [ + mean(0).floor() as i32, + mean(1).floor() as i32, + mean(2).floor() as i32, + ] + }; + let seed = self.world.random.next_long(); + let difficulty = self.difficulty_id(); + let (id, triggered) = self + .raiding + .raids + .create_or_extend(center, difficulty, amplifier, seed); + if triggered { + self.stats.custom("raid_trigger", 1); + self.trigger_player("minecraft:voluntary_exile"); + } + Some(id) + } + /// `ServerLevel.getRaidAt`. + pub(super) fn raiding_nearby(&self, at: [i32; 3]) -> Option { + self.raiding.raids.nearby(at).map(|(id, _)| id) + } + pub(super) fn raid_started(&self, id: i32) -> bool { + self.raiding.raids.get(id).is_some_and(|r| r.started) + } + /// `/raid start`: a raid in the local village at the given omen level. + pub(super) fn raid_command_create(&mut self, at: [i32; 3], omen_level: i32) -> bool { + self.load_raids(); + let Some(id) = self.create_or_extend_raid(at, None) else { + return false; + }; + if let Some(r) = self.raiding.raids.map.get_mut(&id) { + r.omen_level = omen_level; + } + self.raiding.raids.dirty = true; + true + } + pub(super) fn raid_command_stop(&mut self, id: i32) { + if let Some(r) = self.raiding.raids.map.get_mut(&id) { + r.stop(); + } + } + pub(super) fn raid_set_omen(&mut self, id: i32, level: i32) -> i32 { + let Some(r) = self.raiding.raids.map.get_mut(&id) else { + return 0; + }; + std::mem::replace(&mut r.omen_level, level) + } + pub(super) fn raid_glow(&mut self, id: i32) { + for m in &mut self.mobs { + if raider::state(m).is_some_and(|s| s.raid_id == Some(id)) { + m.add_effect("glowing", 1000, 1); + } + } + } + /// The `/raid check` summary line. + pub(super) fn raid_status_text(&self, id: i32) -> String { + let Some(r) = self.raiding.raids.get(id) else { + return String::new(); + }; + let members: Vec<&Mob> = self + .mobs + .iter() + .filter(|m| m.alive() && raider::state(m).is_some_and(|s| s.raid_id == Some(id))) + .collect(); + let health: f32 = members.iter().map(|m| m.health).sum(); + format!( + "Num groups spawned: {} Raid omen level: {} Num mobs: {} Raid health: {} / {}", + r.groups_spawned, + r.omen_level, + members.len(), + health, + r.total_health + ) + } + + /// The living raiders by raid. + fn raider_infos(&self, centers: &HashSet<(i32, i32, i32)>) -> HashMap> { + let mut out: HashMap> = HashMap::new(); + for m in &self.mobs { + if !m.alive() || m.removed { + continue; + } + let Some(s) = raider::state(m) else { continue }; + let Some(id) = s.raid_id else { continue }; + let position = block_of(m.position); + out.entry(id).or_default().push(RaiderInfo { + id: m.id, + wave: s.wave, + health: m.health, + position, + age: m.age, + no_action_time: m.ai.no_action_time, + ticks_outside: s.ticks_outside_raid, + in_village: sections_to_village(centers, section(position)) <= 1, + }); + } + out + } + /// `ServerLevel.tick` for the raids and their raiders. + pub(super) fn tick_raids(&mut self) { + if self.remote.is_some() || self.dim != Dim::Overworld { + return; + } + self.load_raids(); + let centers = self.village_centers(); + let infos = self.raider_infos(¢ers); + let mut raids = std::mem::take(&mut self.raiding.raids); + let actions = { + let lvl = Lvl { + game: self, + difficulty: self.difficulty_id(), + centers: ¢ers, + raiders: &infos, + }; + raids.tick(&lvl, self.ui.rules.bool("raids"), self.player_block()) + }; + self.raiding.raids = raids; + for (id, action) in actions { + self.apply_raid_action(id, action); + } + self.sync_raiders(¢ers); + self.sync_villager_raids(&infos); + } + fn apply_raid_action(&mut self, id: i32, action: Action) { + match action { + Action::Spawn { pos, wave, spawns } => self.spawn_wave(id, pos, wave, &spawns), + Action::Horn { pos } => self.raid_horn(id, pos), + Action::Remove { id: mob } => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { + let s = raider::state_mut(m); + s.raid_id = None; + s.ticks_outside_raid = 0; + s.active_raid = false; + } + } + Action::SetOutside { id: mob, ticks } => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { + raider::state_mut(m).ticks_outside_raid = ticks; + } + } + Action::Victory { heroes, amplifier } => { + let me = self.level.player_uuid; + if me.is_some_and(|u| heroes.contains(&u)) && !self.spectator() { + let mut effect = + EffectInstance::new("hero_of_the_village", raid::HERO_DURATION, amplifier); + effect.visible = false; + self.potions.effects.add(effect); + self.stats.custom("raid_win", 1); + self.trigger_player("minecraft:hero_of_the_village"); + } + } + } + } + /// `Raid.playSound`: the horn, 13 blocks away from the player toward the + /// wave, for players within 64 blocks or in the raid. + fn raid_horn(&mut self, id: i32, pos: [i32; 3]) { + let Some(p) = self.player.as_ref().map(|p| p.position) else { + return; + }; + let in_raid = self.raiding.raids.get(id).is_some_and(|r| r.bar.player); + let (rx, rz) = (f64::from(pos[0]) + 0.5, f64::from(pos[2]) + 0.5); + let distance = ((rx - p.x).powi(2) + (rz - p.z).powi(2)).sqrt(); + if distance <= 64.0 || in_raid { + let k = 13.0 / distance.max(1e-4); + let at = [p.x + k * (rx - p.x), p.y, p.z + k * (rz - p.z)]; + self.audio + .play("minecraft:event.raid.horn", Some(at), 1.0, 1.0); + } + } + /// `Raid.spawnGroup`: a wave of raiders around `pos`, ravagers carrying + /// their riders. + fn spawn_wave(&mut self, raid_id: i32, pos: [i32; 3], wave: i32, spawns: &[Spawn]) { + let odds = self + .raiding + .raids + .get(raid_id) + .map_or(0.0, raid::Raid::enchant_odds); + for sp in spawns { + let Some(id) = self.spawn_raider(sp.kind, pos, raid_id, wave, sp.leader, odds) else { + continue; + }; + if let Some(kind) = sp.rider + && let Some(rider) = self.spawn_raider(kind, pos, raid_id, wave, false, odds) + { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == rider) { + raider::state_mut(m).vehicle = Some(id); + m.extra.passenger = true; + } + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + raider::state_mut(m).rider = true; + } + } + } + } + /// `Raid.joinRaid` for a new raider, with `applyRaidBuffs`. + fn spawn_raider( + &mut self, + kind: RaiderType, + pos: [i32; 3], + raid_id: i32, + wave: i32, + leader: bool, + odds: f32, + ) -> Option { + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 1.0, + f64::from(pos[2]) + 0.5, + ]; + let id = self.spawn_mob_for(kind.entity(), at, false, true)?; + let m = self.mobs.iter_mut().find(|m| m.id == id)?; + if leader { + raider::set_patrol_leader(m, true); + } + raider::finalize(m, raider::Reason::Event); + let s = raider::state_mut(m); + s.raid_id = Some(raid_id); + s.wave = wave; + s.can_join_raid = true; + s.ticks_outside_raid = 0; + s.active_raid = true; + m.on_ground = true; + // applyRaidBuffs: Quick Charge crossbows and Sharpness axes. + let enchant = m.random.next_float() <= odds; + match kind { + RaiderType::Pillager if enchant => { + raider::state_mut(m).enchant = if wave > raid::num_groups(2) { + 2 + } else if wave > raid::num_groups(1) { + 1 + } else { + 0 + }; + } + RaiderType::Vindicator => { + let level = if !enchant { + 0 + } else if wave > raid::num_groups(2) { + 2 + } else { + 1 + }; + raider::state_mut(m).enchant = level; + if level > 0 { + m.attrs.attack_damage += 1.0 + 0.5 * f32::from(level - 1); + } + } + _ => {} + } + Some(id) + } + + /// Per-tick raid bookkeeping of every raider (and the ravagers they + /// ride): the raid's state for the goals, joining and recruiting, + /// the banner of a fallen captain, idle time. + fn sync_raiders(&mut self, centers: &HashSet<(i32, i32, i32)>) { + let now = self.world.game_time; + let golems: HashSet = self + .mobs + .iter() + .filter(|m| m.species() == Species::IronGolem) + .map(|m| m.id) + .collect(); + // Living leaders and carried riders. + let mut leaders: HashSet<(i32, i32)> = HashSet::new(); + let mut ridden: HashSet = HashSet::new(); + let mut positions: Vec<(u32, Vec3, bool)> = Vec::new(); + for m in &self.mobs { + let Some(s) = raider::state(m) else { continue }; + if !m.alive() { + continue; + } + if let (Some(id), true) = (s.raid_id, s.patrol_leader) { + leaders.insert((id, s.wave)); + } + if let Some(v) = s.vehicle { + ridden.insert(v); + } + positions.push((m.id, m.position, s.active_raid)); + } + let banners: Vec<(usize, Vec3)> = self + .dropped + .iter() + .enumerate() + .filter(|(_, e)| { + &*e.stack.item == raider::BANNER + && e.stack.data().is_some_and(|d| d.ominous_banner) + && e.pickup_delay == 0 + }) + .map(|(i, e)| (i, e.position)) + .collect(); + let mut taken: Vec = Vec::new(); + let mut recruit: Vec<(i32, i32, Vec3)> = Vec::new(); + let homes = self.raid_homes(); + for m in &mut self.mobs { + let species = m.species(); + if !raider::is_raider(species) { + continue; + } + let alive = m.alive(); + let position = m.position; + let block = block_of(position); + let in_village = sections_to_village(centers, section(block)) <= 1; + let has_rider = ridden.contains(&m.id); + let target_golem = matches!(m.ai.target, Some(horizon_client::mobs::Who::Mob(t)) if golems.contains(&t)); + let target_player = m.ai.target == Some(horizon_client::mobs::Who::Player); + let (health, age, range) = (m.health, m.age, m.attrs.follow_range); + let raids = &mut self.raiding.raids; + let s = m.extra.raider.get_or_insert_with(Box::default); + s.rider = has_rider; + s.in_village = in_village; + if s.raid_id.is_some_and(|id| raids.get(id).is_none()) { + s.raid_id = None; + s.ticks_outside_raid = 0; + } + match s.raid_id.and_then(|id| raids.get(id)) { + Some(r) => { + s.active_raid = r.active; + s.raid_over = r.is_over(); + s.raid_loss = r.is_loss(); + s.raid_center = r.center; + s.homes = s.raid_id.and_then(|id| homes.get(&id).cloned()); + } + None => { + s.active_raid = false; + s.raid_over = false; + s.raid_loss = false; + s.homes = None; + s.banner_at = None; + } + } + if !alive { + continue; + } + // Raider.updateNoActionTime adds two per tick, and a raider + // fighting a player or golem in a raid is never idle. + if s.raid_id.is_some() { + m.ai.no_action_time = if target_player || target_golem { + 0 + } else { + m.ai.no_action_time + 1 + }; + } + // Raider.aiStep: join the raid the raider stands in. + if s.raid_id.is_none() + && s.can_join_raid + && now % 20 == 0 + && m.ai.no_action_time <= 2400 + && let Some((id, r)) = raids.nearby(block) + { + let wave = r.groups_spawned; + s.raid_id = Some(id); + s.wave = wave; + s.ticks_outside_raid = 0; + if let Some(r) = raids.map.get_mut(&id) { + r.total_health += health; + } + } + // PathfindToRaidGoal.recruitNearby. + if s.active_raid + && !s.raid_over + && !s.in_village + && age % 20 == 0 + && let Some(id) = s.raid_id + { + recruit.push((id, s.wave, position)); + } + // ObtainRaidLeaderBannerGoal. + s.banner_at = None; + if let Some(id) = s.raid_id + && s.active_raid + && !s.raid_over + && raider::can_be_leader(species) + && m.extra.head.as_deref() != Some(raider::BANNER) + && !leaders.contains(&(id, s.wave)) + { + let near = banners + .iter() + .filter(|(i, p)| { + !taken.contains(i) + && (p.x - position.x).abs() <= range + && (p.z - position.z).abs() <= range + && (p.y - position.y).abs() <= 8.0 + }) + .min_by(|a, b| { + a.1.distance_squared(position) + .total_cmp(&b.1.distance_squared(position)) + }); + if let Some((i, p)) = near { + s.banner_at = Some([p.x, p.y, p.z]); + if p.distance_squared(position) < 1.414 * 1.414 { + // pickUpItem: the banner becomes the wave's leader. + taken.push(*i); + leaders.insert((id, s.wave)); + s.banner_at = None; + s.patrol_leader = true; + s.patrolling = true; + m.extra.head = Some(raider::BANNER.into()); + } + } + } + } + taken.sort_unstable(); + for i in taken.into_iter().rev() { + self.dropped.remove(i); + } + // Recruiting: raiders nearby that are in no raid join this one. + for (id, wave, at) in recruit { + let now_nearby: Vec = positions + .iter() + .filter(|(_, p, active)| { + !active + && (p.x - at.x).abs() <= 16.0 + && (p.y - at.y).abs() <= 16.0 + && (p.z - at.z).abs() <= 16.0 + }) + .map(|(i, _, _)| *i) + .collect(); + for mid in now_nearby { + let Some(m) = self.mobs.iter_mut().find(|m| m.id == mid) else { + continue; + }; + let health = m.health; + let idle = m.ai.no_action_time; + let s = raider::state_mut(m); + if s.raid_id.is_none() && s.can_join_raid && idle <= 2400 { + s.raid_id = Some(id); + s.wave = wave; + s.ticks_outside_raid = 0; + s.active_raid = true; + if let Some(r) = self.raiding.raids.map.get_mut(&id) { + r.total_health += health; + } + } + } + } + } + /// Beds within 64 blocks of each raid's centre (the `HOME` points of + /// interest), rescanned every five seconds. + fn raid_homes(&mut self) -> HashMap>> { + let now = self.world.game_time; + let ids: Vec<(i32, [i32; 3])> = self + .raiding + .raids + .map + .iter() + .filter(|(_, r)| r.active && !r.is_over() && r.started) + .map(|(id, r)| (*id, r.center)) + .collect(); + self.raiding + .homes + .retain(|id, _| ids.iter().any(|(i, _)| i == id)); + for (id, c) in ids { + if self + .raiding + .homes + .get(&id) + .is_some_and(|(at, _)| now - at < 100) + { + continue; + } + let mut beds = Vec::new(); + let mut known: HashMap = HashMap::new(); + for y in c[1] - 32..=c[1] + 32 { + for z in c[2] - 64..=c[2] + 64 { + for x in c[0] - 64..=c[0] + 64 { + let state = self.world.block(x, y, z); + if self.res.facts.is_air(state) { + continue; + } + let bed = *known.entry(state.0).or_insert_with(|| { + self.res.facts.get(state).name.ends_with("_bed") + && self.res.assets.registry.state(state).is_some_and(|s| { + s.properties.get("part").map(String::as_str) == Some("head") + }) + }); + if bed { + beds.push([x, y, z]); + } + } + } + } + self.raiding + .homes + .insert(id, (now, std::sync::Arc::new(beds))); + } + self.raiding + .homes + .iter() + .map(|(id, (_, v))| (*id, v.clone())) + .collect() + } + /// A raider riding a ravager sits on its back (`Entity.positionRider` + /// with the ravager's passenger attachment and a 0.6 riding offset). + pub(super) fn sync_riders(&mut self) { + let vehicles: HashMap = self + .mobs + .iter() + .filter(|m| m.species() == Species::Ravager) + .map(|m| { + ( + m.id, + ( + m.position, + m.previous, + m.body_yaw, + m.previous_body_yaw, + m.alive(), + ), + ) + }) + .collect(); + for m in &mut self.mobs { + let Some(v) = raider::state(m).and_then(|s| s.vehicle) else { + continue; + }; + match vehicles.get(&v) { + Some(&(pos, prev, yaw, prev_yaw, true)) => { + let place = |p: Vec3, yaw: f32| { + let a = f64::from(yaw).to_radians(); + // The attachment's z offset of -0.0625, rotated. + Vec3::new( + p.x + a.sin() * -0.0625, + p.y + 2.2625 - 0.6, + p.z - a.cos() * -0.0625, + ) + }; + m.position = place(pos, yaw); + m.previous = place(prev, prev_yaw); + m.velocity = Vec3::ZERO; + m.fall_distance = 0.0; + m.on_ground = false; + m.body_yaw = yaw; + m.previous_body_yaw = prev_yaw; + m.extra.passenger = true; + // Raiders on a ravager never walk off on their own. + m.ai.nav.stop(); + } + _ => { + raider::state_mut(m).vehicle = None; + m.extra.passenger = false; + } + } + } + } + /// `Raider.die`: the killing player becomes a hero of the village. + pub(super) fn raider_died(&mut self, m: &Mob, by_player: bool) { + let Some(id) = raider::state(m).and_then(|s| s.raid_id) else { + return; + }; + if by_player + && let Some(uuid) = self.level.player_uuid + && let Some(r) = self.raiding.raids.map.get_mut(&id) + { + r.add_hero(uuid); + } + } + + /// `SetRaidStatus` / `ResetRaidStatus` for villagers: which raid package + /// they follow, by the raid nearest to them. + fn sync_villager_raids(&mut self, infos: &HashMap>) { + let raids = &self.raiding.raids; + let random = &mut self.world.random; + for m in &mut self.mobs { + if m.species() != Species::Villager { + continue; + } + let at = block_of(m.position); + let status = match raids.nearby(at) { + Some((id, r)) if !r.is_stopped() && !r.is_loss() => { + let alive = infos.get(&id).map_or(0, Vec::len); + if r.is_victory() { + mobs_villager::RAID_VICTORY + } else if r.has_first_wave_spawned() && !r.is_between_waves(alive) { + mobs_villager::RAID + } else { + mobs_villager::PRE_RAID + } + } + _ => mobs_villager::RAID_NONE, + }; + let ext = mobs_villager::ext_mut(m); + // ResetRaidStatus clears at once; SetRaidStatus one tick in twenty. + if status == mobs_villager::RAID_NONE + || ext.raid != status && random.next_int_bound(20).unwrap_or(1) == 0 + { + ext.raid = status; + } + } + } + + /// The raid boss bars (`BossHealthOverlay`): a red notched bar with the + /// raid's title. Returns the next free row. + pub(super) fn draw_raid_bar(&self, batch: &mut HudBatch, mut y: f32) -> f32 { + let atlas = &self.res.atlas; + for raid in self.raiding.raids.map.values() { + if !raid.bar.visible || !raid.bar.player || raid.is_stopped() { + continue; + } + let x = (batch.width / 2.0 - 91.0).floor(); + batch.sprite(atlas, "gui/sprites/boss_bar/red_background", x, y); + batch.sprite(atlas, "gui/sprites/boss_bar/notched_10_background", x, y); + let p = raid.bar.progress; + // Mth.lerpDiscrete(progress, 0, 182). + let width = (p * 181.0).floor() as i32 + i32::from(p > 0.0); + if width > 0 { + let fraction = width as f32 / 182.0; + batch.sprite_part(atlas, "gui/sprites/boss_bar/red_progress", x, y, fraction); + batch.sprite_part( + atlas, + "gui/sprites/boss_bar/notched_10_progress", + x, + y, + fraction, + ); + } + let title = self.translate("event.minecraft.raid", "Raid"); + let name = match raid.bar.name { + BarName::Raid => title, + BarName::Remaining(n) => format!( + "{title} - {}", + self.translate( + "event.minecraft.raid.raiders_remaining", + "Raiders Remaining: %s" + ) + .replace("%s", &n.to_string()) + ), + BarName::Victory => { + self.translate("event.minecraft.raid.victory.full", "Raid - Victory") + } + BarName::Defeat => { + self.translate("event.minecraft.raid.defeat.full", "Raid - Defeat") + } + }; + let w = HudBatch::text_width(atlas, &name); + batch.text( + atlas, + &name, + (batch.width / 2.0 - w / 2.0).floor(), + y - 9.0, + rgba(255, 255, 255, 255), + true, + ); + y += 19.0; + } + y + } + /// A firework a villager launches to celebrate (`CelebrateVillagersSurvivedRaid`). + pub(super) fn villager_firework(&mut self, at: [f64; 3], color: usize, flight: u8) { + let mut stack = horizon_client::items::ItemStack::new("minecraft:firework_rocket", 1); + stack.data_mut().fireworks = Some(( + flight, + vec![horizon_client::particles::FireworkExplosion { + shape: horizon_client::particles::FireworkShape::Burst, + colors: vec![FIREWORK_COLORS[color & 15]], + fade: Vec::new(), + trail: false, + twinkle: false, + }], + )); + let rocket = self.new_rocket(Vec3::new(at[0], at[1], at[2]), &stack, false); + self.rockets.push(rocket); + } + /// `BehaviorUtils.throwItem`: a hero's gift tossed toward the player. + pub(super) fn throw_gift(&mut self, table: &str, from: [f64; 3], to: [f64; 3]) { + let drops = self + .res + .items + .loot_table(table, false, None, &mut self.world.random); + let d = Vec3::new(to[0] - from[0], to[1] - from[1], to[2] - from[2]).normalize(); + for stack in drops { + self.spawn_item(stack, from, [d.x * 0.3, d.y * 0.3, d.z * 0.3], 10); + } + } +} + impl Game<'_> { /// Sections holding a claimed village point of interest (a job site, /// bed or bell a villager has taken): `PoiManager.isVillageCenter`. diff --git a/crates/horizon-client/src/game/wither.rs b/crates/horizon-client/src/game/wither.rs index d6cd6371d..3668e5f9f 100644 --- a/crates/horizon-client/src/game/wither.rs +++ b/crates/horizon-client/src/game/wither.rs @@ -75,9 +75,9 @@ impl Game<'_> { Ok(()) } /// The wither boss bars (purple, below the dragon's), within range. - pub(super) fn draw_wither_bars(&self, batch: &mut HudBatch, mut y: f32) { + pub(super) fn draw_wither_bars(&self, batch: &mut HudBatch, mut y: f32) -> f32 { let Some(p) = self.player.as_ref() else { - return; + return y; }; let atlas = &self.res.atlas; for m in self @@ -117,6 +117,7 @@ impl Game<'_> { ); y += 19.0; } + y } pub(super) fn wither_near(&self) -> bool { self.player.as_ref().is_some_and(|p| { diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 4d9ef4fbc..714f49308 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -53,6 +53,7 @@ pub mod packs; pub mod particles; pub mod pose; pub mod projectiles; +pub mod raid; pub mod save; pub mod screen_effects; pub mod settings; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index d90acb0b1..fa4da287e 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -479,6 +479,8 @@ pub struct Extra { pub trade: Option>, /// A raider's patrol and raid state. pub raider: Option>, + /// A villager's raid activity and gossip. + pub villager: Option>, } #[derive(Clone, Debug)] pub struct Mob { @@ -663,6 +665,18 @@ pub enum MobEvent { kind: DamageKind, amount: f32, }, + /// A villager launches a firework rocket (celebrating a won raid). + Firework { + at: [f64; 3], + color: usize, + flight: u8, + }, + /// A villager throws a hero's gift (a loot table) toward the player. + ThrowGift { + table: String, + from: [f64; 3], + to: [f64; 3], + }, /// A patrol leader hands its patrol target to a companion. PatrolTarget { mob: u32, @@ -753,6 +767,8 @@ pub struct PlayerView { pub hurt_by: Option<(Who, i64)>, /// `getLastHurtMob` and when. pub last_hurt: Option<(Who, i64)>, + /// The Hero of the Village effect. + pub hero: bool, } pub struct MobWorld<'a> { pub world: &'a World, diff --git a/crates/horizon-client/src/mobs/illager.rs b/crates/horizon-client/src/mobs/illager.rs index 155e9ea5e..2351916ad 100644 --- a/crates/horizon-client/src/mobs/illager.rs +++ b/crates/horizon-client/src/mobs/illager.rs @@ -384,8 +384,10 @@ impl CrossbowAttack { pub fn crossbow_goal(speed: f64, radius: f64) -> impl Goal { CrossbowAttack::new(speed, radius) } -/// `CrossbowItem.getChargeDuration` without Quick Charge. -const CHARGE: i32 = 25; +/// `CrossbowItem.getChargeDuration` (25 ticks, 5 fewer per level of Quick Charge). +pub fn charge_ticks(m: &Mob) -> i32 { + 25 - 5 * i32::from(super::raider::state(m).map_or(0, |s| s.enchant)) +} fn holding_crossbow(m: &Mob) -> bool { m.extra.main_hand.as_deref() == Some("minecraft:crossbow") } @@ -469,7 +471,7 @@ impl Goal for CrossbowAttack { } Crossbow::Charging => { m.extra.using_item += 1; - if m.extra.using_item >= CHARGE { + if m.extra.using_item >= charge_ticks(m) { m.extra.using_item = 0; m.extra.flag = false; self.state = Crossbow::Charged; @@ -534,6 +536,7 @@ fn shoot_crossbow(m: &mut Mob, who: Who, cx: &mut Cx) { enum ArmPose { Spellcasting, Crossed, + Celebrating, Neutral, Attacking, CrossbowHold, @@ -554,16 +557,22 @@ fn arm_pose(m: &Mob) -> ArmPose { } } Species::Evoker if m.extra.variant2 != 0 => ArmPose::Spellcasting, + Species::Evoker if celebrating(m) => ArmPose::Celebrating, Species::Evoker => ArmPose::Crossed, _ => { if m.ai.aggressive { ArmPose::Attacking + } else if celebrating(m) { + ArmPose::Celebrating } else { ArmPose::Crossed } } } } +fn celebrating(m: &Mob) -> bool { + super::raider::state(m).is_some_and(|s| s.celebrating) +} /// Whether the held item shows (vindicators only draw their axe when angry). pub fn shows_item(m: &Mob) -> bool { m.species() != Species::Vindicator || m.ai.aggressive @@ -637,8 +646,8 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { ArmPose::CrossbowCharge => { p.yrot("right_arm", -0.8); p.xrot("right_arm", -0.970_796_35); - let a = - (m.extra.using_item as f32 + s.partial).clamp(0.0, CHARGE as f32) / CHARGE as f32; + let charge = charge_ticks(m) as f32; + let a = (m.extra.using_item as f32 + s.partial).clamp(0.0, charge) / charge; p.yrot("left_arm", 0.4 + (0.85 - 0.4) * a); p.xrot("left_arm", -0.970_796_35 + (-PI / 2.0 + 0.970_796_35) * a); } @@ -655,6 +664,19 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { v[5] = z_rot; } } + ArmPose::Celebrating => { + for (arm, x, z_rot) in [ + ("right_arm", -5.0, 2.670_354), + ("left_arm", 5.0, -PI * 0.75), + ] { + let v = p.get(arm); + v[2] = 0.0; + v[0] = x; + v[3] = (s.age * 0.6662).cos() * 0.05; + v[4] = 0.0; + v[5] = z_rot; + } + } ArmPose::Crossed | ArmPose::Neutral => {} } if pose == ArmPose::Crossed { diff --git a/crates/horizon-client/src/mobs/raider.rs b/crates/horizon-client/src/mobs/raider.rs index 95a8f9dea..e2f053801 100644 --- a/crates/horizon-client/src/mobs/raider.rs +++ b/crates/horizon-client/src/mobs/raider.rs @@ -30,6 +30,28 @@ pub struct State { pub celebrating: bool, /// The raid is active (`hasActiveRaid`); set by the game every tick. pub active_raid: bool, + /// The raid is won or lost (`Raid.isOver`), lost (`isLoss`). + pub raid_over: bool, + pub raid_loss: bool, + pub raid_center: [i32; 3], + /// Standing in or beside a village (`ServerLevel.isVillage`). + pub in_village: bool, + /// A dropped ominous banner this raider may fetch. + pub banner_at: Option<[f64; 3]>, + /// Beds around the raid's centre. + pub homes: Option>>, + /// The ravager this raider rides, and (for a ravager) that it carries one. + pub vehicle: Option, + pub rider: bool, + /// Quick Charge (pillager crossbows) or Sharpness (vindicator axes) from + /// the raid's enchanting. + pub enchant: u8, +} +impl State { + /// A ravager carrying a raider (`hasControllingPassenger`). + pub fn has_rider(&self) -> bool { + self.rider + } } /// The raider species (`EntityTypeTags.RAIDERS`). @@ -67,6 +89,10 @@ pub fn register(m: &mut Mob) { } m.extra.raider = Some(Box::default()); let species = m.species(); + m.ai.goals.add(1, ObtainBanner); + m.ai.goals.add(3, PathfindToRaid); + m.ai.goals.add(4, MoveThroughVillage::new(1.05, 1.0)); + m.ai.goals.add(5, Celebration); m.ai.goals.add(4, LongDistancePatrol::new(0.7, 0.595)); // The illagers hold their ground in a patrol (Witch and Ravager do not). if matches!(species, Species::Pillager | Species::Vindicator) { @@ -292,10 +318,203 @@ fn close_to_center(p: [i32; 3], at: Vec3, distance: f64) -> bool { < distance * distance } -impl State { - /// A ravager carrying a raider (`hasControllingPassenger`). - pub fn has_rider(&self) -> bool { - false +/// `Raider.ObtainRaidLeaderBannerGoal`: walk to a fallen ominous banner when +/// the wave has no living leader (the game finds the banner and picks it up). +#[derive(Clone, Debug)] +pub struct ObtainBanner; +impl Goal for ObtainBanner { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + state(m).is_some_and(|s| s.banner_at.is_some()) + } + fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + !m.ai.nav.is_done() && state(m).is_some_and(|s| s.banner_at.is_some()) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + if let Some(at) = state(m).and_then(|s| s.banner_at) { + m.nav_move_to(cx.w, at, 1.15); + } + } +} + +/// `PathfindToRaidGoal`: outside the village, head for the raid's centre in +/// hops of up to 15 blocks. +#[derive(Clone, Debug)] +pub struct PathfindToRaid; +impl PathfindToRaid { + fn valid(s: &State) -> bool { + s.active_raid && !s.raid_over && !s.in_village + } +} +impl Goal for PathfindToRaid { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + m.ai.target.is_none() && state(m).is_some_and(|s| !s.has_rider() && Self::valid(s)) + } + fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + state(m).is_some_and(Self::valid) + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(c) = state(m).map(|s| s.raid_center) else { + return; + }; + if m.ai.nav.is_done() { + let to = [ + f64::from(c[0]) + 0.5, + f64::from(c[1]), + f64::from(c[2]) + 0.5, + ]; + if let Some(at) = + m.default_random_pos_towards(cx.w, 15, 4, to, std::f64::consts::FRAC_PI_2) + { + m.nav_move_to(cx.w, at, 1.0); + } + } + } +} + +/// `Raider.RaiderMoveThroughVillageGoal`: walk to a bed of the village not +/// visited lately, then onwards to the next one. +#[derive(Clone, Debug)] +pub struct MoveThroughVillage { + speed: f64, + distance: f64, + poi: Option<[i32; 3]>, + visited: Vec<[i32; 3]>, + stuck: bool, +} +impl MoveThroughVillage { + pub fn new(speed: f64, distance: f64) -> Self { + Self { + speed, + distance, + poi: None, + visited: Vec::new(), + stuck: false, + } + } +} +impl Goal for MoveThroughVillage { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + if self.visited.len() > 2 { + self.visited.remove(0); + } + let Some(s) = state(m) else { return false }; + if !(s.active_raid && !s.raid_over) || m.ai.target.is_some() { + return false; + } + let Some(homes) = s.homes.clone() else { + return false; + }; + let near: Vec<[i32; 3]> = homes + .iter() + .copied() + .filter(|p| !self.visited.contains(p) && close_to_center(*p, m.position, 48.0)) + .collect(); + if near.is_empty() { + return false; + } + self.poi = Some(near[m.random.next_int_bound(near.len() as i32).unwrap_or(0) as usize]); + true + } + fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + let Some(p) = self.poi else { return false }; + !m.ai.nav.is_done() + && m.ai.target.is_none() + && !close_to_center(p, m.position, f64::from(m.width()) + self.distance) + && !self.stuck + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + m.ai.no_action_time = 0; + if let Some(p) = self.poi { + m.nav_move_to( + cx.w, + [f64::from(p[0]), f64::from(p[1]), f64::from(p[2])], + self.speed, + ); + } + self.stuck = false; + } + fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { + if let Some(p) = self.poi + && close_to_center(p, m.position, self.distance) + { + self.visited.push(p); + } + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(p) = self.poi else { return }; + if !m.ai.nav.is_done() { + return; + } + let to = [ + f64::from(p[0]) + 0.5, + f64::from(p[1]), + f64::from(p[2]) + 0.5, + ]; + let next = m + .default_random_pos_towards(cx.w, 16, 7, to, std::f64::consts::PI / 10.0) + .or_else(|| m.default_random_pos_towards(cx.w, 8, 7, to, std::f64::consts::FRAC_PI_2)); + match next { + Some(at) => { + m.nav_move_to(cx.w, at, self.speed); + } + None => self.stuck = true, + } + } +} + +/// `Raider.RaiderCelebration`: after a lost village, cheer and jump. +#[derive(Clone, Debug)] +pub struct Celebration; +impl Goal for Celebration { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + m.alive() + && m.ai.target.is_none() + && state(m).is_some_and(|s| s.raid_loss && s.raid_id.is_some()) + } + fn start(&mut self, m: &mut Mob, _cx: &mut Cx) { + state_mut(m).celebrating = true; + } + fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { + state_mut(m).celebrating = false; + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if m.random + .next_int_bound(super::goals::reduced(100)) + .unwrap_or(1) + == 0 + { + let sound = match m.species() { + Species::Pillager => "entity.pillager.celebrate", + Species::Vindicator => "entity.vindicator.celebrate", + Species::Evoker => "entity.evoker.celebrate", + Species::Ravager => "entity.ravager.celebrate", + _ => "entity.witch.celebrate", + }; + m.voice(sound, cx.events); + } + if m.random + .next_int_bound(super::goals::reduced(50)) + .unwrap_or(1) + == 0 + { + m.ai.jumping = true; + } } } diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index 105db50f2..5ed95eb3a 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -5,11 +5,11 @@ //! (work and restock at the job site, meet at the bell, sleep in the bed), //! fleeing hostiles (`VillagerPanicTrigger`) and the unhappy head shake. use super::{ - Mob, MobEvent, MobWorld, Species, + Mob, MobEvent, MobWorld, Species, Who, anim::{Poses, State}, goals::{ - Avoid, AvoidEntity, Cx, Float, Goal, LookAtPlayer, MOVE, Panic, RandomLookAround, Stroll, - goal_clone, + Avoid, AvoidEntity, Cx, Float, Goal, LOOK, LookAtPlayer, MOVE, Panic, RandomLookAround, + Stroll, goal_clone, }, }; use horizon_core::random::RandomSource; @@ -74,6 +74,8 @@ pub fn register(m: &mut Mob) { AvoidEntity::new(Avoid::Species(raiders), 12.0, 0.75, 0.75), ); g.add(1, Panic::new(0.75)); + g.add(2, RaidBehavior::default()); + g.add(3, GiftToHero::default()); g.add(3, JobSite::default()); g.add(3, AcquireHome::default()); g.add(4, Schedule::default()); @@ -594,3 +596,216 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { p.yrot("right_leg", 0.0); p.yrot("left_leg", 0.0); } + +// ---- Raids: the raid activities and the gift for a hero. + +pub const RAID_NONE: u8 = 0; +/// A raid is near but no wave is on (`Activity.PRE_RAID`). +pub const PRE_RAID: u8 = 1; +/// A wave is on (`Activity.RAID`). +pub const RAID: u8 = 2; +/// The raid was won: the villagers celebrate. +pub const RAID_VICTORY: u8 = 3; + +/// Villager state beyond `Extra`'s scratch fields. +#[derive(Clone, Debug, Default)] +pub struct Ext { + /// Which raid package the villager follows. + pub raid: u8, +} +pub fn ext(m: &Mob) -> Option<&Ext> { + m.extra.villager.as_deref() +} +pub fn ext_mut(m: &mut Mob) -> &mut Ext { + m.extra.villager.get_or_insert_with(Box::default) +} +fn raid_status(m: &Mob) -> u8 { + ext(m).map_or(RAID_NONE, |e| e.raid) +} + +/// The raid packages of `VillagerGoalPackages`: in a raid villagers hide at +/// home (`LocateHidingPlace`), before one they gather at the bell and ring it +/// (`RingBell`), and after a victory they look for the sky to celebrate +/// (`MoveToSkySeeingSpot`, `CelebrateVillagersSurvivedRaid`). +#[derive(Clone, Debug, Default)] +struct RaidBehavior { + next_move: i32, +} +impl Goal for RaidBehavior { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + raid_status(m) != RAID_NONE && !sleeping(m) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.can_use(m, cx) + } + fn start(&mut self, m: &mut Mob, _cx: &mut Cx) { + self.next_move = 0; + m.nav_stop(); + } + fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { + m.nav_stop(); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.next_move -= 1; + let p = m.position; + match raid_status(m) { + RAID => { + // LocateHidingPlace(24, 0.7, 1): back to the bed. + let Some(home) = m.extra.bed else { return }; + if distance(m, home) > 1.0 && (self.next_move <= 0 || m.ai.nav.is_done()) { + if distance(m, home) <= 24.0 { + m.nav_move_to(cx.w, center(home), 0.7); + } + self.next_move = 40; + } + } + PRE_RAID => { + // RingBell and SetWalkTargetFromBlockMemory(meeting, 0.75). + let Some(bell) = m.extra.meeting else { return }; + if distance(m, bell) > 2.0 && (self.next_move <= 0 || m.ai.nav.is_done()) { + m.nav_move_to(cx.w, center(bell), 0.75); + self.next_move = 40; + } + if distance(m, bell) < 3.0 + && m.random.next_float() > 0.95 + && cx.w.block_name(bell[0], bell[1], bell[2]) == "minecraft:bell" + { + cx.events.push(MobEvent::SoundId( + "minecraft:block.bell.use".into(), + center(bell), + 2.0, + 1.0, + )); + } + } + RAID_VICTORY => { + let (x, y, z) = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); + if cx.w.can_see_sky(x, y, z) { + // CelebrateVillagersSurvivedRaid.tick. + if m.random.next_int_bound(100).unwrap_or(1) == 0 { + m.voice("entity.villager.celebrate", cx.events); + } + if m.random.next_int_bound(200).unwrap_or(1) == 0 { + let color = m.random.next_int_bound(16).unwrap_or(0) as usize; + let flight = m.random.next_int_bound(3).unwrap_or(0) as u8; + cx.events.push(MobEvent::Firework { + at: [p.x, m.eye_y(), p.z], + color, + flight, + }); + } + m.nav_stop(); + } else if self.next_move <= 0 || m.ai.nav.is_done() { + // MoveToSkySeeingSpot: a random spot with a view of the sky. + for _ in 0..5 { + if let Some(at) = m.land_random_pos(cx.w, 15, 7) + && cx.w.can_see_sky( + at[0].floor() as i32, + at[1].floor() as i32, + at[2].floor() as i32, + ) + { + m.nav_move_to(cx.w, at, 0.5); + break; + } + } + self.next_move = 40; + } + } + _ => {} + } + } +} + +/// `GiveGiftToHero`: a villager that sees a hero of the village walks up and +/// throws a gift of its profession, every so often. +#[derive(Clone, Debug)] +struct GiftToHero { + until_next: i32, + started: i64, + given: bool, +} +impl Default for GiftToHero { + fn default() -> Self { + Self { + until_next: 600, + started: 0, + given: false, + } + } +} +/// The gift loot table of a villager (`GiveGiftToHero.getLootTableToThrow`). +fn gift_table(m: &Mob) -> String { + if m.is_baby() { + return "minecraft:gameplay/hero_of_the_village/baby_gift".into(); + } + let profession = super::render::PROFESSIONS[m.extra.variant2 as usize % 15]; + let name = match profession { + "none" | "nitwit" => "unemployed", + other => other, + }; + format!("minecraft:gameplay/hero_of_the_village/{name}_gift") +} +fn hero_in_view(m: &mut Mob, cx: &Cx) -> bool { + let Some(p) = &cx.w.player else { return false }; + p.hero + && p.alive + && !p.spectator + && m.position.distance_squared(p.position) <= 16.0 * 16.0 + && m.sees(cx.w, Who::Player) +} +impl Goal for GiftToHero { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !hero_in_view(m, cx) || sleeping(m) { + return false; + } + if self.until_next > 0 { + self.until_next -= 1; + return false; + } + true + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + hero_in_view(m, cx) && !self.given + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.given = false; + self.started = cx.w.game_time; + if let Some(p) = &cx.w.player { + m.look_at(p.eye); + } + } + fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { + self.until_next = 600 + m.random.next_int_bound(6001).unwrap_or(0); + m.nav_stop(); + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(p) = cx.w.player.clone() else { return }; + m.look_at(p.eye); + let near = m.position.distance_squared(p.position) < 25.0; + if near { + if cx.w.game_time - self.started > 20 { + cx.events.push(MobEvent::ThrowGift { + table: gift_table(m), + from: [m.position.x, m.eye_y() - 0.3, m.position.z], + to: [p.position.x, p.position.y, p.position.z], + }); + self.given = true; + } + m.nav_stop(); + } else if m.ai.nav.is_done() { + m.nav_move_to(cx.w, [p.position.x, p.position.y, p.position.z], 0.5); + } + } +} diff --git a/crates/horizon-client/src/raid.rs b/crates/horizon-client/src/raid.rs new file mode 100644 index 000000000..a3be4d191 --- /dev/null +++ b/crates/horizon-client/src/raid.rs @@ -0,0 +1,1069 @@ +//! Raids (`Raid` and `Raids`): the raid omen that starts one, the waves of +//! raiders each difficulty sends, the boss bar, victory and loss, and +//! `data/minecraft/raids.dat`. The world is reached through [`RaidLevel`] and +//! the results come back as [`Action`]s, so the rules can be tested alone. +use horizon_core::random::{LegacyRandom, RandomSource}; +use horizon_world::nbt::Tag; +use std::collections::BTreeMap; + +pub const MAX_OMEN_LEVEL: i32 = 5; +/// `Raid.RAID_TIMEOUT_TICKS`. +const TIMEOUT: i64 = 48_000; +const PRE_RAID_TICKS: i32 = 300; +const POST_RAID_LIMIT: i32 = 40; +const CELEBRATION_TICKS: i32 = 600; +/// `Raids.getNearbyRaid(pos, 9216)`: within 96 blocks. +pub const VALID_RAID_RADIUS_SQR: f64 = 9216.0; +/// `RAID_REMOVAL_THRESHOLD_SQR`: a raider this far from the centre leaves. +const REMOVAL_THRESHOLD_SQR: f64 = 12544.0; +/// `HERO_OF_THE_VILLAGE_DURATION`. +pub const HERO_DURATION: i32 = 48_000; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Status { + Ongoing, + Victory, + Loss, + Stopped, +} +impl Status { + pub fn name(self) -> &'static str { + match self { + Self::Ongoing => "ongoing", + Self::Victory => "victory", + Self::Loss => "loss", + Self::Stopped => "stopped", + } + } + fn from_name(s: &str) -> Self { + match s { + "victory" => Self::Victory, + "loss" => Self::Loss, + "stopped" => Self::Stopped, + _ => Self::Ongoing, + } + } +} + +/// `Raid.RaiderType`, in spawn order. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RaiderType { + Vindicator, + Evoker, + Pillager, + Witch, + Ravager, +} +impl RaiderType { + pub const ALL: [Self; 5] = [ + Self::Vindicator, + Self::Evoker, + Self::Pillager, + Self::Witch, + Self::Ravager, + ]; + pub fn entity(self) -> &'static str { + match self { + Self::Vindicator => "minecraft:vindicator", + Self::Evoker => "minecraft:evoker", + Self::Pillager => "minecraft:pillager", + Self::Witch => "minecraft:witch", + Self::Ravager => "minecraft:ravager", + } + } + /// The health `addWaveMob` counts toward the bar. + pub fn health(self) -> f32 { + match self { + Self::Witch => 26.0, + Self::Ravager => 100.0, + _ => 24.0, + } + } + pub fn can_be_leader(self) -> bool { + !matches!(self, Self::Witch | Self::Ravager) + } + /// `spawnsPerWaveBeforeBonus`, by wave number. + fn spawns(self) -> [i32; 8] { + match self { + Self::Vindicator => [0, 0, 2, 0, 1, 4, 2, 5], + Self::Evoker => [0, 0, 0, 0, 0, 1, 1, 2], + Self::Pillager => [0, 4, 3, 3, 4, 4, 4, 2], + Self::Witch => [0, 0, 0, 0, 3, 0, 0, 1], + Self::Ravager => [0, 0, 0, 1, 0, 1, 0, 2], + } + } +} +/// `Raid.getNumGroups`: waves per difficulty (0 peaceful to 3 hard). +pub fn num_groups(difficulty: i32) -> i32 { + match difficulty { + 1 => 3, + 2 => 5, + 3 => 7, + _ => 0, + } +} + +/// One raider of a wave, with the raider riding it (ravagers only). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Spawn { + pub kind: RaiderType, + pub leader: bool, + pub rider: Option, +} + +/// A raider that belongs to a raid, as the level reports it. +#[derive(Clone, Debug)] +pub struct RaiderInfo { + pub id: u32, + pub wave: i32, + pub health: f32, + pub position: [i32; 3], + /// `tickCount`. + pub age: u32, + pub no_action_time: i32, + pub ticks_outside: i32, + pub in_village: bool, +} + +/// What a raid asks of the world. +pub trait RaidLevel { + /// The world difficulty, 0 (peaceful) to 3 (hard). + fn difficulty(&self) -> i32; + fn has_chunk_at(&self, pos: [i32; 3]) -> bool; + /// `ServerLevel.isVillage`: within one section of a village centre. + fn is_village(&self, pos: [i32; 3]) -> bool; + /// Centres of the village sections within two sections of `pos`. + fn village_sections_near(&self, pos: [i32; 3]) -> Vec<[i32; 3]>; + /// The living raiders of a raid. + fn raiders(&self, raid: i32) -> Vec; + /// `Heightmap.WORLD_SURFACE` height at a column. + fn surface_height(&self, x: i32, z: i32) -> i32; + /// The chunks around the position are loaded and ticking. + fn is_ticking(&self, pos: [i32; 3]) -> bool; + /// A ravager may spawn there (or on snow), in loaded chunks. + fn can_spawn_at(&self, pos: [i32; 3]) -> bool; +} + +/// What the game must do after a raid tick. +#[derive(Clone, Debug, PartialEq)] +pub enum Action { + /// Spawn the raiders of a wave around `pos`. + Spawn { + pos: [i32; 3], + wave: i32, + spawns: Vec, + }, + /// The raid horn, heard by players near or in the raid. + Horn { + pos: [i32; 3], + }, + /// A raider leaves the raid (far away, despawned or idle outside). + Remove { + id: u32, + }, + SetOutside { + id: u32, + ticks: i32, + }, + /// The raid was won: heroes get the effect at `level` (amplifier). + Victory { + heroes: Vec<[i32; 4]>, + amplifier: i32, + }, +} + +/// The raid boss bar's title. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BarName { + Raid, + Remaining(i32), + Victory, + Defeat, +} +#[derive(Clone, Debug)] +pub struct Bar { + pub name: BarName, + pub progress: f32, + pub visible: bool, + /// The local player is in the raid (`ServerBossEvent.getPlayers`). + pub player: bool, +} + +#[derive(Clone, Debug)] +pub struct Raid { + pub started: bool, + pub active: bool, + pub ticks_active: i64, + pub omen_level: i32, + pub groups_spawned: i32, + pub cooldown_ticks: i32, + pub post_raid_ticks: i32, + pub total_health: f32, + pub num_groups: i32, + pub status: Status, + pub center: [i32; 3], + pub heroes: Vec<[i32; 4]>, + pub bar: Bar, + celebration_ticks: i32, + wave_spawn_pos: Option<[i32; 3]>, + random: LegacyRandom, +} +impl Raid { + /// `new Raid(center, difficulty)`. + pub fn new(center: [i32; 3], difficulty: i32, seed: i64) -> Self { + Self { + started: false, + active: true, + ticks_active: 0, + omen_level: 0, + groups_spawned: 0, + cooldown_ticks: PRE_RAID_TICKS, + post_raid_ticks: 0, + total_health: 0.0, + num_groups: num_groups(difficulty), + status: Status::Ongoing, + center, + heroes: Vec::new(), + bar: Bar { + name: BarName::Raid, + progress: 0.0, + visible: true, + player: false, + }, + celebration_ticks: 0, + wave_spawn_pos: None, + random: LegacyRandom::new(seed), + } + } + pub fn is_over(&self) -> bool { + self.is_victory() || self.is_loss() + } + pub fn is_victory(&self) -> bool { + self.status == Status::Victory + } + pub fn is_loss(&self) -> bool { + self.status == Status::Loss + } + pub fn is_stopped(&self) -> bool { + self.status == Status::Stopped + } + pub fn has_first_wave_spawned(&self) -> bool { + self.groups_spawned > 0 + } + /// `isBetweenWaves`: the next wave is counting down. + pub fn is_between_waves(&self, raiders_alive: usize) -> bool { + self.has_first_wave_spawned() && raiders_alive == 0 && self.cooldown_ticks > 0 + } + pub fn stop(&mut self) { + self.active = false; + self.bar.player = false; + self.status = Status::Stopped; + } + fn has_bonus_wave(&self) -> bool { + self.omen_level > 1 + } + fn is_final_wave(&self) -> bool { + self.groups_spawned == self.num_groups + } + fn has_spawned_bonus_wave(&self) -> bool { + self.groups_spawned > self.num_groups + } + fn has_more_waves(&self) -> bool { + if self.has_bonus_wave() { + !self.has_spawned_bonus_wave() + } else { + !self.is_final_wave() + } + } + fn should_spawn_bonus_group(&self, alive: usize) -> bool { + self.is_final_wave() && alive == 0 && self.has_bonus_wave() + } + fn should_spawn_group(&self, alive: usize) -> bool { + self.cooldown_ticks == 0 + && (self.groups_spawned < self.num_groups || self.should_spawn_bonus_group(alive)) + && alive == 0 + } + /// `Raid.absorbRaidOmen`: the omen level rises by the effect's level. + /// True when this is the omen that first triggers the raid. + pub fn absorb_omen(&mut self, amplifier: i32) -> bool { + self.omen_level = (self.omen_level + amplifier + 1).clamp(0, MAX_OMEN_LEVEL); + !self.has_first_wave_spawned() + } + /// `Raid.getEnchantOdds`. + pub fn enchant_odds(&self) -> f32 { + match self.omen_level { + 2 => 0.1, + 3 => 0.25, + 4 => 0.5, + 5 => 0.75, + _ => 0.0, + } + } + pub fn add_hero(&mut self, uuid: [i32; 4]) { + if !self.heroes.contains(&uuid) { + self.heroes.push(uuid); + } + } + /// `Raid.getDefaultNumSpawns` and `getPotentialBonusSpawns`. + fn wave_count(&mut self, kind: RaiderType, wave: i32, difficulty: i32, bonus: bool) -> i32 { + let index = if bonus { self.num_groups } else { wave } as usize; + let base = kind.spawns()[index.min(7)]; + let easy = difficulty == 1; + let normal = difficulty == 2; + let extra = match kind { + RaiderType::Vindicator | RaiderType::Pillager => { + if easy { + self.random.next_int_bound(2).unwrap_or(0) + } else if normal { + 1 + } else { + 2 + } + } + RaiderType::Evoker => return base, + RaiderType::Witch => { + if easy || wave <= 2 || wave == 4 { + return base; + } + 1 + } + RaiderType::Ravager => i32::from(!easy && bonus), + }; + base + if extra > 0 { + self.random.next_int_bound(extra + 1).unwrap_or(0) + } else { + 0 + } + } + /// The raiders of wave `wave` (`spawnGroup`): per type the counted + /// spawns, the first able raider leading, and ravagers carrying a + /// pillager (the last normal wave) or an evoker and vindicators (hard). + pub fn compose_wave(&mut self, wave: i32, difficulty: i32, bonus: bool) -> Vec { + let mut out = Vec::new(); + let mut leader_set = false; + for kind in RaiderType::ALL { + let count = self.wave_count(kind, wave, difficulty, bonus); + let mut ravagers = 0; + for _ in 0..count { + let leader = !leader_set && kind.can_be_leader(); + leader_set |= leader; + let mut rider = None; + if kind == RaiderType::Ravager { + if wave == num_groups(2) { + rider = Some(RaiderType::Pillager); + } else if wave >= num_groups(3) { + rider = Some(if ravagers == 0 { + RaiderType::Evoker + } else { + RaiderType::Vindicator + }); + } + ravagers += 1; + } + out.push(Spawn { + kind, + leader, + rider, + }); + } + } + out + } + /// The health `joinRaid` adds for a wave. + pub fn wave_health(spawns: &[Spawn]) -> f32 { + spawns + .iter() + .map(|s| s.kind.health() + s.rider.map_or(0.0, RaiderType::health)) + .sum() + } + /// `Raid.findRandomSpawnPos`: a ring around the centre that closes in as + /// the countdown runs down. + fn find_spawn_pos(&mut self, level: &dyn RaidLevel, max_tries: i32) -> Option<[i32; 3]> { + let seconds = self.cooldown_ticks / 20; + let how_far = 0.22 * seconds as f32 - 0.24; + let start = self.random.next_float() * (std::f32::consts::PI * 2.0); + for i in 0..max_tries { + let angle = start + std::f32::consts::PI * i as f32 / 8.0; + let x = self.center[0] + + (angle.cos() * 32.0 * how_far).floor() as i32 + + self.random.next_int_bound(3).unwrap_or(0) * how_far.floor() as i32; + let z = self.center[2] + + (angle.sin() * 32.0 * how_far).floor() as i32 + + self.random.next_int_bound(3).unwrap_or(0) * how_far.floor() as i32; + let y = level.surface_height(x, z); + if (y - self.center[1]).abs() > 96 { + continue; + } + let pos = [x, y, z]; + if (!level.is_village(pos) || seconds <= 7) && level.can_spawn_at(pos) { + return Some(pos); + } + } + None + } + fn move_center_to_nearby_village(&mut self, level: &dyn RaidLevel) { + let c = self.center; + let d = |p: &[i32; 3]| (0..3).map(|i| f64::from(p[i] - c[i]).powi(2)).sum::(); + if let Some(best) = level + .village_sections_near(c) + .into_iter() + .min_by(|a, b| d(a).total_cmp(&d(b))) + { + self.center = best; + } + } + /// Boss bar progress while raiders are alive (`updateBossbar`). + pub fn update_bar(&mut self, living_health: f32) { + self.bar.progress = if self.total_health > 0.0 { + (living_health / self.total_health).clamp(0.0, 1.0) + } else { + 0.0 + }; + } + /// `Raid.tick`. `raiders` are the living members; `player` is whether + /// the local player's position falls in this raid. + pub fn tick(&mut self, id: i32, level: &dyn RaidLevel, player: bool) -> Vec { + let mut actions = Vec::new(); + if self.is_stopped() { + return actions; + } + let raiders = level.raiders(id); + let alive = raiders.len(); + if self.status == Status::Ongoing { + let was_active = self.active; + self.active = level.has_chunk_at(self.center); + if level.difficulty() == 0 { + self.stop(); + return actions; + } + if was_active != self.active { + self.bar.visible = self.active; + } + if !self.active { + return actions; + } + if !level.is_village(self.center) { + self.move_center_to_nearby_village(level); + } + if !level.is_village(self.center) { + if self.groups_spawned > 0 { + self.status = Status::Loss; + } else { + self.stop(); + } + } + self.ticks_active += 1; + if self.ticks_active >= TIMEOUT { + self.stop(); + return actions; + } + // Raid.updateBossbar, as raiders are hurt, die or leave. + if alive > 0 { + self.update_bar(raiders.iter().map(|r| r.health).sum()); + } else if self.started && !self.has_more_waves() { + self.bar.progress = 0.0; + } + if alive == 0 && self.has_more_waves() { + if self.cooldown_ticks <= 0 { + if self.cooldown_ticks == 0 && self.groups_spawned > 0 { + self.cooldown_ticks = PRE_RAID_TICKS; + self.bar.name = BarName::Raid; + return actions; + } + } else { + let cached = self.wave_spawn_pos.is_some(); + let mut try_find = !cached && self.cooldown_ticks % 5 == 0; + if cached && !self.wave_spawn_pos.is_some_and(|p| level.is_ticking(p)) { + try_find = true; + } + if try_find { + self.wave_spawn_pos = self.find_spawn_pos(level, 8); + } + if self.cooldown_ticks == PRE_RAID_TICKS || self.cooldown_ticks % 20 == 0 { + self.bar.player = player; + } + self.cooldown_ticks -= 1; + self.bar.progress = + ((PRE_RAID_TICKS - self.cooldown_ticks) as f32 / 300.0).clamp(0.0, 1.0); + } + } + if self.ticks_active % 20 == 0 { + self.bar.player = player; + self.update_raiders(&raiders, level, &mut actions); + self.bar.name = if alive > 0 && alive <= 2 { + BarName::Remaining(alive as i32) + } else { + BarName::Raid + }; + } + let mut sound = false; + let mut attempt = 0; + let mut spawned_alive = alive; + while self.should_spawn_group(spawned_alive) { + let pos = self + .wave_spawn_pos + .or_else(|| self.find_spawn_pos(level, 20)); + if let Some(pos) = pos { + self.started = true; + let wave = self.groups_spawned + 1; + let bonus = self.should_spawn_bonus_group(spawned_alive); + let difficulty = level.difficulty(); + let spawns = self.compose_wave(wave, difficulty, bonus); + self.total_health = Self::wave_health(&spawns); + spawned_alive = spawns + .iter() + .map(|s| 1 + usize::from(s.rider.is_some())) + .sum(); + self.wave_spawn_pos = None; + self.groups_spawned += 1; + self.bar.progress = 1.0; + actions.push(Action::Spawn { pos, wave, spawns }); + if !sound { + actions.push(Action::Horn { pos }); + sound = true; + } + } else { + attempt += 1; + } + if attempt > 5 { + self.stop(); + break; + } + } + if self.started && !self.has_more_waves() && alive == 0 { + if self.post_raid_ticks < POST_RAID_LIMIT { + self.post_raid_ticks += 1; + } else { + self.status = Status::Victory; + actions.push(Action::Victory { + heroes: self.heroes.clone(), + amplifier: self.omen_level - 1, + }); + } + } + } else if self.is_over() { + self.celebration_ticks += 1; + if self.celebration_ticks >= CELEBRATION_TICKS { + self.stop(); + return actions; + } + if self.celebration_ticks % 20 == 0 { + self.bar.player = player; + self.bar.visible = true; + if self.is_victory() { + self.bar.progress = 0.0; + self.bar.name = BarName::Victory; + } else { + self.bar.name = BarName::Defeat; + } + } + } + actions + } + /// `Raid.updateRaiders`. + fn update_raiders( + &mut self, + raiders: &[RaiderInfo], + level: &dyn RaidLevel, + actions: &mut Vec, + ) { + let _ = level; + for r in raiders { + let d = (0..3) + .map(|i| f64::from(self.center[i] - r.position[i]).powi(2)) + .sum::(); + let mut remove = d >= REMOVAL_THRESHOLD_SQR; + if !remove && r.age > 600 { + let mut outside = r.ticks_outside; + if !r.in_village && r.no_action_time > 2400 { + outside += 1; + actions.push(Action::SetOutside { + id: r.id, + ticks: outside, + }); + } + remove = outside >= 30; + } + if remove { + self.total_health -= r.health; + actions.push(Action::Remove { id: r.id }); + } + } + } + + pub fn to_nbt(&self) -> Tag { + Tag::compound([ + ("started", Tag::Byte(i8::from(self.started))), + ("active", Tag::Byte(i8::from(self.active))), + ("ticks_active", Tag::Long(self.ticks_active)), + ("raid_omen_level", Tag::Int(self.omen_level)), + ("groups_spawned", Tag::Int(self.groups_spawned)), + ("cooldown_ticks", Tag::Int(self.cooldown_ticks)), + ("post_raid_ticks", Tag::Int(self.post_raid_ticks)), + ("total_health", Tag::Float(self.total_health.to_bits())), + ("group_count", Tag::Int(self.num_groups)), + ("status", Tag::String(self.status.name().into())), + ("center", Tag::IntArray(self.center.to_vec())), + ( + "heroes_of_the_village", + Tag::List( + self.heroes + .iter() + .map(|u| Tag::IntArray(u.to_vec())) + .collect(), + ), + ), + ]) + } + pub fn from_nbt(tag: &Tag, seed: i64) -> Option { + let int = |k: &str| match tag.get(k) { + Some(Tag::Int(v)) => Some(*v), + Some(Tag::Byte(v)) => Some(i32::from(*v)), + Some(Tag::Short(v)) => Some(i32::from(*v)), + _ => None, + }; + let center = match tag.get("center") { + Some(Tag::IntArray(v)) if v.len() == 3 => [v[0], v[1], v[2]], + _ => return None, + }; + let mut raid = Self::new(center, 0, seed); + raid.started = int("started")? != 0; + raid.active = int("active")? != 0; + raid.ticks_active = match tag.get("ticks_active") { + Some(Tag::Long(v)) => *v, + _ => 0, + }; + raid.omen_level = int("raid_omen_level").unwrap_or(0); + raid.groups_spawned = int("groups_spawned").unwrap_or(0); + raid.cooldown_ticks = int("cooldown_ticks").unwrap_or(PRE_RAID_TICKS); + raid.post_raid_ticks = int("post_raid_ticks").unwrap_or(0); + raid.total_health = match tag.get("total_health") { + Some(Tag::Float(bits)) => f32::from_bits(*bits), + _ => 0.0, + }; + raid.num_groups = int("group_count").unwrap_or(0); + raid.status = match tag.get("status") { + Some(Tag::String(s)) => Status::from_name(&s.to_string_lossy()), + _ => Status::Ongoing, + }; + if let Some(Tag::List(heroes)) = tag.get("heroes_of_the_village") { + for h in heroes { + if let Tag::IntArray(v) = h + && v.len() == 4 + { + raid.heroes.push([v[0], v[1], v[2], v[3]]); + } + } + } + raid.bar.visible = raid.active; + Some(raid) + } +} + +/// `Raids`: the raids of a dimension by id. +#[derive(Clone, Debug)] +pub struct Raids { + pub map: BTreeMap, + next_id: i32, + tick: i32, + /// Changed since the last save. + pub dirty: bool, +} +impl Default for Raids { + fn default() -> Self { + Self { + map: BTreeMap::new(), + next_id: 1, + tick: 0, + dirty: false, + } + } +} +impl Raids { + pub fn get(&self, id: i32) -> Option<&Raid> { + self.map.get(&id) + } + pub fn id_of(&self, raid: &Raid) -> Option { + self.map + .iter() + .find(|(_, r)| std::ptr::eq(*r, raid)) + .map(|(id, _)| *id) + } + /// `Raids.getNearbyRaid`: the closest active raid within 96 blocks. + pub fn nearby(&self, pos: [i32; 3]) -> Option<(i32, &Raid)> { + let mut best: Option<(i32, &Raid, f64)> = None; + for (id, r) in &self.map { + let d = (0..3) + .map(|i| f64::from(r.center[i] - pos[i]).powi(2)) + .sum::(); + if r.active && d < best.map_or(VALID_RAID_RADIUS_SQR, |b| b.2) { + best = Some((*id, r, d)); + } + } + best.map(|(id, r, _)| (id, r)) + } + /// `Raids.createOrExtendRaid`, after the caller found the village centre: + /// the raid at that position (a new one if none), with the omen's level + /// absorbed. Returns the raid id and whether the omen triggered it. + pub fn create_or_extend( + &mut self, + center: [i32; 3], + difficulty: i32, + omen_amplifier: Option, + seed: i64, + ) -> (i32, bool) { + let id = match self.nearby(center) { + Some((id, _)) => id, + None => { + self.next_id += 1; + self.map + .insert(self.next_id, Raid::new(center, difficulty, seed)); + self.next_id + } + }; + let mut triggered = false; + if let Some(raid) = self.map.get_mut(&id) + && (!raid.started || raid.omen_level < MAX_OMEN_LEVEL) + && let Some(amp) = omen_amplifier + { + triggered = raid.absorb_omen(amp); + } + self.dirty = true; + (id, triggered) + } + /// `Raids.tick`: every raid, stopped ones removed. `rules_raids` is the + /// `raids` game rule; `player` the local player's block position. + pub fn tick( + &mut self, + level: &dyn RaidLevel, + rules_raids: bool, + player: Option<[i32; 3]>, + ) -> Vec<(i32, Action)> { + self.tick += 1; + let inside = player.and_then(|p| self.nearby(p).map(|(id, _)| id)); + let mut out = Vec::new(); + let mut gone = Vec::new(); + for (id, raid) in &mut self.map { + if !rules_raids { + raid.stop(); + } + if raid.is_stopped() { + gone.push(*id); + continue; + } + for a in raid.tick(*id, level, inside == Some(*id)) { + out.push((*id, a)); + } + } + for id in gone { + self.map.remove(&id); + self.dirty = true; + } + if self.tick % 200 == 0 || !out.is_empty() { + self.dirty = true; + } + out + } + pub fn to_nbt(&self) -> Tag { + let raids = self + .map + .iter() + .map(|(id, r)| { + let mut tag = r.to_nbt(); + if let Tag::Compound(map) = &mut tag { + map.insert("id".into(), Tag::Int(*id)); + } + tag + }) + .collect(); + Tag::compound([ + ("raids", Tag::List(raids)), + ("next_id", Tag::Int(self.next_id)), + ("tick", Tag::Int(self.tick)), + ]) + } + pub fn from_nbt(tag: &Tag, seed: i64) -> Self { + let mut out = Self::default(); + if let Some(Tag::Int(v)) = tag.get("next_id") { + out.next_id = *v; + } + if let Some(Tag::Int(v)) = tag.get("tick") { + out.tick = *v; + } + if let Some(Tag::List(list)) = tag.get("raids") { + for (i, r) in list.iter().enumerate() { + if let Some(Tag::Int(id)) = r.get("id") + && let Some(raid) = Raid::from_nbt(r, seed.wrapping_add(i as i64)) + { + out.map.insert(*id, raid); + } + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + struct Level { + village: bool, + raiders: Vec, + difficulty: i32, + } + impl RaidLevel for Level { + fn difficulty(&self) -> i32 { + self.difficulty + } + fn has_chunk_at(&self, _: [i32; 3]) -> bool { + true + } + fn is_village(&self, _: [i32; 3]) -> bool { + self.village + } + fn village_sections_near(&self, _: [i32; 3]) -> Vec<[i32; 3]> { + Vec::new() + } + fn raiders(&self, _: i32) -> Vec { + self.raiders.clone() + } + fn surface_height(&self, _: i32, _: i32) -> i32 { + 64 + } + fn is_ticking(&self, _: [i32; 3]) -> bool { + true + } + fn can_spawn_at(&self, _: [i32; 3]) -> bool { + true + } + } + fn count(spawns: &[Spawn], kind: RaiderType) -> usize { + spawns.iter().filter(|s| s.kind == kind).count() + } + + #[test] + fn waves_per_difficulty() { + assert_eq!( + [0, 1, 2, 3].map(num_groups), + [0, 3, 5, 7], + "peaceful, easy, normal, hard" + ); + } + #[test] + fn first_wave_is_four_pillagers_plus_bonus() { + // Normal difficulty always adds one bonus roll (0 or 1) per + // pillager and vindicator slot: wave 1 has 4 pillagers and 0-1 more. + for seed in 0..50 { + let mut raid = Raid::new([0, 64, 0], 2, seed); + let w = raid.compose_wave(1, 2, false); + let pillagers = count(&w, RaiderType::Pillager); + assert!((4..=5).contains(&pillagers), "{pillagers}"); + assert!(count(&w, RaiderType::Vindicator) <= 1); + assert_eq!(count(&w, RaiderType::Ravager), 0); + assert_eq!(w.iter().filter(|s| s.leader).count(), 1); + } + } + #[test] + fn ravagers_carry_riders_by_wave() { + // Wave 5 on normal: the ravager carries a pillager. + let mut raid = Raid::new([0, 64, 0], 2, 1); + let w = raid.compose_wave(5, 2, false); + let ravagers: Vec<_> = w.iter().filter(|s| s.kind == RaiderType::Ravager).collect(); + assert_eq!(ravagers.len(), 1); + assert_eq!(ravagers[0].rider, Some(RaiderType::Pillager)); + // Wave 7 on hard: an evoker rides the first ravager, vindicators the rest. + let mut raid = Raid::new([0, 64, 0], 3, 1); + let w = raid.compose_wave(7, 3, false); + let riders: Vec<_> = w + .iter() + .filter(|s| s.kind == RaiderType::Ravager) + .map(|s| s.rider) + .collect(); + assert!(riders.len() >= 2); + assert_eq!(riders[0], Some(RaiderType::Evoker)); + assert!( + riders[1..] + .iter() + .all(|r| *r == Some(RaiderType::Vindicator)) + ); + // Wave 4 has no ravager. + let mut raid = Raid::new([0, 64, 0], 3, 1); + assert_eq!( + count(&raid.compose_wave(4, 3, false), RaiderType::Ravager), + 0 + ); + } + #[test] + fn witches_arrive_from_wave_five_and_bonus_waves_reuse_the_last_row() { + let mut raid = Raid::new([0, 64, 0], 2, 3); + assert_eq!(count(&raid.compose_wave(3, 2, false), RaiderType::Witch), 0); + assert_eq!(count(&raid.compose_wave(4, 2, false), RaiderType::Witch), 3); + // Bonus wave of a normal raid: the wave-5 row (and a possible + // extra ravager). + let bonus = raid.compose_wave(6, 2, true); + assert_eq!(count(&bonus, RaiderType::Evoker), 1); + assert!((1..=2).contains(&count(&bonus, RaiderType::Ravager))); + assert!(count(&bonus, RaiderType::Witch) <= 1); + } + #[test] + fn only_able_raiders_lead() { + let mut raid = Raid::new([0, 64, 0], 3, 9); + let w = raid.compose_wave(4, 3, false); + assert!( + w.iter() + .filter(|s| s.leader) + .all(|s| s.kind.can_be_leader()) + ); + assert_eq!(w.iter().filter(|s| s.leader).count(), 1); + } + #[test] + fn omen_levels_stack_and_clamp() { + let mut raid = Raid::new([0, 64, 0], 2, 1); + assert!(raid.absorb_omen(1)); + assert_eq!(raid.omen_level, 2); + raid.absorb_omen(4); + assert_eq!(raid.omen_level, MAX_OMEN_LEVEL); + assert_eq!(raid.enchant_odds(), 0.75); + } + #[test] + fn a_raid_counts_down_spawns_and_is_won() { + let level = Level { + village: true, + raiders: Vec::new(), + difficulty: 1, + }; + let mut raid = Raid::new([0, 64, 0], 1, 5); + raid.absorb_omen(0); + let mut spawned = 0; + // 300 ticks of countdown, then the first wave. + for _ in 0..400 { + for a in raid.tick(1, &level, true) { + if let Action::Spawn { wave, .. } = a { + spawned += 1; + assert_eq!(wave, 1); + } + } + if spawned > 0 { + break; + } + } + assert_eq!(spawned, 1); + assert!(raid.started && raid.groups_spawned == 1); + assert_eq!(raid.bar.progress, 1.0); + assert!(raid.total_health > 0.0); + } + #[test] + fn the_last_wave_cleared_wins_after_a_pause() { + let level = Level { + village: true, + raiders: Vec::new(), + difficulty: 1, + }; + let mut raid = Raid::new([0, 64, 0], 1, 5); + raid.started = true; + raid.groups_spawned = raid.num_groups; + raid.cooldown_ticks = 0; + let mut won = false; + for _ in 0..60 { + for a in raid.tick(1, &level, true) { + if let Action::Victory { amplifier, .. } = a { + won = true; + assert_eq!(amplifier, -1); + } + } + } + assert!(won && raid.is_victory()); + // The celebration lasts 600 ticks, then the raid stops. + for _ in 0..600 { + raid.tick(1, &level, true); + } + assert!(raid.is_stopped()); + } + #[test] + fn losing_the_village_loses_the_raid() { + let level = Level { + village: false, + raiders: Vec::new(), + difficulty: 2, + }; + let mut raid = Raid::new([0, 64, 0], 2, 5); + raid.started = true; + raid.groups_spawned = 2; + raid.tick(1, &level, true); + assert!(raid.is_loss()); + // Before any wave, losing the village just cancels the raid. + let mut fresh = Raid::new([0, 64, 0], 2, 5); + fresh.tick(1, &level, true); + assert!(fresh.is_stopped()); + } + #[test] + fn peaceful_stops_raids() { + let level = Level { + village: true, + raiders: Vec::new(), + difficulty: 0, + }; + let mut raid = Raid::new([0, 64, 0], 2, 5); + raid.tick(1, &level, true); + assert!(raid.is_stopped()); + } + #[test] + fn far_or_idle_raiders_leave() { + let raider = |id, x, no_action, outside| RaiderInfo { + id, + wave: 1, + health: 24.0, + position: [x, 64, 0], + age: 1000, + no_action_time: no_action, + ticks_outside: outside, + in_village: false, + }; + let level = Level { + village: true, + raiders: vec![ + raider(1, 500, 0, 0), + raider(2, 10, 3000, 29), + raider(3, 10, 0, 0), + ], + difficulty: 2, + }; + let mut raid = Raid::new([0, 64, 0], 2, 1); + raid.started = true; + raid.groups_spawned = 1; + raid.total_health = 72.0; + raid.ticks_active = 19; + let actions = raid.tick(1, &level, true); + assert!(actions.contains(&Action::Remove { id: 1 })); + assert!(actions.contains(&Action::Remove { id: 2 })); + assert!(!actions.contains(&Action::Remove { id: 3 })); + assert_eq!(raid.total_health, 24.0); + } + #[test] + fn raids_round_trip_through_nbt() { + let mut raids = Raids::default(); + let (id, triggered) = raids.create_or_extend([10, 64, 20], 2, Some(2), 7); + assert_eq!(id, 2); + assert!(triggered); + raids.map.get_mut(&id).unwrap().add_hero([1, 2, 3, 4]); + let back = Raids::from_nbt(&raids.to_nbt(), 1); + let raid = back.get(2).unwrap(); + assert_eq!(raid.center, [10, 64, 20]); + assert_eq!(raid.omen_level, 3); + assert_eq!(raid.num_groups, 5); + assert_eq!(raid.heroes, vec![[1, 2, 3, 4]]); + assert_eq!(raid.status, Status::Ongoing); + } + #[test] + fn a_second_omen_extends_the_nearby_raid() { + let mut raids = Raids::default(); + let (a, _) = raids.create_or_extend([0, 64, 0], 2, Some(0), 1); + let (b, again) = raids.create_or_extend([20, 64, 20], 2, Some(1), 1); + assert_eq!(a, b); + assert!(again); + assert_eq!(raids.get(a).unwrap().omen_level, 3); + let (c, _) = raids.create_or_extend([300, 64, 0], 2, Some(0), 1); + assert_ne!(a, c); + } +}