Add bad omen, raid omen and raids

Drinking an ominous bottle gives Bad Omen; inside a village it turns into
Raid Omen, and when that runs out a raid starts, or grows, around the
village points villagers have claimed (the raid_trigger statistic and the
voluntary exile trigger fire on the first omen). Raids are saved in
data/minecraft/raids.dat and send waves of pillagers, vindicators, evokers,
witches and ravagers (ravagers carrying pillagers, evokers or vindicators)
by difficulty and omen level, from a ring that closes in as the countdown
runs down, with the raid horn and a red notched boss bar that shows the
raiders left, Victory or Defeat. Raiders walk to the village, move between
beds, take back a dropped captain banner, celebrate a lost village, are
enchanted with Quick Charge or Sharpness at high omen levels and are
dropped from the raid when idle or far away. Killing one makes the player a
hero; a won raid grants Hero of the Village and the hero_of_the_village
trigger. Villagers hide in their beds during a wave, ring the bell before
one, celebrate a victory with fireworks, and toss gifts to a hero. /raid
start, stop, check, spawnleader, setomen, glow and sound are available.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-09 12:58:26 +02:00
parent af791c55b7
commit 44adeb0d3c
16 changed files with 2606 additions and 20 deletions
@@ -111,6 +111,28 @@ pub fn build() -> Dispatcher {
d.executes(dur, "weather");
}
// raid start <omenlvl> | stop | check | sound <type> | spawnleader | setomen <level> | 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 [<targets>]
let kill = d.literal(root, "kill");
d.requires(kill, GAMEMASTERS);
+2
View File
@@ -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();
@@ -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<std::sync::Arc<str>>| {
i.as_ref().map(|id| item_view(&ItemStack::new(id, 1)))
};
let mut equipment: [Option<ItemView>; 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()
}
}
@@ -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),
@@ -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<i32> {
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", &[])),
}
}
}
@@ -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<Seen> = 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);
+2 -1
View File
@@ -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;
};
+1 -1
View File
@@ -37,7 +37,7 @@ fn fireworks_of(stack: &ItemStack) -> (u8, Vec<FireworkExplosion>) {
.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| {
+890 -4
View File
@@ -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<i32, (i64, std::sync::Arc<Vec<[i32; 3]>>)>,
}
/// `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<i32, Vec<RaiderInfo>>,
}
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<RaiderInfo> {
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<i32>) -> Option<i32> {
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::<f64>() <= 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::<f64>() / 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<i32> {
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<i32, Vec<RaiderInfo>> {
let mut out: HashMap<i32, Vec<RaiderInfo>> = 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(&centers);
let mut raids = std::mem::take(&mut self.raiding.raids);
let actions = {
let lvl = Lvl {
game: self,
difficulty: self.difficulty_id(),
centers: &centers,
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(&centers);
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<u32> {
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<u32> = 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<u32> = 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<usize> = 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<u32> = 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<i32, std::sync::Arc<Vec<[i32; 3]>>> {
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<u32, bool> = 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<u32, (Vec3, Vec3, f32, f32, bool)> = 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<i32, Vec<RaiderInfo>>) {
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`.
+3 -2
View File
@@ -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| {
+1
View File
@@ -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;
+16
View File
@@ -479,6 +479,8 @@ pub struct Extra {
pub trade: Option<Box<crate::merchant::Trader>>,
/// A raider's patrol and raid state.
pub raider: Option<Box<raider::State>>,
/// A villager's raid activity and gossip.
pub villager: Option<Box<villager::Ext>>,
}
#[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,
+27 -5
View File
@@ -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 {
+223 -4
View File
@@ -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<std::sync::Arc<Vec<[i32; 3]>>>,
/// The ravager this raider rides, and (for a ravager) that it carries one.
pub vehicle: Option<u32>,
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;
}
}
}
+218 -3
View File
@@ -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);
}
}
}
File diff suppressed because it is too large Load Diff