Merge newer main while retaining consumable guard and review fixes

This commit is contained in:
Cosmic
2026-10-14 12:27:15 -04:00
43 changed files with 3978 additions and 286 deletions
@@ -1,14 +1,17 @@
//! Replays the render states of the vanilla entity-animation oracle through
//! Horizon's `mobs::anim::setup` and writes every part's pose.
//! Horizon's `mobs::anim::setup` and writes every part's pose, then draws the
//! posed model with `mobs::render::draw` under the case's living-entity root
//! transform and writes each drawn part's packed vertex normals.
//!
//! cargo run --profile fast -p horizon-client --example entity_anim_fixture -- \
//! RESOURCES VANILLA.jsonl OUT.jsonl
use horizon_client::mesher::Vertex;
use horizon_client::mobs::{
Mob, MobData, MobTypes, Part, Species, allay,
anim::{self, Poses, State},
aquatic, body_anim as b_anim, equine, guardian,
keyframes::AnimationState,
shulker, sniffer, species, tame,
render, shulker, sniffer, species, tame,
};
use horizon_core::geometry::Vec3;
use serde_json::{Value, json};
@@ -44,6 +47,61 @@ fn walk(part: &Part, path: &str, poses: &Poses, out: &mut BTreeMap<String, Value
}
}
/// Splits the vertices `render::draw` emitted for `part` into its drawn parts,
/// following draw's walk: a hidden or zero-scaled part ends its branch, a
/// skip-draw part keeps its children. Per part: n = packed normal bytes per
/// vertex, p = sum of x + 2y + 3z over the positions.
fn drawn(
part: &Part,
path: &str,
poses: &Poses,
vertices: &[Vertex],
cursor: &mut usize,
out: &mut BTreeMap<String, Value>,
) {
let p = poses.pose(part);
if poses.is_hidden(part) || p[6] == 0.0 && p[7] == 0.0 && p[8] == 0.0 {
return;
}
let count = if poses.skips(part) {
0
} else {
part.polygons.len() * 4
};
if count > 0 {
let own = &vertices[*cursor..*cursor + count];
let normals: Vec<i8> = own.iter().flat_map(|v| v.normal[..3].to_vec()).collect();
let sum: f64 = own
.iter()
.map(|v| f64::from(v.pos[0]) + 2.0 * f64::from(v.pos[1]) + 3.0 * f64::from(v.pos[2]))
.sum();
out.insert(path.to_owned(), json!({"n": normals, "p": sum}));
}
*cursor += count;
for c in &part.children {
let child = if path.is_empty() {
c.name.clone()
} else {
format!("{path}/{}", c.name)
};
drawn(c, &child, poses, vertices, cursor, out);
}
}
/// LivingEntityRenderer's root transform without the entity's position:
/// rotate 180 - yaw about Y, scale(-1, -1, 1), the renderer's own scale, then
/// translate(0, -1.501, 0) (as `render::base_transform`).
fn root_transform(case: &Value) -> glam::Mat4 {
let yaw = case["@rootYaw"].as_f64().unwrap_or(0.0) as f32;
let scale = case["@rootScale"].as_array().map_or(glam::Vec3::ONE, |s| {
glam::Vec3::from_array(std::array::from_fn(|i| s[i].as_f64().unwrap_or(1.0) as f32))
});
glam::Mat4::from_rotation_y((180.0 - yaw).to_radians())
* glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0))
* glam::Mat4::from_scale(scale)
* glam::Mat4::from_translation(glam::Vec3::new(0.0, -1.501, 0.0))
}
/// The entity-side values behind the render-state fields the case sets, for
/// the species whose Horizon animation reads them from the `Mob`.
fn entity_state(mob: &mut Mob, species: Species, case: &Value) {
@@ -518,9 +576,34 @@ fn main() -> horizon_client::Result<()> {
}
_ => anim::setup(&mob, s, p, &animations),
}
// The harness's part-scale override, set after setupAnim as the oracle does.
if let Some(scale) = case["@partScale"].as_array() {
let pose = poses.get(scale[0].as_str().unwrap_or_default());
for i in 0..3 {
pose[6 + i] = scale[1 + i].as_f64().unwrap_or(1.0) as f32;
}
}
let mut parts = BTreeMap::new();
walk(&model, "", &poses, &mut parts);
out.push_str(&format!("{}\n", json!({"parts": parts})));
let mut emitted = Vec::new();
render::draw(
&model,
root_transform(case),
&poses,
[0.0, 0.0, 1.0, 1.0],
0xFFFF_FFFF,
240 | 240 << 8,
0,
&mut emitted,
);
let mut vertices = BTreeMap::new();
let mut cursor = 0;
drawn(&model, "", &poses, &emitted, &mut cursor, &mut vertices);
assert_eq!(cursor, emitted.len(), "{layer}: draw's walk changed");
out.push_str(&format!(
"{}\n",
json!({"parts": parts, "vertices": vertices})
));
}
fs::write(&args[2], out)?;
Ok(())
@@ -245,6 +245,10 @@ fn main() -> Result<()> {
)?;
// The oracle runs block-inside effects only in "snow_tick".
player.block_effects = false;
// Entity.portalCooldown and portalProcess, and the entry of the last
// portal_tick that went through.
let mut portal = horizon_client::nether_portal::PortalState::default();
let mut travel: Option<horizon_core::position::BlockPos> = None;
for op in f["ops"].as_array().unwrap() {
let mut world = MotionWorld {
player: &mut player,
@@ -442,6 +446,14 @@ fn main() -> Result<()> {
world.player.freeze_immune = boots;
}
"frozen" => world.player.ticks_frozen = op["value"].as_i64().unwrap() as i32,
"portal_tick" => {
// Entity.handlePortal without the destination: players wait
// the creative delay (0) when invulnerable, else 80 ticks.
let creative = op["creative"].as_bool().unwrap();
let transition = if creative { 0 } else { 80 };
let alive = !world.player.health.dead_or_dying();
travel = portal.handle(alive, transition, 10);
}
"weaving" => world.player.status.weaving = op["value"].as_bool().unwrap(),
"flying" => {
let flying = op["value"].as_bool().unwrap();
@@ -515,6 +527,14 @@ fn main() -> Result<()> {
}
_ => return Err("unknown motion operation".into()),
}
// NetherPortalBlock.entityInside: canUsePortal, setAsInsidePortal.
for e in &player.events {
if let MotionEvent::InsidePortal { pos } = e
&& !player.health.dead_or_dying()
{
portal.set_inside(*pos, 10);
}
}
let check_block = scene.block(25, 3, 25);
snapshot(&mut out, &player)?;
let stuck = player.stuck_multiplier;
@@ -529,6 +549,18 @@ fn main() -> Result<()> {
stuck.y.to_bits(),
stuck.z.to_bits()
)?;
writeln!(
out,
"portal {} {} {}",
portal.cooldown,
portal.process.map_or("none".into(), |p| format!(
"{},{},{} {} {}",
p.entry.x, p.entry.y, p.entry.z, p.time, p.inside
)),
travel
.take()
.map_or("-".into(), |t| format!("{},{},{}", t.x, t.y, t.z))
)?;
let h = &player.health;
let canonical = |v: f32| {
if v.is_nan() {
+15 -1
View File
@@ -96,6 +96,20 @@ impl SceneCollisions<'_, '_> {
/// `noCollision(null, box)`: block collisions under the empty collision
/// context, as entity-less queries such as spawn checks use.
pub fn no_collision_empty<W, E>(world: &mut W, bounds: Aabb) -> bool
where
W: BlockCollisionWorld<Error = E> + EntityMovementWorld<Error = E>,
{
no_collision_in(world, bounds, false)
}
/// `noCollision(null, box, true)`: the same with liquids colliding as
/// blocks (`CollisionContext.emptyWithFluidCollisions`).
pub fn no_collision_or_liquid<W, E>(world: &mut W, bounds: Aabb) -> bool
where
W: BlockCollisionWorld<Error = E> + EntityMovementWorld<Error = E>,
{
no_collision_in(world, bounds, true)
}
fn no_collision_in<W, E>(world: &mut W, bounds: Aabb, fluids: bool) -> bool
where
W: BlockCollisionWorld<Error = E> + EntityMovementWorld<Error = E>,
{
@@ -103,7 +117,7 @@ where
world,
CollisionCheckRequest {
entity: EntityIdentity(0),
context: CollisionContext::empty(false),
context: CollisionContext::empty(fluids),
bounds,
candidate_budget: 1_000_000,
},
+24 -12
View File
@@ -31,13 +31,16 @@ struct Out {
@location(1) color: vec4<f32>,
@location(2) spherical: f32,
@location(3) cylindrical: f32,
@location(5) flash: f32,
// entity.vsh's overlayColor: the OverlayTexture texel (see overlay_texel).
@location(5) overlay_color: vec4<f32>,
@location(4) @interpolate(flat) overlay: u32,
// Overlay 6: the sprite's v origin and height, for v repeated inside it.
@location(6) @interpolate(flat) wrap: vec2<f32>,
// Overlays 9 and 10: projection_from_position(gl_Position), the End portal's texProj0.
@location(7) proj: vec4<f32>,
@location(8) back_color: vec4<f32>,
// entity.vsh's lightMapColor, multiplied in after the overlay.
@location(9) light_color: vec4<f32>,
}
// Shipped light.glsl; normals are already transformed and RGBA8_SNORM packed.
fn entity_light(normal: vec3<f32>, nether: bool) -> f32 {
@@ -45,6 +48,14 @@ fn entity_light(normal: vec3<f32>, nether: bool) -> f32 {
let l1 = normalize(vec3(-0.2, select(1.0, -1.0, nether), 0.7));
return min(1.0, (max(0.0, dot(l0, normal)) + max(0.0, dot(l1, normal))) * 0.6 + 0.4);
}
// The OverlayTexture texel entity.vsh fetches: rows 0-7 hold the hurt red
// 0xB2FF0000; row 10 is white with alpha (1 - u / 15 * 0.75) * 255, u = 15
// for the primed TNT flash (OverlayTexture.u(1.0)), so 63. Alpha 1 changes nothing.
fn overlay_texel(overlay: u32) -> vec4<f32> {
if overlay == 1u || overlay == 8u { return vec4(1.0, 0.0, 0.0, 178.0 / 255.0); }
if overlay == 5u { return vec4(1.0, 1.0, 1.0, 63.0 / 255.0); }
return vec4(1.0);
}
@vertex fn vs_entity(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
@location(2) overlay: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>, @location(5) normal: vec4<f32>) -> Out {
var out: Out;
@@ -54,24 +65,22 @@ fn entity_light(normal: vec3<f32>, nether: bool) -> f32 {
let l = vec2(f32(light.y), f32(light.x));
let lm = textureSampleLevel(lightmap, lightmap_sampler,
clamp(l / 256.0 + 0.5 / 16.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0)), 0.0);
// Celestial bodies, clouds, beacon beams and breaking cracks are unlit.
var c = select(color * lm, color, overlay == 2u || overlay == 4u || overlay == 6u || overlay == 11u || overlay == 12u);
// Celestial bodies, clouds, beacon beams, End portals and breaking cracks are unlit.
let unlit = overlay == 2u || overlay == 4u || overlay == 6u || overlay == 9u || overlay == 10u
|| overlay == 11u || overlay == 12u;
out.light_color = select(lm, vec4(1.0), unlit);
// Overlay 6 (beacon beams): the light bytes carry the sprite's v range.
out.wrap = vec2(f32(light.x | (light.y << 8u)), f32(light.z | (light.w << 8u))) / 65535.0;
// minecraft_mix_light: the vertex colour times the cardinal light only.
var c = color;
var back = c;
if normal.w != 0.0 {
c = vec4(c.rgb * entity_light(normal.xyz, globals.time.y != 0.0), c.a);
back = select(c, vec4(back.rgb * entity_light(-normal.xyz, globals.time.y != 0.0), back.a), normal.w < 0.0);
}
// Hurt overlay (OverlayTexture red tint).
if overlay == 1u || overlay == 8u {
c = vec4(mix(c.rgb, vec3(1.0, 0.0, 0.0), 0.3), c.a);
back = vec4(mix(back.rgb, vec3(1.0, 0.0, 0.0), 0.3), back.a);
}
out.color = c;
out.back_color = back;
// Overlay 5: OverlayTexture white flash (primed TNT), applied after texturing.
out.flash = select(0.0, 0.75, overlay == 5u);
out.overlay_color = overlay_texel(overlay);
// Sky geometry (clouds, celestial bodies) is exempt from render-distance fog.
out.spherical = select(length(position), 0.0, overlay >= 2u && overlay <= 4u);
out.cylindrical = select(max(length(position.xz), abs(position.y)), 0.0, overlay >= 2u && overlay <= 4u);
@@ -140,7 +149,10 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
return vec4(color.rgb, color.a * (1.0 - linear_fog(in.spherical, 0.0, globals.fog_ends.y)));
}
if color.a < 0.1 { discard; }
color = vec4(mix(color.rgb, vec3(1.0), in.flash), color.a);
// entity.fsh calculateFinalColor: the overlay (hurt red, TNT white) over the
// lit texture, then the lightmap, then the glint and fog.
color = vec4(mix(in.overlay_color.rgb, color.rgb, in.overlay_color.a), color.a);
color *= in.light_color;
if in.overlay == 7u || in.overlay == 8u {
// Enchantment glint (overlay 7, 8 with the hurt tint): the purple
// enchanted_glint sheen drifting diagonally over the item's shape.
@@ -158,6 +170,6 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
}
@fragment fn fs_celestial(in: Out) -> @location(0) vec4<f32> {
let color = textureSample(atlas, atlas_sampler, in.uv) * in.color;
let color = textureSample(atlas, atlas_sampler, in.uv) * in.color * in.light_color;
return color;
}
+2 -2
View File
@@ -29,10 +29,10 @@ pub fn position(tag: &Tag) -> Option<Vec3> {
pub fn uuid(tag: &Tag) -> Option<[i32; 4]> {
uuid_from_tag(tag.get("UUID"))
}
fn motion(tag: &Tag) -> Vec3 {
pub fn motion(tag: &Tag) -> Vec3 {
read_doubles::<3>(tag.get("Motion")).map_or(Vec3::ZERO, |m| Vec3::new(m[0], m[1], m[2]))
}
fn rotation(tag: &Tag) -> [f32; 2] {
pub fn rotation(tag: &Tag) -> [f32; 2] {
read_doubles::<2>(tag.get("Rotation")).map_or([0.0; 2], |r| [r[0] as f32, r[1] as f32])
}
fn flag(tag: &Tag, key: &str) -> bool {
+4
View File
@@ -39,6 +39,10 @@ impl FlatTerrain {
biome: biomes.id(&biome),
})
}
/// FlatLevelSource.getSpawnHeight: the top of the layers.
pub fn spawn_height(&self) -> i32 {
crate::chunk::MIN_Y + self.layers.len().min(crate::chunk::HEIGHT as usize) as i32
}
}
impl ChunkGenerator for FlatTerrain {
type Worker = ();
+110 -225
View File
@@ -45,6 +45,7 @@ mod ghasts;
mod golems;
mod growth;
mod hand;
mod initial_spawn;
mod item_draw;
mod item_particles;
mod jukebox;
@@ -69,6 +70,7 @@ mod names;
mod natural_spawning;
mod nautili;
mod net_harness;
mod nether_portal;
mod options;
mod packs;
mod paintings;
@@ -519,6 +521,13 @@ impl LevelAccess for GameLevel<'_> {
effect: PlayerEffect::DropItem(item),
..
} => self.pop_above(pos, item),
// Picking a sweet berry bush or cave vines: the harvest loot,
// popped before the pick sound draws its pitch.
LevelEvent::Player {
pos,
state,
effect: PlayerEffect::InteractLoot(table),
} => self.drop_interact_loot(pos, state, table),
event => self.events.push(event),
}
}
@@ -678,7 +687,13 @@ struct Game<'a> {
book: Option<books::BookScreen>,
/// Lecterns whose page-turn pulse is running (ticks left).
lectern_pulses: Vec<((i32, i32, i32), i32)>,
/// Steps of the world spawn's chunk spiral taken so far.
spawn_search: u32,
/// The world spawn search's origin chunk and fallback height, once known.
spawn_origin: Option<((i32, i32), i32)>,
spawn_spiral: horizon_client::world_spawn::ChunkSpiral,
/// A new player's spawn search, while its candidates' chunks load.
player_spawn: Option<horizon_client::world_spawn::PlayerSpawnFinder>,
mobs: Vec<Mob>,
arrows: Vec<Arrow>,
creatures: creatures::Creatures,
@@ -751,8 +766,8 @@ struct Game<'a> {
world_root: PathBuf,
/// A player carried through a portal, re-placed once the destination loads.
travelling: Option<(PlayerMotion, Vec3)>,
portal_ticks: u32,
portal_cooldown: u32,
/// Nether portals: the player's, items' and mobs' (game/nether_portal.rs).
portals: nether_portal::Portals,
/// The pending travel goes through an End portal (EndPortalBlock destinations).
end_travel: bool,
/// The next enter_dimension call comes from an End portal.
@@ -2135,14 +2150,16 @@ impl Game<'_> {
game_master: false,
};
let at = Vec3::new(hit.point[0], hit.point[1], hit.point[2]);
let item = held.as_ref().map(|s| s.item.to_string());
let result = self.with_level(|b, level, ticks| {
b.use_without_item(
b.use_item_on(
level,
ticks,
BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]),
face,
at,
player,
item.as_deref(),
)
});
self.process_level_events()?;
@@ -2199,15 +2216,8 @@ impl Game<'_> {
}
return Ok(());
}
if info.consumable
&& info.food.is_some()
&& let Some(p) = self.player.as_ref()
&& (p.health.food.food < 20 || self.creative)
{
// Consumable.startConsuming: held right click for consume_seconds.
if self.using.is_none() {
self.using = Some((self.selected, 0));
}
// Block foods attempt placement before starting consumption.
if !(info.block.is_some() && self.pick().is_some()) && self.start_eating(&info) {
return Ok(());
}
if self.place_boat(&stack) {
@@ -2234,6 +2244,8 @@ impl Game<'_> {
return Ok(());
}
if !self.may_build() {
// ItemStack.useOn passes in adventure mode; useItem eats.
self.start_eating(&info);
return Ok(());
}
let face = match hit.face {
@@ -2259,6 +2271,11 @@ impl Game<'_> {
let outcome = self.with_level(|b, level, ticks| b.place_block(level, ticks, &ctx));
let PlaceOutcome::Placed { pos, state } = outcome else {
self.process_level_events()?;
// BlockItem.useOn: a consumable that could not be placed is used,
// which ItemStack.useOn counts as a use of the item.
if self.start_eating(&info) {
self.stats.add("used", &stack.item, 1);
}
return Ok(());
};
let target = [pos.x, pos.y, pos.z];
@@ -2275,25 +2292,18 @@ impl Game<'_> {
}
}
self.swing_arm();
let sounds = self.res.facts.get(state).sounds.clone();
let center = [
f64::from(target[0]) + 0.5,
f64::from(target[1]) + 0.5,
f64::from(target[2]) + 0.5,
];
// SolidBucketItem.getPlaceSound: the bucket's own empty sound.
// BlockItem.place's sound is among the level events;
// SolidBucketItem.getPlaceSound replaces it with the bucket's own.
let solid_bucket = &*stack.item == "minecraft:powder_snow_bucket";
let place_sound = if solid_bucket {
"minecraft:item.bucket.empty_powder_snow"
} else {
&sounds.place
};
self.audio.play(
place_sound,
Some(center),
(sounds.volume + 1.0) / 2.0,
sounds.pitch * 0.8,
);
if solid_bucket {
for event in &mut self.level_events {
if let LevelEvent::Sound { pos: at, sound, .. } = event
&& *at == pos
{
*sound = "minecraft:item.bucket.empty_powder_snow".into();
}
}
}
self.process_level_events()?;
// BlockItem.place: the used statistic and the placed_block trigger.
self.stats.add("used", &stack.item, 1);
@@ -2307,6 +2317,23 @@ impl Game<'_> {
}
Ok(())
}
/// `Consumable.startConsuming` for held food the player can eat
/// (`Player.canEat`): the right click is held for `consume_seconds`.
fn start_eating(&mut self, info: &horizon_client::items::ItemInfo) -> bool {
if !info.consumable
|| info.food.is_none()
|| !self
.player
.as_ref()
.is_some_and(|p| p.health.food.food < 20 || self.creative)
{
return false;
}
if self.using.is_none() {
self.using = Some((self.selected, 0));
}
true
}
fn consume_held(&mut self) {
if self.creative {
return;
@@ -2517,31 +2544,6 @@ impl Game<'_> {
}
Ok(())
}
/// The i-th world spawn search point: a square spiral in 48-block steps.
fn spawn_candidate(i: u32) -> (i32, i32) {
if i == 0 {
return (0, 0);
}
let mut k = 1u32;
let mut ring = 1i32;
loop {
let points = 8 * ring as u32;
if i < k + points {
let j = (i - k) as i32;
let side = j / (2 * ring);
let t = j % (2 * ring) - ring;
let (x, z) = match side {
0 => (t, -ring),
1 => (ring, t),
2 => (-t, ring),
_ => (-ring, -t),
};
return (x * 48, z * 48);
}
k += points;
ring += 1;
}
}
/// A column whose surface is a full solid, non-fluid, non-leaf block open to the sky.
fn land_column(&self, x: i32, z: i32) -> Option<i32> {
if self.dim == Dim::Nether {
@@ -2600,48 +2602,48 @@ impl Game<'_> {
.spawn
.map(|s| Vec3::new(s[0] + 0.5, s[1], s[2] + 0.5));
}
let anchor = match saved.or(self.spawn) {
Some(p) => (p.x.floor() as i32, p.z.floor() as i32),
None => Self::spawn_candidate(self.spawn_search),
};
let (cx, cz) = (anchor.0 >> 4, anchor.1 >> 4);
self.streaming.center = (cx, cz);
if !(-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) {
return Ok(());
}
let feet = if let Some(p) = saved {
let (cx, cz) = ((p.x.floor() as i32) >> 4, (p.z.floor() as i32) >> 4);
self.streaming.center = (cx, cz);
if !(-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) {
return Ok(());
}
self.level.position = None;
p
} else if let Some(s) = self.spawn {
} else if self.spawn.is_none() || self.player_spawn.is_some() {
// A new world: its spawn, then the first player around it.
if self.spawn.is_none() {
let Some([x, y, z]) = self.find_world_spawn()? else {
return Ok(());
};
self.spawn = Some(Vec3::new(
f64::from(x) + 0.5,
f64::from(y),
f64::from(z) + 0.5,
));
self.level.spawn = Some([f64::from(x), f64::from(y), f64::from(z)]);
}
let s = self
.level
.spawn
.unwrap_or_default()
.map(|v| v.floor() as i32);
let Some(feet) = self.find_player_spawn(s)? else {
return Ok(());
};
feet
} else {
let s = self.spawn.unwrap_or_default();
let (cx, cz) = ((s.x.floor() as i32) >> 4, (s.z.floor() as i32) >> 4);
self.streaming.center = (cx, cz);
if !(-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) {
return Ok(());
}
// WorldSpawn: the stored column, lifted onto its current surface.
let y = self
.land_column(s.x.floor() as i32, s.z.floor() as i32)
.map_or(s.y, f64::from);
Vec3::new(s.x, y.max(s.y), s.z)
} else {
let mut best: Option<(i64, i32, i32, i32)> = None;
for z in (cz - 1) * 16..(cz + 2) * 16 {
for x in (cx - 1) * 16..(cx + 2) * 16 {
if let Some(y) = self.land_column(x, z) {
let d = i64::from(x - anchor.0).pow(2) + i64::from(z - anchor.1).pow(2);
if best.is_none_or(|b| d < b.0) {
best = Some((d, x, y, z));
}
}
}
}
match best {
Some((_, x, y, z)) => {
let spawn = Vec3::new(f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5);
self.spawn = Some(spawn);
self.level.spawn = Some([f64::from(x), f64::from(y), f64::from(z)]);
spawn
}
None => {
self.spawn_search += 1;
return Ok(());
}
}
};
let mut player = PlayerMotion::new(self.motion, feet)?;
player.yaw = self.yaw;
@@ -2881,6 +2883,7 @@ impl Game<'_> {
}
MotionEvent::Snowflake { position, velocity } => self.snowflake(position, velocity),
MotionEvent::EnterBlock { state } => self.trigger_enter_block(state),
MotionEvent::InsidePortal { pos } => self.player_inside_nether_portal(pos),
_ => {}
}
}
@@ -2967,6 +2970,7 @@ impl Game<'_> {
horizon_client::spans::time("tick_rockets", || self.tick_rockets());
}
if running {
horizon_client::spans::time("entity_portals", || self.handle_entity_portals());
horizon_client::spans::time("tick_items", || self.tick_items());
}
horizon_client::spans::time("spawn_loaded_entities", || self.spawn_loaded_entities());
@@ -2974,11 +2978,15 @@ impl Game<'_> {
horizon_client::spans::time("tick_mobs", || self.tick_mobs())?;
horizon_client::spans::time("recheck_golem_openers", || self.recheck_golem_openers());
horizon_client::spans::time("tick_experience", || self.tick_experience());
horizon_client::spans::time("entity_portals", || {
self.find_entity_portals();
self.resolve_arrivals();
});
}
horizon_client::spans::time("tick_lan", || self.tick_lan());
horizon_client::spans::time("tick_hand", || self.tick_hand());
horizon_client::spans::time("tick_sleep", || self.tick_sleep());
horizon_client::spans::time("tick_portal", || self.tick_portal())?;
horizon_client::spans::time("tick_portal", || self.tick_nether_portal())?;
if running {
horizon_client::spans::time("tick_end", || self.tick_end())?;
}
@@ -5675,8 +5683,12 @@ impl Game<'_> {
self.player = None;
self.spawn = None;
self.spawn_search = 0;
self.spawn_origin = None;
self.spawn_spiral = Default::default();
self.player_spawn = None;
self.mobs.clear();
self.creatures.reset_trader();
self.portals = Default::default();
self.arrows.clear();
self.dropped.clear();
self.particles.clear();
@@ -5835,7 +5847,6 @@ impl Game<'_> {
self.orbs.clear();
self.mining = None;
self.travelling = Some((player, destination));
self.portal_cooldown = 300;
self.end_travel = (target == Dim::End || from_end) && self.end_portal_travel;
if let Some(r) = self.renderer.as_mut() {
r.clear_sections();
@@ -5944,138 +5955,9 @@ impl Game<'_> {
}
Ok(false)
}
/// PortalForcer: reuse a nearby portal, else build a 2x3 obsidian portal.
fn place_after_travel(&mut self, mut player: PlayerMotion, target: Vec3) -> Result<()> {
let (tx, tz) = (target.x.floor() as i32, target.z.floor() as i32);
let radius = if self.dim == Dim::Nether { 16 } else { 32 };
let (min_y, max_y) = if self.dim == Dim::Nether {
(1, 126)
} else {
(MIN_Y + 1, MIN_Y + HEIGHT - 3)
};
let portal_name = "minecraft:nether_portal";
let mut best: Option<(i64, [i32; 3])> = None;
for z in tz - radius..=tz + radius {
for x in tx - radius..=tx + radius {
if !self.world.loaded(x, z) {
continue;
}
for y in min_y..max_y {
if &*self.res.facts.get(self.world.block(x, y, z)).name == portal_name
&& &*self.res.facts.get(self.world.block(x, y - 1, z)).name != portal_name
{
let d = i64::from(x - tx).pow(2)
+ i64::from(z - tz).pow(2)
+ i64::from(y - target.y as i32).pow(2);
if best.is_none_or(|b| d < b.0) {
best = Some((d, [x, y, z]));
}
}
}
}
}
let spot = match best {
Some((_, p)) => p,
None => {
// Build: obsidian frame 4 wide, 5 tall, with a floor, carved into the terrain.
let y = (target.y.floor() as i32).clamp(min_y + 1, max_y - 5);
let set = |g: &mut Self, p: [i32; 3], name: &str| -> Result<()> {
if let Some(id) = g.res.assets.registry.default_state(name) {
g.world.set(p[0], p[1], p[2], id)?;
}
Ok(())
};
for dz in -1..=1 {
for dx in -1..=2 {
set(self, [tx + dx, y - 1, tz + dz], "minecraft:obsidian")?;
for dy in 0..4 {
set(self, [tx + dx, y + dy, tz + dz], "minecraft:air")?;
}
}
}
for w in -1..=2 {
for h in -1..=3 {
if w == -1 || w == 2 || h == -1 || h == 3 {
set(self, [tx + w, y + h, tz], "minecraft:obsidian")?;
}
}
}
self.try_light_portal([tx, y, tz])?;
[tx, y, tz]
}
};
player.position = Vec3::new(
f64::from(spot[0]) + 0.5,
f64::from(spot[1]),
f64::from(spot[2]) + 0.5,
);
player.velocity = Vec3::ZERO;
self.previous_position = player.position;
self.player = Some(player);
self.sway = Default::default();
self.apply_equipment();
let at = [f64::from(spot[0]), f64::from(spot[1]), f64::from(spot[2])];
self.audio
.play("minecraft:block.portal.travel", Some(at), 0.25, 1.0);
Ok(())
}
fn tick_portal(&mut self) -> Result<()> {
let Some(p) = self.player.as_ref() else {
return Ok(());
};
let w = f64::from(p.dimensions.width) / 2.0;
let (lo, hi) = (
[p.position.x - w, p.position.y, p.position.z - w],
[
p.position.x + w,
p.position.y + f64::from(p.dimensions.height),
p.position.z + w,
],
);
let mut inside = false;
for x in lo[0].floor() as i32..=hi[0].floor() as i32 {
for y in lo[1].floor() as i32..=hi[1].floor() as i32 {
for z in lo[2].floor() as i32..=hi[2].floor() as i32 {
if &*self.res.facts.get(self.world.block(x, y, z)).name
== "minecraft:nether_portal"
{
inside = true;
}
}
}
}
if !inside {
self.portal_ticks = 0;
self.portal_cooldown = self.portal_cooldown.saturating_sub(1);
return Ok(());
}
if self.portal_cooldown > 0 {
return Ok(());
}
if self.portal_ticks == 0 {
let at = self.eye_position();
self.audio.play(
"minecraft:block.portal.trigger",
at,
0.25,
self.world.random.next_float() * 0.4 + 0.8,
);
}
self.portal_ticks += 1;
// Player.getPortalWaitTime: 80 ticks, or 1 when invulnerable (creative).
let wait = if self.creative { 1 } else { 80 };
if self.portal_ticks >= wait {
self.portal_ticks = 0;
// NetherPortalBlock: the Nether leads to the Overworld, anywhere else to the Nether.
let target = if self.dim == Dim::Nether {
Dim::Overworld
} else {
Dim::Nether
};
self.end_portal_travel = false;
self.enter_dimension(target)?;
}
Ok(())
/// Arrival through a nether portal, once the destination is loaded.
fn place_after_travel(&mut self, player: PlayerMotion, target: Vec3) -> Result<()> {
self.arrive_through_nether_portal(player, target)
}
/// Leaving the game with a world open (window closed, Quit, `quit`):
/// menu items go back (Player.closeContainer), then the world is saved,
@@ -7717,6 +7599,7 @@ impl Game<'_> {
self.save_raids();
self.save_fight();
self.save_wandering_trader();
self.save_portal_arrivals();
self.save_stats();
self.save_advancements();
self.save_scoreboard();
@@ -9167,6 +9050,9 @@ pub fn run() -> Result<()> {
book: None,
lectern_pulses: Vec::new(),
spawn_search: 0,
spawn_origin: None,
spawn_spiral: Default::default(),
player_spawn: None,
mobs: Vec::new(),
arrows: Vec::new(),
creatures: Default::default(),
@@ -9217,8 +9103,7 @@ pub fn run() -> Result<()> {
dim: Dim::Overworld,
world_root: PathBuf::new(),
travelling: None,
portal_ticks: 0,
portal_cooldown: 0,
portals: Default::default(),
end_travel: false,
end_portal_travel: false,
end: Default::default(),
@@ -10,11 +10,13 @@ use super::{
use horizon_client::{
Result,
chunk::Chunk,
command::args::GameMode,
containers::BlockEntity,
gamerules::Value as RuleValue,
item_data::{canon_stack, parse_stack},
items::ItemStack,
mobs::{Mob, Species},
motion::PlayerMotion,
projectiles::ProjectileKind,
world::World,
};
@@ -25,6 +27,7 @@ use horizon_core::{
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};
use winit::keyboard::KeyCode;
thread_local! {
/// Level and game events recorded while a fixture case runs.
@@ -267,6 +270,8 @@ impl Game<'_> {
self.fixture_remove(origin, op)?;
} else if let Some(op) = case.get("use") {
used = self.fixture_use(origin, op)?;
} else if let Some(op) = case.get("use_item") {
used = self.fixture_use_item(origin, op)?;
} else if case.get("hopper").is_some() {
// HopperBlockEntity.pushItemsTick, once.
self.hopper_try_move_items((origin.x, origin.y, origin.z));
@@ -402,6 +407,72 @@ impl Game<'_> {
Ok(out)
}
/// A player three blocks south of `pos` right-clicks its top face holding
/// the case's item (`use_item_as_player` on that hit): the statistics,
/// the held stack and the item it started using, as
/// `VanillaDispenserOracle.useItem` prints them.
fn fixture_use_item(&mut self, pos: BlockPos, op: &Value) -> Result<Vec<String>> {
let stack = parse_stack(op["item"].as_str().unwrap_or("-"))?;
self.mode = if op["creative"].as_bool().unwrap_or(false) {
GameMode::Creative
} else {
GameMode::Survival
};
self.creative = self.mode == GameMode::Creative;
let mut player = PlayerMotion::new(
self.motion,
horizon_core::geometry::Vec3::new(
f64::from(pos.x) + 0.5,
f64::from(pos.y) + 1.0,
f64::from(pos.z) + 3.5,
),
)?;
player.health.food.food = op["food"].as_i64().unwrap_or(20) as i32;
self.player = Some(player);
self.yaw = 0.0;
self.pitch = 90.0;
self.keys.clear();
if op["sneaking"].as_bool().unwrap_or(false) {
self.keys.insert(KeyCode::ShiftLeft);
}
self.using = None;
self.inventory[self.selected] = stack.clone();
let used_before = stack
.as_ref()
.map_or(0, |s| self.stats.get("used", &s.item));
self.forced_hit = Some(super::Hit {
pos: [pos.x, pos.y, pos.z],
face: [0, 1, 0],
point: [
f64::from(pos.x) + 0.5,
f64::from(pos.y) + 1.0,
f64::from(pos.z) + 0.5,
],
});
let used = self.use_item_as_player();
self.forced_hit = None;
used?;
self.process_level_events()?;
let mut out = Vec::new();
if let Some(s) = &stack {
let used = self.stats.get("used", &s.item) - used_before;
if used != 0 {
out.push(format!("stat {} minecraft:used {used}", s.item));
}
}
let using = self
.using
.and_then(|(slot, _)| self.stack_in(slot))
.map_or("-".to_owned(), |s| s.item.to_string());
out.push(format!(
"held {} using {using}",
canon_stack(self.inventory[self.selected].as_ref())
));
self.player = None;
self.using = None;
Ok(out)
}
/// A stack in a block entity's slot: a container's, a jukebox's record, a
/// lectern's book, or the items of a block entity Horizon keeps as saved.
fn fixture_fill(&mut self, p: (i32, i32, i32), slot: usize, stack: Option<ItemStack>) {
+4 -4
View File
@@ -389,7 +389,7 @@ impl Game<'_> {
}
}
if portal {
if self.portal_cooldown == 0 {
if self.portals.player.cooldown == 0 {
let target = if self.dim == Dim::End {
Dim::Overworld
} else {
@@ -400,10 +400,10 @@ impl Game<'_> {
self.end_portal_travel = false;
result?;
// Player.getDimensionChangingDelay.
self.portal_cooldown = 10;
self.portals.player.cooldown = 10;
} else {
// Entity.setAsInsidePortal while cooling down restarts the cooldown.
self.portal_cooldown = 10;
self.portals.player.cooldown = 10;
}
} else if let Some(g) = gateway
&& self.end.gateway_cooldown == 0
@@ -440,7 +440,7 @@ impl Game<'_> {
) -> Result<()> {
self.end_travel = false;
// Player.getDimensionChangingDelay (enter_dimension uses the Nether portal value).
self.portal_cooldown = 10;
self.portals.player.cooldown = 10;
if player.health.dead_or_dying() {
// Respawning out of the End: a fresh player at the spawn.
player = PlayerMotion::new(self.motion, target)?;
+11
View File
@@ -47,9 +47,20 @@ impl Game<'_> {
};
let pos = BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]);
let used = self.with_level(|b, level, ticks| b.use_bone_meal(level, ticks, pos, face));
// ItemStack.causeUseVibration at the player, after the meal is used
// up (shrunk even in creative): an emptied stack has no use effects.
if used
&& stack.count > 1
&& let Some(p) = self.player.as_ref().map(|p| p.position)
{
let ctx = self.player_context(None);
self.post_game_event("minecraft:item_interact_finish", [p.x, p.y, p.z], ctx);
}
self.process_level_events()?;
if used {
self.swing_arm();
// ItemStack.useOn: an item interaction counts as a use.
self.stats.add("used", &stack.item, 1);
self.consume_held();
}
Ok(used)
@@ -0,0 +1,217 @@
//! A new world's spawn and its first player's position: MinecraftServer.
//! setInitialSpawn walks a chunk spiral around NoiseBasedChunkGenerator.
//! getOrigin, then PlayerSpawnFinder.findSpawn picks a free column around
//! the world spawn within the respawn radius.
use super::{Game, dispenser::entity_random};
use horizon_client::{
Result,
assets::Properties,
chunk::{HEIGHT, MIN_Y},
collisions::{SceneCollisions, no_collision_or_liquid},
world::World,
world_spawn::{
PlayerSpawnFinder, SpawnCandidate, SpawnLevel, level_respawn_pos, spawn_pos_in_chunk,
},
};
use horizon_core::{
geometry::{Aabb, Direction, ShapeOp, Vec3, VoxelShape},
position::BlockPos,
random::RandomSource,
};
use horizon_world::{
block_collision::BlockCollisionRegistry, collision_context::CollisionContext,
heightmap::HeightmapType, worldgen::terrain::TerrainBlockStates,
};
/// The loaded world as the spawn searches query it.
struct Columns<'a, 'r> {
world: &'a World,
properties: &'a Properties,
binding: &'a BlockCollisionRegistry<'r>,
}
impl SpawnLevel for Columns<'_, '_> {
fn min_y(&self) -> i32 {
MIN_Y
}
fn height(&self, kind: HeightmapType, x: i32, z: i32) -> i32 {
(MIN_Y..MIN_Y + HEIGHT)
.rev()
.find(|&y| kind.is_opaque(self.properties.heightmap_state(self.world.block(x, y, z))))
.map_or(MIN_Y, |y| y + 1)
}
fn has_fluid(&self, x: i32, y: i32, z: i32) -> bool {
use horizon_world::heightmap::HeightmapState;
self.properties
.heightmap_state(self.world.block(x, y, z))
.has_fluid()
}
fn top_face_full(&self, x: i32, y: i32, z: i32) -> bool {
let mut scene = SceneCollisions {
world: self.world,
binding: self.binding,
subject: None,
};
let state = self.world.block(x, y, z);
let Ok(shape) = self.binding.collision_shape_with_context(
&mut scene,
state,
BlockPos::new(x, y, z),
&CollisionContext::empty(false),
) else {
return false;
};
shape.face_shape(Direction::Up).is_ok_and(|face| {
VoxelShape::block()
.join_is_not_empty(&face, ShapeOp::XOR)
.is_ok_and(|differs| !differs)
})
}
}
impl Game<'_> {
fn spawn_columns(&self) -> Columns<'_, '_> {
Columns {
world: &self.world,
properties: &self.res.assets.properties,
binding: self.collision,
}
}
/// ChunkGenerator.getOrigin and getSpawnHeight of the overworld.
fn spawn_origin(&self) -> Result<((i32, i32), i32)> {
if let Some(flat) =
horizon_client::save::world_gen_settings(&self.world_root).and_then(|s| {
horizon_client::flatgen::FlatTerrain::from_settings(
&s,
self.res.assets.registry,
&self.res.biomes,
)
})
{
return Ok(((0, 0), flat.spawn_height()));
}
if self.options.test_terrain {
return Ok(((0, 0), 64));
}
let origin = match self.end.locator() {
Some(terrain) => terrain.origin()?,
None => horizon_core::position::ChunkPos::new(0, 0),
};
Ok(((origin.x, origin.z), 64))
}
/// MinecraftServer.setInitialSpawn: the first chunk of the spiral with a
/// valid respawn column gives the world spawn, else the origin chunk's
/// centre at the spawn height. None while a chunk to test is loading.
pub(super) fn find_world_spawn(&mut self) -> Result<Option<[i32; 3]>> {
let ((ox, oz), height) = match self.spawn_origin {
Some(origin) => origin,
None => *self.spawn_origin.insert(self.spawn_origin()?),
};
while let Some((dx, dz)) = self.spawn_spiral.current() {
self.spawn_search = self.spawn_spiral.steps() as u32;
if self.spawn_spiral.tested() {
let (cx, cz) = (ox + dx, oz + dz);
if !self.streaming.is_lit(cx, cz) {
self.streaming.center = (cx, cz);
return Ok(None);
}
if let Some(pos) = spawn_pos_in_chunk(&self.spawn_columns(), cx, cz) {
return Ok(Some(pos));
}
}
self.spawn_spiral.advance();
}
Ok(Some([ox * 16 + 8, height, oz * 16 + 8]))
}
/// PlayerSpawnFinder.findSpawn around the world spawn: the feet of a
/// player who has no position yet. None while a candidate's chunk loads.
pub(super) fn find_player_spawn(&mut self, suggestion: [i32; 3]) -> Result<Option<Vec3>> {
let mut finder = match self.player_spawn {
Some(finder) => finder,
None if self.level.game_mode == 2 => {
// Adventure mode: the suggestion itself.
let mut finder = PlayerSpawnFinder::new(suggestion, 0, |_| 0);
finder.next_candidate();
finder
}
None => {
let mut radius = self.ui.rules.int("respawn_radius").max(0);
let to_border = self
.border
.distance(f64::from(suggestion[0]), f64::from(suggestion[2]))
.floor() as i32;
if to_border < radius {
radius = to_border;
}
if to_border <= 1 {
radius = 1;
}
PlayerSpawnFinder::new(suggestion, radius, |n| {
entity_random().next_int_bound(n).unwrap_or(0)
})
}
};
let found = loop {
let Some(candidate) = finder.next_candidate() else {
break Some(self.fixup_spawn_height(suggestion));
};
let (x, z) = match candidate {
SpawnCandidate::Column(x, z) => (x, z),
SpawnCandidate::Suggestion => (suggestion[0], suggestion[2]),
};
if !self.streaming.is_lit(x >> 4, z >> 4) {
self.streaming.center = (x >> 4, z >> 4);
finder.retry();
break None;
}
match candidate {
SpawnCandidate::Column(x, z) => {
if let Some(pos) = level_respawn_pos(&self.spawn_columns(), x, z)
&& self.player_fits(pos)
{
break Some(bottom_center(pos));
}
}
SpawnCandidate::Suggestion => break Some(self.fixup_spawn_height(suggestion)),
}
};
self.player_spawn = found.is_none().then_some(finder);
Ok(found)
}
/// PlayerSpawnFinder.noCollisionNoLiquid: a player's box standing at the
/// block's bottom centre touches no block or liquid.
fn player_fits(&self, pos: [i32; 3]) -> bool {
let feet = bottom_center(pos);
let bounds = Aabb::new(
Vec3::new(feet.x - 0.3, feet.y, feet.z - 0.3),
Vec3::new(feet.x + 0.3, feet.y + 1.8, feet.z + 0.3),
);
let mut scene = SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
no_collision_or_liquid(&mut scene, bounds)
}
/// PlayerSpawnFinder.fixupSpawnHeight: up out of anything solid, then
/// down onto the ground.
fn fixup_spawn_height(&self, pos: [i32; 3]) -> Vec3 {
let [x, mut y, z] = pos;
while !self.player_fits([x, y, z]) && y < MIN_Y + HEIGHT - 1 {
y += 1;
}
y -= 1;
while self.player_fits([x, y, z]) && y > MIN_Y {
y -= 1;
}
bottom_center([x, y + 1, z])
}
}
/// Vec3.atBottomCenterOf.
fn bottom_center(pos: [i32; 3]) -> Vec3 {
Vec3::new(
f64::from(pos[0]) + 0.5,
f64::from(pos[1]),
f64::from(pos[2]) + 0.5,
)
}
+2 -2
View File
@@ -1240,9 +1240,9 @@ impl Game<'_> {
let start = out.len();
self.block_model_vertices(state, m, packed, out);
if flash {
// submitWhiteSolidBlock: OverlayTexture.u(1.0) on the cart's own light.
for v in &mut out[start..] {
v.color = 0xFFFF_FFFF;
v.light = 240 | 240 << 8;
v.layer = 5;
}
}
}
+3 -12
View File
@@ -216,14 +216,13 @@ impl Game<'_> {
light: u32,
out: &mut Vec<Vertex>,
) {
let overlay = u32::from(mob.hurt_time > 0);
self.captain_banner_geometry(mob, camera, alpha, light, out);
self.held_item_geometry(mob, camera, alpha, light, true, out);
if mob.species() == Species::Enderman
&& let Some(state) = mob.extra.carried
&& let Some((sprite, tint)) = self.particle_sprite(state)
{
// CarriedBlockLayer.
// CarriedBlockLayer: OverlayTexture.NO_OVERLAY, never the hurt tint.
let base = render::base_transform(mob, alpha as f32, camera);
let t = base
* glam::Mat4::from_translation(glam::Vec3::new(0.0, 0.6875, -0.75))
@@ -240,7 +239,7 @@ impl Game<'_> {
tint,
},
light,
overlay,
0,
out,
);
}
@@ -257,7 +256,7 @@ impl Game<'_> {
lit: bool,
out: &mut Vec<Vertex>,
) {
let overlay = u32::from(mob.hurt_time > 0);
// ItemInHandLayer submits with OverlayTexture.NO_OVERLAY: no hurt tint.
for (item, left) in [(&mob.extra.main_hand, false), (&mob.extra.off_hand, true)] {
let Some(item) = item else { continue };
let Some(t) =
@@ -297,19 +296,11 @@ impl Game<'_> {
// `updateForLiving`: seeded by the entity id plus the context ordinal.
let seed = mob.id as i32 + if left { 1 } else { 2 };
let state = self.resolve_item(&stack, context, Some(&owner), seed);
let start = out.len();
if lit {
self.submit_item_world(&state, t, light, out);
} else {
self.submit_item_unlit(&state, t, light, out);
}
if overlay != 0 {
for v in &mut out[start..] {
if v.layer == 0 {
v.layer = overlay;
}
}
}
}
}
}
@@ -0,0 +1,722 @@
//! Nether portals for the player and the other entities:
//! `Entity.setAsInsidePortal` / `handlePortal` with `PortalProcessor`,
//! `NetherPortalBlock.getPortalTransitionTime` and `getPortalDestination`
//! (`PortalForcer` through `horizon_world::level::portal_travel`), and
//! `LocalPlayer.handlePortalTransitionEffect`.
//!
//! Only one dimension is loaded at a time. The player's destination is found
//! once the other dimension has loaded around it. An item or mob that goes
//! through waits as an `Arrival` (its saved compound and where it stood in its
//! portal) until the player is in that dimension and its exit is loaded.
use super::{Dim, Game, Screen};
use horizon_client::Result;
use horizon_client::nether_portal::PortalState;
use horizon_core::{
geometry::{Axis, Vec3},
position::BlockPos,
random::RandomSource,
};
use horizon_world::{
level::portal_travel::{
BorderBounds, FoundRectangle, closest_portal, collision_free_position, exit_position,
largest_rectangle_around, relative_position,
},
nbt::Tag,
};
use std::collections::HashMap;
/// `Player.getDimensionChangingDelay`.
pub(super) const PLAYER_DELAY: i32 = 10;
/// `Entity.getDimensionChangingDelay`.
const ENTITY_DELAY: i32 = 300;
/// Where in its portal a traveller stood, and where its exit is to be found.
#[derive(Clone, Copy, Debug)]
pub(super) struct Plan {
pub(super) dim: Dim,
/// The border-clamped, scaled position (`approximateExitPos`).
pub(super) approximate: BlockPos,
entry_x_axis: bool,
offset: Vec3,
width: f32,
height: f32,
}
/// An entity on its way to a dimension that isn't loaded.
#[derive(Clone, Debug)]
struct Arrival {
plan: Plan,
tag: Tag,
}
/// The nether portal state of the world (`Game::portals`).
#[derive(Default)]
pub(super) struct Portals {
/// The player's.
pub(super) player: PortalState,
/// The player's travel, while the destination loads.
pub(super) travel: Option<Plan>,
/// `LocalPlayer.portalProcess.isInsidePortalThisTick`.
client_inside: bool,
/// Items and mobs, by entity id.
entities: HashMap<u32, PortalState>,
/// Positions before this tick's moves, by entity id.
before: HashMap<u32, Vec3>,
arrivals: Vec<Arrival>,
loaded: bool,
dirty: bool,
}
fn rotate_y(v: Vec3, degrees: f32) -> Vec3 {
// Vec3.yRot((float)Math.toRadians(degrees))
let angle = f64::from(degrees.to_radians());
let (cos, sin) = (
f64::from(horizon_core::geometry::trig::cos(angle)),
f64::from(horizon_core::geometry::trig::sin(angle)),
);
Vec3::new(v.x * cos + v.z * sin, v.y, v.z * cos - v.x * sin)
}
fn doubles(values: [f64; 3]) -> Tag {
Tag::List(values.iter().map(|v| Tag::Double(v.to_bits())).collect())
}
impl Game<'_> {
/// The world border's extent.
fn border_bounds(&self) -> BorderBounds {
let [min_x, min_z, max_x, max_z] = self.border.bounds();
BorderBounds {
min_x,
min_z,
max_x,
max_z,
}
}
/// `ServerLevel.isAllowedToEnterPortal`.
fn may_enter(&self, target: Dim) -> bool {
target != Dim::Nether || self.ui.rules.bool("allow_entering_nether_using_portals")
}
/// The plan of an entity of `width` by `height` at `at` going through the
/// portal at `entry` (`getDimensionTransitionFromExit` and the scaled,
/// clamped exit of `getPortalDestination`).
fn portal_plan(
&self,
entry: BlockPos,
at: Vec3,
width: f32,
height: f32,
reset_forward: bool,
) -> Plan {
let target = if self.dim == Dim::Nether {
Dim::Overworld
} else {
Dim::Nether
};
let state = self.world.block(entry.x, entry.y, entry.z);
let b = &self.res.behaviours;
let (entry_x_axis, offset) = match b.portal_axis(state) {
Some(x_axis) => {
let area = largest_rectangle_around(
entry,
if x_axis { Axis::X } else { Axis::Z },
21,
Axis::Y,
21,
|p| self.world.block(p.x, p.y, p.z) == state,
);
let mut offset = relative_position(area, x_axis, at, width, height);
if reset_forward {
offset.z = 0.0;
}
(x_axis, offset)
}
None => (true, Vec3::new(0.5, 0.0, 0.0)),
};
// DimensionType.getTeleportationScale: 8 out of the Nether, 1/8 into it.
let scale = if self.dim == Dim::Nether {
8.0
} else {
1.0 / 8.0
};
Plan {
dim: target,
approximate: self.border_bounds().clamp(at.x * scale, at.y, at.z * scale),
entry_x_axis,
offset,
width,
height,
}
}
/// The nether portal blocks of the chunks within `radius` of `center`
/// (the points of interest `PortalForcer` searches): loaded chunks as
/// they are, the others as saved; chunks never generated have none.
fn portal_blocks(&self, center: BlockPos, radius: i32) -> Vec<BlockPos> {
let b = &self.res.behaviours;
let chunk_radius = radius.div_euclid(16) + 1;
let (cx, cz) = (center.x >> 4, center.z >> 4);
let mut out = Vec::new();
for z in cz - chunk_radius..=cz + chunk_radius {
for x in cx - chunk_radius..=cx + chunk_radius {
let saved;
let chunk = match self.world.chunks.get(&(x, z)) {
Some(c) => &**c,
None => match self
.save
.load(x, z, self.res.assets.registry, &self.res.biomes)
{
Some(c) => {
saved = c;
&saved
}
None => continue,
},
};
for (s, section) in chunk.sections.iter().enumerate() {
if !section.blocks.maybe_has(|v| {
b.portal_axis(horizon_world::registry::BlockStateId(v))
.is_some()
}) {
continue;
}
let base = horizon_client::chunk::MIN_Y + 16 * s as i32;
for y in base..base + 16 {
for lz in 0..16 {
for lx in 0..16 {
let (wx, wz) = (x * 16 + lx, z * 16 + lz);
if b.portal_axis(chunk.block(wx, y, wz)).is_some() {
out.push(BlockPos::new(wx, y, wz));
}
}
}
}
}
}
}
out
}
/// The exit portal of `plan` in the loaded dimension: the closest one
/// within reach, else one built by `PortalForcer.createPortal`.
fn nether_exit_portal(&mut self, plan: &Plan) -> Option<FoundRectangle> {
let to_nether = plan.dim == Dim::Nether;
let radius = if to_nether { 16 } else { 128 };
let border = self.border_bounds();
let portals = self.portal_blocks(plan.approximate, radius);
let (min_section, max_section) = if to_nether { (0, 15) } else { (-4, 19) };
let found = closest_portal(
&portals,
plan.approximate,
to_nether,
&border,
min_section,
max_section,
);
if let Some(found) = found {
let state = self.world.block(found.x, found.y, found.z);
let x_axis = self.res.behaviours.portal_axis(state).unwrap_or(true);
return Some(largest_rectangle_around(
found,
if x_axis { Axis::X } else { Axis::Z },
21,
Axis::Y,
21,
|p| self.world.block(p.x, p.y, p.z) == state,
));
}
let logical = if to_nether { 128 } else { 384 };
let (approximate, x_axis) = (plan.approximate, plan.entry_x_axis);
let created = self.with_level(|b, level, ticks| {
b.create_portal(level, ticks, approximate, x_axis, &border, logical)
});
let _ = self.process_level_events();
created
}
/// `NetherPortalBlock.createDimensionTransition`: the arrival position
/// and the yaw turned by.
fn arrival(&self, plan: &Plan, exit: FoundRectangle) -> (Vec3, f32) {
let b = &self.res.behaviours;
let corner = exit.min_corner;
let exit_x_axis = b
.portal_axis(self.world.block(corner.x, corner.y, corner.z))
.unwrap_or(true);
let (bottom, rotation) = exit_position(
exit,
exit_x_axis,
plan.entry_x_axis,
plan.offset,
plan.width,
plan.height,
);
let border = self.border_bounds();
let at = collision_free_position(bottom, plan.width, plan.height, &border, |p| {
b.collision_shape(self.world.block(p.x, p.y, p.z))
.map(|s| s.moved(Vec3::new(f64::from(p.x), f64::from(p.y), f64::from(p.z))))
});
(at, rotation)
}
// ---- the player ----
/// `NetherPortalBlock.entityInside` for the player: `canUsePortal`, then
/// `setAsInsidePortal` (and the client's own, which drives the effect).
pub(super) fn player_inside_nether_portal(&mut self, pos: BlockPos) {
let alive = self
.player
.as_ref()
.is_some_and(|p| !p.health.dead_or_dying());
if !alive || self.riding.is_some() || self.sleeping.is_some() {
return;
}
self.portals.player.set_inside(pos, PLAYER_DELAY);
self.portals.client_inside = true;
}
/// `ServerPlayer.handlePortal` (not while changing dimension: there is no
/// player then). Players wait `players_nether_portal_default_delay`
/// ticks, or the creative delay with invulnerable abilities.
pub(super) fn tick_nether_portal(&mut self) -> Result<()> {
// A server's portals are its own.
if self.remote.is_some() {
return Ok(());
}
let Some(p) = self.player.as_ref() else {
return Ok(());
};
if self.travelling.is_some() {
return Ok(());
}
let allowed = !p.health.dead_or_dying() && self.riding.is_none() && self.sleeping.is_none();
let rule = if p.invulnerable {
"players_nether_portal_creative_delay"
} else {
"players_nether_portal_default_delay"
};
let transition = self.ui.rules.int(rule).max(0);
let Some(entry) = self
.portals
.player
.handle(allowed, transition, PLAYER_DELAY)
else {
return Ok(());
};
let Some(p) = self.player.as_ref() else {
return Ok(());
};
let plan = self.portal_plan(
entry,
p.position,
p.dimensions.width,
p.dimensions.height,
true,
);
if !self.may_enter(plan.dim) {
return Ok(());
}
self.portals.travel = Some(plan);
self.end_portal_travel = false;
self.enter_dimension(plan.dim)?;
// The destination is all on disk now: load around the portal its
// points of interest lead to, or the approximate exit.
let to_nether = plan.dim == Dim::Nether;
let portals = self.portal_blocks(plan.approximate, if to_nether { 16 } else { 128 });
let (min_section, max_section) = if to_nether { (0, 15) } else { (-4, 19) };
let border = self.border_bounds();
let found = closest_portal(
&portals,
plan.approximate,
to_nether,
&border,
min_section,
max_section,
);
let centre = found.unwrap_or(plan.approximate);
if let Some((_, target)) = self.travelling.as_mut() {
*target = Vec3::new(
f64::from(centre.x) + 0.5,
f64::from(centre.y),
f64::from(centre.z) + 0.5,
);
}
Ok(())
}
/// The player's arrival once the destination has loaded around the
/// approximate exit: the waiting entities first, then the exit portal
/// (found or built), the position in it, the turned yaw and motion, and
/// `TeleportTransition.PLAY_PORTAL_SOUND` (level event 1032).
pub(super) fn arrive_through_nether_portal(
&mut self,
mut player: horizon_client::motion::PlayerMotion,
target: Vec3,
) -> Result<()> {
self.resolve_arrivals();
let plan = self.portals.travel.take();
let exit = plan.as_ref().and_then(|plan| self.nether_exit_portal(plan));
let (position, rotation) = match (plan, exit) {
(Some(plan), Some(exit)) => self.arrival(&plan, exit),
_ => (target, 0.0),
};
player.position = position;
// Relative.ROTATION and Relative.DELTA: the yaw turns, the motion
// turns with it.
player.yaw += rotation;
player.head_yaw += rotation;
self.yaw += rotation;
player.velocity = rotate_y(player.velocity, -rotation);
self.previous_position = player.position;
self.player = Some(player);
self.sway = Default::default();
self.apply_equipment();
let pitch = self.world.random.next_float() * 0.4 + 0.8;
self.audio
.play("minecraft:block.portal.travel", None, 0.25, pitch);
Ok(())
}
/// `LocalPlayer.handlePortalTransitionEffect`: whether the confusion
/// effect grows this tick. Entering a portal closes screens other than
/// the chat and death screens and plays `block.portal.trigger` when the
/// effect starts from nothing.
pub(super) fn client_portal_effect(&mut self) -> bool {
if !std::mem::take(&mut self.portals.client_inside) {
return false;
}
match self.screen {
Screen::Playing | Screen::Chat | Screen::Dead => {}
Screen::Inventory | Screen::Creative => {
self.close_container();
self.carried = None;
self.screen = Screen::Playing;
self.capture(true);
}
_ => {
self.screen = Screen::Playing;
self.capture(true);
}
}
if self.res.screen_fx.portal == 0.0 {
let pitch = self.world.random.next_float() * 0.4 + 0.8;
self.audio
.play("minecraft:block.portal.trigger", None, 0.25, pitch);
}
true
}
// ---- other entities ----
/// Positions before the entities move this tick, and `Entity.handlePortal`
/// at the start of their tick: an item or mob that stayed in a portal
/// goes through (transition time 0) and waits for its dimension.
pub(super) fn handle_entity_portals(&mut self) {
if self.remote.is_some() {
return;
}
self.load_portal_arrivals();
let mut leaving: Vec<(u32, BlockPos)> = Vec::new();
self.portals.before.clear();
for e in &self.dropped {
self.portals.before.insert(e.id, e.position);
}
for m in &self.mobs {
self.portals.before.insert(m.id, m.position);
}
let ids: Vec<(u32, bool)> = self
.dropped
.iter()
.map(|e| (e.id, true))
.chain(self.mobs.iter().map(|m| (m.id, self.mob_can_use_portal(m))))
.collect();
let present: std::collections::HashSet<u32> = ids.iter().map(|(id, _)| *id).collect();
self.portals.entities.retain(|id, _| present.contains(id));
for (id, allowed) in ids {
let Some(state) = self.portals.entities.get_mut(&id) else {
continue;
};
if let Some(entry) = state.handle(allowed, 0, ENTITY_DELAY) {
leaving.push((id, entry));
}
if state.cooldown == 0 && state.process.is_none() {
self.portals.entities.remove(&id);
}
}
for (id, entry) in leaving {
self.send_through_portal(id, entry);
}
}
/// `Entity.load`: the saved `PortalCooldown` (an entity that just came
/// through stands in its exit portal for 300 ticks without going back).
pub(super) fn restore_portal_cooldown(&mut self, id: u32, tag: &Tag) {
if let Some(Tag::Int(cooldown)) = tag.get("PortalCooldown")
&& *cooldown > 0
{
self.portals.entities.insert(
id,
PortalState {
cooldown: *cooldown,
process: None,
},
);
}
}
/// `canUsePortal(false)` of a mob: alive, riding nothing, not asleep,
/// not carrying the player, and not a boss that never travels.
fn mob_can_use_portal(&self, m: &horizon_client::mobs::Mob) -> bool {
use horizon_client::mobs::Species;
m.alive()
&& m.extra.mount.is_none()
&& self.riding != Some(m.id)
&& m.species() != Species::Wither
}
/// `NetherPortalBlock.entityInside` for the items and mobs that moved this
/// tick: the portal blocks their box swept through.
pub(super) fn find_entity_portals(&mut self) {
if self.remote.is_some() {
return;
}
let mut inside: Vec<(u32, BlockPos)> = Vec::new();
let items: Vec<(u32, Vec3, f32, f32)> = self
.dropped
.iter()
.map(|e| (e.id, e.position, 0.25, 0.25))
.collect();
let mobs: Vec<(u32, Vec3, f32, f32)> = self
.mobs
.iter()
.filter(|m| self.mob_can_use_portal(m))
.map(|m| (m.id, m.position, m.width(), m.height()))
.collect();
for (id, to, width, height) in items.into_iter().chain(mobs) {
let from = self.portals.before.get(&id).copied().unwrap_or(to);
if let Some(pos) = self.swept_portal(from, to, width, height) {
inside.push((id, pos));
}
}
for (id, pos) in inside {
self.portals
.entities
.entry(id)
.or_default()
.set_inside(pos, ENTITY_DELAY);
}
}
/// The first nether portal block an entity box swept through
/// (`Entity.checkInsideBlocks`, whose first portal sets the entry).
fn swept_portal(&self, from: Vec3, to: Vec3, width: f32, height: f32) -> Option<BlockPos> {
let half = f64::from(width) / 2.0;
let bounds = horizon_core::geometry::Aabb::new(
Vec3::new(to.x - half, to.y, to.z - half),
Vec3::new(to.x + half, to.y + f64::from(height), to.z + half),
)
.deflate(Vec3::new(
f64::from(1.0e-5_f32),
f64::from(1.0e-5_f32),
f64::from(1.0e-5_f32),
));
let mut found = None;
let _ = horizon_core::geometry::sweep_intersected_blocks(
from,
to,
bounds,
1_000_000,
|p, _| {
if self
.res
.behaviours
.portal_axis(self.world.block(p.x, p.y, p.z))
.is_some()
{
found = Some(p);
return false;
}
true
},
);
found
}
/// `Entity.teleportCrossDimension` away from the loaded dimension: the
/// entity is saved and removed, and waits for its dimension to load.
fn send_through_portal(&mut self, id: u32, entry: BlockPos) {
if let Some(i) = self.dropped.iter().position(|e| e.id == id) {
let e = &self.dropped[i];
let plan = self.portal_plan(entry, e.position, 0.25, 0.25, false);
if !self.may_enter(plan.dim) {
return;
}
let uuid = self.uuid_for(id);
let tag = horizon_client::entity_nbt::item_entity_to_nbt(
&self.dropped[i],
uuid,
self.persist_raw(id),
);
self.dropped.remove(i);
self.forget_entity(id);
self.portals.arrivals.push(Arrival { plan, tag });
self.portals.dirty = true;
} else if let Some(i) = self.mobs.iter().position(|m| m.id == id) {
let m = &self.mobs[i];
let plan = self.portal_plan(entry, m.position, m.width(), m.height(), true);
if !self.may_enter(plan.dim) {
return;
}
let mut tag = self.mob_tree_nbt(i);
// Entity.removeAfterChangingDimensions drops the leash.
if let Tag::Compound(c) = &mut tag {
c.remove(&"leash".into());
}
let mut gone = vec![id];
let mut k = 0;
while k < gone.len() {
let v = gone[k];
gone.extend(
self.mobs
.iter()
.filter(|m| m.extra.mount == Some(v))
.map(|m| m.id),
);
k += 1;
}
self.mobs.retain(|m| !gone.contains(&m.id));
for g in gone {
self.forget_entity(g);
}
self.portals.arrivals.push(Arrival { plan, tag });
self.portals.dirty = true;
}
}
/// Entities waiting for the loaded dimension whose exit area is loaded:
/// their exit portal (found or built), position, turned yaw and motion,
/// and portal cooldown; they join the world with the chunk entities.
pub(super) fn resolve_arrivals(&mut self) {
if self.remote.is_some() {
return;
}
let mut i = 0;
while i < self.portals.arrivals.len() {
let plan = self.portals.arrivals[i].plan;
let (cx, cz) = (plan.approximate.x >> 4, plan.approximate.z >> 4);
let ready = plan.dim == self.dim
&& (-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz)));
if !ready {
i += 1;
continue;
}
let Arrival { plan, mut tag } = self.portals.arrivals.remove(i);
self.portals.dirty = true;
let Some(exit) = self.nether_exit_portal(&plan) else {
continue;
};
let (at, rotation) = self.arrival(&plan, exit);
let motion = rotate_y(horizon_client::entity_nbt::motion(&tag), -rotation);
let [yaw, pitch] = horizon_client::entity_nbt::rotation(&tag);
if let Tag::Compound(c) = &mut tag {
c.insert("Pos".into(), doubles([at.x, at.y, at.z]));
c.insert("Motion".into(), doubles([motion.x, motion.y, motion.z]));
c.insert(
"Rotation".into(),
Tag::List(vec![
Tag::Float((yaw + rotation).to_bits()),
Tag::Float(pitch.to_bits()),
]),
);
// setPortalCooldown before the teleport, copied by restoreFrom.
c.insert("PortalCooldown".into(), Tag::Int(ENTITY_DELAY));
}
let key = ((at.x.floor() as i32) >> 4, (at.z.floor() as i32) >> 4);
match self
.world
.loaded_entities
.iter_mut()
.find(|(k, _)| *k == key)
{
Some((_, tags)) => tags.push(tag),
None => self.world.loaded_entities.push((key, vec![tag])),
}
}
}
// ---- persistence ----
fn arrivals_path(&self) -> std::path::PathBuf {
self.world_root
.join("data")
.join("horizon_portal_arrivals.dat")
}
/// The waiting entities of the open world (read once).
pub(super) fn load_portal_arrivals(&mut self) {
if self.portals.loaded || self.remote.is_some() {
return;
}
self.portals.loaded = true;
let Some(root) = horizon_client::save::read_dat(&self.arrivals_path()) else {
return;
};
let Some(Tag::List(list)) = root.get("arrivals") else {
return;
};
for a in list {
let int = |k: &str| match a.get(k) {
Some(Tag::Int(v)) => Some(*v),
_ => None,
};
let float = |k: &str| match a.get(k) {
Some(Tag::Float(v)) => Some(f32::from_bits(*v)),
_ => None,
};
let double = |k: &str| match a.get(k) {
Some(Tag::Double(v)) => Some(f64::from_bits(*v)),
_ => None,
};
let dim = match horizon_client::save::text(a.get("dimension")).as_deref() {
Some("minecraft:the_nether") => Dim::Nether,
Some(_) => Dim::Overworld,
None => continue,
};
let (Some(x), Some(y), Some(z), Some(tag)) =
(int("x"), int("y"), int("z"), a.get("entity"))
else {
continue;
};
self.portals.arrivals.push(Arrival {
plan: Plan {
dim,
approximate: BlockPos::new(x, y, z),
entry_x_axis: int("x_axis").unwrap_or(1) != 0,
offset: Vec3::new(
double("right").unwrap_or(0.5),
double("up").unwrap_or(0.0),
double("forward").unwrap_or(0.0),
),
width: float("width").unwrap_or(0.25),
height: float("height").unwrap_or(0.25),
},
tag: tag.clone(),
});
}
}
/// Write the waiting entities when they changed.
pub(super) fn save_portal_arrivals(&mut self) {
if !self.portals.dirty || self.remote.is_some() {
return;
}
let list = self
.portals
.arrivals
.iter()
.map(|a| {
let p = &a.plan;
Tag::compound([
("dimension", Tag::String(p.dim.id().into())),
("x", Tag::Int(p.approximate.x)),
("y", Tag::Int(p.approximate.y)),
("z", Tag::Int(p.approximate.z)),
("x_axis", Tag::Int(i32::from(p.entry_x_axis))),
("right", Tag::Double(p.offset.x.to_bits())),
("up", Tag::Double(p.offset.y.to_bits())),
("forward", Tag::Double(p.offset.z.to_bits())),
("width", Tag::Float(p.width.to_bits())),
("height", Tag::Float(p.height.to_bits())),
("entity", a.tag.clone()),
])
})
.collect();
let root = Tag::compound([("arrivals", Tag::List(list))]);
if horizon_client::save::write_dat(&self.arrivals_path(), root).is_ok() {
self.portals.dirty = false;
}
}
}
+7 -1
View File
@@ -440,7 +440,7 @@ impl Game<'_> {
i
}
/// A mob's entity tag with the mobs riding it under `Passengers`.
fn mob_tree_nbt(&mut self, i: usize) -> Tag {
pub(super) fn mob_tree_nbt(&mut self, i: usize) -> Tag {
let id = self.mobs[i].id;
let uuid = self.uuid_for(id);
let mut tag = entity_nbt::mob_to_nbt(&self.mobs[i], uuid, self.persist.raw.get(&id));
@@ -463,11 +463,17 @@ impl Game<'_> {
}
tag
}
/// Forget an entity that left the world (its UUID and loaded compound).
pub(super) fn forget_entity(&mut self, id: u32) {
self.persist.uuids.remove(&id);
self.persist.raw.remove(&id);
}
/// The compound an entity was loaded with (and commands have edited).
pub(super) fn persist_raw(&self, id: u32) -> Option<&Tag> {
self.persist.raw.get(&id)
}
fn remember(&mut self, id: u32, uuid: Option<[i32; 4]>, tag: Tag) {
self.restore_portal_cooldown(id, &tag);
if let Some(u) = uuid {
self.persist.uuids.insert(id, u);
}
@@ -200,7 +200,7 @@ impl Game<'_> {
let eye = self.eye_position();
if let Some(e) = eye {
let brightness = self.eye_brightness(e);
let inside_portal = self.portal_ticks > 0;
let inside_portal = self.client_portal_effect();
self.res.screen_fx.tick(brightness, inside_portal);
// LocalPlayer water vision and AtmosphericFogEnvironment rain fog.
let in_water =
+17
View File
@@ -221,6 +221,23 @@ impl GameLevel<'_> {
delay: 10,
});
}
/// `Block.dropFromBlockInteractLootTable` with `Block.popResource` of
/// every stack.
pub(super) fn drop_interact_loot(&mut self, pos: BlockPos, state: BlockStateId, table: &str) {
let drops = self.items.interact_loot(
table,
self.registry,
state,
&mut self.world.random,
self.rand_sequences,
self.seed,
);
for stack in drops {
if &*stack.item != "minecraft:air" && stack.count > 0 {
self.pop_resource([pos.x, pos.y, pos.z], stack);
}
}
}
/// `Block.dropResources(state, level, pos, blockEntity)`: the block's loot
/// (from its random sequence, else the level random), with what its block
/// entity copies into it, popped at once.
+27
View File
@@ -779,6 +779,33 @@ impl Items {
.as_str()
.map(str::to_owned)
}
/// `Block.dropFromBlockInteractLootTable`: the `block_interact` table `id`
/// for a right click on `state` (its `match_block` conditions see the
/// state), from the table's random sequence when it has one.
pub fn interact_loot(
&self,
id: &str,
registry: &BlockRegistry,
state: BlockStateId,
random: &mut impl RandomSource,
sequences: &mut crate::random_sequences::RandomSequences,
seed: i64,
) -> Vec<ItemStack> {
let (Some(table), Some(block)) = (self.loot.get(id), registry.state(state)) else {
return vec![];
};
let ctx = LootContext {
items: self,
block: &block.name,
properties: &block.properties,
held: None,
killed_by_player: false,
};
match table.get("random_sequence").and_then(Value::as_str) {
Some(sequence) => ctx.evaluate(table, sequences.get(sequence, seed)),
None => ctx.evaluate(table, random),
}
}
/// `loot_table` drawing from any random (a random sequence).
pub fn loot_table_from(
&self,
+2
View File
@@ -92,6 +92,7 @@ pub mod multiplayer;
pub mod music;
pub mod nbt_path;
pub mod net;
pub mod nether_portal;
pub mod options_file;
pub mod options_fixes;
pub mod options_horizon;
@@ -141,6 +142,7 @@ pub mod weather;
pub mod widgets;
pub mod window;
pub mod world;
pub mod world_spawn;
pub mod worldborder;
pub mod zip;
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
+6 -8
View File
@@ -999,10 +999,12 @@ fn render_visible(
} else {
light
};
let overlay = if armor_slot(&layer.model).is_some_and(|s| super::gear::enchanted(m, s)) {
glint_overlay(overlay)
} else {
overlay
// EquipmentLayerRenderer draws armour with OverlayTexture.NO_OVERLAY: never
// the hurt tint, the glint (7) when enchanted.
let overlay = match armor_slot(&layer.model) {
Some(slot) if super::gear::enchanted(m, slot) => 7,
Some(_) => 0,
None => overlay,
};
let start = out.len();
draw(&part, base, &poses, uv, layer.color, light, overlay, out);
@@ -1023,10 +1025,6 @@ fn armor_slot(model: &str) -> Option<usize> {
_ => return None,
})
}
/// The entity shader's glint overlay (7), keeping the hurt tint (8).
fn glint_overlay(overlay: u32) -> u32 {
if overlay == 1 { 8 } else { 7 }
}
/// Render with a fixed texture rect (the earlier API).
pub fn render_single(
m: &Mob,
+9
View File
@@ -143,6 +143,11 @@ pub enum MotionEvent {
EnterBlock {
state: BlockStateId,
},
/// `NetherPortalBlock.entityInside`: the player's box swept through a
/// nether portal block.
InsidePortal {
pos: BlockPos,
},
}
pub struct PlayerMotion {
pub fluids: horizon_world::entity_fluid::EntityFluidInteraction,
@@ -1072,6 +1077,10 @@ impl MotionWorld<'_, '_, '_> {
}
"minecraft:cobweb" => self.web_inside(),
"minecraft:sweet_berry_bush" => self.sweet_berry_bush_inside(state)?,
"minecraft:nether_portal" => self
.player
.events
.push(MotionEvent::InsidePortal { pos: p }),
_ => {}
}
// ServerPlayer.onInsideBlock
@@ -0,0 +1,76 @@
//! `PortalProcessor` and an entity's portal cooldown
//! (`Entity.setAsInsidePortal` / `handlePortal`) for nether portals.
use horizon_core::position::BlockPos;
/// `PortalProcessor` for a nether portal.
#[derive(Clone, Copy, Debug)]
pub struct Process {
pub entry: BlockPos,
pub time: i32,
pub inside: bool,
}
impl Process {
/// `processPortalTeleportation`: whether the entity goes through now.
pub fn process(&mut self, allowed: bool, transition_time: i32) -> bool {
if !self.inside {
// decayTick
self.time = (self.time - 4).max(0);
return false;
}
self.inside = false;
if !allowed {
return false;
}
let time = self.time;
self.time += 1;
time >= transition_time
}
}
/// An entity's `portalCooldown` and `portalProcess`.
#[derive(Clone, Copy, Debug, Default)]
pub struct PortalState {
pub cooldown: i32,
pub process: Option<Process>,
}
impl PortalState {
/// `Entity.setAsInsidePortal` for a nether portal block at `pos`.
pub fn set_inside(&mut self, pos: BlockPos, delay: i32) {
if self.cooldown > 0 {
self.cooldown = delay;
return;
}
match &mut self.process {
None => {
self.process = Some(Process {
entry: pos,
time: 0,
inside: true,
})
}
Some(p) if !p.inside => {
p.entry = pos;
p.inside = true;
}
Some(_) => {}
}
}
/// `Entity.handlePortal`: the entry block when the entity goes through
/// (its cooldown then set to `delay`).
pub fn handle(&mut self, allowed: bool, transition_time: i32, delay: i32) -> Option<BlockPos> {
// processPortalCooldown
if self.cooldown > 0 {
self.cooldown -= 1;
}
let process = self.process.as_mut()?;
if process.process(allowed, transition_time) {
self.cooldown = delay;
return Some(process.entry);
}
// hasExpired
if process.time <= 0 {
self.process = None;
}
None
}
}
+4
View File
@@ -126,6 +126,10 @@ impl VanillaTerrain {
let worker = worker.get_or_insert_with(|| self.generator.worker());
worker.jigsaw_pieces(query)
}
/// NoiseBasedChunkGenerator.getOrigin: where the world spawn search starts.
pub fn origin(&self) -> crate::Result<ChunkPos> {
Ok(self.generator.origin()?)
}
/// Concentric ring positions of a structure set (strongholds), once known.
pub fn ring_positions(&self, set: &str) -> Option<Vec<ChunkPos>> {
self.generator.ring_positions(set)
+269
View File
@@ -0,0 +1,269 @@
//! Where a new world's spawn is and where a player first appears around it:
//! MinecraftServer.setInitialSpawn's chunk spiral and PlayerSpawnFinder.
use horizon_world::heightmap::HeightmapType;
/// The block queries the spawn searches make on full (decorated, lit) chunks.
pub trait SpawnLevel {
fn min_y(&self) -> i32;
/// `chunk.getHeight(kind, x, z)`: one above the column's highest block
/// matching the heightmap, or the minimum height.
fn height(&self, kind: HeightmapType, x: i32, z: i32) -> i32;
/// `!getBlockState(pos).getFluidState().isEmpty()`.
fn has_fluid(&self, x: i32, y: i32, z: i32) -> bool;
/// `Block.isFaceFull(state.getCollisionShape(level, pos), Direction.UP)`.
fn top_face_full(&self, x: i32, y: i32, z: i32) -> bool;
}
/// PlayerSpawnFinder.getLevelRespawnPos in a dimension without a ceiling:
/// the block above the column's top full-topped collision, unless water,
/// lava or only non-colliding blocks are on top.
pub fn level_respawn_pos(level: &impl SpawnLevel, x: i32, z: i32) -> Option<[i32; 3]> {
let top = level.height(HeightmapType::MotionBlocking, x, z);
if top < level.min_y() {
return None;
}
let surface = level.height(HeightmapType::WorldSurface, x, z);
if surface <= top && surface > level.height(HeightmapType::OceanFloor, x, z) {
return None;
}
for y in (level.min_y()..=top + 1).rev() {
if level.has_fluid(x, y, z) {
break;
}
if level.top_face_full(x, y, z) {
return Some([x, y + 1, z]);
}
}
None
}
/// PlayerSpawnFinder.getSpawnPosInChunk: the first valid column, x-major.
pub fn spawn_pos_in_chunk(level: &impl SpawnLevel, cx: i32, cz: i32) -> Option<[i32; 3]> {
for x in cx * 16..cx * 16 + 16 {
for z in cz * 16..cz * 16 + 16 {
if let Some(pos) = level_respawn_pos(level, x, z) {
return Some(pos);
}
}
}
None
}
/// setInitialSpawn's walk: Mth.square(11) steps of a square spiral around
/// the origin chunk, testing the steps within 5 chunks of it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ChunkSpiral {
step: i32,
x: i32,
z: i32,
dx: i32,
dz: i32,
}
impl Default for ChunkSpiral {
fn default() -> Self {
Self::new()
}
}
impl ChunkSpiral {
pub const fn new() -> Self {
Self {
step: 0,
x: 0,
z: 0,
dx: 0,
dz: -1,
}
}
/// Steps taken so far.
pub fn steps(&self) -> i32 {
self.step
}
/// The chunk offset to test now, or None once the walk is over.
pub fn current(&self) -> Option<(i32, i32)> {
(self.step < 11 * 11).then_some((self.x, self.z))
}
/// Whether `current` lies within the tested 11 by 11 chunks.
pub fn tested(&self) -> bool {
(-5..=5).contains(&self.x) && (-5..=5).contains(&self.z)
}
pub fn advance(&mut self) {
if self.x == self.z
|| (self.x < 0 && self.x == -self.z)
|| (self.x > 0 && self.x == 1 - self.z)
{
(self.dx, self.dz) = (-self.dz, self.dx);
}
self.x += self.dx;
self.z += self.dz;
self.step += 1;
}
}
/// What PlayerSpawnFinder tries next.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SpawnCandidate {
/// A column to test with `level_respawn_pos` and a free player box.
Column(i32, i32),
/// Every column failed: the suggestion itself, height fixed up.
Suggestion,
}
/// PlayerSpawnFinder: the columns of the square of `radius` around the
/// suggestion in a random coprime-stride order, then the suggestion.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PlayerSpawnFinder {
pub suggestion: [i32; 3],
radius: i32,
count: i32,
coprime: i32,
offset: i32,
next: i32,
}
impl PlayerSpawnFinder {
/// `radius` is the respawn radius already clamped to the world border
/// (findSpawn); `random(n)` draws the start offset in `0..n`.
pub fn new(suggestion: [i32; 3], radius: i32, random: impl FnOnce(i32) -> i32) -> Self {
let side = i64::from(radius) * 2 + 1;
let count = (side * side).min(1024) as i32;
Self {
suggestion,
radius,
count,
coprime: if count <= 16 { count - 1 } else { 17 },
offset: random(count),
next: 0,
}
}
/// The next candidate, None once the suggestion was handed out.
pub fn next_candidate(&mut self) -> Option<SpawnCandidate> {
let index = self.next;
if index > self.count {
return None;
}
self.next += 1;
if index == self.count {
return Some(SpawnCandidate::Suggestion);
}
let value = (self.offset + self.coprime * index) % self.count;
let side = self.radius * 2 + 1;
Some(SpawnCandidate::Column(
self.suggestion[0] + value % side - self.radius,
self.suggestion[2] + value / side - self.radius,
))
}
/// Hand the last candidate out again (its chunk was not loaded yet).
pub fn retry(&mut self) {
self.next -= 1;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn spiral_walks_out_from_the_origin_like_set_initial_spawn() {
let mut spiral = ChunkSpiral::default();
let mut seen = Vec::new();
while let Some(at) = spiral.current() {
if spiral.tested() {
seen.push(at);
}
spiral.advance();
}
assert_eq!(
&seen[..9],
&[
(0, 0),
(1, 0),
(1, 1),
(0, 1),
(-1, 1),
(-1, 0),
(-1, -1),
(0, -1),
(1, -1)
]
);
seen.sort_unstable();
seen.dedup();
assert_eq!(seen.len(), 121);
}
#[test]
fn finder_visits_every_column_once_then_the_suggestion() {
let mut finder = PlayerSpawnFinder::new([100, 70, -40], 10, |n| n / 3);
let mut columns = Vec::new();
while let Some(c) = finder.next_candidate() {
columns.push(c);
}
assert_eq!(columns.len(), 442);
assert_eq!(columns.last(), Some(&SpawnCandidate::Suggestion));
columns.sort_by_key(|c| format!("{c:?}"));
columns.dedup();
assert_eq!(columns.len(), 442);
let mut zero = PlayerSpawnFinder::new([5, 64, 5], 0, |_| 0);
assert_eq!(zero.next_candidate(), Some(SpawnCandidate::Column(5, 5)));
assert_eq!(zero.next_candidate(), Some(SpawnCandidate::Suggestion));
assert_eq!(zero.next_candidate(), None);
}
struct Flat {
top: i32,
water: bool,
}
impl SpawnLevel for Flat {
fn min_y(&self) -> i32 {
-64
}
fn height(&self, kind: HeightmapType, _: i32, _: i32) -> i32 {
match kind {
HeightmapType::OceanFloor if self.water => self.top - 3,
_ => self.top + 1,
}
}
fn has_fluid(&self, _: i32, y: i32, _: i32) -> bool {
self.water && y <= self.top && y > self.top - 3
}
fn top_face_full(&self, _: i32, y: i32, _: i32) -> bool {
y <= self.top
}
}
#[test]
fn respawn_column_stands_on_land_not_water() {
assert_eq!(
level_respawn_pos(
&Flat {
top: 70,
water: false
},
3,
4
),
Some([3, 71, 4])
);
assert_eq!(
level_respawn_pos(
&Flat {
top: 62,
water: true
},
3,
4
),
None
);
assert_eq!(
spawn_pos_in_chunk(
&Flat {
top: 70,
water: false
},
-2,
1
),
Some([-32, 71, 16])
);
}
}
@@ -0,0 +1,272 @@
//! Rust side of tools/test_nether_portal_parity.py: replays
//! `VanillaPortalOracle` cases (an entity in a nether portal, the destination
//! level's terrain and portals) through `horizon_world::level::portal_travel`
//! and prints the same result text.
use horizon_core::{
geometry::{Axis, Vec3},
position::BlockPos,
random::LegacyRandom,
};
use horizon_world::{
level::{
Behaviours, Dimension, LevelAccess, Ticks,
data::load_registry,
portal_travel::{
BorderBounds, closest_portal, collision_free_position, exit_position,
largest_rectangle_around, relative_position,
},
},
registry::BlockStateId,
};
use serde_json::Value;
use std::{
collections::HashMap,
io::{BufRead, Write},
path::Path,
};
struct Cells {
cells: HashMap<BlockPos, BlockStateId>,
air: BlockStateId,
random: LegacyRandom,
nether: bool,
}
impl LevelAccess for Cells {
fn block_state(&self, pos: BlockPos) -> BlockStateId {
self.cells.get(&pos).copied().unwrap_or(self.air)
}
fn set_raw(&mut self, pos: BlockPos, state: BlockStateId) -> Option<BlockStateId> {
let old = self.block_state(pos);
if state == self.air {
self.cells.remove(&pos);
} else {
self.cells.insert(pos, state);
}
Some(old)
}
fn is_loaded(&self, _pos: BlockPos) -> bool {
true
}
fn min_y(&self) -> i32 {
if self.nether { 0 } else { -64 }
}
fn max_y(&self) -> i32 {
if self.nether { 256 } else { 320 }
}
fn random(&mut self) -> &mut LegacyRandom {
&mut self.random
}
fn game_time(&self) -> i64 {
0
}
fn dimension(&self) -> Dimension {
if self.nether {
Dimension::Nether
} else {
Dimension::Overworld
}
}
}
fn pos(v: &Value) -> BlockPos {
BlockPos::new(
v[0].as_i64().unwrap() as i32,
v[1].as_i64().unwrap() as i32,
v[2].as_i64().unwrap() as i32,
)
}
fn level(case: &Value, key: &str, air: BlockStateId, nether: bool) -> Cells {
let mut cells = HashMap::new();
for c in case[key].as_array().unwrap() {
let state = BlockStateId(c[3].as_i64().unwrap() as u32);
if state != air {
cells.insert(pos(c), state);
}
}
Cells {
cells,
air,
random: LegacyRandom::new(case["seed"].as_i64().unwrap()),
nether,
}
}
fn run(case: &Value, b: &Behaviours, air: BlockStateId, out: &mut Vec<String>) {
let from_nether = case["from"] == "nether";
let source = level(case, "source", air, from_nether);
let mut target = level(case, "target", air, !from_nether);
let dims = &case["entity"]["dims"];
let (width, height) = (
dims[0].as_f64().unwrap() as f32,
dims[1].as_f64().unwrap() as f32,
);
out.push(format!(
"dims {:08x} {:08x}",
width.to_bits(),
height.to_bits()
));
// Exact doubles, as bits.
let e = &case["entity"]["bits"];
let bit = |i: usize| f64::from_bits(u64::from_str_radix(e[i].as_str().unwrap(), 16).unwrap());
let at = Vec3::new(bit(0), bit(1), bit(2));
// WorldBorder: centre and size, the extent clamped to +-29999984.
let border = &case["border"];
let (cx, cz, size) = (
border["x"].as_f64().unwrap(),
border["z"].as_f64().unwrap(),
border["size"].as_f64().unwrap(),
);
let limit = 29_999_984.0;
let clamp = |v: f64| v.clamp(-limit, limit);
let bounds = BorderBounds {
min_x: clamp(cx - size / 2.0),
min_z: clamp(cz - size / 2.0),
max_x: clamp(cx + size / 2.0),
max_z: clamp(cz + size / 2.0),
};
// NetherPortalBlock.getDimensionTransitionFromExit: where in its portal
// the entity stands.
let entry = pos(&case["entry"]);
let entry_state = source.block_state(entry);
let (entry_x_axis, offset) = match b.portal_axis(entry_state) {
Some(x_axis) => {
let rectangle = largest_rectangle_around(
entry,
if x_axis { Axis::X } else { Axis::Z },
21,
Axis::Y,
21,
|p| source.block_state(p) == entry_state,
);
let m = rectangle.min_corner;
out.push(format!(
"entry {},{},{} {}x{}",
m.x, m.y, m.z, rectangle.axis1_size, rectangle.axis2_size
));
let mut offset = relative_position(rectangle, x_axis, at, width, height);
// LivingEntity, AbstractMinecart and AbstractBoat:
// resetForwardDirectionOfRelativePortalPosition.
if case["entity"]["reset_forward"].as_bool().unwrap_or(false) {
offset.z = 0.0;
}
out.push(format!(
"offset {:016x} {:016x} {:016x}",
offset.x.to_bits(),
offset.y.to_bits(),
offset.z.to_bits()
));
(x_axis, offset)
}
None => (true, Vec3::new(0.5, 0.0, 0.0)),
};
// NetherPortalBlock.getPortalDestination.
let scale = if from_nether { 8.0 } else { 1.0 / 8.0 };
let approximate = bounds.clamp(at.x * scale, at.y, at.z * scale);
let portals: Vec<BlockPos> = case["pois"].as_array().unwrap().iter().map(pos).collect();
let (min_section, max_section) = if from_nether { (-4, 19) } else { (0, 15) };
let mut ticks = Ticks::new(0);
out.push(format!(
"approximate {},{},{}",
approximate.x, approximate.y, approximate.z
));
let found = closest_portal(
&portals,
approximate,
!from_nether,
&bounds,
min_section,
max_section,
);
out.push(match found {
Some(p) => format!("found {},{},{}", p.x, p.y, p.z),
None => "found none".into(),
});
let exit = match found {
Some(found) => {
let state = target.block_state(found);
let x_axis = b.portal_axis(state).unwrap_or(true);
Some(largest_rectangle_around(
found,
if x_axis { Axis::X } else { Axis::Z },
21,
Axis::Y,
21,
|p| target.block_state(p) == state,
))
}
None => {
let logical = if from_nether { 384 } else { 128 };
b.create_portal(
&mut target,
&mut ticks,
approximate,
entry_x_axis,
&bounds,
logical,
)
}
};
let mut changed: Vec<BlockPos> = target
.cells
.keys()
.copied()
.chain(
level(case, "target", air, !from_nether)
.cells
.keys()
.copied(),
)
.collect();
changed.sort_by_key(|p| (p.x, p.y, p.z));
changed.dedup();
let before = level(case, "target", air, !from_nether);
for p in changed {
let now = target.block_state(p);
if before.block_state(p) != now {
out.push(format!("set {},{},{} {}", p.x, p.y, p.z, now.0));
}
}
let Some(exit) = exit else {
out.push("dest none".into());
return;
};
let exit_x_axis = b
.portal_axis(target.block_state(exit.min_corner))
.unwrap_or(true);
let (bottom, rotation) = exit_position(exit, exit_x_axis, entry_x_axis, offset, width, height);
let free = collision_free_position(bottom, width, height, &bounds, |p| {
b.collision_shape(target.block_state(p))
.map(|s| s.moved(Vec3::new(f64::from(p.x), f64::from(p.y), f64::from(p.z))))
});
out.push(format!(
"dest {:016x} {:016x} {:016x} {rotation:?}",
free.x.to_bits(),
free.y.to_bits(),
free.z.to_bits()
));
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = std::env::args().skip(1);
let resources = args.next().expect("resource directory");
let cases = args.next().expect("case file");
let output = args.next().expect("output file");
let resources = Path::new(&resources);
let registry = load_registry(resources)?;
let behaviours = Behaviours::load(&registry, resources)?;
let air = registry.default_state("minecraft:air").unwrap();
let mut out = std::io::BufWriter::new(std::fs::File::create(output)?);
for (index, line) in std::io::BufReader::new(std::fs::File::open(cases)?)
.lines()
.enumerate()
{
let case: Value = serde_json::from_str(&line?)?;
let mut lines = Vec::new();
run(&case, &behaviours, air, &mut lines);
writeln!(out, "case {index}")?;
for l in lines {
writeln!(out, "{l}")?;
}
}
Ok(())
}
@@ -0,0 +1,54 @@
//! NoiseSpawnFinder for tools/test_world_spawn_parity.py: for each seed, the
//! column the overworld's spawn search starts from and its chunk
//! (NoiseBasedChunkGenerator.getOrigin), as `seed x z chunk_x chunk_z` lines.
//!
//! usage: spawn_origin <client resource directory> <seed>...
use horizon_world::{
DATA_VERSION,
nbt::Tag,
registry::BlockRegistry,
worldgen::generator::{GeneratorData, OverworldGenerator},
};
use serde_json::Value;
use std::{fs, path::Path};
type Error = Box<dyn std::error::Error + Send + Sync>;
fn tag(v: &Value) -> Tag {
match v {
Value::String(s) => Tag::String(s.as_str().into()),
Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32),
Value::Array(a) => Tag::List(a.iter().map(tag).collect()),
Value::Object(o) => {
Tag::Compound(o.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect())
}
_ => panic!("invalid registry metadata"),
}
}
fn registry(resources: &Path) -> Result<&'static BlockRegistry, Error> {
let facts: Value = serde_json::from_str(&fs::read_to_string(resources.join("facts.json"))?)?;
let states = facts["states"].as_array().ok_or("facts states")?;
let registry = BlockRegistry::from_nbt(&Tag::compound([
("DataVersion", Tag::Int(DATA_VERSION)),
(
"states",
Tag::List(states.iter().map(|v| tag(&v[4])).collect()),
),
("defaults", tag(&facts["defaults"])),
]))?;
Ok(Box::leak(Box::new(registry)))
}
fn main() -> Result<(), Error> {
let mut args = std::env::args().skip(1);
let resources = std::path::PathBuf::from(args.next().ok_or("client resource directory")?);
let data = GeneratorData::load(&resources.join("worldgen"), registry(&resources)?)?;
for seed in args {
let seed: i64 = seed.parse()?;
let generator = OverworldGenerator::new(data.clone(), seed)?;
let [x, z] = generator.spawn_position()?;
let origin = generator.origin()?;
println!("{seed} {x} {z} {} {}", origin.x, origin.z);
}
Ok(())
}
@@ -527,4 +527,28 @@ impl Behaviours {
self.sim(level, ticks)
.use_without_item(pos, face, hit, player)
}
/// `BlockState.useItemOn` with `item` in the main hand, then, when the
/// block asks to try with an empty hand (the default), `useWithoutItem`.
/// `SweetBerryBushBlock.useItemOn` passes bone meal on a bush that can
/// still grow on to the item.
#[allow(clippy::too_many_arguments)]
pub fn use_item_on<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
face: Direction,
hit: Vec3,
player: PlayerContext,
item: Option<&str>,
) -> InteractionResult {
let state = level.block_state(pos);
if item == Some("minecraft:bone_meal")
&& self.data(state).chain.contains(&Class::SweetBerryBush)
&& self.table.int(state, self.props.age) < 3
{
return InteractionResult::Pass;
}
self.use_without_item(level, ticks, pos, face, hit, player)
}
}
+1
View File
@@ -112,6 +112,7 @@ mod interact;
pub mod pistons;
mod place;
mod portal;
pub mod portal_travel;
mod query;
mod rails;
mod redstone;
@@ -0,0 +1,628 @@
//! Nether portal travel: `PortalForcer` (finding and building exit portals),
//! `BlockUtil.getLargestRectangleAround`, `PortalShape.getRelativePosition`
//! and `NetherPortalBlock.createDimensionTransition`.
use super::{Behaviours, LevelAccess, Sim, Ticks};
use crate::fluid::FluidKind;
use crate::{
java_hash_map::{JavaHashMap, JavaKey},
registry::BlockStateId,
};
use horizon_core::{
geometry::{Aabb, Axis, Direction, ShapeOp, Vec3, VoxelShape},
position::BlockPos,
};
use std::cmp::Ordering;
/// `BlockUtil.FoundRectangle`: the low corner and the sizes along the two axes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FoundRectangle {
pub min_corner: BlockPos,
pub axis1_size: i32,
pub axis2_size: i32,
}
/// The world border's extent (`getMinX` .. `getMaxX`, `getMinZ` .. `getMaxZ`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BorderBounds {
pub min_x: f64,
pub min_z: f64,
pub max_x: f64,
pub max_z: f64,
}
impl BorderBounds {
/// `WorldBorder.isWithinBounds(x, z)`.
pub fn contains(&self, x: f64, z: f64) -> bool {
x >= self.min_x && x < self.max_x && z >= self.min_z && z < self.max_z
}
/// `WorldBorder.isWithinBounds(BlockPos)`.
pub fn contains_block(&self, pos: BlockPos) -> bool {
self.contains(f64::from(pos.x), f64::from(pos.z))
}
/// `WorldBorder.clampToBounds(x, y, z)`.
pub fn clamp(&self, x: f64, y: f64, z: f64) -> BlockPos {
let margin = f64::from(1.0e-5_f32);
let clamp = |v: f64, lo: f64, hi: f64| if v < lo { lo } else { v.min(hi) };
BlockPos::new(
clamp(x, self.min_x, self.max_x - margin).floor() as i32,
y.floor() as i32,
clamp(z, self.min_z, self.max_z - margin).floor() as i32,
)
}
}
fn step(pos: BlockPos, direction: Direction, n: i32) -> BlockPos {
let [dx, dy, dz] = direction.normal();
pos.offset(dx * n, dy * n, dz * n)
}
fn negative(axis: Axis) -> Direction {
match axis {
Axis::X => Direction::West,
Axis::Y => Direction::Down,
Axis::Z => Direction::North,
}
}
fn component(pos: BlockPos, axis: Axis) -> i32 {
match axis {
Axis::X => pos.x,
Axis::Y => pos.y,
Axis::Z => pos.z,
}
}
/// `Direction.getClockWise` for the horizontal directions.
fn clockwise(direction: Direction) -> Direction {
match direction {
Direction::North => Direction::East,
Direction::East => Direction::South,
Direction::South => Direction::West,
Direction::West => Direction::North,
other => other,
}
}
/// `BlockUtil.getLimit`: how many steps from `start` along `direction` pass `test`.
fn limit(
test: &mut impl FnMut(BlockPos) -> bool,
start: BlockPos,
direction: Direction,
limit: i32,
) -> i32 {
let mut max = 0;
let mut pos = start;
while max < limit {
pos = step(pos, direction, 1);
if !test(pos) {
break;
}
max += 1;
}
max
}
/// `BlockUtil.getMaxRectangleLocation`: the widest-area run of `columns`
/// (start, end inclusive) and its height.
fn max_rectangle_location(columns: &[i32]) -> (i32, i32, i32) {
let (mut max_start, mut max_end, mut max_height) = (0usize, 0usize, 0i32);
let mut stack: Vec<usize> = vec![0];
for column in 1..=columns.len() {
let height = if column == columns.len() {
0
} else {
columns[column]
};
while let Some(&top) = stack.last() {
let stack_height = columns[top];
if height >= stack_height {
stack.push(column);
break;
}
stack.pop();
let start = stack.last().map_or(0, |t| t + 1);
if i64::from(stack_height) * (column - start) as i64
> i64::from(max_height) * (max_end - max_start) as i64
{
max_end = column;
max_start = start;
max_height = stack_height;
}
}
if stack.is_empty() {
stack.push(column);
}
}
(max_start as i32, max_end as i32 - 1, max_height)
}
/// `BlockUtil.getLargestRectangleAround`: the largest rectangle of positions
/// passing `test` in the plane of `axis1` and `axis2` that contains `center`.
pub fn largest_rectangle_around(
center: BlockPos,
axis1: Axis,
limit1: i32,
axis2: Axis,
limit2: i32,
mut test: impl FnMut(BlockPos) -> bool,
) -> FoundRectangle {
let negative1 = negative(axis1);
let positive1 = negative1.opposite();
let negative2 = negative(axis2);
let positive2 = negative2.opposite();
let negative_delta1 = limit(&mut test, center, negative1, limit1);
let positive_delta1 = limit(&mut test, center, positive1, limit1);
let center_index1 = negative_delta1 as usize;
let mut bounds = vec![(0, 0); center_index1 + 1 + positive_delta1 as usize];
bounds[center_index1] = (
limit(&mut test, center, negative2, limit2),
limit(&mut test, center, positive2, limit2),
);
let center_index2 = bounds[center_index1].0;
for i in 1..=negative_delta1 as usize {
let last = bounds[center_index1 - (i - 1)];
let at = step(center, negative1, i as i32);
bounds[center_index1 - i] = (
limit(&mut test, at, negative2, last.0),
limit(&mut test, at, positive2, last.1),
);
}
for i in 1..=positive_delta1 as usize {
let last = bounds[center_index1 + i - 1];
let at = step(center, positive1, i as i32);
bounds[center_index1 + i] = (
limit(&mut test, at, negative2, last.0),
limit(&mut test, at, positive2, last.1),
);
}
let (mut min_axis1, mut min_axis2, mut size_axis1, mut size_axis2) = (0, 0, 0, 0);
let mut columns = vec![0; bounds.len()];
for i2 in (0..=center_index2).rev() {
for (i1, b) in bounds.iter().enumerate() {
let min2 = center_index2 - b.0;
let max2 = center_index2 + b.1;
columns[i1] = if i2 >= min2 && i2 <= max2 {
max2 + 1 - i2
} else {
0
};
}
let (start, end, height) = max_rectangle_location(&columns);
let new_size1 = 1 + end - start;
if new_size1 * height > size_axis1 * size_axis2 {
min_axis1 = start;
min_axis2 = i2;
size_axis1 = new_size1;
size_axis2 = height;
}
}
let corner = step(
center,
negative1.opposite(),
min_axis1 - center_index1 as i32,
);
let corner = step(corner, negative2.opposite(), min_axis2 - center_index2);
FoundRectangle {
min_corner: corner,
axis1_size: size_axis1,
axis2_size: size_axis2,
}
}
/// `PortalShape.getRelativePosition`: where in the portal rectangle an entity
/// of `width` by `height` at `position` stands (right and up as fractions,
/// forward in blocks; living entities, minecarts and boats then drop the
/// forward part, `LivingEntity.resetForwardDirectionOfRelativePortalPosition`).
pub fn relative_position(
rectangle: FoundRectangle,
x_axis: bool,
position: Vec3,
width: f32,
height: f32,
) -> Vec3 {
let axis = if x_axis { Axis::X } else { Axis::Z };
let room_width = f64::from(rectangle.axis1_size) - f64::from(width);
let room_height = f64::from(rectangle.axis2_size) - f64::from(height);
let bottom = rectangle.min_corner;
let clamp = |v: f64| if v < 0.0 { 0.0 } else { v.min(1.0) };
let right = if room_width > 0.0 {
let start = f64::from(component(bottom, axis)) + f64::from(width) / 2.0;
clamp((position.component(axis) - start) / room_width)
} else {
0.5
};
let up = if room_height > 0.0 {
clamp((position.y - f64::from(bottom.y)) / room_height)
} else {
0.0
};
let forward_axis = if x_axis { Axis::Z } else { Axis::X };
let forward =
position.component(forward_axis) - (f64::from(component(bottom, forward_axis)) + 0.5);
Vec3::new(right, up, forward)
}
/// `NetherPortalBlock.createDimensionTransition` before
/// `PortalShape.findCollisionFreePosition`: the bottom centre of the entity in
/// the exit portal and the yaw it turns by (0 or 90).
pub fn exit_position(
exit: FoundRectangle,
exit_x_axis: bool,
entry_x_axis: bool,
offset: Vec3,
width: f32,
height: f32,
) -> (Vec3, f32) {
let rotation = if entry_x_axis == exit_x_axis {
0.0
} else {
90.0
};
let right = f64::from(width) / 2.0 + (f64::from(exit.axis1_size) - f64::from(width)) * offset.x;
let up = (f64::from(exit.axis2_size) - f64::from(height)) * offset.y;
let forward = 0.5 + offset.z;
let b = exit.min_corner;
let target = Vec3::new(
f64::from(b.x) + if exit_x_axis { right } else { forward },
f64::from(b.y) + up,
f64::from(b.z) + if exit_x_axis { forward } else { right },
);
(target, rotation)
}
impl BorderBounds {
/// `WorldBorder.isWithinBounds(AABB)`: both corners, the far one pulled
/// in by 1.0E-5F.
pub fn contains_box(&self, b: Aabb) -> bool {
let margin = f64::from(1.0e-5_f32);
self.contains(b.min(Axis::X), b.min(Axis::Z))
&& self.contains(b.max(Axis::X) - margin, b.max(Axis::Z) - margin)
}
}
/// `CollisionGetter.findFreePosition` without an entity's collision context:
/// within `allowed`, the point nearest `preferred` where a box of the size
/// centred there meets no block collision inside the border. `shape(pos)`
/// is the block's collision shape there, in world coordinates.
pub fn find_free_position(
allowed: Aabb,
preferred: Vec3,
size: Vec3,
border: &BorderBounds,
mut shape: impl FnMut(BlockPos) -> Option<VoxelShape>,
) -> Option<Vec3> {
let allowed_shape = VoxelShape::from_box(allowed).ok()?;
if allowed_shape.is_empty() {
return None;
}
let search = allowed_shape.bounds()?.inflate(size);
let half = size.scale(0.5);
let mut expanded = VoxelShape::empty();
// BlockCollisions over the search area: every block whose shape meets it.
let lo = |v: f64| (v - 1.0e-7).floor() as i32 - 1;
let hi = |v: f64| (v + 1.0e-7).floor() as i32 + 1;
for z in lo(search.min(Axis::Z))..=hi(search.max(Axis::Z)) {
for y in lo(search.min(Axis::Y))..=hi(search.max(Axis::Y)) {
for x in lo(search.min(Axis::X))..=hi(search.max(Axis::X)) {
let Some(block) = shape(BlockPos::new(x, y, z)) else {
continue;
};
if block.is_empty()
|| !block.boxes().iter().any(|b| b.intersects(search))
|| !block.bounds().is_some_and(|b| border.contains_box(b))
{
continue;
}
for b in block.boxes() {
let grown = VoxelShape::from_box(b.inflate(half)).ok()?;
expanded = expanded.join(&grown, ShapeOp::OR).ok()?;
}
}
}
}
let free = allowed_shape.join(&expanded, ShapeOp::ONLY_FIRST).ok()?;
free.closest_point(preferred)
}
/// `PortalShape.findCollisionFreePosition`: `bottom_center` moved to the
/// nearest spot within its column of the entity's width (and a block up)
/// where it fits; entities over 4 blocks stay put.
pub fn collision_free_position(
bottom_center: Vec3,
width: f32,
height: f32,
border: &BorderBounds,
shape: impl FnMut(BlockPos) -> Option<VoxelShape>,
) -> Vec3 {
if width > 4.0 || height > 4.0 {
return bottom_center;
}
let half_height = f64::from(height) / 2.0;
let center = bottom_center.add_vector(Vec3::new(0.0, half_height, 0.0));
let w = f64::from(width);
let allowed = Aabb::of_size(center, Vec3::new(w, 0.0, w))
.expand_towards(Vec3::new(0.0, 1.0, 0.0))
.inflate(Vec3::new(1.0e-6, 1.0e-6, 1.0e-6));
find_free_position(
allowed,
center,
Vec3::new(w, f64::from(height), w),
border,
shape,
)
.map_or(bottom_center, |p| {
p.subtract(Vec3::new(0.0, half_height, 0.0))
})
}
/// A portal block position as a `PoiRecord` in a `PoiSection`'s hash set.
#[derive(Clone, Copy, PartialEq, Eq)]
struct Record(BlockPos);
impl JavaKey for Record {
/// `Vec3i.hashCode`.
fn java_hash(&self) -> i32 {
let p = self.0;
p.y.wrapping_add(p.z.wrapping_mul(31))
.wrapping_mul(31)
.wrapping_add(p.x)
}
fn tie_break(&self, other: &Self) -> Ordering {
(self.0.y, self.0.z, self.0.x)
.cmp(&(other.0.y, other.0.z, other.0.x))
.then(Ordering::Less)
}
}
/// `PortalForcer.findClosestPortalPosition` over the nether portal blocks
/// `portals` (the points of interest, in the order their sections hold
/// them): within 16 blocks of `approximate` going to the Nether, 128 out of
/// it, inside the border, nearest first, then lowest.
pub fn closest_portal(
portals: &[BlockPos],
approximate: BlockPos,
to_nether: bool,
border: &BorderBounds,
min_section: i32,
max_section: i32,
) -> Option<BlockPos> {
let radius: i32 = if to_nether { 16 } else { 128 };
// PoiManager.getInSquare: the chunks of ChunkPos.rangeClosed (x fastest),
// each section from the bottom, each section's records in hash set order.
let chunk_radius = radius.div_euclid(16) + 1;
let (cx, cz) = (approximate.x >> 4, approximate.z >> 4);
let mut sections: std::collections::HashMap<(i32, i32, i32), JavaHashMap<Record, ()>> =
std::collections::HashMap::new();
for &p in portals {
sections
.entry((p.x >> 4, p.y >> 4, p.z >> 4))
.or_default()
.put(Record(p), ());
}
let mut best: Option<(f64, BlockPos)> = None;
for z in cz - chunk_radius..=cz + chunk_radius {
for x in cx - chunk_radius..=cx + chunk_radius {
for y in min_section..=max_section {
let Some(set) = sections.get(&(x, y, z)) else {
continue;
};
for (record, _) in set.entries() {
let p = record.0;
if (p.x - approximate.x).abs() > radius
|| (p.z - approximate.z).abs() > radius
|| !border.contains_block(p)
{
continue;
}
let (dx, dy, dz) = (
f64::from(p.x) - f64::from(approximate.x),
f64::from(p.y) - f64::from(approximate.y),
f64::from(p.z) - f64::from(approximate.z),
);
let d = dx * dx + dy * dy + dz * dz;
if best.is_none_or(|(bd, bp)| d < bd || (d == bd && p.y < bp.y)) {
best = Some((d, p));
}
}
}
}
}
best.map(|(_, p)| p)
}
/// `BlockPos.spiralAround(center, radius, first, second)`.
fn spiral_around(
center: BlockPos,
radius: i32,
first: Direction,
second: Direction,
) -> Vec<BlockPos> {
let directions = [first, second, first.opposite(), second.opposite()];
let mut out = Vec::new();
let mut last = step(center, second, 1);
let legs = 4 * radius;
let (mut leg, mut leg_size, mut leg_index) = (-1i32, 0, 0);
loop {
let cursor = step(last, directions[((leg + 4) % 4) as usize], 1);
last = cursor;
if leg_index >= leg_size {
if leg >= legs {
return out;
}
leg += 1;
leg_index = 0;
leg_size = leg / 2 + 1;
}
leg_index += 1;
out.push(cursor);
}
}
impl<L: LevelAccess + ?Sized> Sim<'_, L> {
/// `PortalForcer.canPortalReplaceBlock`.
fn portal_can_replace(&self, pos: BlockPos) -> bool {
let state = self.state(pos);
self.b.is_replaceable(state) && self.b.fluid(state).kind() == FluidKind::Empty
}
/// `PortalForcer.canHostFrame`.
fn can_host_frame(&self, origin: BlockPos, direction: Direction, offset: i32) -> bool {
let side = clockwise(direction);
for width in -1..3 {
for height in -1..4 {
let at = step(step(origin, direction, width), side, offset).offset(0, height, 0);
if height < 0 && !self.b.is_solid(self.state(at)) {
return false;
}
if height >= 0 && !self.portal_can_replace(at) {
return false;
}
}
}
true
}
/// `PortalForcer.createPortal`: a 2 by 3 portal in an obsidian frame at the
/// nearest column around `origin` with room for it (on a platform it
/// carves out when none has), facing `x_axis`.
pub fn create_portal(
&mut self,
origin: BlockPos,
x_axis: bool,
border: &BorderBounds,
logical_height: i32,
) -> Option<FoundRectangle> {
let direction = if x_axis {
Direction::East
} else {
Direction::South
};
let (min_y, max_y) = (self.level.min_y(), self.level.max_y() - 1);
let max_placeable = max_y.min(min_y + logical_height - 1);
let distance = |a: BlockPos, b: BlockPos| {
let (dx, dy, dz) = (
f64::from(a.x) - f64::from(b.x),
f64::from(a.y) - f64::from(b.y),
f64::from(a.z) - f64::from(b.z),
);
dx * dx + dy * dy + dz * dz
};
let mut full: Option<(f64, BlockPos)> = None;
let mut partial: Option<(f64, BlockPos)> = None;
for column in spiral_around(origin, 16, Direction::East, Direction::South) {
let top = self.b.motion_blocking_top(&*self.level, column).y;
let height = max_placeable.min(top);
if !border.contains_block(column) || !border.contains_block(step(column, direction, 1))
{
continue;
}
let mut y = height;
while y >= min_y {
let at = BlockPos::new(column.x, y, column.z);
if self.portal_can_replace(at) {
let first_empty = y;
while y > min_y
&& self.portal_can_replace(BlockPos::new(column.x, y - 1, column.z))
{
y -= 1;
}
if y + 4 <= max_placeable {
let delta = first_empty - y;
if delta <= 0 || delta >= 3 {
let at = BlockPos::new(column.x, y, column.z);
if self.can_host_frame(at, direction, 0) {
let d = distance(origin, at);
if self.can_host_frame(at, direction, -1)
&& self.can_host_frame(at, direction, 1)
&& full.is_none_or(|(fd, _)| fd > d)
{
full = Some((d, at));
}
if full.is_none() && partial.is_none_or(|(pd, _)| pd > d) {
partial = Some((d, at));
}
}
}
}
}
y -= 1;
}
}
let b = self.b;
let obsidian = b.default_of(b.named.obsidian);
let spot = match full.or(partial) {
Some((_, spot)) => spot,
None => {
let min_start = (min_y + 1).max(70);
let max_start = max_placeable - 9;
if max_start < min_start {
return None;
}
let [sx, _, sz] = direction.normal();
let y = origin.y.clamp(min_start, max_start);
let spot = border.clamp(
f64::from(origin.x - sx),
f64::from(y),
f64::from(origin.z - sz),
);
let side = clockwise(direction);
let air = b.default_of(b.named.air);
for side_offset in -1..2 {
for width in 0..2 {
for height in -1..3 {
let at = step(step(spot, direction, width), side, side_offset)
.offset(0, height, 0);
self.set_block(at, if height < 0 { obsidian } else { air }, 3);
}
}
}
spot
}
};
for width in -1..3 {
for height in -1..4 {
if width == -1 || width == 2 || height == -1 || height == 3 {
self.set_block(
step(spot, direction, width).offset(0, height, 0),
obsidian,
3,
);
}
}
}
let base = b.default_of(b.named.nether_portal);
let portal = b
.table
.with_text(base, b.props.axis, if x_axis { "x" } else { "z" })
.unwrap_or(base);
for width in 0..2 {
for height in 0..3 {
self.set_block(
step(spot, direction, width).offset(0, height, 0),
portal,
18,
);
}
}
Some(FoundRectangle {
min_corner: spot,
axis1_size: 2,
axis2_size: 3,
})
}
}
impl Behaviours {
/// `PortalForcer.createPortal` on `level` (see `Sim::create_portal`).
pub fn create_portal<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
origin: BlockPos,
x_axis: bool,
border: &BorderBounds,
logical_height: i32,
) -> Option<FoundRectangle> {
self.sim(level, ticks)
.create_portal(origin, x_axis, border, logical_height)
}
/// The axis of a nether portal state: Some(true) for X, Some(false) for
/// Z, None for other blocks.
pub fn portal_axis(&self, state: BlockStateId) -> Option<bool> {
self.is_block(state, self.named.nether_portal)
.then(|| self.table.text(state, self.props.axis) == "x")
}
}
+1
View File
@@ -61,6 +61,7 @@ pub mod sculk;
pub mod settings;
pub mod simple_block;
pub mod snow_freeze;
pub mod spawn_finder;
pub mod speleothem;
pub mod spike;
pub mod spring;
+52 -1
View File
@@ -20,7 +20,7 @@ use super::{
biome_temperature::{BiomeTemperature, BiomeTemperatureSettings},
carver::{CarverCatalog, WorldCarver, generate_carving_mask},
carving::{CarvingBlocks, apply_carving_mask},
climate::{ClimateSampler, quantize},
climate::{ClimateSampler, decode_parameter, quantize},
decode_noise,
density::DensityRegistry,
material_condition::{
@@ -31,6 +31,7 @@ use super::{
material_stage::{SurfaceInputs, TopMaterialInputs, build_surface},
material_surface::{ClayBandBlocks, MaterialSurface},
router::{NoiseRouter, RouterField, RouterSamplers},
spawn_finder::{SpawnTargetPoint, find_spawn_position},
tags::TagDefinitions,
terrain::{PreLightChunkStage, TerrainAquifer, TerrainBlockStates, TerrainChunk, fill_noise},
};
@@ -608,6 +609,9 @@ struct Pipeline<R: RandomSource> {
carver_cache: Mutex<HashMap<(i32, i32), BiomeId>>,
pub(super) decoration: Option<super::generator_decoration::Decoration>,
pub(super) structures: Option<super::generator_structures::StructureState>,
/// The noise settings' `spawn_target` points.
spawn_target: Vec<SpawnTargetPoint>,
spawn_position: std::sync::OnceLock<[i32; 2]>,
}
const CACHE_LIMIT: usize = 16384;
type BiomeCache = Mutex<HashMap<(i32, i32), Arc<BiomeChunk<BiomeId>>>>;
@@ -706,6 +710,27 @@ where
.ok_or_else(|| resource("material_rule"))?;
let rule = library.rule(rule_name)?;
let preliminary = router.get(RouterField::ChunkSurfaceLevel).clone();
let spawn_target = match settings_json.get("spawn_target") {
Some(Value::Array(points)) => points
.iter()
.map(|point| {
let Value::Object(fields) = point else {
return Err(resource("spawn_target point"));
};
let parameters = fields
.iter()
.map(|(name, interval)| {
Ok((
library.named_density(name)?,
decode_parameter(&interval.to_string())?,
))
})
.collect::<Result<_, GeneratorError>>()?;
Ok(SpawnTargetPoint { parameters })
})
.collect::<Result<_, GeneratorError>>()?,
_ => Vec::new(),
};
let source = data
.source_catalog
.decode(&generator["biome_source"].to_string())?
@@ -783,6 +808,8 @@ where
carver_cache: Mutex::new(HashMap::new()),
decoration: None,
structures: None,
spawn_target,
spawn_position: std::sync::OnceLock::new(),
};
pipeline.decoration =
super::generator_decoration::Decoration::new(&pipeline.data, &pipeline.source)?;
@@ -1363,6 +1390,7 @@ trait SeededPipeline: Send + Sync {
fn unsupported_features(&self) -> Vec<(String, String)>;
fn forget_structure_starts(&self);
fn ring_positions(&self, set: &str) -> Option<Vec<ChunkPos>>;
fn spawn_position(&self) -> Result<[i32; 2], GeneratorError>;
fn locate(
&self,
worker: &mut WorkerState,
@@ -1462,6 +1490,19 @@ where
fn ring_positions(&self, set: &str) -> Option<Vec<ChunkPos>> {
self.structures.as_ref()?.cached_rings(set)
}
fn spawn_position(&self) -> Result<[i32; 2], GeneratorError> {
if let Some(position) = self.spawn_position.get() {
return Ok(*position);
}
// ChunkGenerator.getOrigin is 0 0 without a spawn target.
let position = if self.spawn_target.is_empty() {
[0, 0]
} else {
find_spawn_position(&self.spawn_target, &mut SamplerContext::cached())
.map_err(|e| GeneratorError::Stage("spawn search", e.to_string()))?
};
Ok(*self.spawn_position.get_or_init(|| position))
}
fn locate(
&self,
worker: &mut WorkerState,
@@ -1745,6 +1786,16 @@ impl OverworldGenerator {
pub fn ring_positions(&self, set: &str) -> Option<Vec<ChunkPos>> {
self.pipeline.ring_positions(set)
}
/// NoiseBasedChunkGenerator.getOrigin: the chunk a new world's spawn
/// search starts from (NoiseSpawnFinder over the `spawn_target` points).
pub fn origin(&self) -> Result<ChunkPos, GeneratorError> {
let [x, z] = self.spawn_position()?;
Ok(ChunkPos::new(x >> 4, z >> 4))
}
/// NoiseSpawnFinder.findSpawnPosition: the column `origin` is the chunk of.
pub fn spawn_position(&self) -> Result<[i32; 2], GeneratorError> {
self.pipeline.spawn_position()
}
/// Create per-thread state. Workers are cheap; keep one per thread.
pub fn worker(&self) -> GeneratorWorker {
let data = self.pipeline.data();
@@ -0,0 +1,128 @@
//! NoiseSpawnFinder: where a new world's spawn search starts.
//!
//! NoiseBasedChunkGenerator.getOrigin samples the noise settings'
//! `spawn_target` points (SpawnTargetPoint) around the world origin and keeps
//! the block whose climate fits them best, biased towards 0 0. The world spawn
//! search (MinecraftServer.setInitialSpawn) then spirals out from its chunk.
use super::climate::{Parameter, quantize};
use horizon_core::density::{DensitySampler, SampleError, SamplerContext};
use horizon_core::jmath;
use std::sync::Arc;
const MAX_RADIUS: f32 = 2048.0;
/// One `spawn_target` entry: climate intervals over named density functions.
#[derive(Clone, Debug)]
pub struct SpawnTargetPoint {
pub parameters: Vec<(Arc<dyn DensitySampler>, Parameter)>,
}
impl SpawnTargetPoint {
/// SpawnTargetPoint.sampleFitness: the summed squared distances of the
/// quantized samples to their intervals.
pub fn sample_fitness(
&self,
context: &mut SamplerContext,
position: [i32; 3],
) -> Result<i64, SampleError> {
let mut fitness = 0i64;
for (function, parameter) in &self.parameters {
let distance = parameter.distance(quantize(function.sample_value(context, position)?));
fitness = fitness.wrapping_add(distance.wrapping_mul(distance));
}
Ok(fitness)
}
}
#[derive(Clone, Copy, Debug)]
struct Candidate {
x: i32,
z: i32,
fitness: i64,
}
/// NoiseSpawnFinder.findSpawnPosition: the best block column (x, z) of a
/// coarse then a fine radial search around the best of the two.
pub fn find_spawn_position(
targets: &[SpawnTargetPoint],
context: &mut SamplerContext,
) -> Result<[i32; 2], SampleError> {
let mut best = fitness(targets, context, 0, 0)?;
radial_search(targets, context, &mut best, MAX_RADIUS, 512.0)?;
radial_search(targets, context, &mut best, 512.0, 32.0)?;
Ok([best.x, best.z])
}
/// NoiseSpawnFinder.radialSearch: rings `increment` apart around the best
/// position so far, sampled every `increment` blocks along each ring.
fn radial_search(
targets: &[SpawnTargetPoint],
context: &mut SamplerContext,
best: &mut Candidate,
max_radius: f32,
increment: f32,
) -> Result<(), SampleError> {
let mut angle = 0f32;
let mut radius = increment;
let (origin_x, origin_z) = (best.x, best.z);
while radius <= max_radius {
let x = origin_x.wrapping_add((jmath::sin(f64::from(angle)) * f64::from(radius)) as i32);
let z = origin_z.wrapping_add((jmath::cos(f64::from(angle)) * f64::from(radius)) as i32);
let candidate = fitness(targets, context, x, z)?;
if candidate.fitness < best.fitness {
*best = candidate;
}
angle += increment / radius;
if f64::from(angle) > std::f64::consts::PI * 2.0 {
angle = 0.0;
radius += increment;
}
}
Ok(())
}
/// NoiseSpawnFinder.getSpawnPositionAndFitness: the best target's fitness at
/// the column's quart corner, scaled so the squared distance to 0 0 only
/// breaks ties between equally fitting columns.
fn fitness(
targets: &[SpawnTargetPoint],
context: &mut SamplerContext,
x: i32,
z: i32,
) -> Result<Candidate, SampleError> {
let quart = [(x >> 2) << 2, 0, (z >> 2) << 2];
let mut best = i64::MAX;
for target in targets {
best = best.min(target.sample_fitness(context, quart)?);
}
let bias = i64::from(x) * i64::from(x) + i64::from(z) * i64::from(z);
Ok(Candidate {
x,
z,
fitness: best.wrapping_mul(2048 * 2048).wrapping_add(bias),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug)]
struct Gradient;
impl DensitySampler for Gradient {
fn sample_value(&self, _: &mut SamplerContext, p: [i32; 3]) -> Result<f32, SampleError> {
Ok(p[0] as f32 / 1000.0)
}
}
#[test]
fn the_closest_fitting_column_wins() {
// x / 1000 must reach 0.1: every column from x = 100 on fits equally,
// so the distance bias picks the fitting column nearest to 0 0.
let targets = [SpawnTargetPoint {
parameters: vec![(Arc::new(Gradient), Parameter::new(1000, 10_000))],
}];
let [x, z] = find_spawn_position(&targets, &mut SamplerContext::default()).unwrap();
assert!(x >= 100, "{x} {z}");
assert!(x * x + z * z < 160 * 160, "{x} {z}");
}
}
@@ -71,6 +71,7 @@ public final class VanillaBlockUpdateOracle {
if (old == state) {
return null;
}
world.columns = null;
if (state == AIR) {
world.cells.remove(pos);
} else {
@@ -189,8 +190,29 @@ public final class VanillaBlockUpdateOracle {
@Override public boolean hasChunk(int x, int z) { return true; }
@Override public boolean isClientSide() { return false; }
@Override public RandomSource getRandom() { return rng; }
@Override public int getMinY() { return -64; }
@Override public int getHeight() { return 384; }
// Another dimension, border and points of interest (the portal oracle);
// the overworld and an unbounded border when unset.
net.minecraft.world.level.dimension.DimensionType type;
net.minecraft.resources.ResourceKey<net.minecraft.world.level.Level> dimensionKey;
net.minecraft.world.level.border.WorldBorder border;
net.minecraft.world.entity.ai.village.poi.PoiManager poi;
@Override public int getMinY() { return type == null ? -64 : type.minY(); }
@Override public int getHeight() { return type == null ? 384 : type.height(); }
@Override public net.minecraft.world.entity.ai.village.poi.PoiManager getPoiManager() { return poi != null ? poi : super.getPoiManager(); }
/** Level.getHeight from the cells (only for another dimension's level). */
Map<Long, List<BlockPos>> columns;
@Override public int getHeight(net.minecraft.world.level.levelgen.Heightmap.Types kind, int x, int z) {
if (type == null) return super.getHeight(kind, x, z);
if (columns == null) {
columns = new HashMap<>();
for (BlockPos c : cells.keySet()) columns.computeIfAbsent(BlockPos.asLong(c.getX(), 0, c.getZ()), k -> new ArrayList<>()).add(c);
}
int top = getMinY() - 1;
for (BlockPos c : columns.getOrDefault(BlockPos.asLong(x, 0, z), List.of())) {
if (c.getY() > top && kind.isOpaque().test(getBlockState(c))) top = c.getY();
}
return top + 1;
}
@Override public long getGameTime() { return time; }
@Override public long nextSubTickCount() { return subTick++; }
@Override public LevelTicks<Block> getBlockTicks() { return blockTicks; }
@@ -202,7 +224,7 @@ public final class VanillaBlockUpdateOracle {
@Override public GameRules getGameRules() { return rules; }
@Override public net.minecraft.server.MinecraftServer getServer() { return server; }
@Override public net.minecraft.world.item.crafting.RecipeManager recipeAccess() { return Server.recipes; }
@Override public net.minecraft.world.level.border.WorldBorder getWorldBorder() { return new net.minecraft.world.level.border.WorldBorder(); }
@Override public net.minecraft.world.level.border.WorldBorder getWorldBorder() { return border != null ? border : new net.minecraft.world.level.border.WorldBorder(); }
@Override public int getSeaLevel() { return 63; }
@Override public int getBrightness(net.minecraft.world.level.LightLayer layer, BlockPos p) { return layer == net.minecraft.world.level.LightLayer.SKY ? skyLight : blockLight; }
@Override public int getRawBrightness(BlockPos p, int darkening) { return Math.max(skyLight - darkening, blockLight); }
@@ -328,9 +350,9 @@ public final class VanillaBlockUpdateOracle {
}
return attributes;
}
@Override public net.minecraft.world.level.dimension.DimensionType dimensionType() { return OVERWORLD_TYPE; }
@Override public net.minecraft.world.level.dimension.DimensionType dimensionType() { return type != null ? type : 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 net.minecraft.resources.ResourceKey<net.minecraft.world.level.Level> dimension() { return dimensionKey != null ? dimensionKey : 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()];
@@ -408,6 +430,10 @@ public final class VanillaBlockUpdateOracle {
/** The overworld dimension type from the vanilla data pack (its infiniburn tag, attributes and timelines). */
static net.minecraft.world.level.dimension.DimensionType loadOverworld() {
return loadDimensionType(net.minecraft.world.level.dimension.BuiltinDimensionTypes.OVERWORLD);
}
static net.minecraft.world.level.dimension.DimensionType loadDimensionType(net.minecraft.resources.ResourceKey<net.minecraft.world.level.dimension.DimensionType> key) {
var repo = net.minecraft.server.packs.repository.ServerPacksSource.createVanillaTrustedRepository();
repo.reload();
repo.setSelected(List.of("vanilla"));
@@ -417,7 +443,7 @@ public final class VanillaBlockUpdateOracle {
var context = net.minecraft.tags.TagLoader.buildUpdatedLookups(layers.getAccessForLoading(net.minecraft.server.RegistryLayer.WORLD), staticTags);
var world = net.minecraft.resources.RegistryDataLoader.load(resources, context, net.minecraft.resources.RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join();
staticTags.forEach(net.minecraft.core.Registry.PendingTags::apply);
return world.lookupOrThrow(net.minecraft.core.registries.Registries.DIMENSION_TYPE).getOrThrow(net.minecraft.world.level.dimension.BuiltinDimensionTypes.OVERWORLD).value();
return world.lookupOrThrow(net.minecraft.core.registries.Registries.DIMENSION_TYPE).getOrThrow(key).value();
}
static final class Loot extends net.minecraft.server.ReloadableServerRegistries.Holder {
@@ -449,6 +475,9 @@ public final class VanillaBlockUpdateOracle {
@Override public net.minecraft.world.item.crafting.RecipeManager getRecipeManager() { return recipes; }
@Override public net.minecraft.server.ReloadableServerRegistries.Holder reloadableRegistries() { return loot; }
@Override protected boolean initServer() { return false; }
/** The levels by dimension (the portal oracle's two). */
Map<net.minecraft.resources.ResourceKey<net.minecraft.world.level.Level>, net.minecraft.server.level.ServerLevel> levels;
@Override public net.minecraft.server.level.ServerLevel getLevel(net.minecraft.resources.ResourceKey<net.minecraft.world.level.Level> key) { return levels == null ? null : levels.get(key); }
@Override public int getMaxPlayers() { return 0; }
@Override public net.minecraft.server.permissions.LevelBasedPermissionSet operatorUserPermissions() { return null; }
@Override public net.minecraft.server.permissions.PermissionSet getFunctionCompilationPermissions() { return null; }
@@ -295,6 +295,8 @@ public final class VanillaDispenserOracle {
remove(w, origin, f.getAsJsonObject("remove"));
} else if (f.has("use")) {
used = use(w, origin, f.getAsJsonObject("use"));
} else if (f.has("use_item")) {
used = useItem(w, origin, f.getAsJsonObject("use_item"));
} else if (f.has("hopper")) {
// HopperBlockEntity.pushItemsTick, once.
var hopper = (net.minecraft.world.level.block.entity.HopperBlockEntity) w.getBlockEntity(origin);
@@ -410,6 +412,93 @@ public final class VanillaDispenserOracle {
return out;
}
/**
* The player of a "use_item" case: a `User` that also has abilities, food,
* item cooldowns and a place (away from the clicked block), and records
* starting to use its item instead of syncing it.
*/
static final class Clicker extends net.minecraft.server.level.ServerPlayer {
VanillaBlockUpdateOracle.World world;
boolean creative, sneaking;
ItemStack hand;
List<String> stats;
String using;
Clicker() {
super(null, null, null, null);
}
@Override public ServerLevel level() { return world; }
@Override public boolean hasInfiniteMaterials() { return creative; }
@Override public boolean isCreative() { return creative; }
@Override public boolean isSpectator() { return false; }
@Override public boolean isSecondaryUseActive() { return sneaking; }
@Override public boolean isShiftKeyDown() { return sneaking; }
@Override public boolean isDescending() { return sneaking; }
@Override public EntityType<?> getType() { return EntityTypes.PLAYER; }
@Override public net.minecraft.core.Holder<EntityType<?>> typeHolder() { return EntityTypes.PLAYER.builtInRegistryHolder(); }
@Override public ItemStack getItemBySlot(EquipmentSlot slot) { return slot == EquipmentSlot.MAINHAND ? hand : ItemStack.EMPTY; }
@Override public ItemStack getItemInHand(net.minecraft.world.InteractionHand h) {
return h == net.minecraft.world.InteractionHand.MAIN_HAND ? hand : ItemStack.EMPTY;
}
@Override public void setItemInHand(net.minecraft.world.InteractionHand h, ItemStack stack) {
if (h == net.minecraft.world.InteractionHand.MAIN_HAND) hand = stack;
}
@Override public void startUsingItem(net.minecraft.world.InteractionHand h) {
using = BuiltInRegistries.ITEM.getKey(getItemInHand(h).getItem()).toString();
}
@Override public boolean isUsingItem() { return using != null; }
@Override public void awardStat(net.minecraft.stats.Stat<?> stat, int count) {
stats.add("stat " + User.key(stat) + " " + BuiltInRegistries.STAT_TYPE.getKey(stat.getType()) + " " + count);
}
}
/**
* A right click on the top of the block at `pos` (`ServerPlayerGameMode.useItemOn`
* of the real game mode, survival or creative): the block's `useItemOn` and
* `useWithoutItem`, then the item's `useOn` (`BlockItem.place`, falling back
* to eating a consumable), and `useItem` when that passes, as
* `Minecraft.startUseItem` goes on to. The statistics, the held stack and
* the item the player started using follow.
*/
static List<String> useItem(VanillaBlockUpdateOracle.World w, BlockPos pos, JsonObject use) throws Exception {
Clicker player = (Clicker) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, Clicker.class);
player.world = w;
player.creative = use.get("creative").getAsBoolean();
player.sneaking = use.get("sneaking").getAsBoolean();
player.hand = stack(use.get("item").getAsString());
player.stats = new ArrayList<>();
var abilities = new net.minecraft.world.entity.player.Abilities();
abilities.invulnerable = abilities.instabuild = abilities.mayfly = player.creative;
VanillaBlockUpdateOracle.set(net.minecraft.world.entity.player.Player.class, player, "abilities", abilities);
var food = new net.minecraft.world.food.FoodData();
food.setFoodLevel(use.get("food").getAsInt());
VanillaBlockUpdateOracle.set(net.minecraft.world.entity.player.Player.class, player, "foodData", food);
VanillaBlockUpdateOracle.set(net.minecraft.world.entity.player.Player.class, player, "cooldowns", new net.minecraft.world.item.ItemCooldowns());
var advancements = (net.minecraft.server.PlayerAdvancements) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, net.minecraft.server.PlayerAdvancements.class);
VanillaBlockUpdateOracle.set(net.minecraft.server.PlayerAdvancements.class, advancements, "activeTriggers", new HashMap<>());
VanillaBlockUpdateOracle.set(net.minecraft.server.level.ServerPlayer.class, player, "advancements", advancements);
// Standing three blocks south of the clicked block, looking down at it.
var at = net.minecraft.world.phys.Vec3.atBottomCenterOf(pos).add(0, 1, 3);
VanillaBlockUpdateOracle.set(Entity.class, player, "position", at);
VanillaBlockUpdateOracle.set(Entity.class, player, "blockPosition", BlockPos.containing(at));
VanillaBlockUpdateOracle.set(Entity.class, player, "xRot", 90f);
var gameMode = new net.minecraft.server.level.ServerPlayerGameMode(player);
VanillaBlockUpdateOracle.set(net.minecraft.server.level.ServerPlayerGameMode.class, gameMode, "gameModeForPlayer",
player.creative ? net.minecraft.world.level.GameType.CREATIVE : net.minecraft.world.level.GameType.SURVIVAL);
var hit = new net.minecraft.world.phys.BlockHitResult(net.minecraft.world.phys.Vec3.atCenterOf(pos).add(0, 0.5, 0),
net.minecraft.core.Direction.UP, pos, false);
var hand = net.minecraft.world.InteractionHand.MAIN_HAND;
var result = gameMode.useItemOn(player, w, player.getItemInHand(hand), hand, hit);
// Minecraft.startUseItem: a click on a block that neither succeeded nor
// failed goes on to use the item in the same hand.
if (!(result instanceof net.minecraft.world.InteractionResult.Success)
&& !(result instanceof net.minecraft.world.InteractionResult.Fail) && !player.hand.isEmpty()) {
gameMode.useItem(player, w, player.getItemInHand(hand), hand);
}
List<String> out = new ArrayList<>(player.stats);
out.add("held " + ParityData.canon(player.hand) + " using " + (player.using == null ? "-" : player.using));
return out;
}
/** The level's block entity positions by x, y, z. */
static List<BlockPos> sortedEntities(VanillaBlockUpdateOracle.World w) {
List<BlockPos> out = new ArrayList<>(w.blockEntities == null ? List.of() : w.blockEntities.keySet());
@@ -7,6 +7,10 @@ import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.mojang.math.Axis;
import net.minecraft.SharedConstants;
import net.minecraft.client.model.EntityModel;
import net.minecraft.client.model.geom.LayerDefinitions;
@@ -21,7 +25,16 @@ import net.minecraft.server.Bootstrap;
* fields, runs the real setupAnim and writes every part's pose.
*
* Input lines: "layer-key ModelClass|case-json" where case-json is an object of state field
* name to value. Output lines: {layer, case, parts:{path:[x,y,z,xRot,yRot,zRot,xScale,yScale,zScale,visible]}}.
* name to value. Output lines: {layer, case, parts:{path:[x,y,z,xRot,yRot,zRot,xScale,yScale,zScale,visible]},
* vertices:{path:{n, f, p, d}}}.
*
* `vertices` renders the posed model the way ModelPart.render does (translateAndRotate on a
* PoseStack, then Cube.compile: PoseStack.Pose.transformNormal once per polygon and
* VertexConsumer.addVertex/setNormal per vertex) under LivingEntityRenderer's root transform:
* rotateDegrees(YP, 180 - "@rootYaw"), scale(-1, -1, 1), scale("@rootScale"),
* translate(0, -1.501, 0). Per drawn part: n = each vertex's normal as the signed bytes
* BufferBuilder.setNormal writes (its own normalIntValue), f = each polygon's float normal before
* packing, p = sum of x + 2y + 3z over the posed positions, d = all its vertices are one point.
*/
public final class VanillaEntityAnimOracle {
private static Field cubes;
@@ -63,6 +76,82 @@ public final class VanillaEntityAnimOracle {
private static final List<String> CLASS_NAMES = new ArrayList<>();
private static Method normalIntValue;
/** Records what Cube.compile hands its VertexConsumer: each vertex's position and normal. */
private static final class Capture implements VertexConsumer {
final List<float[]> vertices = new ArrayList<>();
private float[] current;
@Override
public VertexConsumer addVertex(float x, float y, float z) {
current = new float[] {x, y, z, Float.NaN, Float.NaN, Float.NaN};
vertices.add(current);
return this;
}
@Override
public VertexConsumer setNormal(float x, float y, float z) {
current[3] = x;
current[4] = y;
current[5] = z;
return this;
}
@Override public VertexConsumer setColor(int r, int g, int b, int a) { return this; }
@Override public VertexConsumer setColor(int color) { return this; }
@Override public VertexConsumer setUv(float u, float v) { return this; }
@Override public VertexConsumer setUv1(int u, int v) { return this; }
@Override public VertexConsumer setUv2(int u, int v) { return this; }
@Override public VertexConsumer setUv3(float u, float v) { return this; }
@Override public VertexConsumer setLineWidth(float width) { return this; }
JsonObject json() throws Exception {
var packed = new JsonArray();
var floats = new JsonArray();
double sum = 0;
boolean degenerate = true;
float[] first = vertices.get(0);
for (int i = 0; i < vertices.size(); i++) {
float[] v = vertices.get(i), corner = vertices.get(i - i % 4);
for (int c = 3; c < 6; c++) packed.add((byte) normalIntValue.invoke(null, v[c]));
if (i % 4 == 0) {
for (int c = 3; c < 6; c++) floats.add(Float.isFinite(v[c]) ? v[c] : 0.0F);
} else if (!Arrays.equals(v, 3, 6, corner, 3, 6)) {
throw new IllegalStateException("normal changes inside a polygon");
}
sum += v[0] + 2.0 * v[1] + 3.0 * v[2];
degenerate &= v[0] == first[0] && v[1] == first[1] && v[2] == first[2];
}
var o = new JsonObject();
o.add("n", packed);
o.add("f", floats);
o.addProperty("p", sum);
o.addProperty("d", degenerate);
return o;
}
}
/** ModelPart.render, keeping each part's vertices apart under its path. */
@SuppressWarnings("unchecked")
private static void render(String path, ModelPart part, PoseStack poseStack, JsonObject out) throws Exception {
if (!part.visible) return;
var cubeList = (List<ModelPart.Cube>) cubes.get(part);
var kids = (Map<String, ModelPart>) children.get(part);
if (cubeList.isEmpty() && kids.isEmpty()) return;
poseStack.pushPose();
part.translateAndRotate(poseStack);
if (!part.skipDraw) {
var capture = new Capture();
for (ModelPart.Cube cube : cubeList)
cube.compile(poseStack.last(), capture, 0xF000F0, net.minecraft.client.renderer.texture.OverlayTexture.NO_OVERLAY, -1);
if (!capture.vertices.isEmpty()) out.add(path, capture.json());
}
for (var entry : kids.entrySet())
render(path.isEmpty() ? entry.getKey() : path + "/" + entry.getKey(), entry.getValue(), poseStack, out);
poseStack.popPose();
}
private static Class<?> raw(java.lang.reflect.Type t, Map<java.lang.reflect.TypeVariable<?>, java.lang.reflect.Type> env) {
if (t instanceof Class<?> c) return c;
if (t instanceof java.lang.reflect.ParameterizedType p) return raw(p.getRawType(), env);
@@ -160,6 +249,8 @@ public final class VanillaEntityAnimOracle {
cubes.setAccessible(true);
children = ModelPart.class.getDeclaredField("children");
children.setAccessible(true);
normalIntValue = BufferBuilder.class.getDeclaredMethod("normalIntValue", float.class);
normalIntValue.setAccessible(true);
try (var zip = new java.util.zip.ZipFile(args[2])) {
zip.stream().map(e -> e.getName()).filter(n -> n.startsWith("net/minecraft/client/model/") && n.endsWith(".class"))
.forEach(n -> CLASS_NAMES.add(n.substring(0, n.length() - 6).replace('/', '.')));
@@ -189,14 +280,36 @@ public final class VanillaEntityAnimOracle {
var type = stateClass(cls);
var state = (EntityRenderState) type.getDeclaredConstructor().newInstance();
state.getClass();
for (var entry : kase.entrySet()) set(state, entry.getKey(), entry.getValue());
for (var entry : kase.entrySet())
if (!entry.getKey().startsWith("@")) set(state, entry.getKey(), entry.getValue());
hooks(state, kase);
if (state instanceof net.minecraft.client.renderer.entity.state.ArmedEntityRenderState armed && armed.swingAnimation > 0)
armed.currentSwing = new net.minecraft.world.entity.LivingEntity.SwingDescription(net.minecraft.world.InteractionHand.MAIN_HAND, net.minecraft.world.item.component.SwingAnimation.DEFAULT, 6);
model.setupAnim(state);
if (kase.has("@partScale")) {
var override = kase.getAsJsonArray("@partScale");
var part = baked.createPartLookup().apply(override.get(0).getAsString());
if (part == null) throw new IllegalArgumentException("no part " + override.get(0));
part.xScale = override.get(1).getAsFloat();
part.yScale = override.get(2).getAsFloat();
part.zScale = override.get(3).getAsFloat();
}
var parts = new JsonObject();
dump("", baked, parts);
result.add("parts", parts);
// LivingEntityRenderer.render/setupRotations, without the entity's position.
var poseStack = new PoseStack();
float yaw = kase.has("@rootYaw") ? kase.get("@rootYaw").getAsFloat() : 0.0F;
poseStack.rotateDegrees(Axis.YP, 180.0F - yaw);
poseStack.scale(-1.0F, -1.0F, 1.0F);
if (kase.has("@rootScale")) {
var scale = kase.getAsJsonArray("@rootScale");
poseStack.scale(scale.get(0).getAsFloat(), scale.get(1).getAsFloat(), scale.get(2).getAsFloat());
}
poseStack.translate(0.0F, -1.501F, 0.0F);
var vertices = new JsonObject();
render("", baked, poseStack, vertices);
result.add("vertices", vertices);
} catch (Throwable error) {
var cause = error.getCause() != null ? error.getCause() : error;
result.addProperty("error", cause.toString());
@@ -0,0 +1,144 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import java.io.PrintWriter;
import java.nio.file.*;
import java.util.*;
import net.minecraft.core.BlockPos;
import net.minecraft.core.SectionPos;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.Identifier;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntitySpawnReason;
import net.minecraft.world.entity.ai.village.poi.PoiManager;
import net.minecraft.world.entity.ai.village.poi.PoiSection;
import net.minecraft.world.entity.ai.village.poi.PoiTypes;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.NetherPortalBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
/**
* Nether portal travel, one entity per case: `NetherPortalBlock.getPortalDestination`
* for an entity standing in a portal of one headless level (the block update
* oracle's), going to another (the Nether from the overworld or back), whose
* points of interest are the case's portal blocks in the case's order. It runs
* `PortalForcer.findClosestPortalPosition` and, when nothing is found,
* `createPortal`, `BlockUtil.getLargestRectangleAround`,
* `PortalShape.getRelativePosition` and `findCollisionFreePosition`. Printed:
* the entity's size, the exit portal found (or "created"), the blocks the
* destination changed and the arrival position (bits) and yaw.
*/
public final class VanillaPortalOracle {
/** The points of interest of the destination: the case's portal blocks. */
static final class Poi extends PoiManager {
Map<Long, PoiSection> sections;
Poi() {
super(null, null, null, false, null, null, null);
}
@Override protected Optional<PoiSection> getOrLoad(long key) { return Optional.ofNullable(sections.get(key)); }
@Override public void ensureLoadedAndValid(net.minecraft.world.level.LevelReader reader, BlockPos center, int radius) { }
}
static net.minecraft.world.level.dimension.DimensionType OVERWORLD, NETHER;
public static void main(String[] args) throws Exception {
ParityData.init();
VanillaBlockUpdateOracle.AIR = Blocks.AIR.defaultBlockState();
VanillaLevelShapeOracle.bindFluidTags(Path.of(args[0]).resolve("data/minecraft/tags/fluid"));
OVERWORLD = VanillaBlockUpdateOracle.OVERWORLD_TYPE = VanillaBlockUpdateOracle.loadOverworld();
NETHER = VanillaBlockUpdateOracle.loadDimensionType(BuiltinDimensionTypes.NETHER);
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();
out.print("case " + index++ + "\n");
try {
for (String s : run(f)) out.print(s + "\n");
} 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();
out.print("error " + c.getClass().getSimpleName() + " " + (st.length > 0 ? st[0].toString() : "") + " " + c.getMessage() + "\n");
}
}
}
}
static VanillaBlockUpdateOracle.World level(JsonObject f, String cells, boolean nether) throws Exception {
var copy = new JsonObject();
copy.add("cells", f.get(cells));
copy.add("seed", f.get("seed"));
var w = VanillaBlockUpdateOracle.build(copy);
w.type = nether ? NETHER : OVERWORLD;
w.dimensionKey = nether ? Level.NETHER : Level.OVERWORLD;
return w;
}
static List<String> run(JsonObject f) throws Exception {
boolean fromNether = f.get("from").getAsString().equals("nether");
var source = level(f, "source", fromNether);
var target = level(f, "target", !fromNether);
var levels = new HashMap<net.minecraft.resources.ResourceKey<Level>, net.minecraft.server.level.ServerLevel>();
levels.put(source.dimension(), source);
levels.put(target.dimension(), target);
source.server.levels = levels;
target.server = source.server;
var border = new net.minecraft.world.level.border.WorldBorder();
var b = f.getAsJsonObject("border");
border.setCenter(b.get("x").getAsDouble(), b.get("z").getAsDouble());
border.setSize(b.get("size").getAsDouble());
target.border = border;
var poi = (Poi) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, Poi.class);
poi.sections = new HashMap<>();
VanillaBlockUpdateOracle.set(net.minecraft.world.level.chunk.storage.SectionStorage.class, poi, "levelHeightAccessor", target);
var portalType = BuiltInRegistries.POINT_OF_INTEREST_TYPE.getOrThrow(PoiTypes.NETHER_PORTAL);
for (var p : f.getAsJsonArray("pois")) {
BlockPos at = VanillaBlockUpdateOracle.readPos(p.getAsJsonArray());
poi.sections.computeIfAbsent(SectionPos.asLong(at), k -> new PoiSection(() -> { })).add(at, portalType);
}
target.poi = poi;
VanillaBlockUpdateOracle.set(net.minecraft.server.level.ServerLevel.class, target, "portalForcer", new net.minecraft.world.level.portal.PortalForcer(target));
var e = f.getAsJsonObject("entity");
Entity entity = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(e.get("type").getAsString())).create(source, EntitySpawnReason.LOAD);
// Exact doubles, as bits.
var at = e.getAsJsonArray("bits");
java.util.function.IntToDoubleFunction bit = i -> Double.longBitsToDouble(Long.parseUnsignedLong(at.get(i).getAsString(), 16));
entity.setPos(bit.applyAsDouble(0), bit.applyAsDouble(1), bit.applyAsDouble(2));
List<String> out = new ArrayList<>();
var dimensions = entity.getDimensions(entity.getPose());
out.add(String.format("dims %08x %08x", Float.floatToIntBits(dimensions.width()), Float.floatToIntBits(dimensions.height())));
Map<BlockPos, BlockState> before = new HashMap<>(target.cells);
BlockPos entry = VanillaBlockUpdateOracle.readPos(f.getAsJsonArray("entry"));
// The steps getPortalDestination takes, for the report.
BlockState entryState = source.getBlockState(entry);
if (entryState.hasProperty(NetherPortalBlock.AXIS)) {
var axis = entryState.getValue(NetherPortalBlock.AXIS);
var area = net.minecraft.util.BlockUtil.getLargestRectangleAround(entry, axis, 21, net.minecraft.core.Direction.Axis.Y, 21, q -> source.getBlockState(q) == entryState);
out.add("entry " + VanillaBlockUpdateOracle.pos(area.minCorner) + " " + area.axis1Size + "x" + area.axis2Size);
var offset = entity.getRelativePortalPosition(axis, area);
out.add(String.format("offset %016x %016x %016x", Double.doubleToLongBits(offset.x), Double.doubleToLongBits(offset.y), Double.doubleToLongBits(offset.z)));
}
double scale = net.minecraft.world.level.dimension.DimensionType.getTeleportationScale(source.dimensionType(), target.dimensionType());
BlockPos approximate = border.clampToBounds(entity.getX() * scale, entity.getY(), entity.getZ() * scale);
out.add("approximate " + VanillaBlockUpdateOracle.pos(approximate));
out.add("found " + target.getPortalForcer().findClosestPortalPosition(approximate, !fromNether, border).map(VanillaBlockUpdateOracle::pos).orElse("none"));
var transition = ((NetherPortalBlock) Blocks.NETHER_PORTAL).getPortalDestination(source, entity, entry);
out.addAll(VanillaBlockUpdateOracle.summary(target, before));
if (transition == null) {
out.add("dest none");
} else {
var p = transition.position();
out.add(String.format("dest %016x %016x %016x %s", Double.doubleToLongBits(p.x), Double.doubleToLongBits(p.y), Double.doubleToLongBits(p.z),
Float.toString(transition.yRot())));
}
return out;
}
}
@@ -227,6 +227,21 @@ public final class VanillaSceneMotionOracle {
@Override public Vec3 getKnownMovement(){return tickStart==null?Vec3.ZERO:position().subtract(tickStart);}
@Override protected void applyInput(){if(!preparedInput)super.applyInput();}
void peaceful(){tickRegeneration();}
// Entity.handlePortal without the destination (none: one level here),
// remembering the entry of a portal it would go through.
String travel;
// The creative delay applies with invulnerable abilities, set only for
// the transition time (the scene's food code runs without abilities).
void portalTick(boolean creative){
processPortalCooldown();
if(portalProcess!=null){
var entry=portalProcess.getEntryPosition();
boolean was=getAbilities().invulnerable;getAbilities().invulnerable=creative;
boolean through;try{through=portalProcess.processPortalTeleportation((net.minecraft.server.level.ServerLevel)sceneLevel,this,canUsePortal(false));}finally{getAbilities().invulnerable=was;}
if(through){travel=entry.getX()+","+entry.getY()+","+entry.getZ();setPortalCooldown();}
else if(portalProcess.hasExpired())portalProcess=null;
}
}
void clock()throws Exception{sceneLevel.time++;tickCount++;if(cooldown.getInt(this)>0)cooldown.setInt(this,cooldown.getInt(this)-1);if(hurtTime>0)hurtTime--;}
void playerMovementTick(Vec3 input,boolean jumping){
preparedInput=true;xxa=(float)input.x;yya=0;zza=(float)input.z;setJumping(jumping);
@@ -257,6 +272,8 @@ public final class VanillaSceneMotionOracle {
p.onGround(),noBlocks.getBoolean(p),pos(support.get(p)),Double.doubleToLongBits(p.fallDistance),pos(last.get(p)),p.needsSync,p.syncPosition,Float.floatToIntBits(storedSpeed.getFloat(p)),delay.getInt(p),Float.floatToIntBits(p.yHeadRot),trigger.getInt(p),grace.getInt(p),impact.get(p)==null?"none":vectorBits((Vec3)impact.get(p)),String.join(";",attributes));
out.println("events "+String.join(" | ",p.events));p.events.clear();
out.println("block "+Block.getId(p.level().getBlockState(new BlockPos(25,3,25)))+" frozen "+p.frozen+" "+p.isInPowderSnow+" "+p.wasInPowderSnow+" "+vectorBits((Vec3)stuck.get(p)));
var pp=p.portalProcess;
out.println("portal "+p.getPortalCooldown()+" "+(pp==null?"none":pp.getEntryPosition().getX()+","+pp.getEntryPosition().getY()+","+pp.getEntryPosition().getZ()+" "+pp.getPortalTime()+" "+pp.isInsidePortalThisTick())+" "+(p.travel==null?"-":p.travel));p.travel=null;
out.printf("health %08x %08x %08x %d %d %08x %d %d %s %d %s %s %s %s %s %d%n",
Float.floatToIntBits(p.getHealth()),Float.floatToIntBits(p.getAbsorptionAmount()),Float.floatToIntBits(foodExhaustion.getFloat(p.getFoodData())),
noAction.getInt(p),cooldown.getInt(p),Float.floatToIntBits(lastHurt.getFloat(p)),p.hurtDuration,p.hurtTime,sourceName((DamageSource)lastDamage.get(p)),lastStamp.getLong(p),healthDead.getBoolean(p),p.syncVelocity,
@@ -373,6 +390,7 @@ public final class VanillaSceneMotionOracle {
((EntityEquipment)field(LivingEntity.class,"equipment").get(p)).set(net.minecraft.world.entity.EquipmentSlot.FEET,stack);
}
case "frozen"->p.frozen=op.get("value").getAsInt();
case "portal_tick"->p.portalTick(op.get("creative").getAsBoolean());
case "weaving"->p.weaving=op.get("value").getAsBoolean();
case "flying"->{var a=p.getAbilities();a.mayfly=a.flying=op.get("value").getAsBoolean();}
case "trigger"->trigger.setInt(p,op.get("value").getAsInt());
@@ -0,0 +1,61 @@
package dev.horizonlab.parity;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import net.minecraft.SharedConstants;
import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.server.Bootstrap;
import net.minecraft.server.RegistryLayer;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.server.packs.resources.MultiPackResourceManager;
import net.minecraft.tags.TagLoader;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.biome.MultiNoiseBiomeSource;
import net.minecraft.world.level.biome.MultiNoiseBiomeSourceParameterLists;
import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import net.minecraft.world.level.levelgen.NoiseSpawnFinder;
import net.minecraft.world.level.levelgen.RandomState;
import net.minecraft.world.level.levelgen.densityfunction.SamplerContext;
/**
* The overworld's spawn origin for tools/test_world_spawn_parity.py: for each
* seed, NoiseSpawnFinder.findSpawnPosition over the noise settings' spawn
* target and NoiseBasedChunkGenerator.getOrigin, as `seed x z chunk_x chunk_z`.
*
* usage: VanillaWorldSpawnOracle <out> <seed>...
*/
public final class VanillaWorldSpawnOracle {
public static void main(String[] args) throws Exception {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
var repo = ServerPacksSource.createVanillaTrustedRepository();
repo.reload();
repo.setSelected(List.of("vanilla"));
var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected());
var layers = RegistryLayer.createRegistryAccess();
var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC));
var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags);
var world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join();
var settings = world.lookupOrThrow(Registries.NOISE_SETTINGS).getOrThrow(NoiseGeneratorSettings.OVERWORLD);
var presets = world.lookupOrThrow(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST);
var biomeSource = MultiNoiseBiomeSource.createFromPreset(presets.getOrThrow(MultiNoiseBiomeSourceParameterLists.OVERWORLD));
var generator = new NoiseBasedChunkGenerator(biomeSource, settings);
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[0]), StandardCharsets.UTF_8))) {
for (int i = 1; i < args.length; i++) {
long seed = Long.parseLong(args[i]);
var randomState = RandomState.create(world.lookupOrThrow(Registries.NOISE), seed, settings.value());
BlockPos spawn = NoiseSpawnFinder.findSpawnPosition(
settings.value().spawnTarget(), randomState.samplersWithContext(SamplerContext.builder().enableCaches().build()));
ChunkPos origin = generator.getOrigin(randomState);
out.println(seed + " " + spawn.getX() + " " + spawn.getZ() + " " + origin.x() + " " + origin.z());
}
}
}
}
+107 -4
View File
@@ -8,7 +8,18 @@ state fields), runs the real `setupAnim` and writes every part's pose.
`mobs::anim::setup` and the loaded model tree; the two must agree on every part
pose and on the baked polygon count and vertex sums.
Both sides then draw the posed model under LivingEntityRenderer's root transform
(vanilla: ModelPart.render's PoseStack walk and Cube.compile into a capturing
VertexConsumer; Horizon: `mobs::render::draw`) and compare every vertex's normal
as the signed bytes each puts in its vertex buffer: vanilla's BufferBuilder.setNormal
truncates clamp(c) * 127 toward zero (normalIntValue) for the entity format's byte
normal, Horizon packs its RGBA8_SNORM `Vertex.normal` the same way. A one-step
difference is accepted only where vanilla's float lies within --normal-edge of a
truncation step (float rounding); any other difference fails. A checksum of each
drawn part's posed positions is compared too.
test_entity_model_parity.py [--filter SUBSTRING] [--detail LAYER] [--tolerance EPS]
[--normal-edge EPS] [--position-tolerance EPS]
"""
import argparse
import json
@@ -101,7 +112,34 @@ def layers(models):
return chosen
def cases(layer):
# The renderer's root transform for the normal comparison (keys starting with
# '@' are not render-state fields): LivingEntityRenderer's body yaw, and the
# renderer's own scale (uniform like an age scale, or non-uniform like
# CreeperRenderer's swell, which makes PoseStack.Pose's normals untrusted).
ROOT_YAWS = [0.0, 37.5, -112.25, 90.0, 180.0, 213.7, -45.0]
ROOT_SCALES = [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [0.5, 0.5, 0.5], [1.18, 0.92, 1.18], [1.0, 1.0, 1.0]]
# No vanilla setupAnim scales a part negatively, so '@partScale' sets one part's scale after
# setupAnim on both sides: PoseStack.Pose.scale flips the normal matrix's signs when |x|=|y|=|z|
# (trusted), and scales it by 1/x, 1/y, 1/z and normalises otherwise.
PART_SCALES = [[-1.0, -1.0, -1.0], [-1.0, 1.0, 1.0], [1.0, -1.0, 1.0], [-0.75, 1.25, 1.0], [0.6, 0.6, 0.6]]
def scaled_part(model):
"""A part with cubes, preferably with children, whose name is unique in the tree (Horizon's
poses are keyed by name)."""
names, found = {}, []
def walk(name, node, depth):
names[name] = names.get(name, 0) + 1
if depth and node.get('polygons'):
found.append((not node.get('children'), depth, name))
for key, child in sorted(node.get('children', {}).items()):
walk(key, child, depth + 1)
walk('root', model, 0)
found = [f for f in found if names[f[2]] == 1]
return min(found)[2] if found else None
def cases(layer, model=None):
rng = random.Random(0x414e494d + sum(map(ord, layer)))
baby = '_baby#' in layer
base_cases = [
@@ -117,14 +155,19 @@ def cases(layer):
rng.uniform(-50, 50), rng.uniform(-70, 70),
rng.choice([0.0, rng.uniform(0.01, 0.99)])))
cases_out = []
for pos, speed, age, y, x, attack in base_cases:
for index, (pos, speed, age, y, x, attack) in enumerate(base_cases):
cases_out.append({'walkAnimationPos': pos, 'walkAnimationSpeed': speed, 'ageInTicks': age,
'yRot': y, 'xRot': x, 'swingAnimation': attack, 'isBaby': baby, 'ageScale': 0.5 if baby else 1.0,
'entityId': 7, 'yHeadRot': y, 'yBodyRot': 0.0})
'entityId': 7, 'yHeadRot': y, 'yBodyRot': 0.0,
'@rootYaw': ROOT_YAWS[index % len(ROOT_YAWS)], '@rootScale': ROOT_SCALES[index % len(ROOT_SCALES)]})
name = layer.split(':')[1].split('#')[0].removesuffix('_baby')
cases_out = [{**c, **DEFAULTS.get(name, {})} for c in cases_out]
yield from cases_out
yield from species_cases(layer, cases_out)
part = model and scaled_part(model)
if part:
for index, scale in enumerate(PART_SCALES):
yield {**cases_out[2 + index % 2], '@partScale': [part, *scale]}
T, F = True, False
@@ -233,11 +276,65 @@ def species_cases(layer, base_cases):
yield {**base_cases[index], **extra}
def compare_vertices(v, r, args, stats):
"""The posed model's per-vertex normals, as the signed bytes both clients put in the vertex
buffer (BufferBuilder.setNormal's normalIntValue; Horizon's RGBA8_SNORM `Vertex.normal`), and
a checksum of each drawn part's posed positions."""
bad = []
vanilla, rust = v.get('vertices', {}), r.get('vertices', {})
for path, ve in vanilla.items():
ru = rust.get(path)
if ru is None:
# Horizon does not draw a part scaled to zero: vanilla's vertices all collapse there.
if ve['d']:
stats['degenerate'] += len(ve['n']) // 3
else:
bad.append((path, 'drawn by vanilla, not by Horizon'))
continue
if len(ve['n']) != len(ru['n']):
bad.append((path, f'{len(ve["n"]) // 3} vertices != {len(ru["n"]) // 3}'))
continue
stats['parts'] += 1
first = None
for i in range(0, len(ve['n']), 3):
stats['vertices'] += 1
exact = True
for c in range(3):
a, b = ve['n'][i + c], ru['n'][i + c]
f = ve['f'][i // 12 * 3 + c]
if a == b:
continue
exact = False
stats['max_bytes'] = max(stats['max_bytes'], abs(a - b))
# A one-byte step where vanilla's float sits within float rounding of a
# truncation step (normalIntValue truncates c * 127 toward zero).
edge = abs(f * 127.0 - round(f * 127.0)) <= args.normal_edge and abs(a - b) == 1
if edge:
stats['edge'] += 1
elif first is None:
first = (path, f'vertex {i // 3} normal {ve["n"][i:i + 3]} != {ru["n"][i:i + 3]}'
f' (vanilla float {ve["f"][i // 12 * 3:i // 12 * 3 + 3]})')
stats['exact'] += exact
if first:
bad.append(first)
count = len(ve['n']) // 3
if abs(ve['p'] - ru['p']) > args.position_tolerance * count * (1.0 + abs(ve['p']) / max(count, 1)):
bad.append((path, f'posed position sum {ve["p"]!r} != {ru["p"]!r}'))
for path in rust:
if path not in vanilla:
bad.append((path, 'drawn by Horizon, not by vanilla'))
return bad
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--filter', default='')
parser.add_argument('--detail', default='')
parser.add_argument('--tolerance', type=float, default=5e-7)
parser.add_argument('--normal-edge', type=float, default=1e-4,
help='accept a one-byte normal step when vanilla\'s float * 127 is this close to an integer')
parser.add_argument('--position-tolerance', type=float, default=1e-5,
help='per-vertex tolerance of the posed position checksums, in blocks')
args = parser.parse_args()
lock, jars, _ = base.verify_artifacts()
libraries = baking.client_libraries()
@@ -249,7 +346,7 @@ def main():
if Path(__file__).with_suffix('.cases.json').exists() else {}
lines = []
for layer, cls in sorted(chosen.items()):
for case in cases(layer):
for case in cases(layer, models[layer]):
lines.append(f'{layer} {cls}|{json.dumps(case)}')
for case in extra_cases.get(layer.split(':')[1].split('#')[0], []):
lines.append(f'{layer} {cls}|{json.dumps(case)}')
@@ -271,6 +368,7 @@ def main():
rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()]
assert len(vanilla) == len(rust), (len(vanilla), len(rust))
errors, skipped, mismatched, checked = {}, set(), {}, 0
stats = dict.fromkeys(['parts', 'vertices', 'exact', 'edge', 'degenerate', 'max_bytes'], 0)
for v, r in zip(vanilla, rust):
layer = v['layer']
if 'error' in v:
@@ -297,9 +395,14 @@ def main():
for path in r['parts']:
if path not in v['parts']:
bad.append((path, 'extra in Horizon'))
bad += compare_vertices(v, r, args, stats)
if bad:
mismatched.setdefault(layer, []).append((v['case'], bad))
print(f'{checked} cases compared over {len(chosen) - len(skipped) - len(errors)} layers')
print(f'normals: {stats["vertices"]} vertices in {stats["parts"]} drawn parts, {stats["exact"]} with identical '
f'packed bytes, {stats["edge"]} components one step apart at a truncation edge, max byte difference '
f'{stats["max_bytes"]} (max normal error {stats["max_bytes"] / 127:.5f}); '
f'{stats["degenerate"]} collapsed vertices of zero-scaled parts left out')
if errors:
print('oracle errors:'); [print(' ', k, v) for k, v in sorted(errors.items())]
if skipped:
File diff suppressed because one or more lines are too long
+182
View File
@@ -0,0 +1,182 @@
#!/usr/bin/env python3
"""Compare where vanilla's nether portals send an entity with Horizon's.
Every case has an entity (an item, a mob, a minecart, an arrow) standing in a
nether portal of one level (the overworld or the Nether), a random destination
around the scaled position (terrain, water, lava, ceilings, other portals) and
a world border, sometimes tight enough to clamp the exit. Vanilla runs
`NetherPortalBlock.getPortalDestination` over two headless levels of the block
update oracle (`VanillaPortalOracle`): `PortalForcer.findClosestPortalPosition`
over the destination's portal points of interest, `createPortal` when there is
none, `BlockUtil.getLargestRectangleAround`, `PortalShape.getRelativePosition`
and `findCollisionFreePosition`. Horizon runs `horizon_world::level::portal_travel`
(`portal_travel_fixture`). Both print the entity's size, the blocks the
destination changed, and the arrival position (bits) and yaw.
"""
import json
import os
import random
import struct
try:
from . import block_update_harness as h, lab, test_dispenser_parity as d, test_rust_parity as base
except ImportError:
import block_update_harness as h
import lab
import test_dispenser_parity as d
import test_rust_parity as base
PARITY_RUST_SCOPE = ['crates/horizon-world/', 'crates/horizon-core/']
# EntityType dimensions (width, height) of the travellers.
ENTITIES = {'minecraft:item': (0.25, 0.25), 'minecraft:zombie': (0.6, 1.95), 'minecraft:skeleton': (0.6, 1.99),
'minecraft:creeper': (0.6, 1.7), 'minecraft:minecart': (0.98, 0.7), 'minecraft:arrow': (0.5, 0.5),
'minecraft:horse': (1.3964844, 1.6), 'minecraft:spider': (1.4, 0.9), 'minecraft:ghast': (4.0, 4.0),
'minecraft:oak_boat': (1.375, 0.5625)}
GROUND = ['stone', 'dirt', 'grass_block', 'netherrack', 'sand', 'gravel', 'oak_planks', 'soul_sand', 'blackstone']
DECOR = ['short_grass', 'snow', 'water', 'lava', 'oak_leaves', 'oak_fence', 'torch', 'glass', 'stone_slab', 'dead_bush']
def portal(states, cells, pois, corner, x_axis, width, height, frame=True):
"""Obsidian around a width by height portal whose bottom left is `corner`."""
x, y, z = corner
dx, dz = (1, 0) if x_axis else (0, 1)
state = states.get('nether_portal', axis='x' if x_axis else 'z')
for w in range(-1, width + 1):
for v in range(-1, height + 1):
at = [x + dx * w, y + v, z + dz * w]
if 0 <= w < width and 0 <= v < height:
cells[tuple(at)] = state
if pois is not None:
pois.append(at)
elif frame:
cells[tuple(at)] = states.get('obsidian')
def terrain(states, rng, cells, center, nether):
"""Columns around `center`: ground, holes, liquids, plants, a ceiling."""
cx, cy, cz = center
lo, hi = (1, 120) if nether else (-60, 300)
style = rng.choice(['flat', 'flat', 'hills', 'solid', 'empty', 'cave', 'sea'])
base = max(lo + 2, min(hi - 12, cy + rng.randint(-12, 12)))
span = rng.choice([8, 20, 24])
for x in range(cx - span, cx + span + 1):
for z in range(cz - span, cz + span + 1):
if style == 'empty':
continue
top = base + (rng.randint(-3, 3) if style == 'hills' else 0)
if style == 'solid':
for y in range(top - 6, top + 9):
cells[(x, y, z)] = states.get(rng.choice(GROUND))
continue
if rng.random() < 0.04:
continue
for y in range(top - 3, top + 1):
cells[(x, y, z)] = states.get(rng.choice(GROUND) if y < top else rng.choice(['grass_block', 'stone', 'netherrack']))
if style == 'sea':
for y in range(top + 1, top + 3):
cells[(x, y, z)] = states.get('water')
elif rng.random() < 0.08:
cells[(x, top + 1, z)] = states.get(rng.choice(DECOR))
if style == 'cave':
for y in range(top + 4, top + 7):
cells[(x, y, z)] = states.get('stone')
def cases(facts, count, seed):
rng = random.Random(seed)
states = d.States(facts)
for n in range(count):
from_nether = rng.random() < 0.5
x_axis = rng.random() < 0.5
width, height = rng.choice([2, 2, 3, 4]), rng.choice([3, 3, 4, 5])
spread = rng.choice([30, 300, 3000])
lo, hi = (5, 100) if from_nether else (-50, 250)
corner = (rng.randint(-spread, spread), rng.randint(lo, hi), rng.randint(-spread, spread))
source = {}
portal(states, source, None, corner, x_axis, width, height)
kind = rng.choice(sorted(ENTITIES))
dims = ENTITIES[kind]
dx, dz = (1, 0) if x_axis else (0, 1)
along = rng.uniform(0, width)
up = rng.uniform(0, height - 0.1)
across = rng.uniform(0.1, 0.9)
position = [corner[0] + dx * along + dz * across, corner[1] + up, corner[2] + dz * along + dx * across]
entry = [int(position[0] // 1), int(position[1] // 1), int(position[2] // 1)]
if tuple(entry) not in source:
entry = list(corner)
scale = 8.0 if from_nether else 1 / 8
approx = (int((position[0] * scale) // 1), int(position[1] // 1), int((position[2] * scale) // 1))
target, pois = {}, []
terrain(states, rng, target, approx, not from_nether)
radius = 128 if from_nether else 16
for _ in range(rng.choice([0, 0, 1, 1, 2, 3])):
reach = rng.choice([4, radius, radius + 6])
other = (approx[0] + rng.randint(-reach, reach), approx[1] + rng.randint(-10, 10), approx[2] + rng.randint(-reach, reach))
portal(states, target, pois, other, rng.random() < 0.5, rng.choice([2, 3]), rng.choice([3, 4]), rng.random() < 0.8)
if rng.random() < 0.25:
# A tight border near the exit.
border = {'x': approx[0] + rng.randint(-20, 20) + 0.5 * rng.randint(0, 1), 'z': approx[2] + rng.randint(-20, 20),
'size': rng.choice([4, 9, 16, 30, 60])}
else:
border = {'x': 0.0, 'z': 0.0, 'size': 59999968.0}
yield {'seed': rng.randrange(1 << 40), 'from': 'nether' if from_nether else 'overworld',
'source': [[*p, s] for p, s in source.items()], 'target': [[*p, s] for p, s in target.items()],
'pois': pois, 'entry': entry, 'entity': {'type': kind, 'pos': position, 'bits': [struct.pack('>d', v).hex() for v in position], 'dims': list(dims),
'reset_forward': kind not in ('minecraft:item', 'minecraft:arrow')}, 'border': border}
def main():
parser = h.argument_parser(__doc__)
args = parser.parse_args()
if args.count == 40000:
args.count = 1500
lock, jars, libraries = base.verify_artifacts()
facts = h.load_facts()
resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
work = lab.LOCAL / 'nether-portal-parity'
work.mkdir(parents=True, exist_ok=True)
all_cases = list(cases(facts, args.count, args.seed))
(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'
h.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/VanillaPortalOracle.java')])
h.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaPortalOracle',
str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')])
h.run(['cargo', 'run', '-q', '--release', '-p', 'horizon-world', '--example', 'portal_travel_fixture', '--',
str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], cwd=lab.ROOT)
native = h.split_cases((work / 'native.txt').read_text(), ())
rust = h.split_cases((work / 'rust.txt').read_text(), ())
assert len(native) == len(rust) == len(all_cases), (len(native), len(rust), len(all_cases))
groups, errors = {}, {}
created = found = 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 any(line.startswith('set ') for line in a):
created += 1
elif not any(line == 'dest none' for line in a):
found += 1
if sorted(a) != sorted(b):
key = f"{case['from']} {case['entity']['type']} {'pois' if case['pois'] else 'no pois'}"
groups.setdefault(key, []).append((case, a, b))
for name, entries in sorted(errors.items(), key=lambda e: -len(e[1])):
print(f'oracle error x{len(entries)}: {name}')
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(f" case entry={case['entry']} entity={case['entity']} border={case['border']} pois={len(case['pois'])}")
print(' native ' + ' | '.join(sorted(a))[:1500])
print(' rust ' + ' | '.join(sorted(b))[:1500])
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'vanilla linked to an existing portal {found} times and built one {created} times')
h.finish(total + skipped)
if __name__ == '__main__':
main()
+136
View File
@@ -0,0 +1,136 @@
#!/usr/bin/env python3
"""Compare a player's right click on a block with vanilla's, for items that are
both food and blocks (sweet and glow berries, carrots, potatoes) and for sweet
berry bushes.
Every case has a block at the origin, something above it, and a player three
blocks south, survival or creative, hungry or full, sneaking or not, who
right-clicks the top face of the origin holding an item. Vanilla runs the real
`ServerPlayerGameMode.useItemOn` over the headless level of the dispenser
harness (`VanillaDispenserOracle.useItem`): the block's `useItemOn` and
`useWithoutItem` (picking a bush's berries, `SweetBerryBushBlock.useItemOn`
passing bone meal on), then `ItemStack.useOn` (`BlockItem.place` with its
`mayPlaceOn` rules, `BoneMealItem.useOn`, and eating a consumable that could
not be placed). Horizon runs `use_item_as_player` on that hit in a headless
game (`HORIZON_DISPENSE_FIXTURE`). Both print block changes, dropped items,
level events, sounds, game events, the used statistic, the held stack, the
item the player started using, and the level random afterwards.
"""
import json
import os
import random
try:
from . import block_update_harness as h, lab, test_dispenser_parity as d, test_rust_parity as base
except ImportError:
import block_update_harness as h
import lab
import test_dispenser_parity as d
import test_rust_parity as base
# Blocks the item is used on: the supports of the planted blocks and others.
GROUNDS = ['grass_block', 'dirt', 'coarse_dirt', 'podzol', 'rooted_dirt', 'moss_block', 'pale_moss_block', 'mud',
'muddy_mangrove_roots', 'farmland', 'stone', 'sand', 'gravel', 'clay', 'snow_block', 'oak_planks']
ITEMS = ['sweet_berries', 'sweet_berries', 'sweet_berries', 'glow_berries', 'carrot', 'potato', 'bone_meal',
'wheat_seeds', 'beetroot_seeds', 'apple']
# What is in the way above the clicked block.
ABOVE = ['air'] * 8 + ['short_grass', 'snow', 'stone', 'water', 'dead_bush', 'fern']
def cases(facts, count, seed):
rng = random.Random(seed)
states = d.States(facts)
for n in range(count):
case = {**h.environment(rng), 'pos': [0, 0, 0]}
case.pop('raining', None)
case.pop('thundering', None)
cells = []
item = rng.choice(ITEMS)
if rng.random() < 0.3:
# A sweet berry bush on grass: pick it, bone meal it, or plant against it.
age = rng.randrange(4)
cells.append([0, 0, 0, states.get('sweet_berry_bush', age=str(age))])
cells.append([0, -1, 0, states.get(rng.choice(['grass_block', 'dirt', 'podzol', 'farmland']))])
item = rng.choice(['bone_meal', 'bone_meal', 'sweet_berries', 'apple', '-', 'stick'])
else:
ground = rng.choice(GROUNDS)
cells.append([0, 0, 0, states.any(rng, ground) if ground == 'farmland' else states.get(ground)])
above = rng.choice(ABOVE)
if above != 'air':
cells.append([0, 1, 0, states.get(above)])
if item == 'glow_berries' and rng.random() < 0.5:
# A ceiling two blocks up for the cave vines to hang from.
cells.append([0, 2, 0, states.get(rng.choice(['stone', 'dirt', 'oak_leaves']))])
if item == 'bone_meal' and ground in ('grass_block', 'moss_block', 'pale_moss_block'):
# Bone meal on spreading blocks is the bone meal harness's.
item = 'sweet_berries'
held = '-' if item == '-' else d.plain(item, rng.choice([1, 1, 2, 16, 64]))
case['use_item'] = {'item': held, 'creative': rng.random() < 0.2, 'sneaking': rng.random() < 0.2,
'food': rng.choice([20, 20, 19, 10, 0])}
case['cells'] = cells
case['items'] = []
case['mode'] = 'dispense'
yield case
def kind(case, facts):
first = facts.states[case['cells'][0][3]][0].split(':')[1]
item = case['use_item']['item']
item = item.split('"')[1].split(':')[1] if item != '-' else 'empty hand'
return f'{item} on {first}'
def main():
parser = h.argument_parser(__doc__)
args = parser.parse_args()
if args.count == 40000:
args.count = 4000
lock, jars, libraries = base.verify_artifacts()
facts = h.load_facts()
resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
work = lab.LOCAL / 'use-item-on-parity'
work.mkdir(parents=True, exist_ok=True)
all_cases = list(cases(facts, args.count, args.seed))
(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'
d.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')])
d.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle',
str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')])
d.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')})
d.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'})
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 = {}, {}
planted = eaten = 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
planted += any(line.startswith('set 0,1,0') for line in a)
eaten += any(line.startswith('held') and not line.endswith('using -') for line in a)
if not d.same(a, b):
groups.setdefault(kind(case, facts), []).append((case, a, b))
for name, entries in sorted(errors.items(), key=lambda e: -len(e[1])):
print(f'oracle error x{len(entries)}: {name}')
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 ' + d.describe(case, facts) + ' use=' + json.dumps(case['use_item']))
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'vanilla planted in {planted} and started eating in {eaten}')
h.finish(total + skipped)
if __name__ == '__main__':
main()
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env python3
"""Compare a new world's spawn with vanilla's, seed by seed.
A new overworld's spawn comes from two steps (MinecraftServer.setInitialSpawn):
1. the origin: NoiseBasedChunkGenerator.getOrigin runs NoiseSpawnFinder over
the noise settings' `spawn_target` points (a coarse then a fine radial
search of the climate fields) and takes the chunk of the best column;
2. the spawn: an 11 by 11 chunk spiral around that chunk, the first chunk
with a column PlayerSpawnFinder.getSpawnPosInChunk accepts (a full-topped
block under open sky, no liquid on top) gives the world spawn.
Origins: VanillaWorldSpawnOracle calls NoiseSpawnFinder.findSpawnPosition and
getOrigin for every seed; the spawn_origin example asks Horizon's generator.
World spawns: the pinned vanilla dedicated server creates each world and
stops; Horizon's (`horizon-client --dedicated --nogui`) creates its own from
the same server.properties and stops; the `spawn` position of both
level.dat files is compared.
Vanilla is not deterministic everywhere: trees of neighbouring chunks
overlap on chunk corners, and which one is placed last depends on the order
the server's worker threads decorate the chunks. A spawn column on such a
corner can then stand on different leaves from one vanilla run to the next.
When the spawns differ, vanilla creates the world up to RETRIES more times;
Horizon's spawn passes if one of vanilla's runs gives it too, and the seed is
reported as varying in vanilla.
Seeds: the player report's seed (1891623539983467248: Horizon spawned at
-48 -48, vanilla at 152 145), the chunk generation harness's seeds and
--random seeds from a fixed generator.
usage: test_world_spawn_parity.py [--random N] [--jobs N] [--origins-only]
"""
import argparse
import json
import os
import random
import shutil
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
try:
from . import anvil_dump, lab, oracle_harness as oh, test_rust_parity as base
from .test_dedicated_server_parity import Server, free_port
except ImportError:
import anvil_dump
import lab
import oracle_harness as oh
import test_rust_parity as base
from test_dedicated_server_parity import Server, free_port
NAME = 'world-spawn-parity'
REPORT = 1891623539983467248
RETRIES = 3
SEEDS = [REPORT, 12345, -7046029254386353131, 987654321987, 4242, -1, 0x5DEECE66D, 20260607, 777, 0]
RESOURCES = lab.LOCAL / 'horizon-client/26.3'
def seeds(count):
rng = random.Random(20261014)
return SEEDS + [rng.randrange(-2**63, 2**63) for _ in range(count)]
def target_dir():
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
cwd=lab.ROOT, text=True))
return Path(metadata['target_directory']) / 'release'
def origins(build, classes, dependencies, all_seeds):
vanilla_out = build / 'origins-vanilla.txt'
oh.run_logged(['java', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaWorldSpawnOracle',
vanilla_out, *all_seeds], build, 'origins-vanilla')
rust = subprocess.run([target_dir() / 'examples/spawn_origin', RESOURCES, *map(str, all_seeds)],
capture_output=True, text=True, check=True, cwd=lab.ROOT).stdout
vanilla = vanilla_out.read_text()
parse = lambda text: {int(l.split()[0]): tuple(map(int, l.split()[1:])) for l in text.splitlines() if l}
return parse(vanilla), parse(rust)
def world_spawn(command, directory, seed, log_name):
"""Creates a world with `seed` in `directory`, stops, returns its level.dat spawn position."""
if directory.exists():
shutil.rmtree(directory)
directory.mkdir(parents=True)
props = {'online-mode': 'false', 'level-seed': str(seed), 'server-port': str(free_port()),
'view-distance': '4', 'simulation-distance': '4', 'pause-when-empty-seconds': '-1'}
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()), encoding='iso-8859-1')
(directory / 'eula.txt').write_text('eula=true\n')
server = Server(command, directory, log_name)
try:
server.wait_for(r'Done \(', timeout=900)
finally:
server.stop()
data = anvil_dump.read_dat(directory / 'world/level.dat')['Data']
return tuple(data['spawn']['pos'][1])
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--random', type=int, default=50, help='random seeds besides the fixed ones')
parser.add_argument('--jobs', type=int, default=max(1, min(4, int(os.environ.get('FLEET_LOAD_JOBS', '4')) // 4)),
help='worlds created at once (each side)')
parser.add_argument('--origins-only', action='store_true', help='compare the spawn search origins only')
parser.add_argument('--seed', type=int, action='append', help='only these seeds (repeatable)')
args = parser.parse_args()
lock, jars, libraries = base.verify_artifacts()
build = lab.LOCAL / NAME
build.mkdir(parents=True, exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
classes = build / 'classes'
classes.mkdir(exist_ok=True)
oh.run_logged(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies,
'-d', classes, lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldSpawnOracle.java'],
build, 'compile-java')
oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'spawn_origin'], build, 'compile-probe')
all_seeds = args.seed or seeds(args.random)
started = time.time()
vanilla, rust = origins(build, classes, dependencies, all_seeds)
origin_diffs = [s for s in all_seeds if vanilla.get(s) != rust.get(s)]
for s in origin_diffs:
print(f'origin {s}: vanilla column {vanilla.get(s)} / horizon {rust.get(s)}')
print(f'Origins: {len(all_seeds) - len(origin_diffs)}/{len(all_seeds)} seeds match '
f'(column x z, chunk x z) in {time.time() - started:.0f}s', flush=True)
if args.origins_only:
sys.exit(1 if origin_diffs else 0)
oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], build,
'compile-rust', timeout=3600)
binary = target_dir() / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
vanilla_server = ['java', '-Xmx2g', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
horizon_server = [binary, '--resources', RESOURCES, '--dedicated', '--nogui']
os.environ['HORIZON_NO_AUDIO'] = '1'
def one(seed):
t0 = time.time()
a = world_spawn(vanilla_server, build / f'vanilla-{seed}', seed, f'vanilla-{seed}')
b = world_spawn(horizon_server, build / f'horizon-{seed}', seed, f'horizon-{seed}')
runs = [a]
while b not in runs and len(runs) <= RETRIES:
runs.append(world_spawn(vanilla_server, build / f'vanilla-{seed}-{len(runs)}', seed, f'vanilla-{seed}-{len(runs)}'))
return seed, runs, b, time.time() - t0
spawn_diffs, varying = [], []
with ThreadPoolExecutor(args.jobs) as pool:
for seed, runs, b, took in pool.map(one, all_seeds):
ok = b in runs
if not ok:
spawn_diffs.append(seed)
elif len(set(runs)) > 1:
varying.append(seed)
seen = ', '.join(' '.join(map(str, r)) for r in dict.fromkeys(runs))
print(f'{"ok " if ok else "DIFF"} {seed}: vanilla {seen} / horizon {b[0]} {b[1]} {b[2]} '
f'(origin chunk {vanilla[seed][2]} {vanilla[seed][3]}; {took:.0f}s)', flush=True)
if ok:
for path in build.glob(f'*-{seed}*'):
shutil.rmtree(path, ignore_errors=True)
print(f'World spawns: {len(all_seeds) - len(spawn_diffs)}/{len(all_seeds)} seeds match in {time.time() - started:.0f}s'
+ (f'; vanilla itself gave several spawns for {len(varying)}: {varying}' if varying else ''))
if origin_diffs or spawn_diffs:
sys.exit(1)
if __name__ == '__main__':
main()