Merge pull request #439 from ludovic111/feat/ominous-trials
Trial spawners: become ominous, Trial Omen and ominous item spawners
This commit is contained in:
@@ -38,7 +38,10 @@ use horizon_client::{
|
||||
},
|
||||
spawner::{Spawner, SpawnerAdded, SpawnerEvent, SpawnerLevel, SpawnerSpawn},
|
||||
species::{self, Baby},
|
||||
trial_spawner::{TrialEvent, TrialPlayer, TrialSpawner, TrialSpawnerLevel, TrialState},
|
||||
trial_spawner::{
|
||||
Omen, TRIAL_OMEN_TICKS_PER_LEVEL, TrialEvent, TrialPlayer, TrialSpawner,
|
||||
TrialSpawnerLevel, TrialState,
|
||||
},
|
||||
},
|
||||
vault::{Vault, VaultEvent, VaultLevel, VaultPlayer, VaultState},
|
||||
};
|
||||
@@ -119,8 +122,14 @@ struct World<'a> {
|
||||
placed: RefCell<Vec<([i32; 3], BlockStateId)>>,
|
||||
/// The game time (trial cases advance it).
|
||||
time: Cell<i64>,
|
||||
/// The mobs a trial spawner added: UUID, position and box.
|
||||
trial_mobs: RefCell<Vec<([i32; 4], [f64; 3], Aabb)>>,
|
||||
/// The mobs a trial spawner added: UUID, position, height and box.
|
||||
trial_mobs: RefCell<Vec<([i32; 4], [f64; 3], f32, Aabb)>>,
|
||||
/// How many mobs a trial spawner added (their UUIDs count up).
|
||||
trial_count: Cell<i32>,
|
||||
/// Each player's omen and its amplifier (`/trial_omen:A`, `/bad_omen:A`).
|
||||
omens: RefCell<Vec<Option<(Omen, i32)>>>,
|
||||
/// Loot tables (trial cases).
|
||||
loot: Option<std::sync::Arc<horizon_world::loot::LootData>>,
|
||||
}
|
||||
impl World<'_> {
|
||||
fn biome_at(&self, x: i32, y: i32, z: i32) -> &str {
|
||||
@@ -382,6 +391,16 @@ impl TrialSpawnerLevel for World<'_> {
|
||||
eye: [p[0], p[1] + f64::from(1.62f32), p[2]],
|
||||
creative: mode == "creative",
|
||||
spectator: mode == "spectator",
|
||||
position: *p,
|
||||
height: 1.8,
|
||||
alive: true,
|
||||
omen: self
|
||||
.omens
|
||||
.borrow()
|
||||
.get(i)
|
||||
.copied()
|
||||
.flatten()
|
||||
.map(|(o, _)| o),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -404,9 +423,38 @@ impl TrialSpawnerLevel for World<'_> {
|
||||
}
|
||||
fn entity_block(&self, uuid: [i32; 4]) -> Option<[i32; 3]> {
|
||||
let mobs = self.trial_mobs.borrow();
|
||||
let (_, p, _) = mobs.iter().find(|(u, ..)| *u == uuid)?;
|
||||
let (_, p, ..) = mobs.iter().find(|(u, ..)| *u == uuid)?;
|
||||
Some(p.map(|v| v.floor() as i32))
|
||||
}
|
||||
fn entity_box(&self, uuid: [i32; 4]) -> Option<([f64; 3], f32)> {
|
||||
let mobs = self.trial_mobs.borrow();
|
||||
let (_, p, h, _) = mobs.iter().find(|(u, ..)| *u == uuid)?;
|
||||
Some((*p, *h))
|
||||
}
|
||||
fn no_block_collision(&self, block: [i32; 3]) -> bool {
|
||||
let lookup = |x: i32, y: i32, z: i32| self.state(x, y, z);
|
||||
let mut scene = LookupCollisions {
|
||||
block: &lookup,
|
||||
binding: self.s.collision,
|
||||
};
|
||||
let state = self.state(block[0], block[1], block[2]);
|
||||
self.s
|
||||
.collision
|
||||
.collision_shape(&mut scene, state, block)
|
||||
.map_or(true, |shape| shape.is_empty())
|
||||
}
|
||||
fn loot_items(&self, table: &str, seed: i64) -> Vec<horizon_client::items::ItemStack> {
|
||||
let Some(loot) = &self.loot else {
|
||||
return Vec::new();
|
||||
};
|
||||
loot.roll_split(table, &mut LegacyRandom::new(seed))
|
||||
.iter()
|
||||
.map(horizon_client::structure_blocks::loot_item_with_components)
|
||||
.collect()
|
||||
}
|
||||
fn seed(&self) -> i64 {
|
||||
self.seed
|
||||
}
|
||||
}
|
||||
|
||||
/// The box a mob is left with by `finalizeSpawn` under the oracle's fixed random.
|
||||
@@ -585,6 +633,19 @@ fn main() -> horizon_client::Result<()> {
|
||||
bounds: Bx(b),
|
||||
});
|
||||
}
|
||||
// A player's third field: an omen and its amplifier.
|
||||
let omens = indexed("p")
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let (effect, amplifier) = p.split('/').nth(2)?.split_once(':')?;
|
||||
let omen = if effect == "trial_omen" {
|
||||
Omen::Trial
|
||||
} else {
|
||||
Omen::Bad
|
||||
};
|
||||
Some((omen, amplifier.parse().ok()?))
|
||||
})
|
||||
.collect();
|
||||
let players = indexed("p")
|
||||
.into_iter()
|
||||
.map(|p| {
|
||||
@@ -671,6 +732,9 @@ fn main() -> horizon_client::Result<()> {
|
||||
placed: RefCell::new(Vec::new()),
|
||||
time: Cell::new(0),
|
||||
trial_mobs: RefCell::new(Vec::new()),
|
||||
trial_count: Cell::new(0),
|
||||
omens: RefCell::new(omens),
|
||||
loot: loot.clone(),
|
||||
entities: RefCell::new(
|
||||
case_entities
|
||||
.iter()
|
||||
@@ -979,8 +1043,22 @@ fn trial_case(
|
||||
let scale = size as f32;
|
||||
let bounds = spawn_box(x, y, z, t.width as f32 * scale, t.height as f32 * scale);
|
||||
l.entities.borrow_mut().push((r.id.to_owned(), bounds));
|
||||
let uuid = [1, 0, 0, l.trial_mobs.borrow().len() as i32];
|
||||
l.trial_mobs.borrow_mut().push((uuid, r.position, bounds));
|
||||
let uuid = [1, 0, 0, l.trial_count.get()];
|
||||
l.trial_count.set(l.trial_count.get() + 1);
|
||||
// Zombie.readAdditionalSaveData: IsBaby halves the box
|
||||
// (getAgeScale); finalizeSpawn's fixed random never makes one.
|
||||
let baby = match r
|
||||
.entity
|
||||
.get(&horizon_world::nbt::JavaString::from("IsBaby"))
|
||||
{
|
||||
Some(Tag::Byte(v)) => *v != 0,
|
||||
Some(Tag::Int(v)) => *v != 0,
|
||||
_ => false,
|
||||
};
|
||||
let height = t.height as f32 * scale * if baby { 0.5 } else { 1.0 };
|
||||
l.trial_mobs
|
||||
.borrow_mut()
|
||||
.push((uuid, r.position, height, bounds));
|
||||
spawned.push_back(format!(
|
||||
"{tick} spawn {} {} {} {} {}",
|
||||
r.id,
|
||||
@@ -1035,7 +1113,7 @@ fn trial_case(
|
||||
for e in events {
|
||||
match e {
|
||||
TrialEvent::BlockUpdated => log.push(format!("{tick} update")),
|
||||
TrialEvent::LevelEvent(id, _, data) => {
|
||||
TrialEvent::LevelEvent(id, p, data) => {
|
||||
// A spawn's events follow its tryAddFreshEntityWithPassengers,
|
||||
// a reward's its items.
|
||||
match id {
|
||||
@@ -1043,7 +1121,13 @@ fn trial_case(
|
||||
3014 => log.append(&mut items),
|
||||
_ => {}
|
||||
}
|
||||
log.push(format!("{tick} levent {id} {data}"));
|
||||
match id {
|
||||
3020 | 3012 => log.push(format!(
|
||||
"{tick} levent {id} {data} at {},{},{}",
|
||||
p[0], p[1], p[2]
|
||||
)),
|
||||
_ => log.push(format!("{tick} levent {id} {data}")),
|
||||
}
|
||||
}
|
||||
TrialEvent::Sound(name) => log.push(format!(
|
||||
"{tick} sound minecraft:{name} {} {} {} 1.0 1.0",
|
||||
@@ -1055,6 +1139,44 @@ fn trial_case(
|
||||
"{tick} gevent minecraft:entity_place {} {} {}",
|
||||
p[0], p[1], p[2]
|
||||
)),
|
||||
TrialEvent::TrialOmen(uuid) => {
|
||||
let i = (uuid[3] - 1) as usize;
|
||||
let mut omens = world.omens.borrow_mut();
|
||||
let amplifier = omens.get(i).copied().flatten().map_or(0, |(_, a)| a);
|
||||
log.push(format!("{tick} effect remove minecraft:bad_omen"));
|
||||
log.push(format!(
|
||||
"{tick} effect add minecraft:trial_omen {} 0",
|
||||
TRIAL_OMEN_TICKS_PER_LEVEL * (amplifier + 1)
|
||||
));
|
||||
if let Some(o) = omens.get_mut(i) {
|
||||
*o = Some((Omen::Trial, 0));
|
||||
}
|
||||
}
|
||||
TrialEvent::Discard(uuid) => {
|
||||
let mut mobs = world.trial_mobs.borrow_mut();
|
||||
if let Some(i) = mobs.iter().position(|(u, ..)| *u == uuid) {
|
||||
let (.., b) = mobs.remove(i);
|
||||
world.entities.borrow_mut().retain(|(_, e)| *e != b);
|
||||
}
|
||||
}
|
||||
TrialEvent::SoundAt(name, b, pitch) => log.push(format!(
|
||||
"{tick} sound minecraft:{name} {} {} {} 1.0 {pitch:?}",
|
||||
bits(f64::from(b[0]) + 0.5),
|
||||
bits(f64::from(b[1]) + 0.5),
|
||||
bits(f64::from(b[2]) + 0.5)
|
||||
)),
|
||||
TrialEvent::ItemSpawner {
|
||||
item,
|
||||
position,
|
||||
delay,
|
||||
} => log.push(format!(
|
||||
"{tick} ispawner {} {} {} {} {} {delay}",
|
||||
item.item,
|
||||
item.count,
|
||||
bits(position[0]),
|
||||
bits(position[1]),
|
||||
bits(position[2])
|
||||
)),
|
||||
TrialEvent::OminousSet(set) => {
|
||||
ominous = set;
|
||||
world
|
||||
|
||||
@@ -435,8 +435,8 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
});
|
||||
}
|
||||
"minecraft:zombie" => {
|
||||
map.insert("IsBaby".into(), Tag::Byte(i8::from(m.is_baby())));
|
||||
for (key, value) in [
|
||||
("IsBaby", Tag::Byte(0)),
|
||||
("CanBreakDoors", Tag::Byte(0)),
|
||||
("DrownedConversionTime", Tag::Int(-1)),
|
||||
("InWaterTime", Tag::Int(-1)),
|
||||
@@ -845,6 +845,11 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
m.health = health;
|
||||
m.extra.flag2 = flag(tag, "wasOnGround");
|
||||
}
|
||||
// Zombie, Piglin and Zoglin.readAdditionalSaveData: IsBaby (the baby
|
||||
// zombies of trial spawners).
|
||||
if !crate::mobs::finalize::ageable(m.species()) && flag(tag, "IsBaby") {
|
||||
crate::mobs::finalize::set_baby(&mut m, true);
|
||||
}
|
||||
crate::mobs::raider::read_nbt(&mut m, tag);
|
||||
crate::mobs::riders::read_nbt(&mut m, tag);
|
||||
// A mob saved mid-death finishes dying; one saved dead is dropped.
|
||||
|
||||
@@ -81,6 +81,7 @@ mod natural_spawning;
|
||||
mod nautili;
|
||||
mod net_harness;
|
||||
mod nether_portal;
|
||||
mod ominous_item_spawner;
|
||||
mod options;
|
||||
mod packs;
|
||||
mod pad;
|
||||
@@ -948,6 +949,8 @@ struct Game<'a> {
|
||||
hook: Option<fishing::Hook>,
|
||||
tridents: Vec<trident::ThrownTrident>,
|
||||
rockets: Vec<fireworks::Rocket>,
|
||||
/// Ominous trial spawners' item spawners.
|
||||
ominous_spawners: Vec<ominous_item_spawner::OminousItemSpawner>,
|
||||
creaking: creaking::CreakingState,
|
||||
/// Monster spawners' display mobs (`game/spawner.rs`).
|
||||
spawners: spawner::SpawnerState,
|
||||
@@ -3330,6 +3333,9 @@ impl Game<'_> {
|
||||
horizon_client::spans::time("tick_fishing", || self.tick_fishing());
|
||||
horizon_client::spans::time("tick_tridents", || self.tick_tridents());
|
||||
horizon_client::spans::time("tick_rockets", || self.tick_rockets());
|
||||
horizon_client::spans::time("tick_ominous_item_spawners", || {
|
||||
self.tick_ominous_item_spawners()
|
||||
});
|
||||
}
|
||||
if running {
|
||||
horizon_client::spans::time("entity_portals", || self.handle_entity_portals());
|
||||
@@ -5307,6 +5313,7 @@ impl Game<'_> {
|
||||
self.dropped_item_geometry(camera, alpha, &mut out);
|
||||
// `VaultRenderer`.
|
||||
self.vault_geometry(camera, alpha, &mut out);
|
||||
self.ominous_item_spawner_geometry(camera, alpha, &mut out);
|
||||
// Mobs and their projectiles.
|
||||
self.mob_geometry(camera, alpha, &mut out);
|
||||
self.player_model_geometry(camera, alpha, &mut out);
|
||||
@@ -10017,6 +10024,7 @@ pub fn run() -> Result<()> {
|
||||
hook: None,
|
||||
tridents: Vec::new(),
|
||||
rockets: Vec::new(),
|
||||
ominous_spawners: Vec::new(),
|
||||
creaking: Default::default(),
|
||||
spawners: Default::default(),
|
||||
trident_model: horizon_client::mobs::load_model(&root, "minecraft:trident#main"),
|
||||
|
||||
@@ -933,6 +933,21 @@ impl Game<'_> {
|
||||
LAUNCH,
|
||||
),
|
||||
};
|
||||
self.shoot_projectile_item(at, dir, &stack, power, uncertainty);
|
||||
(shrink(stack), event)
|
||||
}
|
||||
|
||||
/// `ProjectileItem.asProjectile` and `Projectile.spawnProjectileUsingShoot`:
|
||||
/// one of `stack` fired from `at` along `dir`.
|
||||
pub(super) fn shoot_projectile_item(
|
||||
&mut self,
|
||||
at: Vec3,
|
||||
dir: [f64; 3],
|
||||
stack: &ItemStack,
|
||||
power: f32,
|
||||
uncertainty: f32,
|
||||
) {
|
||||
let item = stack.item.to_string();
|
||||
let one = ItemStack {
|
||||
count: 1,
|
||||
..stack.clone()
|
||||
@@ -967,7 +982,7 @@ impl Game<'_> {
|
||||
"minecraft:tipped_arrow" => ProjectileKind::Arrow {
|
||||
base_damage: 2.0,
|
||||
critical: false,
|
||||
effect: tipped_effect(&stack),
|
||||
effect: tipped_effect(stack),
|
||||
},
|
||||
"minecraft:fire_charge" | "minecraft:wind_charge" => {
|
||||
// asProjectile aims with the level's random first; the
|
||||
@@ -1000,7 +1015,6 @@ impl Game<'_> {
|
||||
self.creatures.projectiles.push(shot);
|
||||
}
|
||||
}
|
||||
(shrink(stack), event)
|
||||
}
|
||||
|
||||
// ---- entities placed by items ----
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
//! `OminousItemSpawner`: the item an ominous trial spawner drops on its
|
||||
//! fight. It floats, growing and turning (`OminousItemSpawnerRenderer`), for
|
||||
//! 60 to 120 ticks, then falls as an item or is fired straight down as a
|
||||
//! projectile (`spawnItem`). Not saved: a spawner left in an unloaded chunk
|
||||
//! is lost.
|
||||
use super::Game;
|
||||
use horizon_assets::item_model::DisplayContext;
|
||||
use horizon_client::{
|
||||
block_entity_render::vertex_light,
|
||||
item_render,
|
||||
items::ItemStack,
|
||||
mesher::Vertex,
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
};
|
||||
use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
|
||||
/// `TICKS_BEFORE_ABOUT_TO_SPAWN_SOUND`.
|
||||
const ABOUT_TO_SPAWN: i64 = 36;
|
||||
/// `OminousItemSpawnerRenderer`: grows over its first 50 ticks, turning 40
|
||||
/// degrees a tick.
|
||||
const TICKS_SCALING: f32 = 50.0;
|
||||
const ROTATION_SPEED: f32 = 40.0;
|
||||
|
||||
pub(super) struct OminousItemSpawner {
|
||||
item: ItemStack,
|
||||
position: [f64; 3],
|
||||
spawn_item_after: i64,
|
||||
tick_count: i64,
|
||||
}
|
||||
|
||||
/// `ProjectileItem.DispenseConfig` of the items fired down: power,
|
||||
/// uncertainty and `overrideDispenseEvent`; None for items that just fall.
|
||||
fn projectile(item: &str) -> Option<(f32, f32, Option<i32>)> {
|
||||
Some(match item {
|
||||
"minecraft:fire_charge" => (1.0, 6.666_666_5, Some(1018)),
|
||||
"minecraft:wind_charge" => (1.0, 6.666_666_5, Some(1051)),
|
||||
"minecraft:firework_rocket" => (0.5, 1.0, Some(1004)),
|
||||
"minecraft:experience_bottle"
|
||||
| "minecraft:splash_potion"
|
||||
| "minecraft:lingering_potion" => (1.375, 3.0, None),
|
||||
"minecraft:arrow"
|
||||
| "minecraft:spectral_arrow"
|
||||
| "minecraft:tipped_arrow"
|
||||
| "minecraft:snowball"
|
||||
| "minecraft:egg"
|
||||
| "minecraft:blue_egg"
|
||||
| "minecraft:brown_egg" => (1.1, 6.0, None),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn block(p: [f64; 3]) -> [i32; 3] {
|
||||
p.map(|v| v.floor() as i32)
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `OminousItemSpawner.create` added at `position`.
|
||||
pub(super) fn add_ominous_item_spawner(
|
||||
&mut self,
|
||||
item: ItemStack,
|
||||
position: [f64; 3],
|
||||
delay: i32,
|
||||
) {
|
||||
self.ominous_spawners.push(OminousItemSpawner {
|
||||
item,
|
||||
position,
|
||||
spawn_item_after: i64::from(delay),
|
||||
tick_count: 0,
|
||||
});
|
||||
}
|
||||
/// Every item spawner's tick: `commonTick`'s count, `tickServer` (the
|
||||
/// warning sound, then the item) and `tickClient` (particles every 5
|
||||
/// game ticks).
|
||||
pub(super) fn tick_ominous_item_spawners(&mut self) {
|
||||
let spawners = std::mem::take(&mut self.ominous_spawners);
|
||||
let mut kept = Vec::with_capacity(spawners.len());
|
||||
for mut s in spawners {
|
||||
s.tick_count += 1;
|
||||
let at = block(s.position);
|
||||
let center = at.map(|v| f64::from(v) + 0.5);
|
||||
if s.tick_count == s.spawn_item_after - ABOUT_TO_SPAWN {
|
||||
self.audio.play(
|
||||
"minecraft:block.trial_spawner.about_to_spawn_item",
|
||||
Some(center),
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
}
|
||||
if s.tick_count >= s.spawn_item_after {
|
||||
self.spawn_ominous_item(&s);
|
||||
continue;
|
||||
}
|
||||
if self.world.game_time % 5 == 0 {
|
||||
self.ominous_spawner_particles(s.position);
|
||||
}
|
||||
kept.push(s);
|
||||
}
|
||||
kept.append(&mut self.ominous_spawners);
|
||||
self.ominous_spawners = kept;
|
||||
}
|
||||
/// `spawnItem`: a projectile shot down, or an item entity; level event
|
||||
/// 3021 and the entity_place game event.
|
||||
fn spawn_ominous_item(&mut self, s: &OminousItemSpawner) {
|
||||
let at = block(s.position);
|
||||
let p = s.position;
|
||||
match projectile(&s.item.item) {
|
||||
Some((power, uncertainty, event)) => {
|
||||
if let Some(event) = event {
|
||||
self.level_event_at(event, at, 0);
|
||||
}
|
||||
let from = Vec3::new(p[0], p[1], p[2]);
|
||||
self.shoot_projectile_item(from, [0.0, -1.0, 0.0], &s.item, power, uncertainty);
|
||||
}
|
||||
None => self.spawn_item(s.item.clone(), p, super::dispenser::new_item_motion(), 0),
|
||||
}
|
||||
self.level_event_at(3021, at, 1);
|
||||
self.post_block_game_event("minecraft:entity_place", at, None, None);
|
||||
}
|
||||
/// `OminousItemSpawner.addParticles`: one to three ominous spawning
|
||||
/// particles from the spawner out to points around it.
|
||||
fn ominous_spawner_particles(&mut self, at: [f64; 3]) {
|
||||
let options = ParticleOptions::simple(ParticleType::OminousSpawning);
|
||||
let r = self.particles.random();
|
||||
let count = r.next_int_between_inclusive(1, 3).unwrap_or(1);
|
||||
let mut flights = Vec::new();
|
||||
for _ in 0..count {
|
||||
let mut spread = || 0.4 * (r.next_gaussian() - r.next_gaussian());
|
||||
let from = [at[0] + spread(), at[1] + spread(), at[2] + spread()];
|
||||
flights.push([from[0] - at[0], from[1] - at[1], from[2] - at[2]]);
|
||||
}
|
||||
for v in flights {
|
||||
self.particles.add(&options, at, v);
|
||||
}
|
||||
}
|
||||
/// `OminousItemSpawnerRenderer`: the item, full bright, growing over its
|
||||
/// first 50 ticks and turning.
|
||||
pub(super) fn ominous_item_spawner_geometry(
|
||||
&self,
|
||||
camera: glam::DVec3,
|
||||
alpha: f64,
|
||||
out: &mut Vec<Vertex>,
|
||||
) {
|
||||
for s in &self.ominous_spawners {
|
||||
let at = glam::DVec3::from_array(s.position);
|
||||
if at.distance_squared(camera) >= 64.0 * 64.0 {
|
||||
continue;
|
||||
}
|
||||
let state = self.resolve_item(&s.item, DisplayContext::Ground, None, 0);
|
||||
if state.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let age = s.tick_count as f32 + alpha as f32;
|
||||
let scale = if age <= TICKS_SCALING {
|
||||
age.min(TICKS_SCALING) / TICKS_SCALING
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
let spin = (age * ROTATION_SPEED).rem_euclid(360.0);
|
||||
let pose = glam::Mat4::from_translation((at - camera).as_vec3())
|
||||
* glam::Mat4::from_scale(glam::Vec3::splat(scale))
|
||||
* glam::Mat4::from_rotation_y(spin.to_radians());
|
||||
let seed =
|
||||
i64::from(self.res.item_renderer.item_id(&s.item.item)) + i64::from(s.item.damage);
|
||||
for copy in item_render::cluster_poses(
|
||||
&state,
|
||||
pose,
|
||||
item_render::rendered_amount(s.item.count),
|
||||
seed,
|
||||
) {
|
||||
self.submit_item_world(&state, copy, vertex_light(0xFF), out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,8 @@ use horizon_client::{
|
||||
Who,
|
||||
spawner::SpawnerSpawn,
|
||||
trial_spawner::{
|
||||
TrialEvent, TrialPlayer, TrialSpawner, TrialSpawnerLevel, TrialState, Uuid,
|
||||
Omen, TRIAL_OMEN_TICKS_PER_LEVEL, TrialEvent, TrialPlayer, TrialSpawner,
|
||||
TrialSpawnerLevel, TrialState, Uuid,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -40,6 +41,14 @@ impl TrialSpawnerLevel for GameLevel<'_, '_> {
|
||||
eye: view.eye,
|
||||
creative: self.game.creative,
|
||||
spectator: self.game.spectator(),
|
||||
position: [p.position.x, p.position.y, p.position.z],
|
||||
height: p.dimensions.height,
|
||||
alive: self.game.level.health > 0.0,
|
||||
omen: if self.game.potions.effects.get("trial_omen").is_some() {
|
||||
Some(Omen::Trial)
|
||||
} else {
|
||||
self.game.potions.effects.get("bad_omen").map(|_| Omen::Bad)
|
||||
},
|
||||
}]
|
||||
}
|
||||
fn visual_hit(&self, from: [f64; 3], to: [f64; 3]) -> Option<[i32; 3]> {
|
||||
@@ -52,6 +61,35 @@ impl TrialSpawnerLevel for GameLevel<'_, '_> {
|
||||
(!m.removed && m.alive())
|
||||
.then(|| [m.position.x, m.position.y, m.position.z].map(|v| v.floor() as i32))
|
||||
}
|
||||
fn entity_box(&self, uuid: Uuid) -> Option<([f64; 3], f32)> {
|
||||
let (id, _) = self.game.persist.uuids.iter().find(|(_, u)| **u == uuid)?;
|
||||
let m = self.game.mobs.iter().find(|m| m.id == *id)?;
|
||||
let b = m.bounds();
|
||||
(!m.removed && m.alive()).then(|| {
|
||||
(
|
||||
[m.position.x, m.position.y, m.position.z],
|
||||
(b.max_position().y - b.min_position().y) as f32,
|
||||
)
|
||||
})
|
||||
}
|
||||
fn no_block_collision(&self, block: [i32; 3]) -> bool {
|
||||
self.w
|
||||
.block_collision_boxes(block[0], block[1], block[2])
|
||||
.is_empty()
|
||||
}
|
||||
fn loot_items(&self, table: &str, seed: i64) -> Vec<ItemStack> {
|
||||
let Some(loot) = horizon_client::structure_blocks::loot_data(&self.game.options.resources)
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
loot.roll_split(table, &mut LegacyRandom::new(seed))
|
||||
.iter()
|
||||
.map(horizon_client::structure_blocks::loot_item_with_components)
|
||||
.collect()
|
||||
}
|
||||
fn seed(&self) -> i64 {
|
||||
self.game.level.seed
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
@@ -209,6 +247,26 @@ impl Game<'_> {
|
||||
let who = by_uuid.get(&uuid).map(|id| Who::Mob(*id));
|
||||
self.post_block_game_event("minecraft:entity_place", at, who, None);
|
||||
}
|
||||
TrialEvent::TrialOmen(_) => self.bad_omen_to_trial_omen(),
|
||||
TrialEvent::Discard(uuid) => {
|
||||
let id = self.persist.uuids.iter().find(|(_, u)| **u == uuid);
|
||||
if let Some((id, _)) = id
|
||||
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == *id)
|
||||
{
|
||||
m.removed = true;
|
||||
}
|
||||
}
|
||||
TrialEvent::SoundAt(name, at, pitch) => self.audio.play(
|
||||
&format!("minecraft:{name}"),
|
||||
Some(at.map(|v| f64::from(v) + 0.5)),
|
||||
1.0,
|
||||
pitch,
|
||||
),
|
||||
TrialEvent::ItemSpawner {
|
||||
item,
|
||||
position,
|
||||
delay,
|
||||
} => self.add_ominous_item_spawner(item, position, delay),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -233,6 +291,27 @@ impl Game<'_> {
|
||||
let id = self.res.assets.registry.resolve(&block)?;
|
||||
self.level_set([key.0, key.1, key.2], id)
|
||||
}
|
||||
/// `transformBadOmenIntoTrialOmen`: Bad Omen becomes Trial Omen, 15
|
||||
/// minutes per level, with Trial Omen's sound when it is new.
|
||||
fn bad_omen_to_trial_omen(&mut self) {
|
||||
let Some(amplifier) = self.potions.effects.amplifier("bad_omen") else {
|
||||
return;
|
||||
};
|
||||
self.potions.effects.list.retain(|e| e.id != "bad_omen");
|
||||
let new = self.potions.effects.get("trial_omen").is_none();
|
||||
self.potions
|
||||
.effects
|
||||
.add(horizon_client::effects::EffectInstance::new(
|
||||
"trial_omen",
|
||||
TRIAL_OMEN_TICKS_PER_LEVEL * (amplifier + 1),
|
||||
0,
|
||||
));
|
||||
if new {
|
||||
let eye = self.eye_position().unwrap_or_default();
|
||||
self.audio
|
||||
.play("minecraft:event.mob_effect.trial_omen", Some(eye), 1.0, 1.0);
|
||||
}
|
||||
}
|
||||
/// `sendBlockUpdated` of a block entity: the clients load its new update tag.
|
||||
pub(super) fn mark_block_entity_updated(&mut self, key: Pos) {
|
||||
if let Some(log) = self.world.block_log.as_mut() {
|
||||
|
||||
@@ -26,6 +26,11 @@ const MAX_MOB_TRACKING_DISTANCE: i64 = 47;
|
||||
/// `DELAY_BEFORE_EJECT_AFTER_KILLING_LAST_MOB` and `TIME_BETWEEN_EACH_EJECTION`.
|
||||
const DELAY_BEFORE_EJECT: f32 = 40.0;
|
||||
const TIME_BETWEEN_EJECTIONS: f32 = 30.0;
|
||||
/// `TrialSpawnerConfig.ticksBetweenItemSpawners`.
|
||||
const TICKS_BETWEEN_ITEM_SPAWNERS: i64 = 160;
|
||||
/// `transformBadOmenIntoTrialOmen`: Trial Omen lasts this long per level of
|
||||
/// Bad Omen.
|
||||
pub const TRIAL_OMEN_TICKS_PER_LEVEL: i32 = 18000;
|
||||
|
||||
/// `TrialSpawnerConfig`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -261,6 +266,20 @@ pub struct TrialPlayer {
|
||||
pub eye: [f64; 3],
|
||||
pub creative: bool,
|
||||
pub spectator: bool,
|
||||
/// `position()` and the box's height.
|
||||
pub position: [f64; 3],
|
||||
pub height: f32,
|
||||
pub alive: bool,
|
||||
pub omen: Option<Omen>,
|
||||
}
|
||||
|
||||
/// The effect that turns a trial spawner ominous when its player is seen.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Omen {
|
||||
/// `MobEffects.TRIAL_OMEN`.
|
||||
Trial,
|
||||
/// `MobEffects.BAD_OMEN`, which becomes Trial Omen.
|
||||
Bad,
|
||||
}
|
||||
|
||||
/// What a trial spawner did that the level shows or sends.
|
||||
@@ -277,6 +296,21 @@ pub enum TrialEvent {
|
||||
/// `setBlockAndUpdate` of the `ominous` property alone, even when it
|
||||
/// does not change (`removeOminous`).
|
||||
OminousSet(bool),
|
||||
/// `transformBadOmenIntoTrialOmen`: the player's Bad Omen becomes Trial
|
||||
/// Omen for [`TRIAL_OMEN_TICKS_PER_LEVEL`] per level.
|
||||
TrialOmen(Uuid),
|
||||
/// `resetAfterBecomingOminous`: the mob is discarded (after its level
|
||||
/// event 3012).
|
||||
Discard(Uuid),
|
||||
/// `playSound(null, block, sound, BLOCKS, 1, pitch)`.
|
||||
SoundAt(&'static str, [i32; 3], f32),
|
||||
/// `OminousItemSpawner.create(level, item)` added at `position`, spawning
|
||||
/// its item after `delay` ticks.
|
||||
ItemSpawner {
|
||||
item: crate::items::ItemStack,
|
||||
position: [f64; 3],
|
||||
delay: i32,
|
||||
},
|
||||
}
|
||||
|
||||
/// What a trial spawner reads from the level besides the spawn rules.
|
||||
@@ -290,6 +324,15 @@ pub trait TrialSpawnerLevel: SpawnerLevel {
|
||||
fn visual_hit(&self, from: [f64; 3], to: [f64; 3]) -> Option<[i32; 3]>;
|
||||
/// The block position of a living entity of this dimension, if any.
|
||||
fn entity_block(&self, uuid: Uuid) -> Option<[i32; 3]>;
|
||||
/// A living entity's position and box height, if it is in this dimension.
|
||||
fn entity_box(&self, uuid: Uuid) -> Option<([f64; 3], f32)>;
|
||||
/// The block's collision shape is empty.
|
||||
fn no_block_collision(&self, block: [i32; 3]) -> bool;
|
||||
/// `LootTable.getRandomItems` of `table` seeded with `seed` (an empty
|
||||
/// context, stacks split).
|
||||
fn loot_items(&self, table: &str, seed: i64) -> Vec<crate::items::ItemStack>;
|
||||
/// `getSeed`.
|
||||
fn seed(&self) -> i64;
|
||||
}
|
||||
|
||||
/// `TrialSpawner` with its `TrialSpawnerStateData`.
|
||||
@@ -313,6 +356,9 @@ pub struct TrialSpawner {
|
||||
pub has_display: bool,
|
||||
pub spin: f64,
|
||||
pub o_spin: f64,
|
||||
/// `getDispensingItems`, kept once rolled (not saved): the ominous items
|
||||
/// and their weights (the rolled counts).
|
||||
pub dispensing: Option<Vec<crate::items::ItemStack>>,
|
||||
}
|
||||
impl Default for TrialSpawner {
|
||||
fn default() -> Self {
|
||||
@@ -332,6 +378,7 @@ impl Default for TrialSpawner {
|
||||
has_display: false,
|
||||
spin: 0.0,
|
||||
o_spin: 0.0,
|
||||
dispensing: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -530,7 +577,8 @@ impl TrialSpawner {
|
||||
.map(|p| p.uuid)
|
||||
.collect()
|
||||
}
|
||||
/// `tryDetectPlayers`, every 20 ticks.
|
||||
/// `tryDetectPlayers`, every 20 ticks: a player seen with Trial Omen or
|
||||
/// Bad Omen turns the spawner ominous.
|
||||
fn try_detect_players<L: TrialSpawnerLevel>(
|
||||
&mut self,
|
||||
l: &L,
|
||||
@@ -542,10 +590,43 @@ impl TrialSpawner {
|
||||
if packed.wrapping_add(l.game_time()) % 20 != 0 {
|
||||
return;
|
||||
}
|
||||
if state == TrialState::Cooldown {
|
||||
let cooldown = state == TrialState::Cooldown;
|
||||
if cooldown && self.is_ominous {
|
||||
return;
|
||||
}
|
||||
let in_sight = self.detect(l, pos, true);
|
||||
let mut became_ominous = false;
|
||||
if !self.is_ominous && !in_sight.is_empty() {
|
||||
// findPlayerWithOminousEffect: the first with Trial Omen, else
|
||||
// the last with Bad Omen.
|
||||
let players = l.players();
|
||||
let mut found = None;
|
||||
for uuid in &in_sight {
|
||||
let Some(p) = players.iter().find(|p| p.uuid == *uuid) else {
|
||||
continue;
|
||||
};
|
||||
match p.omen {
|
||||
Some(Omen::Trial) => {
|
||||
found = Some((*p, Omen::Trial));
|
||||
break;
|
||||
}
|
||||
Some(Omen::Bad) => found = Some((*p, Omen::Bad)),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
if let Some((player, omen)) = found {
|
||||
if omen == Omen::Bad {
|
||||
events.push(TrialEvent::TrialOmen(player.uuid));
|
||||
}
|
||||
let eye = player.eye.map(|v| v.floor() as i32);
|
||||
events.push(TrialEvent::LevelEvent(3020, eye, 0));
|
||||
self.apply_ominous(l, pos, events);
|
||||
became_ominous = true;
|
||||
}
|
||||
}
|
||||
if cooldown && !became_ominous {
|
||||
return;
|
||||
}
|
||||
let found = if self.detected_players.is_empty() {
|
||||
in_sight
|
||||
} else {
|
||||
@@ -560,14 +641,155 @@ impl TrialSpawner {
|
||||
}
|
||||
if added {
|
||||
self.next_mob_spawns_at = (l.game_time() + 40).max(self.next_mob_spawns_at);
|
||||
let id = if self.is_ominous { 3019 } else { 3013 };
|
||||
events.push(TrialEvent::LevelEvent(
|
||||
id,
|
||||
pos,
|
||||
self.detected_players.len() as i32,
|
||||
));
|
||||
if !became_ominous {
|
||||
let id = if self.is_ominous { 3019 } else { 3013 };
|
||||
events.push(TrialEvent::LevelEvent(
|
||||
id,
|
||||
pos,
|
||||
self.detected_players.len() as i32,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `applyOminous`, then `resetAfterBecomingOminous`: the spawner's mobs
|
||||
/// vanish and the ominous config starts over.
|
||||
fn apply_ominous<L: TrialSpawnerLevel>(
|
||||
&mut self,
|
||||
l: &L,
|
||||
pos: [i32; 3],
|
||||
events: &mut Vec<TrialEvent>,
|
||||
) {
|
||||
events.push(TrialEvent::OminousSet(true));
|
||||
events.push(TrialEvent::LevelEvent(3020, pos, 1));
|
||||
self.is_ominous = true;
|
||||
for uuid in hash_order(&self.current_mobs) {
|
||||
if let Some(block) = l.entity_block(uuid) {
|
||||
// FlameParticle.NORMAL.
|
||||
events.push(TrialEvent::LevelEvent(3012, block, 0));
|
||||
events.push(TrialEvent::Discard(uuid));
|
||||
}
|
||||
}
|
||||
// WeightedList.isEmpty: a total weight of 0.
|
||||
if self
|
||||
.ominous
|
||||
.config
|
||||
.spawn_potentials
|
||||
.iter()
|
||||
.any(|(_, w)| *w > 0)
|
||||
{
|
||||
self.next_spawn_data = None;
|
||||
}
|
||||
self.total_mobs_spawned = 0;
|
||||
self.current_mobs.clear();
|
||||
let now = l.game_time();
|
||||
self.next_mob_spawns_at = now + i64::from(self.ominous.config.ticks_between_spawn);
|
||||
events.push(TrialEvent::BlockUpdated);
|
||||
self.cooldown_ends_at = now + TICKS_BETWEEN_ITEM_SPAWNERS;
|
||||
}
|
||||
/// `TrialSpawnerState.spawnOminousOminousItemSpawner`: every tick an item
|
||||
/// is drawn; once the item spawner cooldown is over, an ominous item
|
||||
/// spawner appears above a player or one of the spawner's mobs.
|
||||
fn spawn_ominous_item_spawner<L: TrialSpawnerLevel, R: RandomSource>(
|
||||
&mut self,
|
||||
l: &L,
|
||||
random: &mut R,
|
||||
pos: [i32; 3],
|
||||
events: &mut Vec<TrialEvent>,
|
||||
) {
|
||||
// getDispensingItems: rolled once with a seed from the level seed and
|
||||
// the spawner's 30x20x30 cell; an empty roll is not kept.
|
||||
if self.dispensing.is_none() {
|
||||
let cell = BlockPos::new(
|
||||
(pos[0] as f32 / 30.0).floor() as i32,
|
||||
(pos[1] as f32 / 20.0).floor() as i32,
|
||||
(pos[2] as f32 / 30.0).floor() as i32,
|
||||
);
|
||||
let table = &self.active_config().items_to_drop_when_ominous;
|
||||
let drops = l.loot_items(table, l.seed().wrapping_add(cell.pack()));
|
||||
if !drops.is_empty() {
|
||||
self.dispensing = Some(drops);
|
||||
}
|
||||
}
|
||||
let items = self.dispensing.as_deref().unwrap_or_default();
|
||||
// WeightedList.getRandom: each stack weighs its count; one item spawns.
|
||||
let Some(index) = spawner::weighted_index(items.iter().map(|s| s.count as i32), random)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let item = crate::items::ItemStack {
|
||||
count: 1,
|
||||
..items[index].clone()
|
||||
};
|
||||
if l.game_time() < self.cooldown_ends_at {
|
||||
return;
|
||||
}
|
||||
let Some(position) = self.item_spawner_position(l, random, pos) else {
|
||||
return;
|
||||
};
|
||||
let delay = random.next_int_between_inclusive(60, 120).unwrap_or(60);
|
||||
events.push(TrialEvent::ItemSpawner {
|
||||
item,
|
||||
position,
|
||||
delay,
|
||||
});
|
||||
let pitch = (random.next_float() - random.next_float()) * 0.2 + 1.0;
|
||||
events.push(TrialEvent::SoundAt(
|
||||
"block.trial_spawner.spawn_item_begin",
|
||||
position.map(|v| v.floor() as i32),
|
||||
pitch,
|
||||
));
|
||||
self.cooldown_ends_at = l.game_time() + TICKS_BETWEEN_ITEM_SPAWNERS;
|
||||
}
|
||||
/// `calculatePositionToSpawnSpawner`: above a player in range or one of
|
||||
/// the spawner's mobs (a coin decides which), under the first block in
|
||||
/// the way, unless that spot is solid.
|
||||
fn item_spawner_position<L: TrialSpawnerLevel, R: RandomSource>(
|
||||
&self,
|
||||
l: &L,
|
||||
random: &mut R,
|
||||
pos: [i32; 3],
|
||||
) -> Option<[f64; 3]> {
|
||||
let c = center(pos);
|
||||
let range = f64::from(self.required_player_range * self.required_player_range);
|
||||
let near = |p: [f64; 3]| {
|
||||
(p[0] - c[0]).powi(2) + (p[1] - c[1]).powi(2) + (p[2] - c[2]).powi(2) <= range
|
||||
};
|
||||
let all = l.players();
|
||||
let players: Vec<([f64; 3], f32)> = hash_order(&self.detected_players)
|
||||
.into_iter()
|
||||
.filter_map(|uuid| all.iter().find(|p| p.uuid == uuid))
|
||||
.filter(|p| !p.creative && !p.spectator && p.alive && near(p.position))
|
||||
.map(|p| (p.position, p.height))
|
||||
.collect();
|
||||
if players.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mobs: Vec<([f64; 3], f32)> = hash_order(&self.current_mobs)
|
||||
.into_iter()
|
||||
.filter_map(|uuid| l.entity_box(uuid))
|
||||
.filter(|(p, _)| near(*p))
|
||||
.collect();
|
||||
let eligible = if random.next_boolean() { mobs } else { players };
|
||||
let (at, height) = match eligible.len() {
|
||||
0 => return None,
|
||||
1 => eligible[0],
|
||||
n => eligible[random.next_int_bound(n as i32).unwrap_or(0) as usize],
|
||||
};
|
||||
// calculatePositionAbove: a VISUAL clip up to 2 to 5 blocks over the
|
||||
// entity's head; a miss ends in the block holding the end point.
|
||||
let up = height + 2.0 + random.next_int_bound(4).unwrap_or(0) as f32;
|
||||
let to = [at[0], at[1] + f64::from(up), at[2]];
|
||||
let hit = l
|
||||
.visual_hit(at, to)
|
||||
.unwrap_or_else(|| to.map(|v| v.floor() as i32));
|
||||
let down = [
|
||||
f64::from(hit[0]) + 0.5,
|
||||
f64::from(hit[1]) + 0.5 - 1.0,
|
||||
f64::from(hit[2]) + 0.5,
|
||||
];
|
||||
l.no_block_collision(down.map(|v| v.floor() as i32))
|
||||
.then_some(down)
|
||||
}
|
||||
/// `TrialSpawner.tickServer`: the next state of the block.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn server_tick<L: TrialSpawnerLevel, R: RandomSource>(
|
||||
@@ -649,6 +871,9 @@ impl TrialSpawner {
|
||||
let config = self.active_config().clone();
|
||||
let additional = (self.detected_players.len() as i32 - 1).max(0);
|
||||
self.try_detect_players(l, pos, state, events);
|
||||
if self.is_ominous {
|
||||
self.spawn_ominous_item_spawner(l, random, pos, events);
|
||||
}
|
||||
if self.total_mobs_spawned >= config.target_total_mobs(additional) {
|
||||
if self.current_mobs.is_empty() {
|
||||
self.cooldown_ends_at = now + i64::from(self.target_cooldown_length);
|
||||
@@ -704,7 +929,10 @@ impl TrialSpawner {
|
||||
{
|
||||
events.push(TrialEvent::LevelEvent(3014, pos, 0));
|
||||
}
|
||||
self.detected_players.remove(0);
|
||||
// detectedPlayers.remove(iterator().next()).
|
||||
if let Some(first) = hash_order(&self.detected_players).first() {
|
||||
self.detected_players.retain(|u| u != first);
|
||||
}
|
||||
state
|
||||
}
|
||||
S::Cooldown => {
|
||||
@@ -804,6 +1032,23 @@ impl TrialSpawner {
|
||||
}
|
||||
|
||||
/// `Vec3.atCenterOf`.
|
||||
/// The iteration order of a `HashSet<UUID>` holding `ids` (inserted in
|
||||
/// order): `HashMap` buckets by the spread `UUID.hashCode`, in a table of 16
|
||||
/// slots grown to keep it at most three quarters full; within a bucket,
|
||||
/// insertion order.
|
||||
fn hash_order(ids: &[Uuid]) -> Vec<Uuid> {
|
||||
let mut table = 16usize;
|
||||
while ids.len() > table * 3 / 4 {
|
||||
table *= 2;
|
||||
}
|
||||
let bucket = |u: &Uuid| {
|
||||
let h = (u[0] ^ u[1] ^ u[2] ^ u[3]) as u32;
|
||||
((h ^ (h >> 16)) as usize) & (table - 1)
|
||||
};
|
||||
let mut out = ids.to_vec();
|
||||
out.sort_by_key(bucket);
|
||||
out
|
||||
}
|
||||
fn center(pos: [i32; 3]) -> [f64; 3] {
|
||||
pos.map(|v| f64::from(v) + 0.5)
|
||||
}
|
||||
|
||||
@@ -177,6 +177,14 @@ public final class VanillaNaturalSpawnOracle {
|
||||
/** The game time (trial cases advance it). */
|
||||
long time;
|
||||
net.minecraft.world.level.block.entity.BlockEntity trial;
|
||||
/** Trial cases: the mobs added so far, which name their UUIDs. */
|
||||
int trialMobs;
|
||||
/** Mobs a trial spawner discards stop being tracked as waypoints. */
|
||||
net.minecraft.server.waypoints.ServerWaypointManager waypoints;
|
||||
@Override public net.minecraft.server.waypoints.ServerWaypointManager getWaypointManager() {
|
||||
if (waypoints == null) waypoints = new net.minecraft.server.waypoints.ServerWaypointManager();
|
||||
return waypoints;
|
||||
}
|
||||
@Override public long getGameTime() { return time; }
|
||||
@Override public int getNextEntityId() { return next++; }
|
||||
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags(); }
|
||||
@@ -285,6 +293,17 @@ public final class VanillaNaturalSpawnOracle {
|
||||
return out;
|
||||
}
|
||||
@Override public boolean addFreshEntity(Entity entity) {
|
||||
if (entity instanceof OminousItemSpawner spawner && tick >= 0) {
|
||||
try {
|
||||
Field delay = OminousItemSpawner.class.getDeclaredField("spawnItemAfterTicks");
|
||||
delay.setAccessible(true);
|
||||
log.add(tick + " ispawner " + BuiltInRegistries.ITEM.getKey(spawner.getItem().getItem()) + " " + spawner.getItem().getCount() + " "
|
||||
+ bits(spawner.getX()) + " " + bits(spawner.getY()) + " " + bits(spawner.getZ()) + " " + delay.getLong(spawner));
|
||||
} catch (ReflectiveOperationException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (entity instanceof net.minecraft.world.entity.item.ItemEntity item && tick >= 0) {
|
||||
Vec3 v = item.getDeltaMovement();
|
||||
log.add(tick + " item " + BuiltInRegistries.ITEM.getKey(item.getItem().getItem()) + " " + item.getItem().getCount() + " " + bits(item.getX()) + " " + bits(item.getY()) + " " + bits(item.getZ()) + " " + bits(v.x) + " " + bits(v.y) + " " + bits(v.z));
|
||||
@@ -292,7 +311,17 @@ public final class VanillaNaturalSpawnOracle {
|
||||
entities.add(entity);
|
||||
return true;
|
||||
}
|
||||
@Override public void addFreshEntityWithPassengers(Entity entity) { entity.getSelfAndPassengers().forEach(this::addFreshEntity); }
|
||||
@Override public void addFreshEntityWithPassengers(Entity entity) {
|
||||
// A trial spawner's mob gets a UUID in spawn order (its own is random),
|
||||
// so the spawner's HashSet iterates them the same way on every run.
|
||||
if (trial instanceof net.minecraft.world.level.block.entity.TrialSpawnerBlockEntity && entity instanceof Mob) entity.setUUID(new UUID(1L << 32, trialMobs++));
|
||||
entity.getSelfAndPassengers().forEach(this::addFreshEntity);
|
||||
}
|
||||
/** Ominous trial spawners: their level events at a player's eye or a mob carry the position. */
|
||||
@Override public void levelEvent(int type, BlockPos pos, int data) {
|
||||
if (type != 3020 && type != 3012) { super.levelEvent(type, pos, data); return; }
|
||||
if (tick >= 0) log.add(tick + " levent " + type + " " + data + " at " + pos.getX() + "," + pos.getY() + "," + pos.getZ());
|
||||
}
|
||||
@Override public Player getNearestPlayer(double x, double y, double z, double maxDist, boolean filter) {
|
||||
if (maxDist == -1.0 && !filter) log.add("try " + (int) Math.floor(x) + " " + (int) Math.floor(z));
|
||||
return super.getNearestPlayer(x, y, z, maxDist, filter);
|
||||
@@ -386,6 +415,17 @@ public final class VanillaNaturalSpawnOracle {
|
||||
static final class OraclePlayer extends ServerPlayer {
|
||||
OraclePlayer() { super(null, null, null, null); }
|
||||
GameType mode;
|
||||
Lvl lvl;
|
||||
// Trial Omen replacing Bad Omen: logged, without the client updates.
|
||||
@Override public boolean addEffect(net.minecraft.world.effect.MobEffectInstance effect, Entity source) {
|
||||
if (lvl.tick >= 0) lvl.log.add(lvl.tick + " effect add " + effect.getEffect().unwrapKey().orElseThrow().identifier() + " " + effect.getDuration() + " " + effect.getAmplifier());
|
||||
getActiveEffectsMap().put(effect.getEffect(), effect);
|
||||
return true;
|
||||
}
|
||||
@Override public boolean removeEffect(Holder<net.minecraft.world.effect.MobEffect> effect) {
|
||||
if (lvl.tick >= 0) lvl.log.add(lvl.tick + " effect remove " + effect.unwrapKey().orElseThrow().identifier());
|
||||
return getActiveEffectsMap().remove(effect) != null;
|
||||
}
|
||||
@Override public boolean isSpectator() { return mode == GameType.SPECTATOR; }
|
||||
@Override public boolean isCreative() { return mode == GameType.CREATIVE; }
|
||||
@Override public GameType gameMode() { return mode; }
|
||||
@@ -512,6 +552,7 @@ public final class VanillaNaturalSpawnOracle {
|
||||
var entity = new net.minecraft.world.level.block.entity.TrialSpawnerBlockEntity(at, block);
|
||||
entity.setLevel(level);
|
||||
level.trial = entity;
|
||||
level.trialMobs = 0;
|
||||
entity.getTrialSpawner().load(net.minecraft.world.level.storage.TagValueInput.create(net.minecraft.util.ProblemReporter.DISCARDING, access, nbt));
|
||||
int ticks = Integer.parseInt(c.getOrDefault("ticks", "1"));
|
||||
long t0 = Long.parseLong(c.getOrDefault("t0", "0"));
|
||||
@@ -523,6 +564,8 @@ public final class VanillaNaturalSpawnOracle {
|
||||
level.time = t0 + t;
|
||||
BlockState state = level.getBlockState(at);
|
||||
entity.getTrialSpawner().tickServer(level, at, state.getValue(net.minecraft.world.level.block.TrialSpawnerBlock.OMINOUS));
|
||||
// Mobs discarded as the spawner turned ominous leave the level.
|
||||
level.entities.removeIf(Entity::isRemoved);
|
||||
if (kill > 0 && t % kill == kill - 1) {
|
||||
int n = 0;
|
||||
for (Iterator<Entity> it = level.entities.subList(before, level.entities.size()).iterator(); it.hasNext(); ) {
|
||||
@@ -700,6 +743,14 @@ public final class VanillaNaturalSpawnOracle {
|
||||
put(player, Entity.class, "uuid", new UUID(0L, i + 1));
|
||||
eyeHeight.setFloat(player, 1.62F);
|
||||
put(player, LivingEntity.class, "activeEffects", new HashMap<>());
|
||||
put(player, Entity.class, "dimensions", EntityTypes.PLAYER.getDimensions());
|
||||
player.lvl = level;
|
||||
if (p.length > 2) {
|
||||
// An omen: trial_omen or bad_omen, with its amplifier.
|
||||
String[] effect = p[2].split(":");
|
||||
var omen = effect[0].equals("trial_omen") ? net.minecraft.world.effect.MobEffects.TRIAL_OMEN : net.minecraft.world.effect.MobEffects.BAD_OMEN;
|
||||
player.getActiveEffectsMap().put(omen, new net.minecraft.world.effect.MobEffectInstance(omen, 6000, Integer.parseInt(effect[1])));
|
||||
}
|
||||
level.playerList.add(player);
|
||||
}
|
||||
level.entities.clear();
|
||||
|
||||
@@ -22,9 +22,15 @@ state of the block, every difficulty and both game rules. Every so many ticks
|
||||
the case kills the mobs the spawner added, so waves finish, rewards are
|
||||
ejected and cooldowns run out.
|
||||
|
||||
Some players carry Trial Omen or Bad Omen, which turn a spawner that sees them
|
||||
ominous (Bad Omen becoming Trial Omen, the spawner's mobs discarded, the
|
||||
ominous config starting over), and some spawners start ominous. Ominous
|
||||
spawners drop ominous item spawners above a player or a mob (item, exact
|
||||
position and delay compared); the item spawners themselves are not ticked.
|
||||
|
||||
finalizeSpawn runs with a fixed random in the oracle; its own outcomes are not
|
||||
compared. Ominous spawners (which also drop ominous item spawners) are not in
|
||||
the corpus yet.
|
||||
compared. Spawned mobs get UUIDs in spawn order on both sides, so the
|
||||
spawner's HashSets iterate them alike.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
@@ -145,7 +151,10 @@ def players(w, rng, spos, half, height):
|
||||
else:
|
||||
x, y, z = spos[0] + rng.uniform(-20, 21), spos[1] + rng.choice([0, 0, -8, 10]), spos[2] + rng.uniform(-20, 21)
|
||||
mode = rng.choice(['survival'] * 7 + ['creative', 'adventure', 'spectator'])
|
||||
w.players.append(f'{x:.3f},{y:.3f},{z:.3f}/{mode}')
|
||||
omen = ''
|
||||
if rng.random() < 0.3:
|
||||
omen = f'/{rng.choice(["bad_omen", "bad_omen", "trial_omen"])}:{rng.choice([0, 0, 1, 4])}'
|
||||
w.players.append(f'{x:.3f},{y:.3f},{z:.3f}/{mode}{omen}')
|
||||
|
||||
|
||||
def corpus():
|
||||
@@ -164,6 +173,8 @@ def corpus():
|
||||
t0 = rng.choice([0, 1, 19, 1000, rng.randrange(0, 10**6), rng.randrange(10**9, 10**12)])
|
||||
w.kv['spos'] = f'{spos[0]},{spos[1]},{spos[2]}'
|
||||
w.kv['state'] = rng.choices(STATES, [2, 6, 4, 1, 1, 1])[0]
|
||||
if rng.random() < 0.15:
|
||||
w.kv['ominous'] = 1
|
||||
w.kv['snbt'] = base64.b64encode(trial_snbt(rng, t0).encode()).decode()
|
||||
w.kv['t0'] = t0
|
||||
w.kv['ticks'] = rng.choice([1, 2, 20, 41, 100, 200, 400, 600])
|
||||
@@ -219,7 +230,9 @@ def main():
|
||||
base.ensure_sources_unchanged(sources, tested)
|
||||
count = lambda text: sum(line.count(text) for line in vanilla)
|
||||
stats = {'spawns': count(' spawn minecraft:'), 'items': count(' item minecraft:'), 'states': count(' state '),
|
||||
'detections': count(' levent 3013 '), 'rewards': count(' levent 3014 '), 'kills': count(' kill ')}
|
||||
'detections': count(' levent 3013 '), 'rewards': count(' levent 3014 '), 'kills': count(' kill '),
|
||||
'became_ominous': count(' levent 3020 1 '), 'trial_omens': count(' effect add minecraft:trial_omen'),
|
||||
'item_spawners': count(' ispawner ')}
|
||||
for state in STATES:
|
||||
stats[f'reached_{state}'] = sum(f' state {state} ' in line for line in vanilla)
|
||||
lab.write_json(build / 'report.json', {
|
||||
@@ -229,8 +242,9 @@ def main():
|
||||
'tracking), TrialSpawnerState.tickAndGetNext for every state (display entity, canSpawnInLevel, '
|
||||
'tryDetectPlayers with line of sight, waves and their targets per player, spawnMob with its '
|
||||
'collision, line of sight, spawn rules, yaw and obstruction checks, next spawn data, reward '
|
||||
'ejection with the loot tables and spawnItem, shutter sounds, cooldown) with every level random '
|
||||
'draw. finalizeSpawn runs with a fixed random in the oracle; its own outcomes are not compared.'})
|
||||
'ejection with the loot tables and spawnItem, shutter sounds, cooldown, becoming ominous with Trial '
|
||||
'and Bad Omen, ominous item spawners with their items, positions and delays) with every level '
|
||||
'random draw. finalizeSpawn runs with a fixed random in the oracle; its own outcomes are not compared.'})
|
||||
print(f'{len(cases):,} trial spawner cases match vanilla (' + ', '.join(f'{v:,} {k}' for k, v in stats.items()) + ')')
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user