Merge branch 'parity/blocks' into parity-base

This commit is contained in:
Ludovic Marie
2026-10-12 14:06:53 +02:00
29 changed files with 2812 additions and 418 deletions
+2 -2
View File
@@ -42,7 +42,7 @@ round-trip harness has not been rerun.
| Interaction and inventory | 1 | None: menu clicks match over 6,000 click sequences |
| Menus, HUD and chat | 0.75 | Commands parse as vanilla over 39,685 inputs, but /item modify, /spectate, /waypoint and /dialog do not run; no tab list or world border rendering |
| Audio | 0.75 | Sound engine, music and ambience not compared with vanilla |
| Block behaviours and ticking | 0.75 | Block updates, random ticks and redstone match vanilla; dispensers lack several behaviours |
| Block behaviours and ticking | 0.75 | Block updates, random ticks, redstone and dispensers match vanilla; a container replaced by another block keeps its contents instead of spilling them, and there are no copper golems |
### Next steps
@@ -50,7 +50,7 @@ round-trip harness has not been rerun.
2. Draw every item through the item model pipeline, and add the resource pack screen.
3. An audio harness: sound engine attenuation, weighted sound events, music and ambience.
4. A mob AI harness, and an oracle for drowned, villagers, traders and the wither.
5. The missing commands and dispenser behaviours, the tab list and world border rendering.
5. The missing commands, containers spilling when replaced, copper golems, the tab list and world border rendering.
6. Test LAN hosting with a vanilla client, and add a dedicated server mode.
```sh
+11 -10
View File
@@ -1136,22 +1136,19 @@ pub fn armor_stand_from_nbt(tag: &Tag, id: u32) -> Option<ArmorStand> {
a.on_ground = flag(tag, "OnGround");
Some(a)
}
/// A boat entity (`minecraft:<wood>_boat`, `minecraft:bamboo_raft`).
/// A boat entity (`minecraft:<wood>_boat`, `minecraft:bamboo_chest_raft`...):
/// chest boats keep their slots in `Items` (`ContainerHelper.saveAllItems`).
pub fn boat_to_nbt(
wood: &str,
id: &str,
position: Vec3,
motion: Vec3,
yaw: f32,
uuid: [i32; 4],
raw: Option<&Tag>,
items: Option<&[Option<crate::items::ItemStack>]>,
) -> Tag {
let id = if wood == "bamboo" {
"minecraft:bamboo_raft".to_owned()
} else {
format!("minecraft:{wood}_boat")
};
Base {
id: &id,
let mut tag = Base {
id,
uuid,
position,
motion,
@@ -1159,7 +1156,11 @@ pub fn boat_to_nbt(
on_ground: false,
fall_distance: 0.0,
}
.tag(raw)
.tag(raw);
if let (Some(items), Tag::Compound(map)) = (items, &mut tag) {
map.insert("Items".into(), crate::save::encode_items(items));
}
tag
}
/// A vehicle's base entity tag (boats and minecarts).
pub fn vehicle_to_nbt(
+37 -22
View File
@@ -19,6 +19,7 @@ mod control;
mod creaking;
mod creatures;
mod crossbow;
mod dispense_fixture;
mod dispenser;
mod dragon;
mod enchant_effects;
@@ -1020,8 +1021,9 @@ impl Game<'_> {
f64::from(pos[2]) + d(z),
];
let v = [d(x) - 0.5, d(y) - 0.5, d(z) - 0.5];
// LevelEventHandler (2001) runs on the client: its random, not the level's.
let particle =
Particle::terrain(&mut self.world.random, p, v, sprite.clone(), tint);
Particle::terrain(self.particles.random(), p, v, sprite.clone(), tint);
self.particles.push(particle);
}
}
@@ -1032,7 +1034,8 @@ impl Game<'_> {
let Some((sprite, tint)) = self.particle_sprite(state) else {
return;
};
let r = &mut self.world.random;
// Client-side particles draw from the client random, not the level's.
let r = self.particles.random();
let mut p = [0.0; 3];
for i in 0..3 {
let base = f64::from(pos[i]);
@@ -1059,7 +1062,8 @@ impl Game<'_> {
) {
self.next_entity += 1;
let p = Vec3::new(position[0], position[1], position[2]);
let bob = self.world.random.next_float() * std::f32::consts::PI * 2.0;
// ItemEntity.bobOffs comes from the entity's own random, not the level's.
let bob = self.particles.random().next_float() * std::f32::consts::PI * 2.0;
self.dropped.push(ItemEntity {
id: self.next_entity,
stack,
@@ -1072,23 +1076,36 @@ impl Game<'_> {
bob_offset: bob,
});
}
/// `Block.getDrops`: the block's loot table, drawing from its server random
/// sequence (`LootContext.Builder.create`), else the level random.
fn block_loot(&mut self, state: BlockStateId, held: Option<&ItemStack>) -> Vec<ItemStack> {
let registry = self.res.assets.registry;
match self.res.items.block_loot_sequence(registry, state) {
Some(sequence) => {
let random = self.rand_sequences.get(&sequence, self.level.seed);
self.res.items.block_drops(registry, state, held, random)
}
None => self
.res
.items
.block_drops(registry, state, held, &mut self.world.random),
}
}
/// Block.popResource
fn pop_resource(&mut self, pos: [i32; 3], mut stack: ItemStack) {
self.attach_shulker_contents(pos, &mut stack);
self.attach_container_name(pos, &mut stack);
self.attach_banner_layers(pos, &mut stack);
// Block.popResource: Mth.nextDouble offsets from the level random; the
// motion is `new ItemEntity(..)`'s own, from the item's random.
let r = &mut self.world.random;
let mut offset = || f64::from(r.next_float()) * 0.5 - 0.25;
let mut offset = || -0.25 + r.next_double() * 0.5;
let p = [
f64::from(pos[0]) + 0.5 + offset(),
f64::from(pos[1]) + 0.5 + offset() - 0.125,
f64::from(pos[2]) + 0.5 + offset(),
];
let v = [
r.next_double() * 0.2 - 0.1,
0.2,
r.next_double() * 0.2 - 0.1,
];
let v = dispenser::new_item_motion();
self.spawn_item(stack, p, v, 10);
}
/// Player.drop: thrown from the eyes along the view direction.
@@ -1363,6 +1380,7 @@ impl Game<'_> {
fn process_level_events(&mut self) -> Result<()> {
let events = std::mem::take(&mut self.level_events);
self.lan_record_events(&events);
dispense_fixture::record_events(&events);
for event in events {
match event {
LevelEvent::LevelEvent {
@@ -1370,10 +1388,14 @@ impl Game<'_> {
pos,
data,
} => {
// LevelRenderer: destroy particles and the block's break sound.
// LevelEventHandler: destroy particles and the block's
// break sound (none for air).
let state = BlockStateId(data as u32);
let p = [pos.x, pos.y, pos.z];
self.destroy_particles(p, state);
if self.res.facts.is_air(state) {
continue;
}
let sounds = self.res.facts.get(state).sounds.clone();
let c = [
f64::from(pos.x) + 0.5,
@@ -1436,12 +1458,7 @@ impl Game<'_> {
let name = self.res.facts.get(state).name.clone();
self.release_contents([pos.x, pos.y, pos.z], entity, &name);
}
let drops = self.res.items.block_drops(
self.res.assets.registry,
state,
None,
&mut self.world.random,
);
let drops = self.block_loot(state, None);
for d in drops {
if &*d.item != "minecraft:air" {
self.pop_resource([pos.x, pos.y, pos.z], d);
@@ -1787,12 +1804,7 @@ impl Game<'_> {
let harvest = !facts.requires_tool
|| self.res.items.correct_for_drops(held.as_ref(), &facts.name);
if harvest {
let drops = self.res.items.block_drops(
self.res.assets.registry,
state,
held.as_ref(),
&mut self.world.random,
);
let drops = self.block_loot(state, held.as_ref());
let silk = held
.as_ref()
.is_some_and(|h| h.enchantment_level("minecraft:silk_touch") > 0);
@@ -8143,6 +8155,9 @@ pub fn run() -> Result<()> {
eprintln!("Horizon: control socket {}", server.path().display());
game.control = Some(server);
}
if let Ok(spec) = std::env::var("HORIZON_DISPENSE_FIXTURE") {
return game.dispense_fixture(&spec);
}
match game.options.world.clone() {
_ if game.options.server.is_some() => {
let (address, name) = (
+96 -17
View File
@@ -48,7 +48,12 @@ pub(super) struct Boat {
/// left, right, up, down
pub input: [bool; 4],
pub on_ground: bool,
/// `ChestBoat`: a chest with 27 slots in the back seat.
pub chest: bool,
pub items: Vec<Option<ItemStack>>,
}
/// `ChestBoat.CONTAINER_SIZE`.
pub(super) const CHEST_SLOTS: usize = 27;
const WIDTH: f64 = 1.375;
const HEIGHT: f64 = 0.5625;
/// Player.DEFAULT_VEHICLE_ATTACHMENT minus the boat's passenger attachment.
@@ -76,8 +81,16 @@ impl Boat {
paddling: [false; 2],
input: [false; 4],
on_ground: false,
chest: false,
items: Vec::new(),
}
}
/// A chest boat or chest raft.
pub fn with_chest(mut self) -> Self {
self.chest = true;
self.items = vec![None; CHEST_SLOTS];
self
}
pub fn bounds(&self) -> Aabb {
let (w, p) = (WIDTH / 2.0, self.position);
Aabb::new(
@@ -95,6 +108,30 @@ impl Boat {
}
}
/// Item id -> (boat entity id, wood).
impl Boat {
/// The vanilla entity type id (`oak_boat`, `bamboo_chest_raft`), also
/// the item it drops.
pub(super) fn entity_type(&self) -> String {
let chest = if self.chest { "chest_" } else { "" };
if &*self.wood == "bamboo" {
format!("minecraft:bamboo_{chest}raft")
} else {
format!("minecraft:{}_{chest}boat", self.wood)
}
}
}
/// The wood of a boat or chest boat item or entity type, and whether it
/// carries a chest.
pub(super) fn any_boat_wood(item: &str) -> Option<(&str, bool)> {
let name = item.strip_prefix("minecraft:")?;
if let Some(wood) = name
.strip_suffix("_chest_boat")
.or_else(|| name.strip_suffix("_chest_raft"))
{
return Some((wood, true));
}
boat_wood(item).map(|w| (w, false))
}
pub(super) fn boat_wood(item: &str) -> Option<&str> {
let name = item.strip_prefix("minecraft:")?;
name.strip_suffix("_boat")
@@ -103,10 +140,20 @@ pub(super) fn boat_wood(item: &str) -> Option<&str> {
}
pub(super) struct BoatModels {
pub models: HashMap<String, Part>,
pub chest_models: HashMap<String, Part>,
}
impl BoatModels {
/// Whether a boat of this wood (with or without a chest) can be drawn.
pub fn has(&self, wood: &str, chest: bool) -> bool {
if chest {
self.chest_models.contains_key(wood)
} else {
self.models.contains_key(wood)
}
}
pub fn load(root: &std::path::Path) -> Self {
let mut models = HashMap::new();
let mut chest_models = HashMap::new();
if let Ok(bytes) = std::fs::read(root.join("entity-models.json"))
&& let Ok(serde_json::Value::Object(all)) =
serde_json::from_slice::<serde_json::Value>(&bytes)
@@ -119,9 +166,19 @@ impl BoatModels {
{
models.insert(wood.to_owned(), part);
}
if let Some(wood) = key
.strip_prefix("minecraft:chest_boat/")
.and_then(|k| k.strip_suffix("#main"))
&& let Some(part) = horizon_client::mobs::load_model(root, key)
{
chest_models.insert(wood.to_owned(), part);
}
}
}
Self { models }
Self {
models,
chest_models,
}
}
}
impl Game<'_> {
@@ -457,10 +514,10 @@ impl Game<'_> {
}
/// `BoatItem.use`: aim at a block or the water surface.
pub(super) fn place_boat(&mut self, stack: &ItemStack) -> bool {
let Some(wood) = boat_wood(&stack.item) else {
let Some((wood, chest)) = any_boat_wood(&stack.item) else {
return false;
};
if !self.boat_models.models.contains_key(wood) {
if !self.boat_models.has(wood, chest) {
return false;
}
let Some(eye) = self.eye_position() else {
@@ -507,12 +564,15 @@ impl Game<'_> {
(None, Some(w)) => w.0,
(None, None) => return false,
};
let boat = Boat::new(
let mut boat = Boat::new(
self.next_entity + 1,
Arc::from(wood),
Vec3::new(hit[0], hit[1], hit[2]),
self.yaw,
);
if chest {
boat = boat.with_chest();
}
let bb = boat.bounds();
let (lo, hi) = (bb.min_position(), bb.max_position());
let e = 1.0e-7;
@@ -575,11 +635,24 @@ impl Game<'_> {
return false;
};
let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft);
if !self.before_block(d)
|| sneaking
|| self.boats[i].out_of_control >= 60.0
|| self.riding.is_some()
{
if !self.before_block(d) {
return false;
}
// ChestBoat.interact: sneaking (or a full seat) opens the chest.
if self.boats[i].chest && (sneaking || self.riding.is_some()) {
let b = &self.boats[i];
let key = (i32::MAX - 15, super::minecarts::CART_KEY_Y, b.id as i32);
self.world.block_entities.insert(
key,
horizon_client::containers::BlockEntity::Chest(b.items.clone()),
);
self.container = Some(key);
self.screen = super::Screen::Inventory;
self.capture(false);
self.right = false;
return true;
}
if sneaking || self.boats[i].out_of_control >= 60.0 || self.riding.is_some() {
return false;
}
self.riding = Some(self.boats[i].id);
@@ -601,13 +674,13 @@ impl Game<'_> {
let destroyed = self.creative || b.damage > 40.0;
if destroyed {
let b = self.boats.remove(i);
let at = [b.position.x, b.position.y, b.position.z];
if !self.creative && self.ui.rules.bool("entity_drops") {
let item = if &*b.wood == "bamboo" {
"minecraft:bamboo_raft".to_owned()
} else {
format!("minecraft:{}_boat", b.wood)
};
let at = [b.position.x, b.position.y, b.position.z];
// ChestBoat.destroy: chestVehicleDestroyed spills the contents.
for stack in b.items.iter().flatten() {
self.spawn_item(stack.clone(), at, super::dispenser::new_item_motion(), 10);
}
let item = b.entity_type();
self.spawn_item(
ItemStack {
item: Arc::from(item.as_str()),
@@ -628,14 +701,20 @@ impl Game<'_> {
pub(super) fn boat_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
let a = alpha as f32;
for b in &self.boats {
let Some(model) = self.boat_models.models.get(&*b.wood) else {
let models = if b.chest {
&self.boat_models.chest_models
} else {
&self.boat_models.models
};
let Some(model) = models.get(&*b.wood) else {
continue;
};
let folder = if b.chest { "chest_boat" } else { "boat" };
let Some(uv) = self
.res
.atlas
.sprites
.get(&format!("entity/boat/{}", b.wood))
.get(&format!("entity/{folder}/{}", b.wood))
.map(|r| [r.u0, r.v0, r.u1, r.v1])
else {
continue;
+5 -7
View File
@@ -266,13 +266,11 @@ impl Game<'_> {
}
}
Target::Painting(_) => "minecraft:painting".into(),
Target::Boat(id) => self.boats.iter().find(|b| b.id == id).map_or_else(
|| "minecraft:oak_boat".into(),
|b| {
let kind = if &*b.wood == "bamboo" { "raft" } else { "boat" };
format!("minecraft:{}_{kind}", b.wood)
},
),
Target::Boat(id) => self
.boats
.iter()
.find(|b| b.id == id)
.map_or_else(|| "minecraft:oak_boat".into(), |b| b.entity_type()),
Target::Cart(id) => self
.carts
.iter()
@@ -73,12 +73,13 @@ impl Game<'_> {
let uuid = self.uuid_for(id);
let b = self.boats.iter().find(|b| b.id == id)?;
entity_nbt::boat_to_nbt(
&b.wood,
&b.entity_type(),
b.position,
b.velocity,
b.yaw,
uuid,
self.persist.raw.get(&id),
b.chest.then_some(&b.items[..]),
)
}
Target::Cart(id) => {
@@ -0,0 +1,510 @@
//! The Rust side of tools/test_dispenser_parity.py: with
//! `HORIZON_DISPENSE_FIXTURE=CASES,OUTPUT` the game loads its resources, runs
//! every case (a dispenser or dropper with items, blocks and target entities
//! around it) through `dispense_from` on a fresh headless world and prints what
//! changed in the format of `VanillaDispenserOracle`.
use super::{
Game,
dispenser::{Slot, body_in_head, mob_set_slot, mob_slot_item},
};
use horizon_client::{
Result,
chunk::Chunk,
containers::BlockEntity,
gamerules::Value as RuleValue,
item_data::{canon_stack, parse_stack},
mobs::{Mob, Species},
projectiles::ProjectileKind,
world::World,
};
use horizon_core::{
position::BlockPos,
random::{LegacyRandom, RandomSource},
};
use horizon_world::{level::Ticks, registry::BlockStateId};
use serde_json::Value;
use std::{cell::RefCell, collections::HashMap, fmt::Write as _, io::Write as _, sync::Arc};
thread_local! {
/// Level and game events recorded while a fixture case runs.
static LOG: RefCell<Option<Vec<String>>> = const { RefCell::new(None) };
}
/// Record a line if a fixture case is running.
pub(super) fn record(line: impl FnOnce() -> String) {
LOG.with(|log| {
if let Some(lines) = log.borrow_mut().as_mut() {
lines.push(line());
}
});
}
/// `Level.levelEvent` lines for the level events the behaviour library reported.
pub(super) fn record_events(events: &[horizon_world::level::LevelEvent]) {
for event in events {
if let horizon_world::level::LevelEvent::LevelEvent { id, pos, data } = event {
record(|| format!("L {id} {},{},{} {data}", pos.x, pos.y, pos.z));
}
}
}
fn num(v: f64) -> String {
format!("{v:.6}")
}
fn floor_pos(p: [f64; 3]) -> String {
format!(
"{},{},{}",
p[0].floor() as i32,
p[1].floor() as i32,
p[2].floor() as i32
)
}
/// The targets a case put in front of the dispenser.
enum Target {
Mob(u32),
Stand(u32),
}
impl Game<'_> {
/// Run every case of `spec` ("CASES,OUTPUT") and write the results.
pub(super) fn dispense_fixture(&mut self, spec: &str) -> Result<()> {
let (input, output) = spec
.split_once(',')
.ok_or("HORIZON_DISPENSE_FIXTURE=CASES,OUTPUT")?;
// Saplings and feature placers grow from the live feature registry.
self.install_live_features();
let text = std::fs::read_to_string(input)?;
let mut out = std::io::BufWriter::new(std::fs::File::create(output)?);
for (index, line) in text.lines().enumerate() {
let case: Value = serde_json::from_str(line)?;
writeln!(out, "case {index}")?;
match self.dispense_case(&case) {
Ok(lines) => {
for l in lines {
writeln!(out, "{l}")?;
}
}
Err(e) => writeln!(out, "failed {e}")?,
}
}
LOG.with(|log| *log.borrow_mut() = None);
Ok(())
}
fn fixture_reset(&mut self, seed: i64) {
self.world = World::new(self.res.facts.air, seed);
// The oracle level is plains everywhere (bone meal's flowers, freezing).
let plains = u32::from(self.res.biomes.id("minecraft:plains"));
for cx in -2..=2 {
for cz in -2..=2 {
let mut chunk = Chunk::empty(cx, cz);
for section in &mut chunk.sections {
Arc::make_mut(section).biomes = horizon_core::paletted::PalettedContainer::new(
horizon_client::chunk::BIOME_STRATEGY,
plains,
);
}
self.world.chunks.insert((cx, cz), Arc::new(chunk));
}
}
self.block_ticks = Ticks::new(0);
self.tick_chunks.clear();
self.sync_tick_chunks();
self.mobs.clear();
self.dropped.clear();
self.creatures.projectiles.clear();
self.tnts.clear();
self.boats.clear();
self.carts.clear();
self.armor_stands.clear();
self.rockets.clear();
self.potions.clear_thrown();
self.level_events.clear();
self.orbs.clear();
self.falling.clear();
self.ui.rules = Default::default();
// The oracle level plays on normal difficulty.
self.ui.difficulty = 2;
// The oracle level has world seed 0 and fresh random sequences.
self.level.seed = 0;
self.rand_sequences = Default::default();
}
fn dispense_case(&mut self, case: &Value) -> Result<Vec<String>> {
let seed = case["seed"].as_i64().unwrap_or(0);
self.fixture_reset(seed);
// The oracle level answers one sky and one block light everywhere.
let light = case["light"].as_array();
let level = |i: usize, default: i64| {
light
.and_then(|l| l.get(i))
.and_then(Value::as_i64)
.unwrap_or(default) as u8
};
let packed = (level(0, 15) << 4) | level(1, 0);
for chunk in self.world.chunks.values_mut() {
for section in &mut Arc::make_mut(chunk).sections {
Arc::make_mut(section).light = horizon_client::chunk::Light::Uniform(packed);
}
}
self.world.game_time = case["time"].as_i64().unwrap_or(0);
// The oracle level's clock stands at day time 6000.
self.world.day_time = 6000;
if let Some(rules) = case["rules"].as_object() {
for (name, value) in rules {
if let Some(b) = value.as_bool() {
self.ui.rules.set(name, RuleValue::Bool(b));
}
}
}
let mut before: HashMap<(i32, i32, i32), u32> = HashMap::new();
for cell in case["cells"].as_array().into_iter().flatten() {
let p = (
cell[0].as_i64().unwrap_or(0) as i32,
cell[1].as_i64().unwrap_or(0) as i32,
cell[2].as_i64().unwrap_or(0) as i32,
);
let state = BlockStateId(cell[3].as_u64().unwrap_or(0) as u32);
self.world.set(p.0, p.1, p.2, state)?;
before.insert(p, state.0);
if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) {
self.world.block_entities.insert(p, entity);
}
}
for item in case["items"].as_array().into_iter().flatten() {
let p = (
item[0].as_i64().unwrap_or(0) as i32,
item[1].as_i64().unwrap_or(0) as i32,
item[2].as_i64().unwrap_or(0) as i32,
);
let slot = item[3].as_u64().unwrap_or(0) as usize;
let stack = parse_stack(item[4].as_str().unwrap_or("-"))?;
if let Some(cell) = self
.world
.block_entities
.get_mut(&p)
.and_then(|e| e.slots_mut().get_mut(slot))
{
*cell = stack;
}
}
let mut targets = Vec::new();
for e in case["entities"].as_array().into_iter().flatten() {
targets.push(self.fixture_target(e)?);
}
// Leashable.setLeashedTo: a lead from a target to an earlier one.
for (e, t) in case["entities"]
.as_array()
.into_iter()
.flatten()
.zip(&targets)
{
let (Some(holder), Target::Mob(id)) = (e["leash"].as_u64(), t) else {
continue;
};
let holder = match targets.get(holder as usize) {
Some(Target::Mob(h)) => horizon_client::mobs::leash::Holder::Mob(*h),
_ => continue,
};
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == *id) {
m.extra.leash = Some(holder);
}
}
// Creating the targets must not move the stream the dispenser draws from.
self.world.random = LegacyRandom::new(seed);
self.world.block_log = Some(Vec::new());
self.audio.capture = Some(Vec::new());
LOG.with(|log| *log.borrow_mut() = Some(Vec::new()));
let old_mobs: Vec<u32> = self.mobs.iter().map(|m| m.id).collect();
let old_stands: Vec<u32> = self.armor_stands.iter().map(|s| s.id).collect();
let pos = &case["pos"];
let origin = BlockPos::new(
pos[0].as_i64().unwrap_or(0) as i32,
pos[1].as_i64().unwrap_or(0) as i32,
pos[2].as_i64().unwrap_or(0) as i32,
);
let state = self.world.block(origin.x, origin.y, origin.z);
self.dispense_from(origin, state)?;
let mut out = Vec::new();
let mut changed: Vec<(i32, i32, i32)> = self.world.block_log.take().unwrap_or_default();
changed.sort_unstable();
changed.dedup();
for p in changed {
let now = self.world.block(p.0, p.1, p.2).0;
if before.get(&p).copied().unwrap_or(self.res.facts.air.0) != now {
out.push(format!("set {},{},{} {now}", p.0, p.1, p.2));
}
}
let mut containers: Vec<_> = self.world.block_entities.keys().copied().collect();
containers.sort_unstable();
for p in containers {
let entity = &self.world.block_entities[&p];
for (i, slot) in entity.slots().iter().enumerate() {
if let Some(stack) = slot {
out.push(format!(
"inv {},{},{} {i} {}",
p.0,
p.1,
p.2,
canon_stack(Some(stack))
));
}
}
}
self.fixture_entities(&old_mobs, &old_stands, &mut out);
for (i, t) in targets.iter().enumerate() {
out.push(self.fixture_describe(i, t));
}
let log = LOG.with(|log| log.borrow_mut().take()).unwrap_or_default();
out.extend(log);
for (sound, at, _, _) in self.audio.capture.take().unwrap_or_default() {
out.push(format!("S {} {sound}", floor_pos(at)));
}
out.push(format!("rng {}", self.world.random.next_long()));
Ok(out)
}
/// `EntityType.create` and `snapTo` for one target: no spawn finalization.
fn fixture_target(&mut self, e: &Value) -> Result<Target> {
let kind = e["type"].as_str().unwrap_or("minecraft:pig");
let p = &e["pos"];
let at = horizon_core::geometry::Vec3::new(
p[0].as_f64().unwrap_or(0.0),
p[1].as_f64().unwrap_or(0.0),
p[2].as_f64().unwrap_or(0.0),
);
let yaw = e["yaw"].as_f64().unwrap_or(0.0) as f32;
self.next_entity += 1;
let id = self.next_entity;
if kind == "minecraft:armor_stand" {
self.armor_stands
.push(horizon_client::entities::ArmorStand::new(id, at, yaw));
return Ok(Target::Stand(id));
}
let t = self
.res
.mob_types
.get(kind)
.cloned()
.ok_or_else(|| format!("no mob type {kind}"))?;
let mut mob = Mob::new(id, t, at, yaw);
// EntityType.create equips nothing (that is finalizeSpawn's job).
for slot in [
&mut mob.extra.main_hand,
&mut mob.extra.off_hand,
&mut mob.extra.head,
&mut mob.extra.chest,
&mut mob.extra.legs,
&mut mob.extra.feet,
] {
*slot = None;
}
let s = mob.species();
let flag = |name: &str| e[name].as_bool().unwrap_or(false);
let ageable = !matches!(
s,
Species::Zombie | Species::Skeleton | Species::Bogged | Species::SnowGolem
);
if flag("baby") && ageable {
mob.extra.age = -24000;
}
let tamable =
body_in_head(s) || matches!(s, Species::Cat | Species::Parrot | Species::Ocelot);
if flag("tame") && tamable {
mob.extra.tame = true;
}
if flag("sheared") && matches!(s, Species::Sheep | Species::Bogged | Species::SnowGolem) {
mob.extra.sheared = true;
}
if flag("chest")
&& matches!(
s,
Species::Donkey | Species::Mule | Species::Llama | Species::TraderLlama
)
{
mob.extra.chested = true;
}
if flag("loot") {
mob.extra.pick_up_loot = true;
}
if flag("brown") && s == Species::Mooshroom {
mob.extra.variant = 1;
}
for (slot, snbt) in e["equip"].as_object().into_iter().flatten() {
if let (Some(slot), Some(stack)) = (
Slot::from_name(slot),
parse_stack(snbt.as_str().unwrap_or("-"))?,
) {
mob_set_slot(&mut mob, slot, stack);
}
}
self.mobs.push(mob);
Ok(Target::Mob(id))
}
/// `T` lines: removal, equipment by `EquipmentSlot`, shearing readiness, chests.
fn fixture_describe(&self, index: usize, target: &Target) -> String {
let mut line = format!("T {index} ");
match *target {
Target::Stand(id) => {
line.push_str("minecraft:armor_stand");
let Some(stand) = self.armor_stands.iter().find(|s| s.id == id) else {
line.push_str(" removed");
return line;
};
for (slot, name) in [
(0, "mainhand"),
(1, "offhand"),
(2, "feet"),
(3, "legs"),
(4, "chest"),
(5, "head"),
] {
if let Some(s) = &stand.equipment[slot] {
let _ = write!(line, " {name}={}x{}", s.item, s.count);
}
}
}
Target::Mob(id) => {
let Some(m) = self.mobs.iter().find(|m| m.id == id) else {
return line + "removed";
};
line.push_str(&m.kind.id);
if m.removed || !m.alive() {
line.push_str(" removed");
}
let s = m.species();
let x = &m.extra;
for (slot, name) in [
(Slot::MainHand, "mainhand"),
(Slot::OffHand, "offhand"),
(Slot::Feet, "feet"),
(Slot::Legs, "legs"),
(Slot::Chest, "chest"),
(Slot::Head, "head"),
(Slot::Body, "body"),
(Slot::Saddle, "saddle"),
] {
if let Some(item) = mob_slot_item(m, slot) {
let _ = write!(line, " {name}={item}x1");
}
}
let ready = match s {
Species::Sheep => Some(!x.sheared && !m.is_baby()),
Species::Mooshroom => Some(!m.is_baby()),
Species::Bogged => Some(!x.sheared),
Species::SnowGolem => Some(!x.sheared),
_ => None,
};
if let Some(r) = ready {
line.push_str(if r { " ready" } else { " unready" });
}
if x.chested
&& matches!(
s,
Species::Donkey | Species::Mule | Species::Llama | Species::TraderLlama
)
{
line.push_str(" chest");
}
if x.leash.is_some() {
line.push_str(" leashed");
}
}
}
line
}
/// `N` lines for every entity the dispenser added.
fn fixture_entities(&self, old_mobs: &[u32], old_stands: &[u32], out: &mut Vec<String>) {
let line = |kind: &str, p: [f64; 3], v: [f64; 3], extra: &str| {
let mut l = format!(
"N {kind} {} {} {} {} {} {}",
num(p[0]),
num(p[1]),
num(p[2]),
num(v[0]),
num(v[1]),
num(v[2])
);
if !extra.is_empty() {
l.push(' ');
l.push_str(extra);
}
l
};
for m in self.mobs.iter().filter(|m| !old_mobs.contains(&m.id)) {
let (p, v) = (m.position, m.velocity);
out.push(line(&m.kind.id, [p.x, p.y, p.z], [v.x, v.y, v.z], ""));
}
for s in self
.armor_stands
.iter()
.filter(|s| !old_stands.contains(&s.id))
{
let (p, v) = (s.position, s.velocity);
out.push(line(
"minecraft:armor_stand",
[p.x, p.y, p.z],
[v.x, v.y, v.z],
"",
));
}
for d in &self.dropped {
let (p, v) = (d.position, d.velocity);
out.push(line(
"minecraft:item",
[p.x, p.y, p.z],
[v.x, v.y, v.z],
&canon_stack(Some(&d.stack)),
));
}
for shot in &self.creatures.projectiles {
let kind = match &shot.kind {
ProjectileKind::Arrow {
effect: Some(("minecraft:glowing", 200)),
..
} => "minecraft:spectral_arrow",
ProjectileKind::Arrow { .. } => "minecraft:arrow",
ProjectileKind::Snowball => "minecraft:snowball",
ProjectileKind::Egg => "minecraft:egg",
ProjectileKind::SmallFireball => "minecraft:small_fireball",
ProjectileKind::WindCharge => "minecraft:wind_charge",
_ => "minecraft:unknown_projectile",
};
let (p, v) = (shot.position, shot.velocity);
out.push(line(kind, [p.x, p.y, p.z], [v.x, v.y, v.z], ""));
}
for (kind, p, v) in self.potions.thrown_entities() {
out.push(line(kind, [p.x, p.y, p.z], [v.x, v.y, v.z], ""));
}
for (p, v) in self.rockets.iter().map(|r| r.motion()) {
out.push(line(
"minecraft:firework_rocket",
[p.x, p.y, p.z],
[v.x, v.y, v.z],
"",
));
}
for t in &self.tnts {
let (p, v) = (t.position, t.velocity);
out.push(line(
"minecraft:tnt",
[p.x, p.y, p.z],
[v.x, v.y, v.z],
&format!("fuse={}", t.fuse),
));
}
for b in &self.boats {
let kind = b.entity_type();
let (p, v) = (b.position, b.velocity);
out.push(line(&kind, [p.x, p.y, p.z], [v.x, v.y, v.z], ""));
}
for c in &self.carts {
let (p, v) = (c.position, c.velocity);
out.push(line(c.kind.id(), [p.x, p.y, p.z], [v.x, v.y, v.z], ""));
}
}
}
File diff suppressed because it is too large Load Diff
+9 -4
View File
@@ -29,6 +29,12 @@ pub(super) struct Rocket {
angled: bool,
icon: Option<String>,
}
impl Rocket {
/// Position and motion (the dispenser parity fixture).
pub(super) fn motion(&self) -> (Vec3, Vec3) {
(self.position, self.velocity)
}
}
fn fireworks_of(stack: &ItemStack) -> (u8, Vec<FireworkExplosion>) {
// The item's default component: flight 1, no explosions.
stack
@@ -39,10 +45,9 @@ fn fireworks_of(stack: &ItemStack) -> (u8, Vec<FireworkExplosion>) {
impl Game<'_> {
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| {
0.002297 * (f64::from(r.next_float()) - f64::from(r.next_float()))
};
// FireworkRocketEntity: motion and lifetime come from the rocket's own random.
let r = &mut super::dispenser::entity_random();
let tri = |r: &mut horizon_core::random::LegacyRandom| r.triangle(0.0, 0.002297);
let velocity = Vec3::new(tri(r), 0.05, tri(r));
let lifetime = 10 * (1 + i32::from(flight))
+ r.next_int_bound(6).unwrap_or(0)
+62 -18
View File
@@ -24,6 +24,7 @@ impl Game<'_> {
if self.golem_block(below(1)) == "minecraft:snow_block"
&& self.golem_block(below(2)) == "minecraft:snow_block"
{
// The pattern ("^", "#", "#") is one column.
return Some((
"minecraft:snow_golem",
vec![head, below(1), below(2)],
@@ -38,9 +39,11 @@ impl Game<'_> {
&& self.golem_block(side(0, 2)) == "minecraft:iron_block"
&& [-1, 1].iter().all(|&s| air(side(s, 0)) && air(side(s, 2)))
{
let mut blocks = vec![head];
blocks.extend((-1..=1).map(|s| side(s, 1)));
blocks.push(side(0, 2));
// Every cell of ("~^~", "###", "~#~"), the air ones included.
let blocks = (-1..=1)
.flat_map(|s| (0..3).map(move |row| (s, row)))
.map(|(s, row)| side(s, row))
.collect();
return Some(("minecraft:iron_golem", blocks, side(0, 2)));
}
}
@@ -58,27 +61,68 @@ impl Game<'_> {
let Some((kind, blocks, base)) = self.find_golem(head) else {
return self.try_spawn_copper_golem(head);
};
for p in blocks {
let state = self.world.block(p[0], p[1], p[2]);
self.destroy_particles(p, state);
self.level_set(p, self.world.air)?;
}
// CarvedPumpkinBlock.spawnGolemInWorld
self.clear_pattern_blocks(&blocks)?;
let at = [
f64::from(base[0]) + 0.5,
f64::from(base[1]) + 0.05,
f64::from(base[2]) + 0.5,
];
if let Some(id) = self.spawn_mob(kind, at, false)
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
{
m.yaw = 0.0;
m.body_yaw = 0.0;
m.head_yaw = 0.0;
m.previous_yaw = 0.0;
m.previous_body_yaw = 0.0;
m.previous_head_yaw = 0.0;
self.create_triggered(kind, at, 0.0);
self.update_pattern_blocks(&blocks)
}
/// Whether placing a golem head at `head` completes a snow or iron golem.
pub(super) fn completes_golem(&self, head: [i32; 3]) -> bool {
self.find_golem(head).is_some()
}
/// `EntityType.create(level, TRIGGERED)` and `snapTo`: a built golem or
/// wither has no spawn finalization and draws nothing from the level.
pub(super) fn create_triggered(&mut self, kind: &str, at: [f64; 3], yaw: f32) -> Option<u32> {
let t = self.res.mob_types.get(kind).cloned()?;
self.next_entity += 1;
let mut mob = horizon_client::mobs::Mob::new(
self.next_entity,
t,
horizon_core::geometry::Vec3::new(at[0], at[1], at[2]),
yaw,
);
mob.head_yaw = yaw;
mob.body_yaw = yaw;
mob.previous_yaw = yaw;
mob.previous_body_yaw = yaw;
mob.previous_head_yaw = yaw;
let id = mob.id;
self.mobs.push(mob);
Some(id)
}
/// `CarvedPumpkinBlock.clearPatternBlocks`: every cell of the match
/// becomes air (flags 2) with its destroy event (2001).
pub(super) fn clear_pattern_blocks(&mut self, cells: &[[i32; 3]]) -> Result<()> {
let air = self.world.air;
for &p in cells {
let state = self.world.block(p[0], p[1], p[2]);
let pos = horizon_core::position::BlockPos::new(p[0], p[1], p[2]);
self.with_level(|b, level, ticks| b.set_block(level, ticks, pos, air, 2));
self.level_events
.push(horizon_world::level::LevelEvent::LevelEvent {
id: 2001,
pos,
data: state.0 as i32,
});
}
Ok(())
self.process_level_events()
}
/// `CarvedPumpkinBlock.updatePatternBlocks`: neighbours of every cell
/// hear that air arrived.
pub(super) fn update_pattern_blocks(&mut self, cells: &[[i32; 3]]) -> Result<()> {
let air = self.world.air;
for &p in cells {
let pos = horizon_core::position::BlockPos::new(p[0], p[1], p[2]);
self.with_level(|b, level, ticks| {
b.update_neighbors_at(level, ticks, pos, b.block(air))
});
}
self.process_level_events()
}
/// A pumpkin on a copper block: the block turns into the matching copper
/// chest (facing the pumpkin's way) and a copper golem appears where the
+3 -7
View File
@@ -8,7 +8,6 @@ use horizon_client::{
mesher::Vertex,
mobs::leash::{self, Holder, Pending},
};
use horizon_core::random::RandomSource;
use horizon_world::nbt::Tag;
/// `Vec3.yRot(angle)`.
@@ -66,13 +65,10 @@ impl Game<'_> {
})
.collect()
}
/// `Entity.spawnAtLocation(level, Items.LEAD)`: the item entity draws its
/// motion from its own random, not the level's.
fn drop_lead_item(&mut self, at: [f64; 3]) {
let r = &mut self.world.random;
let v = [
f64::from(r.next_float()) * 0.2 - 0.1,
0.2,
f64::from(r.next_float()) * 0.2 - 0.1,
];
let v = super::dispenser::new_item_motion();
self.spawn_item(ItemStack::new("minecraft:lead", 1), at, v, 10);
}
/// `Leashable.dropLeash` / `removeLeash`: the lead falls as an item.
+29 -3
View File
@@ -28,6 +28,9 @@ pub(super) enum CartKind {
Hopper,
Furnace,
Tnt,
/// `MinecartCommandBlock`; its command block holds no command, so an
/// activator rail runs nothing.
CommandBlock,
}
impl CartKind {
pub fn from_id(id: &str) -> Option<Self> {
@@ -37,6 +40,7 @@ impl CartKind {
"hopper_minecart" => Self::Hopper,
"furnace_minecart" => Self::Furnace,
"tnt_minecart" => Self::Tnt,
"command_block_minecart" => Self::CommandBlock,
_ => return None,
})
}
@@ -47,6 +51,7 @@ impl CartKind {
Self::Hopper => "minecraft:hopper_minecart",
Self::Furnace => "minecraft:furnace_minecart",
Self::Tnt => "minecraft:tnt_minecart",
Self::CommandBlock => "minecraft:command_block_minecart",
}
}
fn slots(self) -> usize {
@@ -192,6 +197,7 @@ impl CartModels {
CartKind::Hopper,
CartKind::Furnace,
CartKind::Tnt,
CartKind::CommandBlock,
];
let models = kinds
.into_iter()
@@ -981,6 +987,8 @@ impl Game<'_> {
self.prime_cart(&mut c);
self.carts[i] = c;
}
// BaseCommandBlock.usedBy: only an operator in creative opens it.
CartKind::CommandBlock => return false,
}
self.swing_arm();
true
@@ -990,9 +998,10 @@ impl Game<'_> {
let Some(key) = self.container.filter(|k| k.1 == CART_KEY_Y) else {
return;
};
if let Some(BlockEntity::Chest(items)) = self.world.block_entities.remove(&key)
&& let Some(c) = self.carts.iter_mut().find(|c| c.id as i32 == key.2)
{
let Some(BlockEntity::Chest(items)) = self.world.block_entities.remove(&key) else {
return;
};
if let Some(c) = self.carts.iter_mut().find(|c| c.id as i32 == key.2) {
c.items = items;
let at = [c.position.x, c.position.y, c.position.z];
if c.kind == CartKind::Chest {
@@ -1000,15 +1009,24 @@ impl Game<'_> {
self.audio
.play("minecraft:block.chest.close", Some(at), 0.5, pitch);
}
} else if let Some(b) = self.boats.iter_mut().find(|b| b.id as i32 == key.2) {
b.items = items;
}
}
/// The open cart's kind when a cart container is shown.
pub(super) fn open_cart_kind(&self) -> Option<CartKind> {
let key = self.container.filter(|k| k.1 == CART_KEY_Y)?;
// A chest boat's chest shows like a chest minecart's.
self.carts
.iter()
.find(|c| c.id as i32 == key.2)
.map(|c| c.kind)
.or_else(|| {
self.boats
.iter()
.any(|b| b.chest && b.id as i32 == key.2)
.then_some(CartKind::Chest)
})
}
/// `VehicleEntity.hurtServer` from the player's attack.
pub(super) fn attack_cart(&mut self, damage: f32) -> bool {
@@ -1121,6 +1139,7 @@ impl Game<'_> {
],
),
CartKind::Tnt => registry.default_state("minecraft:tnt"),
CartKind::CommandBlock => registry.default_state("minecraft:command_block"),
}
}
/// `AbstractMinecartRenderer` (old render): on the rail between the
@@ -1283,6 +1302,13 @@ impl Minecart {
put("Fuel", Tag::Short(self.fuel as i16));
}
CartKind::Tnt => put("fuse", Tag::Int(self.fuse)),
// BaseCommandBlock.save of an empty command block.
CartKind::CommandBlock => {
put("Command", Tag::String(JavaString::from("")));
put("SuccessCount", Tag::Int(0));
put("TrackOutput", Tag::Byte(1));
put("UpdateLastExecution", Tag::Byte(1));
}
CartKind::Rideable => {}
}
}
+19 -9
View File
@@ -198,18 +198,27 @@ impl Game<'_> {
});
}
}
k if super::boats::boat_wood(k).is_some()
&& self
.boat_models
.models
.contains_key(super::boats::boat_wood(k).unwrap_or("")) =>
k if super::boats::any_boat_wood(k)
.is_some_and(|(wood, chest)| self.boat_models.has(wood, chest)) =>
{
if let Some((position, velocity, yaw)) = entity_nbt::boat_from_nbt(&tag) {
self.next_entity += 1;
let id = self.next_entity;
let wood =
std::sync::Arc::from(super::boats::boat_wood(k).unwrap_or("oak"));
let mut b = super::boats::Boat::new(id, wood, position, yaw);
let (wood, chest) =
super::boats::any_boat_wood(k).unwrap_or(("oak", false));
let mut b = super::boats::Boat::new(
id,
std::sync::Arc::from(wood),
position,
yaw,
);
if chest {
b = b.with_chest();
b.items = horizon_client::save::decode_items(
tag.get("Items"),
super::boats::CHEST_SLOTS,
);
}
b.velocity = velocity;
self.remember(id, uuid, tag);
self.boats.push(b);
@@ -536,12 +545,13 @@ impl Game<'_> {
.copied()
.unwrap_or_else(random_uuid);
let tag = entity_nbt::boat_to_nbt(
&b.wood,
&b.entity_type(),
b.position,
b.velocity,
b.yaw,
uuid,
self.persist.raw.get(&b.id),
b.chest.then_some(&b.items[..]),
);
out.entry(chunk_of(b.position)).or_default().push(tag);
}
+21
View File
@@ -65,6 +65,27 @@ pub(super) struct PotionState {
std::collections::HashMap<String, horizon_core::random::XoroshiroRandom>,
}
impl PotionState {
/// Thrown potions in flight as (entity type, position, motion), for the
/// dispenser parity fixture.
pub(super) fn thrown_entities(&self) -> Vec<(&'static str, Vec3, Vec3)> {
self.thrown
.iter()
.map(|t| {
let kind = match &*t.stack.item {
"minecraft:lingering_potion" => "minecraft:lingering_potion",
"minecraft:experience_bottle" => "minecraft:experience_bottle",
_ => "minecraft:splash_potion",
};
(kind, t.position, t.velocity)
})
.collect()
}
pub(super) fn clear_thrown(&mut self) {
self.thrown.clear();
}
}
impl Game<'_> {
/// Right-click with a potion, splash/lingering potion or glass bottle.
pub(super) fn use_potion_item(&mut self, stack: &ItemStack) -> horizon_client::Result<bool> {
+8
View File
@@ -437,6 +437,14 @@ impl Game<'_> {
/// `Level.gameEvent`: tell the listeners within reach.
pub(super) fn post_game_event(&mut self, event: &'static str, pos: [f64; 3], ctx: Context) {
super::dispense_fixture::record(|| {
format!(
"G {},{},{} {event}",
pos[0].floor() as i32,
pos[1].floor() as i32,
pos[2].floor() as i32
)
});
if self.remote.is_some() || !self.sculk.tables.built {
return;
}
+11 -16
View File
@@ -40,35 +40,30 @@ impl Game<'_> {
if !ok {
continue;
}
for row in 0..3 {
for c in 0..3 {
let p = at(c, row);
let state = self.world.block(p[0], p[1], p[2]);
if !self.res.facts.is_air(state) {
self.destroy_particles(p, state);
self.world.set(p[0], p[1], p[2], self.world.air)?;
}
}
}
// WitherSkullBlock.checkSpawn: clear the pattern, the wither
// appears on the middle of the bottom row, then neighbours update.
let cells: Vec<[i32; 3]> = (0..3)
.flat_map(|c| (0..3).map(move |row| (c, row)))
.map(|(c, row)| at(c, row))
.collect();
self.clear_pattern_blocks(&cells)?;
let base = at(1, 2);
let at = [
f64::from(base[0]) + 0.5,
f64::from(base[1]) + 0.55,
f64::from(base[2]) + 0.5,
];
if let Some(id) = self.spawn_mob("minecraft:wither", at, true)
let yaw = if ax == 1 { 0.0 } else { 90.0 };
if let Some(id) = self.create_triggered("minecraft:wither", at, yaw)
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
{
let yaw = if ax == 1 { 0.0 } else { 90.0 };
m.yaw = yaw;
m.body_yaw = yaw;
m.previous_body_yaw = yaw;
m.head_yaw = yaw;
m.persistent = true;
horizon_client::mobs::wither::make_invulnerable(m);
let view =
self.mob_entity(&self.mobs.iter().find(|m| m.id == id).cloned().unwrap());
self.trigger_entity("minecraft:summoned_entity", "entity", &view);
}
self.update_pattern_blocks(&cells)?;
return Ok(());
}
}
+58 -10
View File
@@ -526,13 +526,27 @@ impl Items {
pub fn has_loot_table(&self, id: &str) -> bool {
self.loot.contains_key(id)
}
/// The server random sequence the block's loot table draws from.
pub fn block_loot_sequence(
&self,
registry: &BlockRegistry,
state: BlockStateId,
) -> Option<String> {
let block = registry.state(state)?;
let name = block.name.trim_start_matches("minecraft:");
let standing = name.replacen("_wall_", "_", 1);
let standing = standing.strip_prefix("wall_").unwrap_or(&standing);
let standing = standing.replacen("wall_", "", 1);
self.loot_sequence(&format!("minecraft:blocks/{name}"))
.or_else(|| self.loot_sequence(&format!("minecraft:blocks/{standing}")))
}
/// Evaluate the block's loot table for a player break without explosions.
pub fn block_drops(
&self,
registry: &BlockRegistry,
state: BlockStateId,
held: Option<&ItemStack>,
random: &mut LegacyRandom,
random: &mut impl RandomSource,
) -> Vec<ItemStack> {
let Some(block) = registry.state(state) else {
return vec![];
@@ -581,6 +595,34 @@ impl Items {
};
ctx.evaluate(table, random)
}
/// The server random sequence a loot table draws from (`random_sequence`):
/// vanilla's `LootContext.Builder.create` uses it instead of the level random.
pub fn loot_sequence(&self, id: &str) -> Option<String> {
self.loot.get(id)?["random_sequence"]
.as_str()
.map(str::to_owned)
}
/// `loot_table` drawing from any random (a random sequence).
pub fn loot_table_from(
&self,
id: &str,
killed_by_player: bool,
held: Option<&ItemStack>,
random: &mut impl RandomSource,
) -> Vec<ItemStack> {
let Some(table) = self.loot.get(id) else {
return vec![];
};
let empty = BTreeMap::new();
let ctx = LootContext {
items: self,
block: "",
properties: &empty,
held,
killed_by_player,
};
ctx.evaluate(table, random)
}
pub fn entity_drops(
&self,
entity: &str,
@@ -604,14 +646,15 @@ impl Items {
}
}
impl LootContext<'_> {
fn evaluate(&self, table: &Value, random: &mut LegacyRandom) -> Vec<ItemStack> {
fn evaluate(&self, table: &Value, random: &mut impl RandomSource) -> Vec<ItemStack> {
let ctx = self;
let mut out = Vec::new();
for pool in table["pools"].as_array().into_iter().flatten() {
if !ctx.conditions(pool, random) {
continue;
}
let rolls = ctx.number(&pool["rolls"], random).max(0.0) as u32;
// LootPool: rolls.getInt (Mth.randomBetweenInclusive for uniform rolls).
let rolls = ctx.int_number(&pool["rolls"], random).max(0) as u32;
for _ in 0..rolls {
let mut produced = Vec::new();
ctx.choose(
@@ -643,7 +686,7 @@ impl LootContext<'_> {
fn enchantment_level(&self, id: &str) -> u32 {
self.held.map_or(0, |h| h.enchantment_level(id))
}
fn number(&self, v: &Value, random: &mut LegacyRandom) -> f32 {
fn number(&self, v: &Value, random: &mut impl RandomSource) -> f32 {
match v {
Value::Number(n) => n.as_f64().unwrap_or(0.0) as f32,
Value::Object(o) => match o
@@ -674,7 +717,7 @@ impl LootContext<'_> {
_ => 1.0,
}
}
fn int_number(&self, v: &Value, random: &mut LegacyRandom) -> i32 {
fn int_number(&self, v: &Value, random: &mut impl RandomSource) -> i32 {
if let Value::Object(o) = v
&& o.get("type")
.and_then(Value::as_str)
@@ -691,7 +734,7 @@ impl LootContext<'_> {
}
self.number(v, random).round() as i32
}
fn condition(&self, c: &Value, random: &mut LegacyRandom) -> bool {
fn condition(&self, c: &Value, random: &mut impl RandomSource) -> bool {
let (kind, c) = match c {
Value::String(s) => (s.as_str(), &Value::Null),
Value::Object(o) => (o.get("type").and_then(Value::as_str).unwrap_or(""), c),
@@ -800,7 +843,7 @@ impl LootContext<'_> {
_ => true,
}
}
fn conditions(&self, o: &Value, random: &mut LegacyRandom) -> bool {
fn conditions(&self, o: &Value, random: &mut impl RandomSource) -> bool {
if let Some(c) = o.get("condition")
&& !self.condition(c, random)
{
@@ -816,7 +859,7 @@ impl LootContext<'_> {
fn expand(
&self,
e: &Value,
random: &mut LegacyRandom,
random: &mut impl RandomSource,
out: &mut Vec<(i32, ItemStack, Value)>,
) -> bool {
if !self.conditions(e, random) {
@@ -874,7 +917,12 @@ impl LootContext<'_> {
_ => false,
}
}
fn choose(&self, entries: &[Value], random: &mut LegacyRandom, produced: &mut Vec<ItemStack>) {
fn choose(
&self,
entries: &[Value],
random: &mut impl RandomSource,
produced: &mut Vec<ItemStack>,
) {
let mut candidates = Vec::new();
for e in entries {
self.expand(e, random, &mut candidates);
@@ -901,7 +949,7 @@ impl LootContext<'_> {
self.modifiers(&modifiers, &mut stack, random);
produced.push(stack);
}
fn modifiers(&self, m: &Value, stack: &mut ItemStack, random: &mut LegacyRandom) {
fn modifiers(&self, m: &Value, stack: &mut ItemStack, random: &mut impl RandomSource) {
let list: Vec<&Value> = match m {
Value::Array(a) => a.iter().collect(),
Value::Object(_) => vec![m],
+14 -1
View File
@@ -995,6 +995,18 @@ impl Mob {
},
kind,
};
// setCanPickUpLoot(true) in the Villager, AbstractPiglin, Allay,
// Dolphin, Fox and Panda constructors.
mob.extra.pick_up_loot = matches!(
mob.species(),
Species::Villager
| Species::Piglin
| Species::PiglinBrute
| Species::Allay
| Species::Dolphin
| Species::Fox
| Species::Panda
);
ai::register(&mut mob);
mob
}
@@ -1216,7 +1228,8 @@ impl Mob {
/// Mob.playSound with LivingEntity.getVoicePitch.
pub fn voice(&mut self, event: &'static str, events: &mut Vec<MobEvent>) {
let pitch = self.voice_pitch();
let at = [self.position.x, self.eye_y(), self.position.z];
// Entity.playSound: at the entity's feet.
let at = [self.position.x, self.position.y, self.position.z];
events.push(MobEvent::Sound(event, at, ai::sound_volume(self), pitch));
}
}
+4
View File
@@ -420,6 +420,10 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
// Entity.baseTick ends with Leashable.tickLeash.
super::leash::tick(m, w, events);
}
/// `Mob.playAmbientSound` on demand: a spawn egg or a mob bucket just placed `m`.
pub fn ambient_sound(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
play_ambient(m, w, events);
}
fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
let sound = match m.species() {
// Warden.getAmbientSound: by anger, silent while roaring or digging.
+21 -5
View File
@@ -19,6 +19,10 @@ pub enum BucketContent {
Fluid(FluidKind),
/// `SolidBucketItem`: the block placed into an empty space (powder snow).
Powder,
/// `MobBucketItem` holding water: its empty sound posts no `FLUID_PLACE`.
MobWater,
/// `MobBucketItem` without a fluid (the sulfur cube bucket): only the sound.
Nothing,
}
impl<L: LevelAccess + ?Sized> Sim<'_, L> {
@@ -58,14 +62,23 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
if self.is_in_valid_bounds(pos) && b.is_air(self.state(pos)) {
let snow = b.table.default_state(b.named.powder_snow);
self.set_block_and_update(pos, snow);
// SolidBucketItem.emptyContents: one FLUID_PLACE, then the place sound.
self.game_event(pos, "minecraft:fluid_place");
self.empty_sound(pos, sound);
let sound: Arc<str> = sound.into();
self.sound(pos, &sound, 1.0, 1.0);
return true;
}
return false;
}
BucketContent::Nothing => {
let sound: Arc<str> = sound.into();
self.sound(pos, &sound, 1.0, 1.0);
return true;
}
BucketContent::MobWater => FluidKind::Water,
BucketContent::Fluid(fluid) => fluid,
};
let mob = content == BucketContent::MobWater;
let state = self.state(pos);
// canBeReplaced(fluid): replaceable or not solid (portals refuse).
let may_replace = !b.instance_of(state, Class::EndPortal)
@@ -91,7 +104,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
}
if liquid_container && water {
self.place_liquid(pos, state, FluidState::new(FluidKind::Water, 8, false));
self.empty_sound(pos, sound);
self.empty_sound(pos, sound, mob);
return true;
}
if may_replace && !b.instance_of(state, Class::Liquid) {
@@ -112,13 +125,16 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
{
return false;
}
self.empty_sound(pos, sound);
self.empty_sound(pos, sound, mob);
true
}
fn empty_sound(&mut self, pos: BlockPos, sound: &str) {
/// `playEmptySound`: `MobBucketItem` overrides it without the game event.
fn empty_sound(&mut self, pos: BlockPos, sound: &str, mob: bool) {
let sound: Arc<str> = sound.into();
self.sound(pos, &sound, 1.0, 1.0);
self.game_event(pos, "minecraft:fluid_place");
if !mob {
self.game_event(pos, "minecraft:fluid_place");
}
}
}
+2
View File
@@ -265,7 +265,9 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
return false;
}
if b.is_block(state, b.named.powder_snow) {
// PowderSnowBlock.pickupBlock: the block breaks with its particles and sound.
self.set_block(pos, b.air(), 11);
self.level_event(2001, pos, state.0 as i32);
return true;
}
false
+15 -2
View File
@@ -452,9 +452,22 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
// ---- misc helpers ----
/// `BaseFireBlock.onPlace` (portal ignition is not modelled).
/// `BaseFireBlock.onPlace`: a fire inside an empty obsidian frame (in the
/// overworld or the nether) lights it, otherwise one that cannot survive
/// goes out.
fn base_fire_on_place(&mut self, pos: BlockPos, state: BlockStateId, same: bool) {
if !same && !self.can_survive(state, pos) {
if same {
return;
}
if matches!(
self.level.dimension(),
super::Dimension::Overworld | super::Dimension::Nether
) && let Some(shape) = self.find_empty_portal_shape(pos, true)
{
self.create_portal_blocks(&shape);
return;
}
if !self.can_survive(state, pos) {
self.remove_block(pos, false);
}
}
+20
View File
@@ -549,6 +549,26 @@ impl Behaviours {
) -> bool {
self.sim(level, ticks).player_destroy(pos, creative)
}
/// `BaseFireBlock.getState(level, pos)`: soul fire on its base blocks,
/// otherwise fire shaped by its neighbours.
pub fn fire_state_for<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
) -> BlockStateId {
self.sim(level, ticks).fire_state_for(pos)
}
/// `BaseFireBlock.canBePlacedAt(level, pos, forwardDirection)`.
pub fn fire_can_be_placed_at<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
forward: horizon_core::geometry::Direction,
) -> bool {
self.sim(level, ticks).fire_can_be_placed_at(pos, forward)
}
/// `BlockState.canSurvive(level, pos)`.
pub fn can_survive<L: LevelAccess + ?Sized>(
&self,
+23
View File
@@ -1595,6 +1595,29 @@ impl Behaviours {
) -> PlaceOutcome {
self.sim(level, ticks).place(ctx)
}
/// `DirectionalPlaceContext.canPlace`: whether the block at the clicked
/// position can be replaced by the item (a dispenser places only there).
pub fn directional_can_place<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
ctx: &PlaceContext,
) -> bool {
let sim = self.sim(level, ticks);
let inner = Ctx {
pos: ctx.clicked_pos,
hit_pos: ctx.clicked_pos,
face: ctx.face,
hit: ctx.hit,
inside: ctx.inside,
yaw: ctx.yaw,
pitch: ctx.pitch,
sneaking: ctx.sneaking,
item: ctx.item.clone(),
replace_clicked: true,
};
sim.can_be_replaced(sim.state(ctx.clicked_pos), &inner)
}
/// The position and state `BlockItem.place` would place for `ctx`, without
/// writing anything (None when vanilla's placement fails).
pub fn placement_state<L: LevelAccess + ?Sized>(
+56 -1
View File
@@ -1,7 +1,7 @@
//! `PortalShape`: the obsidian frame search used by nether portal blocks.
use super::{LevelAccess, Sim, update::rel};
use crate::registry::BlockStateId;
use horizon_core::{geometry::Direction, position::BlockPos};
use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource};
const MIN_WIDTH: i32 = 2;
const MAX_WIDTH: i32 = 21;
@@ -126,4 +126,59 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
};
shape
}
/// `PortalShape.findEmptyPortalShape`: a valid frame holding no portal
/// block yet, on the preferred axis first.
pub fn find_empty_portal_shape(&self, pos: BlockPos, x_axis: bool) -> Option<PortalShape> {
[x_axis, !x_axis]
.into_iter()
.map(|axis| self.find_portal_shape(pos, axis))
.find(|shape| shape.is_valid() && shape.portal_blocks == 0)
}
/// `PortalShape.createPortalBlocks`: fill the frame (flags 18).
pub fn create_portal_blocks(&mut self, shape: &PortalShape) {
let b = self.b;
let base = b.default_of(b.named.nether_portal);
let state = b
.table
.with_text(base, b.props.axis, if shape.x_axis { "x" } else { "z" })
.unwrap_or(base);
for h in 0..shape.height {
for w in 0..shape.width {
let at = step(step(shape.bottom_left, Direction::Up, h), shape.right, w);
self.set_block(at, state, 18);
}
}
}
/// `BaseFireBlock.canBePlacedAt(level, pos, forwardDirection)`: air where
/// fire would survive, or the inside of an empty portal frame (vertical
/// directions pick the frame axis with the level random).
pub fn fire_can_be_placed_at(&mut self, pos: BlockPos, forward: Direction) -> bool {
if !self.b.is_air(self.state(pos)) {
return false;
}
if self.can_survive(self.fire_state_for(pos), pos) {
return true;
}
// isPortal
if !matches!(
self.level.dimension(),
super::Dimension::Overworld | super::Dimension::Nether
) {
return false;
}
for face in Direction::ALL {
if self.portal_frame(self.state(rel(pos, face))) {
// getCounterClockWise().getAxis(): north/south turn to X.
let x_axis = match forward {
Direction::North | Direction::South => true,
Direction::West | Direction::East => false,
Direction::Up | Direction::Down => {
self.random().next_int_bound(2).unwrap_or(0) == 0
}
};
return self.find_empty_portal_shape(pos, x_axis).is_some();
}
}
false
}
}
@@ -30,6 +30,8 @@ public final class ParityData {
public static RegistryAccess access;
public static RegistryOps<Tag> ops;
public static ServerLevel level;
/** The loot tables of the vanilla data pack. */
public static ReloadableServerRegistries.Holder loot;
public static void init() throws Exception {
SharedConstants.tryDetectVersion();
@@ -44,6 +46,7 @@ public final class ParityData {
RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join();
var worldLayers = layers.replaceFrom(RegistryLayer.WORLD, world);
var loaded = ReloadableServerRegistries.reload(worldLayers, staticTags, resources, Runnable::run).join();
loot = new ReloadableServerRegistries.Holder(loaded.lookupWithUpdatedTags());
lookup = loaded.lookupWithUpdatedTags();
var components = BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(lookup);
staticTags.forEach(Registry.PendingTags::apply);
@@ -91,6 +91,12 @@ public final class VanillaBlockUpdateOracle {
return old;
}
@Override
public void markUnsaved() { }
@Override
public BlockState getBlockState(BlockPos pos) { return world.getBlockState(pos); }
@Override
public FluidState getFluidState(BlockPos pos) { return world.getFluidState(pos); }
@Override
public net.minecraft.world.level.chunk.status.ChunkStatus getPersistedStatus() {
return net.minecraft.world.level.chunk.status.ChunkStatus.FULL;
}
@@ -145,6 +151,23 @@ public final class VanillaBlockUpdateOracle {
}
@Override public LevelChunk getChunkAt(BlockPos p) { return chunk; }
@Override public LevelChunk getChunk(int x, int z) { return chunk; }
@Override public net.minecraft.world.level.chunk.ChunkAccess getChunk(int x, int z, net.minecraft.world.level.chunk.status.ChunkStatus status, boolean load) { return chunk; }
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;
}
net.minecraft.server.ServerScoreboard scoreboard;
@Override public net.minecraft.server.ServerScoreboard getScoreboard() {
if (scoreboard == null) scoreboard = new net.minecraft.server.ServerScoreboard(server);
return scoreboard;
}
/** The biome every position reads (plains), for the oracles that load the world registries. */
net.minecraft.core.Holder<net.minecraft.world.level.biome.Biome> biome;
@Override public net.minecraft.core.Holder<net.minecraft.world.level.biome.Biome> getBiome(BlockPos p) {
if (biome == null) biome = registryAccess().lookupOrThrow(net.minecraft.core.registries.Registries.BIOME).getOrThrow(net.minecraft.world.level.biome.Biomes.PLAINS);
return biome;
}
@Override public boolean isLoaded(BlockPos p) { return true; }
@Override public boolean hasChunkAt(BlockPos p) { return true; }
@Override public boolean hasChunksAt(int x0, int z0, int x1, int z1) { return true; }
@@ -160,7 +183,7 @@ public final class VanillaBlockUpdateOracle {
@Override public LevelTicks<Fluid> getFluidTicks() { return fluidTicks; }
@Override public void sendBlockUpdated(BlockPos p, BlockState a, BlockState b, int f) { }
@Override public void setBlocksDirty(BlockPos p, BlockState a, BlockState b) { }
@Override public net.minecraft.core.RegistryAccess registryAccess() { return RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY); }
@Override public net.minecraft.core.RegistryAccess registryAccess() { return registries != null ? registries : RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY); }
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return FeatureFlags.DEFAULT_FLAGS; }
@Override public GameRules getGameRules() { return rules; }
@Override public net.minecraft.server.MinecraftServer getServer() { return server; }
@@ -174,12 +197,51 @@ public final class VanillaBlockUpdateOracle {
@Override public boolean isRainingAt(BlockPos p) { return raining; }
@Override public boolean isUnobstructed(BlockState state, BlockPos pos, net.minecraft.world.phys.shapes.CollisionContext c) { return true; }
@Override public boolean isUnobstructed(Entity entity) { return true; }
@Override public List<Entity> getEntities(Entity except, AABB box, java.util.function.Predicate<? super Entity> filter) { return List.of(); }
@Override public <T extends Entity> List<T> getEntitiesOfClass(Class<T> type, AABB box, java.util.function.Predicate<? super T> filter) { return List.of(); }
// Entities exist only when a harness opts in (the dispenser oracle);
// they are searched in the order they were added, as within one entity section.
List<Entity> entities;
net.minecraft.core.RegistryAccess registries;
@Override public List<Entity> getEntities(Entity except, AABB box, java.util.function.Predicate<? super Entity> filter) {
if (entities == null) return List.of();
List<Entity> out = new ArrayList<>();
for (Entity e : List.copyOf(entities)) if (e != except && !e.isRemoved() && e.getBoundingBox().intersects(box) && filter.test(e)) out.add(e);
return out;
}
@Override public <T extends Entity> void getEntities(net.minecraft.world.level.entity.EntityTypeTest<Entity, T> type, AABB box, java.util.function.Predicate<? super T> filter, List<? super T> out, int max) {
if (entities == null) return;
for (Entity e : List.copyOf(entities)) {
T t = type.tryCast(e);
if (t != null && !e.isRemoved() && e.getBoundingBox().intersects(box) && filter.test(t)) {
out.add(t);
if (out.size() >= max) return;
}
}
}
/** ServerLevel.getEntity(id) over the level's entities. */
@Override public Entity getEntity(int id) {
if (entities == null) return null;
for (Entity e : entities) if (e.getId() == id && !e.isRemoved()) return e;
return null;
}
/** Every entity of the level (no area), as ServerLevel's entity getter would. */
@Override public <T extends Entity> void getEntities(net.minecraft.world.level.entity.EntityTypeTest<Entity, T> type, java.util.function.Predicate<? super T> filter, List<? super T> out, int max) {
if (entities == null) return;
for (Entity e : List.copyOf(entities)) {
T t = type.tryCast(e);
if (t != null && !e.isRemoved() && filter.test(t)) {
out.add(t);
if (out.size() >= max) return;
}
}
}
@Override public <T extends Entity> List<T> getEntitiesOfClass(Class<T> type, AABB box, java.util.function.Predicate<? super T> filter) {
return getEntities(net.minecraft.world.level.entity.EntityTypeTest.forClass(type), box, filter);
}
@Override public List<net.minecraft.server.level.ServerPlayer> players() { return List.of(); }
@Override public net.minecraft.world.entity.player.Player getNearestPlayer(double x, double y, double z, double d, boolean b) { return null; }
@Override public boolean addFreshEntity(Entity entity) {
emit("E " + BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType()));
if (entities != null) entities.add(entity);
return true;
}
@Override public void levelEvent(Entity source, int type, BlockPos p, int data) { emit("L " + type + " " + pos(p) + " " + data); }
@@ -187,7 +249,7 @@ public final class VanillaBlockUpdateOracle {
emit("S " + pos(BlockPos.containing(x, y, z)) + " " + sound.value().location());
}
@Override public void playSeededSound(Entity except, Entity src, net.minecraft.core.Holder<SoundEvent> sound, SoundSource source, float volume, float pitch, long seed) {
emit("S entity " + sound.value().location());
emit("S " + (entities != null ? pos(BlockPos.containing(src.position())) : "entity") + " " + sound.value().location());
}
@Override public void gameEvent(net.minecraft.core.Holder<net.minecraft.world.level.gameevent.GameEvent> e, Vec3 p, net.minecraft.world.level.gameevent.GameEvent.Context c) {
emit("G " + pos(BlockPos.containing(p)) + " " + e.getRegisteredName());
@@ -252,6 +314,12 @@ public final class VanillaBlockUpdateOracle {
return attributes;
}
@Override public net.minecraft.world.level.dimension.DimensionType dimensionType() { return OVERWORLD_TYPE; }
/** The overworld (fire in an obsidian frame lights a portal here). */
@Override public net.minecraft.resources.ResourceKey<net.minecraft.world.level.Level> dimension() { return net.minecraft.world.level.Level.OVERWORLD; }
@Override public long getOverworldClockTime() { return DAY.totalTicks(); }
@Override public float getMoonBrightness(BlockPos p) {
return net.minecraft.world.level.dimension.DimensionType.MOON_BRIGHTNESS_PER_PHASE[environmentAttributes().getValue(net.minecraft.world.attribute.EnvironmentAttributes.MOON_PHASE, p).index()];
}
@Override public net.minecraft.world.level.storage.ServerLevelData getLevelData() { return LEVEL_DATA; }
@Override public boolean anyPlayerCloseEnoughForSpawning(BlockPos p) { return false; }
@Override public void playSound(Entity except, double x, double y, double z, SoundEvent sound, SoundSource source, float volume, float pitch) {
@@ -339,13 +407,15 @@ public final class VanillaBlockUpdateOracle {
static final class Loot extends net.minecraft.server.ReloadableServerRegistries.Holder {
World world;
/** The real loot tables, for the oracles that compare drops (the dispenser's). */
net.minecraft.server.ReloadableServerRegistries.Holder delegate;
Loot() {
super(null);
}
@Override
public net.minecraft.world.level.storage.loot.LootTable getLootTable(net.minecraft.resources.ResourceKey<net.minecraft.world.level.storage.loot.LootTable> id) {
world.emit("D " + id.identifier());
return net.minecraft.world.level.storage.loot.LootTable.EMPTY;
return delegate != null ? delegate.getLootTable(id) : net.minecraft.world.level.storage.loot.LootTable.EMPTY;
}
}
@@ -371,6 +441,12 @@ public final class VanillaBlockUpdateOracle {
@Override public boolean isPublished() { return false; }
@Override public boolean shouldInformAdmins() { return false; }
@Override public boolean isSingleplayerOwner(net.minecraft.server.players.NameAndId id) { return false; }
net.minecraft.world.RandomSequences sequences;
/** Loot tables with a random_sequence draw from the server's sequences (world seed 0). */
@Override public RandomSource getRandomSequence(net.minecraft.resources.Identifier key) {
if (sequences == null) sequences = new net.minecraft.world.RandomSequences();
return sequences.get(key, 0L);
}
}
static List<String> summary(World w, Map<BlockPos, BlockState> before) {
@@ -441,8 +517,34 @@ public final class VanillaBlockUpdateOracle {
return new BlockPos(a.get(0).getAsInt(), a.get(1).getAsInt(), a.get(2).getAsInt());
}
/**
* The chunk source bone meal reaches for: saplings, grass and moss place
* their features with `getChunkSource().getGenerator()`, which none of
* them reads beyond passing it along.
*/
static final class Chunks extends net.minecraft.server.level.ServerChunkCache {
static net.minecraft.world.level.chunk.ChunkGenerator generator;
private Chunks() {
super(null, null, null, null, null, null, 0, 0, false, null);
}
@Override
public net.minecraft.world.level.chunk.ChunkGenerator getGenerator() {
return generator;
}
/** Leads send entity link packets; nobody is tracking. */
@Override
public void sendToTrackingPlayers(final net.minecraft.world.entity.Entity entity, final net.minecraft.network.protocol.Packet<? super net.minecraft.network.protocol.game.ClientGamePacketListener> packet) {
}
}
static World build(JsonObject f) throws Exception {
World w = make(World.class);
// Saplings, grass and moss place features through the chunk source's generator.
if (Chunks.generator == null) Chunks.generator = make(net.minecraft.world.level.levelgen.FlatLevelSource.class);
set(net.minecraft.server.level.ServerLevel.class, w, "chunkSource", make(Chunks.class));
w.cells = new HashMap<>();
w.log = new StringBuilder();
w.blockEvents = new java.util.LinkedHashSet<>();
@@ -0,0 +1,288 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.file.*;
import java.util.*;
import net.minecraft.core.BlockPos;
import net.minecraft.core.NonNullList;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.Identifier;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.Container;
import net.minecraft.world.entity.*;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.item.PrimedTnt;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.gamerules.GameRules;
import net.minecraft.world.level.levelgen.LegacyRandomSource;
/**
* Drives vanilla `DispenserBlock.dispenseFrom` (and the dropper's) over the
* headless level of {@link VanillaBlockUpdateOracle}, with entities: the
* dispenser holds the case's items, target entities stand in front, and the
* result lists block changes, container contents, spawned entities with their
* position and motion, the targets' state afterwards, level events, sounds
* (those the client plays for level events included), game events and the
* level random. Every case runs three times: numbers that differ between the
* runs come from an entity's own unseeded random and are marked with "~".
* Used by tools/test_dispenser_parity.py.
*/
public final class VanillaDispenserOracle {
/** The sound LevelEventHandler plays for a level event a dispenser can cause, or null. */
static String eventSound(int id, int data) {
return switch (id) {
case 1000 -> "minecraft:block.dispenser.dispense";
case 1001 -> "minecraft:block.dispenser.fail";
case 1002 -> "minecraft:block.dispenser.launch";
case 1004 -> "minecraft:entity.firework_rocket.shoot";
case 1018 -> "minecraft:entity.blaze.shoot";
case 1051 -> "minecraft:entity.wind_charge.throw";
case 1505 -> "minecraft:item.bone_meal.use";
case 1501 -> "minecraft:block.lava.extinguish";
case 1009 -> data == 0 ? "minecraft:block.fire.extinguish" : data == 1 ? "minecraft:block.generic.extinguish_fire" : null;
case 2001 -> {
BlockState state = Block.stateById(data);
yield state.isAir() ? null : state.getSoundType().getBreakSound().location().toString();
}
default -> null;
};
}
public static void main(String[] args) throws Exception {
ParityData.init();
VanillaBlockUpdateOracle.AIR = Blocks.AIR.defaultBlockState();
Path resources = Path.of(args[0]);
VanillaLevelShapeOracle.bindFluidTags(resources.resolve("data/minecraft/tags/fluid"));
VanillaBlockUpdateOracle.OVERWORLD_TYPE = VanillaBlockUpdateOracle.loadOverworld();
var allocator = Class.forName("sun.misc.Unsafe");
var field = allocator.getDeclaredField("theUnsafe");
field.setAccessible(true);
VanillaBlockUpdateOracle.unsafe = field.get(null);
VanillaBlockUpdateOracle.allocate = allocator.getMethod("allocateInstance", Class.class);
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2]))); var lines = Files.lines(Path.of(args[1]))) {
int index = 0;
for (var line : (Iterable<String>) lines::iterator) {
var f = JsonParser.parseString(line).getAsJsonObject();
// Three runs: a value from an unseeded random rarely repeats thrice.
List<String> a = attempt(f), b = attempt(f), c = attempt(f);
out.print("case " + index++ + "\n");
for (String s : merge(merge(a, b), c)) out.print(s + "\n");
}
}
}
static List<String> attempt(JsonObject f) {
List<String> result = new ArrayList<>();
try {
run(f, result);
} catch (Throwable e) {
Throwable c = e;
while (c.getCause() != null) c = c.getCause();
if (System.getenv("ORACLE_TRACE") != null) c.printStackTrace();
StackTraceElement[] st = c.getStackTrace();
result.clear();
result.add("error " + c.getClass().getSimpleName() + " " + (st.length > 0 ? st[0].toString() : "") + " " + c.getMessage());
}
return result;
}
/** Lines equal in both runs stay; numbers that differ are marked "~" (from an unseeded entity random). */
static List<String> merge(List<String> a, List<String> b) {
if (a.size() != b.size()) return a;
List<String> out = new ArrayList<>();
for (int i = 0; i < a.size(); i++) {
String x = a.get(i), y = b.get(i);
if (x.equals(y)) {
out.add(x);
continue;
}
String[] p = x.split(" "), q = y.split(" ");
if (p.length != q.length) {
out.add(x);
continue;
}
// A token already marked in an earlier merge stays marked.
for (int j = 0; j < p.length; j++) if (!p[j].equals(q[j]) && !p[j].startsWith("~")) p[j] = "~" + p[j];
out.add(String.join(" ", p));
}
return out;
}
static String num(double v) {
return String.format(Locale.ROOT, "%.6f", v);
}
static ItemStack stack(String snbt) throws Exception {
return ParityData.stack(snbt);
}
/** The item list of a container block entity (dispensers, droppers, chests, hoppers, barrels...). */
@SuppressWarnings("unchecked")
static NonNullList<ItemStack> slots(BlockEntity be) throws Exception {
for (Class<?> c = be.getClass(); c != null; c = c.getSuperclass()) {
for (Field fd : c.getDeclaredFields()) {
if (fd.getType() == NonNullList.class && !java.lang.reflect.Modifier.isStatic(fd.getModifiers())) {
fd.setAccessible(true);
return (NonNullList<ItemStack>) fd.get(be);
}
}
}
throw new IllegalStateException("no slots in " + be);
}
static Method dispenseFrom(Class<?> type) throws Exception {
for (Class<?> c = type; c != null; c = c.getSuperclass()) {
try {
Method m = c.getDeclaredMethod("dispenseFrom", ServerLevel.class, BlockState.class, BlockPos.class);
m.setAccessible(true);
return m;
} catch (NoSuchMethodException ignored) {
}
}
throw new IllegalStateException("no dispenseFrom on " + type);
}
static Entity target(VanillaBlockUpdateOracle.World w, JsonObject e) throws Exception {
EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(e.get("type").getAsString()));
Entity ent = type.create(w, EntitySpawnReason.COMMAND);
var p = e.getAsJsonArray("pos");
ent.snapTo(p.get(0).getAsDouble(), p.get(1).getAsDouble(), p.get(2).getAsDouble(), e.has("yaw") ? e.get("yaw").getAsFloat() : 0f, 0f);
if (e.has("baby") && ent instanceof AgeableMob ageable) ageable.setAge(-24000);
if (e.has("tame")) {
if (ent instanceof net.minecraft.world.entity.animal.equine.AbstractHorse horse) horse.setTamed(true);
if (ent instanceof TamableAnimal tamable) tamable.setTame(true, false);
}
if (e.has("sheared")) {
if (ent instanceof net.minecraft.world.entity.animal.sheep.Sheep sheep) sheep.setSheared(true);
if (ent instanceof net.minecraft.world.entity.monster.skeleton.Bogged bogged) bogged.setSheared(true);
if (ent instanceof net.minecraft.world.entity.animal.golem.SnowGolem golem) golem.setPumpkin(false);
}
if (e.has("chest") && ent instanceof net.minecraft.world.entity.animal.equine.AbstractChestedHorse chested) chested.setChest(true);
if (e.has("loot") && ent instanceof Mob mob) mob.setCanPickUpLoot(true);
if (e.has("brown") && ent instanceof net.minecraft.world.entity.animal.cow.MushroomCow cow) {
Method variant = net.minecraft.world.entity.animal.cow.MushroomCow.class.getDeclaredMethod("setVariant", net.minecraft.world.entity.animal.cow.MushroomCow.Variant.class);
variant.setAccessible(true);
variant.invoke(cow, net.minecraft.world.entity.animal.cow.MushroomCow.Variant.BROWN);
}
// A target has lived in the level for a while: past its first tick, so
// equipping it plays the equip sound.
VanillaBlockUpdateOracle.set(Entity.class, ent, "firstTick", false);
if (e.has("equip") && ent instanceof LivingEntity living) {
for (var slot : e.getAsJsonObject("equip").entrySet()) {
living.setItemSlot(EquipmentSlot.byName(slot.getKey()), stack(slot.getValue().getAsString()));
}
// A target that has ticked since it was equipped has run
// collectEquipmentChanges (a sulfur cube takes its archetype then).
Map<EquipmentSlot, ItemStack> last = new EnumMap<>(EquipmentSlot.class);
for (EquipmentSlot slot : EquipmentSlot.values()) last.put(slot, ItemStack.EMPTY);
Method collect = LivingEntity.class.getDeclaredMethod("collectEquipmentChanges", Map.class);
collect.setAccessible(true);
collect.invoke(ent, last);
}
return ent;
}
static void run(JsonObject f, List<String> result) throws Exception {
VanillaBlockUpdateOracle.World w = VanillaBlockUpdateOracle.build(f);
w.entities = new ArrayList<>();
w.registries = ParityData.access;
w.server.loot.delegate = ParityData.loot;
VanillaBlockUpdateOracle.set(Level.class, w, "damageSources", new net.minecraft.world.damagesource.DamageSources(ParityData.access));
if (f.has("rules")) {
for (var rule : f.getAsJsonObject("rules").entrySet()) {
if (rule.getKey().equals("tnt_explodes")) w.rules.set(GameRules.TNT_EXPLODES, rule.getValue().getAsBoolean(), null);
}
}
if (f.has("items")) {
for (var item : f.getAsJsonArray("items")) {
var it = item.getAsJsonArray();
BlockPos at = new BlockPos(it.get(0).getAsInt(), it.get(1).getAsInt(), it.get(2).getAsInt());
slots(w.getBlockEntity(at)).set(it.get(3).getAsInt(), stack(it.get(4).getAsString()));
}
}
if (f.has("entities")) {
List<Entity> created = new ArrayList<>();
for (var e : f.getAsJsonArray("entities")) {
Entity ent = target(w, e.getAsJsonObject());
created.add(ent);
w.entities.add(ent);
}
var list = f.getAsJsonArray("entities");
for (int i = 0; i < list.size(); i++) {
var e = list.get(i).getAsJsonObject();
if (e.has("leash") && created.get(i) instanceof Leashable leashable) {
leashable.setLeashedTo(created.get(e.get("leash").getAsInt()), true);
}
}
}
// Creating the targets must not move the stream the dispenser draws from.
w.rng = new LegacyRandomSource(f.get("seed").getAsLong());
VanillaBlockUpdateOracle.set(Level.class, w, "random", w.rng);
w.log = new StringBuilder();
w.blockEvents.clear();
Map<BlockPos, BlockState> before = new HashMap<>(w.cells);
List<Entity> targets = List.copyOf(w.entities);
BlockPos origin = VanillaBlockUpdateOracle.readPos(f.getAsJsonArray("pos"));
BlockState state = w.getBlockState(origin);
dispenseFrom(state.getBlock().getClass()).invoke(state.getBlock(), w, state, origin);
result.addAll(VanillaBlockUpdateOracle.summary(w, before));
List<BlockPos> containers = new ArrayList<>(w.blockEntities == null ? List.of() : w.blockEntities.keySet());
containers.sort(Comparator.<BlockPos>comparingInt(q -> q.getX()).thenComparingInt(q -> q.getY()).thenComparingInt(q -> q.getZ()));
for (BlockPos at : containers) {
if (!(w.blockEntities.get(at) instanceof Container) || w.getBlockEntity(at) != w.blockEntities.get(at)) continue;
var items = slots(w.blockEntities.get(at));
for (int i = 0; i < items.size(); i++) {
if (!items.get(i).isEmpty()) result.add("inv " + VanillaBlockUpdateOracle.pos(at) + " " + i + " " + ParityData.canon(items.get(i)));
}
}
for (Entity e : w.entities) {
if (targets.contains(e)) continue;
StringBuilder line = new StringBuilder("N ").append(BuiltInRegistries.ENTITY_TYPE.getKey(e.getType()));
line.append(' ').append(num(e.getX())).append(' ').append(num(e.getY())).append(' ').append(num(e.getZ()));
var v = e.getDeltaMovement();
line.append(' ').append(num(v.x)).append(' ').append(num(v.y)).append(' ').append(num(v.z));
if (e instanceof ItemEntity item) line.append(' ').append(ParityData.canon(item.getItem()));
if (e instanceof PrimedTnt tnt) line.append(" fuse=").append(tnt.getFuse());
result.add(line.toString());
}
for (int i = 0; i < targets.size(); i++) result.add(describe(i, targets.get(i)));
for (String s : w.log.toString().split("\n")) {
if (s.isEmpty() || s.startsWith("E ")) continue;
result.add(s);
if (s.startsWith("L ")) {
String[] p = s.split(" ");
String sound = eventSound(Integer.parseInt(p[1]), Integer.parseInt(p[3]));
if (sound != null) result.add("S " + p[2] + " " + sound);
}
}
result.addAll(w.blockEvents);
result.add("rng " + w.rng.nextLong());
}
/** A target's state after dispensing: removal, equipment and readiness for shearing. */
static String describe(int index, Entity e) {
StringBuilder line = new StringBuilder("T " + index + " " + BuiltInRegistries.ENTITY_TYPE.getKey(e.getType()));
if (e.isRemoved()) line.append(" removed");
if (e instanceof LivingEntity living) {
for (EquipmentSlot slot : EquipmentSlot.values()) {
ItemStack s = living.getItemBySlot(slot);
if (!s.isEmpty()) line.append(' ').append(slot.getName()).append('=').append(BuiltInRegistries.ITEM.getKey(s.getItem())).append('x').append(s.getCount());
}
}
boolean listed = e instanceof net.minecraft.world.entity.animal.sheep.Sheep || e instanceof net.minecraft.world.entity.animal.cow.MushroomCow
|| e instanceof net.minecraft.world.entity.monster.skeleton.Bogged || e instanceof net.minecraft.world.entity.animal.golem.SnowGolem;
if (listed && e instanceof Shearable shearable) line.append(shearable.readyForShearing() ? " ready" : " unready");
if (e instanceof net.minecraft.world.entity.animal.equine.AbstractChestedHorse chested && chested.hasChest()) line.append(" chest");
if (e instanceof Leashable leashable && leashable.isLeashed()) line.append(" leashed");
return line.toString();
}
}
+468
View File
@@ -0,0 +1,468 @@
#!/usr/bin/env python3
"""Compare vanilla dispensers and droppers with Horizon's, one activation per case.
A dispenser or dropper at the origin faces a random direction and holds the
case's items; the block in front (and below it) comes from a palette of blocks
the behaviours care about, and some cases put a target entity in front. Vanilla
`DispenserBlock.dispenseFrom` runs over the headless level of the block update
oracle (`VanillaDispenserOracle`); Horizon runs its game glue in a headless game
(`HORIZON_DISPENSE_FIXTURE`). Both print block changes, container contents,
spawned entities (type, position, motion), the targets afterwards, level events,
sounds, game events and the level random. Motion drawn from an entity's own
unseeded random (vanilla marks it "~") is compared within its spread.
"""
import json
import os
import random
import subprocess
try:
from . import block_update_harness as h, lab, test_rust_parity as base
except ImportError:
import block_update_harness as h
import lab
import test_rust_parity as base
DIRECTIONS = ['down', 'up', 'north', 'south', 'west', 'east']
STEP = {'down': (0, -1, 0), 'up': (0, 1, 0), 'north': (0, 0, -1), 'south': (0, 0, 1), 'west': (-1, 0, 0), 'east': (1, 0, 0)}
def potion(item, name):
return '{id:"minecraft:%s",count:1,components:{"minecraft:potion_contents":{potion:"minecraft:%s"}}}' % (item, name)
def plain(item, count=1):
return '{id:"minecraft:%s",count:%d}' % (item, count)
WOODS = ['oak', 'spruce', 'birch', 'jungle', 'acacia', 'cherry', 'dark_oak', 'mangrove', 'pale_oak', 'poplar']
# Items with the blocks and entities in front that exercise their behaviour:
# one entry per DispenseItemBehavior.bootStrap registration family, plus the
# defaults of DispenserBlock.getDefaultDispenseMethod (equippables, sulfur
# cube swallowables, spawn eggs, a plain drop).
ITEMS = {
'drop': [plain('stone', 5), plain('diamond'), plain('stick', 64), plain('oak_sapling', 3), plain('redstone', 2), plain('lead'),
plain('wheat_seeds', 7)],
'projectile': [plain('arrow', 3), potion('tipped_arrow', 'poison'), plain('spectral_arrow'), plain('egg', 2), plain('blue_egg'),
plain('brown_egg'), plain('snowball', 4), plain('experience_bottle'), potion('splash_potion', 'healing'),
potion('lingering_potion', 'swiftness'), plain('firework_rocket', 2), plain('fire_charge', 2), plain('wind_charge', 3)],
'bucket': [plain('water_bucket'), plain('lava_bucket'), plain('powder_snow_bucket'), plain('salmon_bucket'), plain('cod_bucket'),
plain('pufferfish_bucket'), plain('tropical_fish_bucket'), plain('axolotl_bucket'), plain('tadpole_bucket'),
plain('sulfur_cube_bucket'), plain('bucket'), plain('bucket', 3)],
'block': [plain('bone_meal', 4), plain('tnt', 2), plain('flint_and_steel'), plain('glowstone', 3), plain('honeycomb', 2),
plain('glass_bottle', 2), potion('potion', 'water'), potion('potion', 'healing'), plain('shulker_box'),
plain('red_shulker_box'), plain('lime_shulker_box'), plain('carved_pumpkin'), plain('wither_skeleton_skull'),
plain('shears'), plain('brush')],
'vehicle': [plain('oak_boat'), plain('bamboo_raft'), plain('bamboo_chest_raft'), plain('minecart'), plain('chest_minecart'),
plain('furnace_minecart'), plain('tnt_minecart'), plain('hopper_minecart'), plain('command_block_minecart'),
plain('armor_stand', 2), 'BOAT', 'CHEST_BOAT'],
'spawn': [plain('pig_spawn_egg'), plain('sheep_spawn_egg', 2), plain('zombie_spawn_egg'), plain('cow_spawn_egg'),
plain('chicken_spawn_egg'), plain('skeleton_spawn_egg'), plain('creeper_spawn_egg'), plain('villager_spawn_egg'),
plain('wolf_spawn_egg'), plain('horse_spawn_egg'), plain('squid_spawn_egg'), plain('slime_spawn_egg')],
'equipment': [plain('iron_helmet'), plain('diamond_chestplate'), plain('leather_leggings'), plain('golden_boots'),
plain('chainmail_helmet'), plain('netherite_boots'), plain('turtle_helmet'), plain('saddle'),
plain('iron_horse_armor'), plain('diamond_horse_armor'), plain('leather_horse_armor'), plain('white_carpet'),
plain('red_carpet'), plain('chest'), plain('carved_pumpkin'), plain('elytra'), plain('wolf_armor'), plain('shears'),
plain('brush'), plain('player_head'), plain('zombie_head'), plain('white_harness')],
'swallow': [plain('slime_block'), plain('oak_planks', 3), plain('packed_ice'), plain('soul_sand'), plain('magma_block'),
plain('white_wool'), plain('mud', 2), plain('andesite'), plain('iron_block'), plain('mushroom_stem'),
plain('honeycomb_block'), plain('tube_coral_block'), plain('tnt'), plain('stone')],
}
FRONT = {
'drop': ['air', 'stone', 'water', 'chest', 'hopper'],
'projectile': ['air', 'air', 'water', 'stone', 'glass'],
'bucket': ['air', 'air', 'water', 'water', 'lava', 'powder_snow', 'oak_slab', 'seagrass', 'stone', 'cauldron', 'kelp',
'grass_block', 'fire'],
'block': ['air', 'grass_block', 'wheat', 'oak_sapling', 'tnt', 'campfire', 'candle', 'respawn_anchor', 'beehive', 'bee_nest',
'copper_block', 'exposed_cut_copper_stairs', 'dirt', 'coarse_dirt', 'rooted_dirt', 'water', 'seagrass', 'stone',
'sweet_berry_bush', 'cocoa', 'obsidian', 'soul_campfire', 'candle_cake', 'netherrack', 'moss_block'],
'vehicle': ['air', 'air', 'water', 'rail', 'powered_rail', 'activator_rail', 'stone', 'detector_rail'],
'spawn': ['air', 'air', 'water', 'stone', 'grass_block'],
'equipment': ['air'],
'swallow': ['air'],
}
# The blocks a behaviour reacts to, drawn for that item most of the time.
FRONT_FOR = {
'flint_and_steel': ['air', 'air', 'air', 'campfire', 'soul_campfire', 'candle', 'blue_candle', 'candle_cake',
'red_candle_cake', 'tnt', 'stone', 'obsidian', 'netherrack', 'water'],
'glowstone': ['respawn_anchor', 'respawn_anchor', 'respawn_anchor', 'air', 'stone', 'glowstone'],
'bone_meal': ['grass_block', 'wheat', 'carrots', 'potatoes', 'beetroots', 'oak_sapling', 'birch_sapling', 'spruce_sapling',
'cherry_sapling', 'mangrove_propagule', 'moss_block', 'sweet_berry_bush', 'cocoa', 'bamboo_sapling', 'bamboo',
'pumpkin_stem', 'melon_stem', 'torchflower_crop', 'pitcher_crop', 'rooted_dirt', 'glow_lichen', 'small_dripleaf',
'big_dripleaf', 'crimson_nylium', 'warped_fungus', 'brown_mushroom', 'kelp', 'sea_pickle', 'seagrass', 'water',
'short_grass', 'fern', 'dandelion', 'pink_petals', 'cave_vines', 'twisting_vines', 'weeping_vines', 'azalea',
'pale_moss_block', 'stone', 'air'],
'honeycomb': ['copper_block', 'exposed_copper', 'weathered_cut_copper', 'oxidized_cut_copper_slab', 'copper_door',
'exposed_copper_trapdoor', 'copper_bulb', 'lightning_rod', 'waxed_copper_block', 'copper_grate', 'stone', 'air'],
'glass_bottle': ['beehive', 'beehive', 'bee_nest', 'bee_nest', 'water', 'water', 'air', 'stone', 'seagrass'],
'potion': ['dirt', 'coarse_dirt', 'rooted_dirt', 'dirt', 'stone', 'air', 'mud', 'water'],
'shears': ['beehive', 'bee_nest', 'beehive', 'air', 'air', 'stone', 'pumpkin'],
'brush': ['air', 'air', 'suspicious_sand', 'stone'],
'tnt': ['air', 'air', 'stone', 'water', 'tnt'],
'shulker_box': ['air', 'air', 'stone', 'water', 'short_grass', 'snow'],
'carved_pumpkin': ['air', 'air', 'stone', 'snow'],
'wither_skeleton_skull': ['air', 'air', 'stone'],
'armor_stand': ['air', 'air', 'stone', 'water', 'short_grass'],
}
# Structures a behaviour completes (golems, the wither, a nether portal).
SCENES = {'carved_pumpkin': ['snow_golem', 'iron_golem'], 'wither_skeleton_skull': ['wither'], 'flint_and_steel': ['portal']}
# Plants that need soil (or a log) under them to exist at all.
ROOTED = {'wheat', 'carrots', 'potatoes', 'beetroots', 'oak_sapling', 'birch_sapling', 'spruce_sapling', 'cherry_sapling',
'mangrove_propagule', 'sweet_berry_bush', 'cocoa', 'bamboo_sapling', 'bamboo', 'pumpkin_stem', 'melon_stem',
'torchflower_crop', 'pitcher_crop', 'small_dripleaf', 'big_dripleaf', 'warped_fungus', 'brown_mushroom', 'kelp',
'sea_pickle', 'seagrass', 'short_grass', 'fern', 'dandelion', 'pink_petals', 'twisting_vines', 'azalea'}
BELOW = ['air', 'stone', 'water', 'rail', 'grass_block', 'soul_sand', 'dirt', 'farmland', 'netherrack']
TARGETS = {
'iron_helmet': ['zombie', 'skeleton', 'armor_stand', 'pig'],
'chainmail_helmet': ['zombie', 'armor_stand', 'villager'],
'diamond_chestplate': ['zombie', 'armor_stand'],
'leather_leggings': ['skeleton', 'armor_stand'],
'golden_boots': ['zombie', 'armor_stand'],
'netherite_boots': ['zombie', 'piglin', 'armor_stand'],
'turtle_helmet': ['armor_stand', 'zombie'],
'saddle': ['pig', 'horse', 'strider', 'donkey', 'camel', 'llama', 'mule', 'skeleton_horse', 'nautilus'],
'iron_horse_armor': ['horse', 'donkey'],
'diamond_horse_armor': ['horse', 'zombie_horse'],
'leather_horse_armor': ['horse'],
'white_carpet': ['llama', 'horse', 'trader_llama'],
'red_carpet': ['llama', 'trader_llama'],
'chest': ['donkey', 'mule', 'llama', 'horse', 'trader_llama'],
'carved_pumpkin': ['zombie', 'armor_stand', 'snow_golem'],
'elytra': ['armor_stand', 'zombie'],
'wolf_armor': ['wolf'],
'white_harness': ['happy_ghast'],
'shears': ['sheep', 'sheep', 'mooshroom', 'bogged', 'snow_golem', 'sulfur_cube', 'pig', 'cow'],
'brush': ['armadillo'],
'tnt': ['sulfur_cube'],
'flint_and_steel': ['sulfur_cube'],
'player_head': ['armor_stand', 'zombie'],
'zombie_head': ['armor_stand', 'skeleton'],
}
for _block in ('stone', 'slime_block', 'oak_planks', 'packed_ice', 'soul_sand', 'magma_block', 'white_wool', 'mud', 'andesite',
'iron_block', 'mushroom_stem', 'honeycomb_block', 'tube_coral_block'):
TARGETS[_block] = ['sulfur_cube']
SWALLOWED = ['tnt', 'stone', 'slime_block', 'magma_block', 'white_wool', 'iron_block']
def item_choice(rng, kind):
item = rng.choice(ITEMS[kind])
if item == 'BOAT':
return plain(rng.choice(WOODS) + '_boat')
if item == 'CHEST_BOAT':
return plain(rng.choice(WOODS) + '_chest_boat')
return item
class States:
def __init__(self, facts):
self.facts = facts
def get(self, name, **props):
name = name if ':' in name else 'minecraft:' + name
best = self.facts.defaults[name]
if not props:
return best
for index in self.facts.by_block[name]:
have = self.facts.states[index][4].get('properties', {})
if all(have.get(k) == v for k, v in props.items()):
return index
raise KeyError((name, props))
def any(self, rng, name):
name = name if ':' in name else 'minecraft:' + name
return rng.choice(self.facts.by_block[name])
def build_scene(cells, states, rng, scene, front, facing):
"""Put the rest of a structure the behaviour's block completes around the front."""
x, y, z = front
across = rng.choice([(1, 0, 0), (0, 0, 1)])
def put(at, name, **props):
if at != (0, 0, 0) and at != front:
h.put(cells, at, states.get(name, **props))
def side(at, k):
return (at[0] + across[0] * k, at[1], at[2] + across[2] * k)
if scene == 'snow_golem':
put((x, y - 1, z), 'snow_block')
put((x, y - 2, z), 'snow_block')
elif scene == 'iron_golem':
put((x, y - 1, z), 'iron_block')
put((x, y - 2, z), 'iron_block')
put(side((x, y - 1, z), -1), 'iron_block')
put(side((x, y - 1, z), 1), 'iron_block')
elif scene == 'wither':
put((x, y - 1, z), 'soul_sand')
put((x, y - 2, z), 'soul_sand')
put(side((x, y - 1, z), -1), rng.choice(['soul_sand', 'soul_soil']))
put(side((x, y - 1, z), 1), 'soul_sand')
put(side((x, y, z), -1), 'wither_skeleton_skull')
put(side((x, y, z), 1), rng.choice(['wither_skeleton_skull', 'wither_skeleton_skull', 'skeleton_skull']))
elif scene == 'portal':
# An obsidian frame around a 2x3 inside that holds the front block.
width, height = rng.choice([(2, 3), (2, 3), (3, 4)])
left, low = rng.randrange(width), rng.randrange(height)
for i in range(-1, width + 1):
for j in range(-1, height + 1):
at = side((x, y + j - low, z), i - left)
edge = i in (-1, width) or j in (-1, height)
if edge and not (i in (-1, width) and j in (-1, height)):
put(at, 'obsidian')
elif not edge:
if at not in ((0, 0, 0), front):
h.put(cells, at, states.get('air'))
def halves(states, name):
"""Whether a block comes in an upper and a lower half (tall plants, dripleaves, pitchers)."""
name = name if ':' in name else 'minecraft:' + name
return any(states.facts.states[i][4].get('properties', {}).get('half') == 'upper' for i in states.facts.by_block[name])
def front_state(states, rng, name):
"""Mostly the default state, sometimes a random one (charges, honey, ages, lit...)."""
if halves(states, name):
# A lone half is not a world vanilla makes; the pair is placed by put_front.
return states.get(name)
if name in ('respawn_anchor', 'beehive', 'bee_nest', 'campfire', 'candle', 'wheat', 'sweet_berry_bush', 'rail', 'powered_rail',
'candle_cake', 'soul_campfire') or rng.random() < 0.3:
return states.any(rng, name)
return states.get(name)
def cases(facts, count, seed, only):
rng = random.Random(seed)
states = States(facts)
kinds = list(ITEMS)
for n in range(count):
kind = kinds[n % len(kinds)]
item = item_choice(rng, kind)
if only and only not in item:
continue
bare = item.split('"')[1].split(':')[1]
facing = rng.choice(DIRECTIONS)
block = 'dropper' if rng.random() < 0.12 else 'dispenser'
cells = [[0, 0, 0, states.get(block, facing=facing, triggered='false')]]
dx, dy, dz = STEP[facing]
front = (dx, dy, dz)
below = (dx, dy - 1, dz)
palette = FRONT_FOR[bare] if bare in FRONT_FOR and rng.random() < 0.8 else FRONT[kind]
front_name = rng.choice(palette)
if facing == 'up' and front_name in ROOTED:
# Nothing grows out of a dispenser: vanilla never lets these stand on one.
front_name = 'air'
above = (dx, dy + 1, dz)
if halves(states, front_name) and front_name != 'pitcher_crop':
if above == (0, 0, 0):
front_name = 'air'
else:
# The upper half matches the lower one in everything but its half.
lower = states.facts.states[states.get(front_name)][4].get('properties', {})
h.put(cells, above, states.get(front_name, **{**lower, 'half': 'upper'}))
if front_name != 'air':
h.put(cells, front, front_state(states, rng, front_name))
if below != (0, 0, 0) and rng.random() < 0.8:
name = rng.choice(BELOW)
if name != 'air':
h.put(cells, below, front_state(states, rng, name))
scene = rng.choice(SCENES[bare]) if bare in SCENES and rng.random() < 0.45 else None
# A few random blocks around (portal frames, fire supports, neighbours).
for _ in range(rng.randrange(0, 6)):
at = (rng.randrange(-2, 3), rng.randrange(-2, 3), rng.randrange(-2, 3))
if at in ((0, 0, 0), front):
continue
h.put(cells, at, states.get(rng.choice(['stone', 'obsidian', 'dirt', 'water', 'soul_sand', 'grass_block', 'oak_planks'])))
if scene:
build_scene(cells, states, rng, scene, front, facing)
items = []
slots = rng.sample(range(9), rng.choice([1, 1, 1, 2, 3, 9]))
for i, slot in enumerate(slots):
items.append([0, 0, 0, slot, item if i == 0 or rng.random() < 0.6 else plain('cobblestone', rng.randrange(1, 65))])
case = {**h.environment(rng), 'mode': 'dispense', 'pos': [0, 0, 0], 'cells': cells, 'items': items}
case.pop('raining', None)
case.pop('thundering', None)
if rng.random() < 0.08:
case['rules'] = {'tnt_explodes': False}
if kind in ('equipment', 'swallow') or (bare in TARGETS and rng.random() < 0.5):
entities = []
for _ in range(rng.choice([1, 1, 1, 2])):
target = {'type': 'minecraft:' + rng.choice(TARGETS.get(bare, ['zombie'])),
'pos': [dx + 0.5, dy + rng.choice([0.0, 0.0, 0.25]), dz + 0.5], 'yaw': rng.choice([0.0, 90.0, 180.0])}
for flag, odds in (('baby', 0.2), ('tame', 0.6), ('sheared', 0.25), ('chest', 0.15), ('loot', 0.5), ('brown', 0.3)):
if rng.random() < odds:
target[flag] = True
if target['type'] == 'minecraft:sulfur_cube' and rng.random() < 0.5:
target['equip'] = {'body': plain(rng.choice(SWALLOWED))}
# Leads: tied to an earlier target, or that target holds this one's.
holders = [i for i, e in enumerate(entities) if e['type'] != 'minecraft:armor_stand']
if holders and rng.random() < 0.3:
target['leash'] = rng.choice(holders)
entities.append(target)
if bare == 'shears' and len(entities) == 1 and rng.random() < 0.3:
# A holder out of the dispenser's reach whose lead runs to the target.
entities.append({'type': 'minecraft:' + rng.choice(['cow', 'wolf']), 'pos': [dx + 3.5, dy, dz + 3.5], 'yaw': 0.0})
entities[0]['leash'] = 1
case['entities'] = entities
if block == 'dropper' and rng.random() < 0.5:
h.put(cells, front, states.get(rng.choice(['chest', 'hopper', 'barrel', 'dispenser'])))
if rng.random() < 0.5:
items.append([dx, dy, dz, 0, plain(rng.choice(['stone', 'diamond', 'stick']), rng.randrange(1, 65))])
yield case
# Items whose behaviour runs Mob.finalizeSpawn (spawn eggs, mob buckets). The
# finalization draws belong to the entity spawning port; for these cases the
# level random's end state is not compared, everything else is.
FINALIZED = ('_spawn_egg', 'salmon_bucket', 'cod_bucket', 'pufferfish_bucket', 'tropical_fish_bucket', 'axolotl_bucket',
'tadpole_bucket', 'sulfur_cube_bucket')
def finalizes(case):
return any(any(tag in i[4] for tag in FINALIZED) for i in case['items'] if i[:3] == [0, 0, 0])
def spawned_type(case):
item = next(i[4] for i in case['items'] if i[:3] == [0, 0, 0]).split('"')[1].split(':')[1]
return 'minecraft:' + item.removesuffix('_spawn_egg').removesuffix('_bucket')
def rider(line, spawned):
parts = line.split(' ')
return parts[0] == 'N' and parts[1] not in (spawned, 'minecraft:item')
def voice(line):
parts = line.split(' ')
if parts[0] == 'S' and len(parts) == 3 and parts[2].lstrip('~').startswith('minecraft:entity.'):
parts[2] = 'entity-voice'
return ' '.join(parts)
def run(command, **kwargs):
done = subprocess.run(command, capture_output=True, text=True, **kwargs)
if done.returncode:
print((done.stdout + done.stderr)[-4000:])
raise SystemExit(f'{command[0]} failed')
return done
def numbers_close(java, rust):
"""Token-wise equality; a "~" token is an unseeded entity draw and only needs to fall in its spread."""
a, b = java.split(' '), rust.split(' ')
if len(a) != len(b):
return False
for x, y in zip(a, b):
if x.startswith('~'):
try:
# An item's own motion spans 0.2 per axis, and a shearing
# sheep pushes each wool with its own random by up to 0.1 more.
if abs(float(x[1:]) - float(y)) > 0.4:
return False
except ValueError:
return False
elif x != y:
return False
return True
def same(java, rust):
java = sorted(java)
rust = sorted(rust)
if len(java) != len(rust):
return False
pending = list(rust)
for line in java:
if line in pending:
pending.remove(line)
continue
if '~' not in line:
return False
match = next((r for r in pending if numbers_close(line, r)), None)
if match is None:
return False
pending.remove(match)
return True
def main():
parser = h.argument_parser(__doc__)
args = parser.parse_args()
if args.count == 40000:
args.count = 6000
lock, jars, libraries = base.verify_artifacts()
facts = h.load_facts()
resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
work = lab.LOCAL / 'dispenser-parity'
work.mkdir(parents=True, exist_ok=True)
all_cases = list(cases(facts, args.count, args.seed, args.only))
(work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in all_cases))
classes = work / 'classes'
classes.mkdir(exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
java_root = lab.ROOT / 'mods/horizon/src/test/java'
run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-sourcepath', str(java_root), '-nowarn',
'-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')])
run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle',
str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')])
run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
# Loot table names (D) are vanilla's bookkeeping; the drops themselves are compared.
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
native = h.split_cases((work / 'native.txt').read_text(), ignore)
rust = h.split_cases((work / 'rust.txt').read_text(), ignore)
assert len(native) == len(rust) == len(all_cases), (len(native), len(rust), len(all_cases))
groups, errors = {}, {}
unseeded = 0
for case, a, b in zip(all_cases, native, rust):
if a and a[0].startswith('error'):
errors.setdefault(a[0], []).append(case)
continue
if finalizes(case):
unseeded += 1
# Riders finalizeSpawn adds (a baby zombie's chicken, a spider's
# skeleton) depend on whether the mob came out a baby and on the
# jockey odds, both finalization draws: only the egg's own mob is compared.
spawned = spawned_type(case)
a = [line for line in a if not rider(line, spawned)]
b = [line for line in b if not rider(line, spawned)]
# EntityType.spawn plays the new mob's ambient sound: which one (a
# wolf pants or barks, in its sound variant) comes from the mob's
# own unseeded random, so only that a voice plays, and where, is compared.
a = [voice(line) for line in a if not line.startswith('rng ')]
b = [voice(line) for line in b if not line.startswith('rng ')]
if not same(a, b):
item = next(i[4] for i in case['items'] if i[:3] == [0, 0, 0])
block = facts.states[case['cells'][0][3]][0].split(':')[1]
groups.setdefault(f'{block} {item.split(chr(34))[1]}', []).append((case, a, b))
for kind, entries in sorted(errors.items(), key=lambda e: -len(e[1])):
print(f'oracle error x{len(entries)}: {kind}')
for name, entries in sorted(groups.items(), key=lambda e: -len(e[1])):
print(f'{name}: {len(entries)} differing')
for case, a, b in entries[:args.show]:
print(' case ' + describe(case, facts))
print(' native ' + ' | '.join(sorted(a)))
print(' rust ' + ' | '.join(sorted(b)))
total = sum(len(v) for v in groups.values())
skipped = sum(len(v) for v in errors.values())
print(f'{len(all_cases) - total - skipped}/{len(all_cases) - skipped} cases match ({skipped} oracle errors; '
f'{unseeded} spawning cases compared without the final level random)')
(work / 'differences.json').write_text(json.dumps({k: [[c, a, b] for c, a, b in v[:5]] for k, v in groups.items()}))
h.finish(total)
def describe(case, facts):
cells = ' '.join(f'{c[0]},{c[1]},{c[2]}={facts.describe(c[3])}' for c in case['cells'])
extra = ''
if case.get('entities'):
extra += ' entities=' + json.dumps(case['entities'])
if case.get('rules'):
extra += ' rules=' + json.dumps(case['rules'])
return f'{cells} items={json.dumps(case["items"])}{extra} seed={case["seed"]}'
if __name__ == '__main__':
main()